@hol-org/hashnet-mcp 1.0.20 → 1.0.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/up.cjs +1284 -0
- package/dist/index.cjs +1279 -0
- package/package.json +24 -25
- package/AGENTS.md +0 -163
- package/deploy/Dockerfile +0 -24
- package/deploy/README.md +0 -31
- package/deploy/fly.toml +0 -41
- package/dist/cli/up.js +0 -175
- package/dist/cli/up.js.map +0 -1
- package/dist/index.js +0 -2767
- package/dist/index.js.map +0 -1
- package/examples/agent-registration-request.json +0 -48
- package/examples/workflows/workflow.agentverseBridge.json +0 -15
- package/examples/workflows/workflow.chatSmoke.json +0 -8
- package/examples/workflows/workflow.discovery.json +0 -4
- package/examples/workflows/workflow.erc8004Discovery.json +0 -4
- package/examples/workflows/workflow.erc8004X402.json +0 -87
- package/examples/workflows/workflow.fullRegistration.json +0 -73
- package/examples/workflows/workflow.historyTopUp.json +0 -14
- package/examples/workflows/workflow.ledgerAuth.json +0 -8
- package/examples/workflows/workflow.openrouterChat.json +0 -7
- package/examples/workflows/workflow.opsCheck.json +0 -3
- package/examples/workflows/workflow.registerAgentAdvanced.json +0 -84
- package/examples/workflows/workflow.registerAgentErc8004.json +0 -82
- package/examples/workflows/workflow.registerMcp.json +0 -71
- package/examples/workflows/workflow.registryBrokerShowcase.json +0 -6
- package/examples/workflows/workflow.x402Registration.json +0 -83
- package/examples/workflows/workflow.x402TopUp.json +0 -13
- /package/dist/{index.d.ts → index.d.cts} +0 -0
package/dist/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/transports/index.ts","../src/mcp.ts","../src/broker.ts","../src/config.ts","../src/logger.ts","../src/schemas/agent.ts","../src/workflows/env.ts","../src/workflows/pipeline.ts","../src/workflows/registry.ts","../src/workflows/discovery.ts","../src/workflows/utils/credits.ts","../src/workflows/errors.ts","../src/workflows/registration.ts","../src/memory/factory.ts","../src/memory/in-memory-store.ts","../src/memory/types.ts","../src/memory/file-store.ts","../src/memory/service.ts","../src/memory/index.ts","../src/workflows/utils/memory.ts","../src/workflows/chat.ts","../src/workflows/ops.ts","../src/workflows/combined.ts","../src/workflows/scaffold.ts","../src/workflows/openrouter-chat.ts","../src/workflows/registry-showcase.ts","../src/workflows/agentverse-bridge.ts","../src/workflows/erc8004-discovery.ts","../src/workflows/register-advanced.ts","../src/workflows/register-erc8004.ts","../src/workflows/x402-topup.ts","../src/workflows/erc8004-x402.ts","../src/workflows/x402-registration.ts","../src/index.ts"],"sourcesContent":["import http, { IncomingMessage, ServerResponse } from 'node:http';\nimport { randomUUID } from 'node:crypto';\nimport { PassThrough } from 'node:stream';\nimport { mcp, registeredTools } from '../mcp';\nimport { config } from '../config';\nimport { logger } from '../logger';\n\nconst LOOPBACK = '127.0.0.1';\n\nexport async function runStdio() {\n logger.info('Starting stdio transport');\n await mcp.start({ transportType: 'stdio' });\n logger.info('Stdio transport started');\n}\n\nexport async function runSSE() {\n const upstreamPort = config.httpStreamPort ?? config.port + 1;\n await startHttpStreamBackend(upstreamPort);\n\n const gateway = createGatewayServer(upstreamPort);\n await new Promise<void>((resolve, reject) => {\n gateway.once('error', reject);\n gateway.listen(config.port, () => {\n logger.info({ port: config.port, upstreamPort }, 'Gateway listening');\n resolve();\n });\n });\n}\n\nasync function startHttpStreamBackend(port: number) {\n await mcp.start({\n transportType: 'httpStream',\n httpStream: {\n port,\n host: LOOPBACK,\n endpoint: '/mcp/stream',\n enableJsonResponse: false,\n },\n });\n logger.info({ port }, 'HTTP stream backend ready');\n}\n\nexport function createGatewayServer(upstreamPort: number) {\n return http.createServer(createGatewayHandler(upstreamPort));\n}\n\nexport function createGatewayHandler(upstreamPort: number) {\n return (req: IncomingMessage, res: ServerResponse) => {\n if (!req.url) {\n res.writeHead(400).end('Missing URL');\n return;\n }\n if (req.url.startsWith('/healthz')) {\n const body = JSON.stringify({\n status: 'ok',\n uptime: process.uptime(),\n tools: registeredTools.length,\n requestId: randomUUID(),\n });\n res.writeHead(200, { 'content-type': 'application/json' });\n res.end(body);\n return;\n }\n proxyRequest(req, res, upstreamPort);\n };\n}\n\nfunction proxyRequest(req: IncomingMessage, res: ServerResponse, upstreamPort: number) {\n logger.debug({ method: req.method, url: req.url }, 'gateway.forward');\n const proxyReq = http.request(\n {\n hostname: LOOPBACK,\n port: upstreamPort,\n method: req.method,\n path: req.url,\n headers: {\n ...req.headers,\n host: `${LOOPBACK}:${upstreamPort}`,\n },\n },\n (proxyRes) => {\n res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers);\n proxyRes.pipe(res);\n },\n );\n\n proxyReq.on('error', (error) => {\n logger.error({ error }, 'proxy.error');\n if (!res.headersSent) {\n res.writeHead(502);\n }\n res.end('Upstream error');\n });\n\n if (req.method && ['POST', 'PUT', 'PATCH'].includes(req.method)) {\n const tee = new PassThrough();\n let preview = '';\n tee.on('data', (chunk) => {\n if (preview.length < 512) {\n preview += chunk.toString();\n }\n });\n tee.on('end', () => {\n if (preview.length) {\n logger.debug({ preview: preview.slice(0, 512) }, 'proxy.preview');\n }\n });\n req.pipe(tee).pipe(proxyReq);\n } else {\n req.pipe(proxyReq);\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport { AgentAuthConfig, LedgerChallengeRequest, LedgerVerifyRequest, RegistryBrokerClient, RegistryBrokerError } from '@hashgraphonline/standards-sdk';\nimport { FastMCP } from 'fastmcp';\nimport type { Context, Content } from 'fastmcp';\nimport { z } from 'zod';\nimport { getCreditBalance, withBroker } from './broker';\nimport { config } from './config';\nimport { logger } from './logger';\nimport { agentRegistrationSchema } from './schemas/agent';\nimport { discoveryPipeline } from './workflows/discovery';\nimport { registrationPipeline } from './workflows/registration';\nimport { chatPipeline } from './workflows/chat';\nimport { opsPipeline } from './workflows/ops';\nimport { fullWorkflowPipeline } from './workflows/combined';\nimport { openRouterChatWorkflow } from './workflows/openrouter-chat';\nimport { registryBrokerShowcaseWorkflow } from './workflows/registry-showcase';\nimport { agentverseBridgeWorkflow } from './workflows/agentverse-bridge';\nimport { erc8004DiscoveryWorkflow } from './workflows/erc8004-discovery';\nimport { erc8004X402Workflow } from './workflows/erc8004-x402';\nimport { x402RegistrationWorkflow } from './workflows/x402-registration';\nimport type { PipelineRunResult } from './workflows/types';\nimport { memoryService } from './memory';\nimport type { MemoryScope } from './memory';\n\ntype AgentRegistrationRequest = Parameters<RegistryBrokerClient['registerAgent']>[0];\ntype ChatCreateSessionPayload = Parameters<RegistryBrokerClient['chat']['createSession']>[0];\ntype ChatSendMessagePayload = Parameters<RegistryBrokerClient['chat']['sendMessage']>[0];\ntype ChatCompactPayload = Parameters<RegistryBrokerClient['chat']['compactHistory']>[0];\ntype UpdateAgentPayload = Parameters<RegistryBrokerClient['updateAgent']>[1];\ntype RegistrySearchNamespaceArgs = Parameters<RegistryBrokerClient['registrySearchByNamespace']>;\ntype PurchaseHbarPayload = Parameters<RegistryBrokerClient['purchaseCreditsWithHbar']>[0];\ntype BuyX402Payload = Parameters<RegistryBrokerClient['buyCreditsWithX402']>[0];\n\nconst connectionInstructions = [\n 'You expose the Hashgraph Online Registry Broker via hol.* primitives and workflow.* pipelines. Prefer workflow.* when possible—they bundle common steps and return a pipeline summary plus full results.',\n 'Discovery: use workflow.discovery (or hol.search / hol.vectorSearch) to find UAIDs/agents/MCP servers; pass q/query and optional filters like capabilities, metadata, or type=ai-agents|mcp-servers.',\n 'Registration: workflow.registerMcp (quote → register → wait) is the default; workflow.fullRegistration adds discovery/chat/ops. hol.registerAgent + hol.waitForRegistrationCompletion are the lower-level primitives.',\n 'Chat: call hol.resolveUaid if the UAID is unverified, then hol.chat.createSession (uaid + optional auth) followed by hol.chat.sendMessage (sessionId or uaid). Use hol.chat.history/compact/end to manage the session.',\n 'Operations: workflow.opsCheck or hol.stats/hol.metricsSummary/hol.dashboardStats show registry health; hol.listProtocols + hol.detectProtocol help route third-party requests.',\n 'Credits: check hol.credits.balance before purchases. Use hol.purchaseCredits.hbar or hol.x402.buyCredits only with explicit user approval (X402 requires an EVM key); hol.x402.minimums provides thresholds.',\n 'Always include UAIDs/sessionIds exactly as given and echo any auth headers/tokens the user supplies. If required fields are missing (UAID, payload, accountId), ask for them before calling tools.',\n 'Additional help resources: help://rb/search documents hol.search filters; help://hol/usage lists common recipes.',\n].join('\\n');\n\nconst agentAuthSchema: z.ZodType<AgentAuthConfig> = z\n .object({\n type: z.enum(['bearer', 'basic', 'header', 'apiKey']).optional(),\n token: z.string().optional(),\n username: z.string().optional(),\n password: z.string().optional(),\n headerName: z.string().optional(),\n headerValue: z.string().optional(),\n headers: z.record(z.string(), z.string()).optional(),\n })\n .partial() as z.ZodType<AgentAuthConfig>;\n\nconst chatSessionSchema: z.ZodType<ChatCreateSessionPayload> = z.object({\n uaid: z.string().min(1),\n historyTtlSeconds: z.number().int().positive().optional(),\n auth: agentAuthSchema.optional(),\n senderUaid: z.string().min(1).optional(),\n encryptionRequested: z.boolean().optional(),\n}) as z.ZodType<ChatCreateSessionPayload>;\n\nconst chatMessageSchema: z.ZodType<ChatSendMessagePayload> = z\n .object({\n sessionId: z.string().min(1).optional(),\n uaid: z.string().min(1).optional(),\n message: z.string().min(1),\n streaming: z.boolean().optional(),\n auth: agentAuthSchema.optional(),\n })\n .superRefine((value, ctx) => {\n if (!value.sessionId && !value.uaid) {\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Provide sessionId for existing chats or uaid to start a new one.' });\n }\n }) as z.ZodType<ChatSendMessagePayload>;\n\nconst chatCompactSchema: z.ZodType<ChatCompactPayload> = z.object({\n sessionId: z.string().min(1),\n preserveEntries: z.number().int().min(0).default(4),\n auth: agentAuthSchema.optional(),\n}) as z.ZodType<ChatCompactPayload>;\n\nconst searchInput = z.object({\n q: z.string().optional(),\n limit: z.number().int().min(1).max(50).default(10),\n capabilities: z.array(z.string()).optional(),\n registries: z.array(z.string()).optional(),\n minTrust: z.number().int().min(0).max(100).optional(),\n verified: z.boolean().optional(),\n online: z.boolean().optional(),\n sortBy: z.enum(['trust', 'latency', 'most-recent']).optional(),\n sortOrder: z.enum(['asc', 'desc']).optional(),\n metadata: z.record(z.string(), z.array(z.string())).optional(),\n type: z.enum(['ai-agents', 'mcp-servers']).optional(),\n});\n\nconst vectorSearchInput = z.object({\n query: z.string().min(1),\n limit: z.number().int().min(1).max(20).default(5),\n});\n\nconst uaidInput = z.object({ uaid: z.string().min(1) });\n\nconst registrationPayload = z.object({\n payload: agentRegistrationSchema,\n});\n\nconst workflowDiscoveryInput = z.object({\n query: z.string().optional(),\n limit: z.number().int().min(1).max(50).optional(),\n});\n\nconst workflowRegistrationInput = z.object({\n payload: agentRegistrationSchema,\n});\n\nconst workflowChatInput = z.object({\n uaid: z.string().min(1),\n message: z.string().optional(),\n disableMemory: z.boolean().optional(),\n});\n\nconst workflowOpsInput = z.object({});\n\nconst workflowFullInput = z.object({\n registrationPayload: agentRegistrationSchema,\n discoveryQuery: z.string().optional(),\n chatMessage: z.string().optional(),\n disableMemory: z.boolean().optional(),\n});\nconst openRouterChatToolSchema = z.object({\n modelId: z.string().min(1),\n registry: z.string().optional(),\n message: z.string(),\n authToken: z.string().optional(),\n disableMemory: z.boolean().optional(),\n});\nconst registryShowcaseToolSchema = z.object({\n query: z.string().optional(),\n uaid: z.string().optional(),\n message: z.string().optional(),\n performCreditCheck: z.boolean().optional(),\n disableMemory: z.boolean().optional(),\n});\nconst erc8004DiscoveryToolSchema = z.object({ query: z.string().optional(), limit: z.number().int().positive().optional() });\nconst bridgePayloadSchema = z.object({\n uaid: z.string().min(1),\n agentverseUaid: z.string().min(1),\n localMessage: z.string().min(1),\n agentverseMessage: z.string().min(1),\n iterations: z.number().int().positive().optional(),\n});\nconst erc8004X402ToolSchema = z.object({\n payload: agentRegistrationSchema,\n erc8004Networks: z.array(z.string()).optional(),\n chatMessage: z.string().optional(),\n});\nconst x402RegistrationToolSchema = z.object({\n payload: agentRegistrationSchema,\n x402: z.object({\n accountId: z.string().min(1),\n credits: z.number().positive(),\n evmPrivateKey: z.string().min(1),\n ledgerVerification: z\n .object({\n challengeId: z.string().min(1),\n accountId: z.string().min(1),\n network: z.enum(['mainnet', 'testnet']),\n signature: z.string().min(1),\n signatureKind: z.enum(['raw', 'map']).optional(),\n publicKey: z.string().optional(),\n expiresInMinutes: z.number().int().positive().optional(),\n })\n .optional(),\n }),\n chatMessage: z.string().optional(),\n});\n\ntype SearchInput = z.infer<typeof searchInput>;\ntype VectorSearchInput = z.infer<typeof vectorSearchInput>;\ntype UaidInput = z.infer<typeof uaidInput>;\ntype SessionAuth = Record<string, unknown> | undefined;\ntype RegistrationInput = z.infer<typeof registrationPayload>;\ntype WaitForRegistrationInput = z.infer<typeof waitForRegistrationInput>;\ntype UpdateAgentInput = z.infer<typeof updateAgentInput>;\ntype RegistryNamespaceInput = z.infer<typeof registryNamespaceInput>;\ntype ChatSessionInput = z.infer<typeof chatSessionSchema>;\ntype ChatMessageInput = z.infer<typeof chatMessageSchema>;\ntype ChatCompactInput = z.infer<typeof chatCompactSchema>;\ntype CreditBalanceInput = z.infer<typeof creditBalanceInput>;\ntype LedgerChallengeInput = z.infer<typeof ledgerChallengeInput>;\ntype LedgerVerifyInput = z.infer<typeof ledgerVerifyInput>;\ntype PurchaseHbarInput = z.infer<typeof purchaseHbarInput>;\ntype BuyX402Input = z.infer<typeof buyX402Input>;\ntype BridgePayload = z.infer<typeof bridgePayloadSchema>;\ntype Erc8004X402Input = z.infer<typeof erc8004X402ToolSchema>;\ntype X402RegistrationInput = z.infer<typeof x402RegistrationToolSchema>;\ntype FullWorkflowInput = z.infer<typeof workflowFullInput>;\nconst memoryScopeSchema = z\n .object({\n uaid: z.string().min(1).optional(),\n sessionId: z.string().min(1).optional(),\n namespace: z.string().min(1).optional(),\n userId: z.string().min(1).optional(),\n })\n .refine((value) => Boolean(value.uaid || value.sessionId || value.namespace || value.userId), {\n message: 'Provide at least one scope identifier (uaid, sessionId, namespace, or userId).',\n });\n\nconst memoryContextSchema = z.object({\n scope: memoryScopeSchema,\n limit: z.number().int().positive().max(200).optional(),\n includeSummary: z.boolean().optional(),\n});\n\nconst memoryNoteSchema = z.object({\n scope: memoryScopeSchema,\n content: z.string().min(1),\n});\n\nconst memoryClearSchema = z.object({\n scope: memoryScopeSchema,\n});\n\nconst memorySearchSchema = z.object({\n scope: memoryScopeSchema,\n query: z.string().min(1),\n limit: z.number().int().positive().max(200).optional(),\n});\n\nconst waitForRegistrationInput = z.object({\n attemptId: z.string(),\n intervalMs: z.number().int().positive().default(2_000),\n timeoutMs: z.number().int().positive().default(5 * 60 * 1000),\n});\n\nconst detectProtocolInput = z.object({\n headers: z.record(z.string(), z.string()),\n body: z.string().optional(),\n});\n\nconst sessionIdInput = z.object({ sessionId: z.string().min(1) });\n\nconst emptyObject = z.object({});\n\nconst updateAgentInput = z.object({\n uaid: z.string().min(1),\n payload: agentRegistrationSchema,\n});\n\nconst registryNamespaceInput = z.object({\n registry: z.string().min(1),\n query: z.string().optional(),\n});\n\nconst creditBalanceInput = z.object({\n hederaAccountId: z.string().min(1).optional(),\n x402AccountId: z.string().min(1).optional(),\n});\n\nconst ledgerNetworkEnum = z.enum(['mainnet', 'testnet']);\n\nconst ledgerChallengeInput = z.object({\n accountId: z.string().min(1),\n network: ledgerNetworkEnum,\n});\n\nconst ledgerVerifyInput = z.object({\n challengeId: z.string().min(1),\n accountId: z.string().min(1),\n network: ledgerNetworkEnum,\n signature: z.string().min(1),\n signatureKind: z.enum(['raw', 'map']).optional(),\n publicKey: z.string().optional(),\n expiresInMinutes: z.number().int().positive().optional(),\n});\n\nconst purchaseHbarInput: z.ZodType<PurchaseHbarPayload> = z.object({\n accountId: z.string().min(1),\n privateKey: z.string().min(1),\n hbarAmount: z.number().positive(),\n memo: z.string().optional(),\n metadata: z.record(z.string(), z.any()).optional(),\n}) as z.ZodType<PurchaseHbarPayload>;\n\nconst buyX402Input: z.ZodType<BuyX402Payload> = z.object({\n accountId: z.string().min(1),\n credits: z.number().positive(),\n usdAmount: z.number().positive().optional(),\n description: z.string().optional(),\n metadata: z.record(z.string(), z.any()).optional(),\n evmPrivateKey: z.string().min(1),\n network: z.enum(['base', 'base-sepolia']).optional(),\n rpcUrl: z.string().url().optional(),\n}) as z.ZodType<BuyX402Payload>;\n\nexport const mcp = new FastMCP({\n name: 'hashgraph-standards',\n version: '1.0.0',\n instructions: connectionInstructions,\n // Route FastMCP logging to our pino logger (stderr) to keep stdio transport clean.\n logger: {\n debug: (...args: unknown[]) => logger.debug(args),\n info: (...args: unknown[]) => logger.info(args),\n warn: (...args: unknown[]) => logger.warn(args),\n error: (...args: unknown[]) => logger.error(args),\n log: (...args: unknown[]) => logger.info(args),\n },\n});\n\ntype ToolDefinition<Schema extends z.ZodTypeAny = z.ZodTypeAny> = {\n name: string;\n description: string;\n schema: Schema;\n handler: (input: z.infer<Schema>) => Promise<unknown>;\n};\n\nconst rawToolDefinitions = [\n {\n name: 'hol.search',\n description: 'Keyword search for agents or MCP servers with filtering controls.',\n schema: searchInput,\n handler: (input: SearchInput) => withBroker((client) => client.search(input), 'hol.search'),\n },\n {\n name: 'hol.vectorSearch',\n description: 'Vector similarity search across registered agents.',\n schema: vectorSearchInput,\n handler: (input: VectorSearchInput) => withBroker((client) => client.vectorSearch(input), 'hol.vectorSearch'),\n },\n {\n name: 'hol.resolveUaid',\n description: 'Resolve, validate, and check the status of a UAID in one call.',\n schema: uaidInput,\n handler: ({ uaid }: UaidInput) =>\n withBroker(async (client) => {\n const [resolved, validation, status] = await Promise.all([\n client.resolveUaid(uaid),\n client.validateUaid(uaid),\n client.getUaidConnectionStatus(uaid),\n ]);\n return { resolved, validation, status };\n }, 'hol.resolveUaid'),\n },\n {\n name: 'hol.closeUaidConnection',\n description: 'Force-close any open UAID connection.',\n schema: uaidInput,\n handler: ({ uaid }: UaidInput) => withBroker((client) => client.closeUaidConnection(uaid), 'hol.closeUaidConnection'),\n },\n {\n name: 'hol.getRegistrationQuote',\n description: 'Estimate fees for a given agent registration payload.',\n schema: registrationPayload,\n handler: ({ payload }: RegistrationInput) => withBroker((client) => client.getRegistrationQuote(payload), 'hol.getRegistrationQuote'),\n },\n {\n name: 'hol.registerAgent',\n description: 'Submit an HCS-11-compatible agent registration.',\n schema: registrationPayload,\n handler: ({ payload }: RegistrationInput) => withBroker((client) => client.registerAgent(payload), 'hol.registerAgent'),\n },\n {\n name: 'hol.waitForRegistrationCompletion',\n description: 'Poll the registry broker until a registration attempt resolves.',\n schema: waitForRegistrationInput,\n handler: ({ attemptId, intervalMs, timeoutMs }: WaitForRegistrationInput) =>\n withBroker((client) =>\n client.waitForRegistrationCompletion(attemptId, {\n intervalMs,\n timeoutMs,\n }),\n 'hol.waitForRegistrationCompletion',\n ),\n },\n {\n name: 'hol.updateAgent',\n description: 'Update an existing agent registration payload.',\n schema: updateAgentInput,\n handler: ({ uaid, payload }: UpdateAgentInput) =>\n withBroker((client) => client.updateAgent(uaid, payload as UpdateAgentPayload), 'hol.updateAgent'),\n },\n {\n name: 'hol.additionalRegistries',\n description: 'Retrieve the catalog of additional registries and networks.',\n schema: emptyObject,\n handler: () => withBroker((client) => client.getAdditionalRegistries(), 'hol.additionalRegistries'),\n },\n {\n name: 'hol.registrySearchByNamespace',\n description: 'Search within a specific registry namespace.',\n schema: registryNamespaceInput,\n handler: ({ registry, query }: RegistryNamespaceInput) =>\n withBroker((client) => client.registrySearchByNamespace(registry, query), 'hol.registrySearchByNamespace'),\n },\n {\n name: 'hol.chat.createSession',\n description: 'Open a chat session linked to a UAID.',\n schema: chatSessionSchema,\n handler: (input: ChatSessionInput) => withBroker((client) => client.chat.createSession(input), 'hol.chat.createSession'),\n },\n {\n name: 'hol.chat.sendMessage',\n description: 'Send a message to an active chat session.',\n schema: chatMessageSchema,\n handler: (input: ChatMessageInput) =>\n withBroker(async (client) => {\n const { sessionId, uaid, message, auth, streaming } = input;\n const scopeForMemory: MemoryScope = { sessionId: sessionId ?? undefined, uaid: uaid ?? undefined };\n if (sessionId) {\n const payload: ChatSendMessagePayload = { sessionId, message, auth, streaming };\n await recordMemory(scopeForMemory, 'user', message, 'hol.chat.sendMessage');\n const response = await client.chat.sendMessage(payload);\n await recordMemory(scopeForMemory, 'assistant', stringifyForMemory(response), 'hol.chat.sendMessage');\n return response;\n }\n\n if (!uaid) {\n throw new Error('sessionId missing; provide uaid so a session can be created before sending.');\n }\n\n // Auto-create a session when callers only supply a UAID.\n const session = await client.chat.createSession({ uaid, auth });\n const derivedSessionId = session.sessionId;\n if (!derivedSessionId) {\n throw new Error('Unable to determine sessionId from broker response when auto-creating chat session.');\n }\n\n const payload: ChatSendMessagePayload = {\n sessionId: derivedSessionId,\n message,\n auth,\n streaming,\n };\n\n scopeForMemory.sessionId = derivedSessionId;\n\n await recordMemory(scopeForMemory, 'user', message, 'hol.chat.sendMessage');\n\n const response = await client.chat.sendMessage(payload);\n\n await recordMemory(scopeForMemory, 'assistant', stringifyForMemory(response), 'hol.chat.sendMessage');\n\n return response;\n }, 'hol.chat.sendMessage'),\n },\n {\n name: 'hol.chat.history',\n description: 'Retrieve the message history for a chat session.',\n schema: sessionIdInput,\n handler: ({ sessionId }: z.infer<typeof sessionIdInput>) =>\n withBroker((client) => client.chat.getHistory(sessionId), 'hol.chat.history'),\n },\n {\n name: 'hol.chat.compact',\n description: 'Compact chat history while preserving the latest entries.',\n schema: chatCompactSchema,\n handler: (input: ChatCompactInput) => withBroker((client) => client.chat.compactHistory(input), 'hol.chat.compact'),\n },\n {\n name: 'hol.chat.end',\n description: 'End a chat session and release broker resources.',\n schema: sessionIdInput,\n handler: ({ sessionId }: z.infer<typeof sessionIdInput>) =>\n withBroker((client) => client.chat.endSession(sessionId), 'hol.chat.end'),\n },\n {\n name: 'hol.stats',\n description: 'High-level registry statistics and usage metrics.',\n schema: emptyObject,\n handler: () => withBroker((client) => client.stats(), 'hol.stats'),\n },\n {\n name: 'hol.metricsSummary',\n description: 'Aggregated broker metrics suitable for dashboards.',\n schema: emptyObject,\n handler: () => withBroker((client) => client.metricsSummary(), 'hol.metricsSummary'),\n },\n {\n name: 'hol.dashboardStats',\n description: 'Detailed dashboard statistics from the broker.',\n schema: emptyObject,\n handler: () => withBroker((client) => client.dashboardStats(), 'hol.dashboardStats'),\n },\n {\n name: 'hol.websocketStats',\n description: 'Retrieve websocket connection counts and throughput.',\n schema: emptyObject,\n handler: () => withBroker((client) => client.websocketStats(), 'hol.websocketStats'),\n },\n {\n name: 'hol.ledger.challenge',\n description: 'Create a ledger challenge message for account verification.',\n schema: ledgerChallengeInput,\n handler: (input: LedgerChallengeInput) =>\n withBroker((client) => client.createLedgerChallenge(input as LedgerChallengeRequest), 'hol.ledger.challenge'),\n },\n {\n name: 'hol.ledger.authenticate',\n description: 'Verify a signed ledger challenge (sets ledger API key).',\n schema: ledgerVerifyInput,\n handler: (input: LedgerVerifyInput) =>\n withBroker((client) => client.verifyLedgerChallenge(input as LedgerVerifyRequest), 'hol.ledger.authenticate'),\n },\n {\n name: 'hol.purchaseCredits.hbar',\n description: 'Purchase registry credits using HBAR funds.',\n schema: purchaseHbarInput,\n handler: (input: PurchaseHbarInput) =>\n withBroker((client) => client.purchaseCreditsWithHbar(input), 'hol.purchaseCredits.hbar'),\n },\n {\n name: 'hol.credits.balance',\n description: 'Fetch credit balances for the current API key and optional Hedera/X402 accounts.',\n schema: creditBalanceInput,\n handler: async (input: CreditBalanceInput) => {\n const hederaAccountId = input.hederaAccountId;\n const [apiKeyBalance, hederaBalance, x402Balance] = await Promise.all([\n getCreditBalance(),\n hederaAccountId ? safeBalanceLookup('hedera', hederaAccountId) : Promise.resolve(null),\n input.x402AccountId ? safeBalanceLookup('x402', input.x402AccountId) : Promise.resolve(null),\n ]);\n return {\n apiKey: apiKeyBalance,\n hedera: hederaBalance,\n x402: x402Balance,\n };\n },\n },\n {\n name: 'hol.x402.minimums',\n description: 'Fetch the minimum credit purchase requirements for X402.',\n schema: emptyObject,\n handler: () => withBroker((client) => client.getX402Minimums(), 'hol.x402.minimums'),\n },\n {\n name: 'hol.x402.buyCredits',\n description: 'Buy registry credits via X402 using an EVM private key.',\n schema: buyX402Input,\n handler: (input: BuyX402Input) => withBroker((client) => client.buyCreditsWithX402(input), 'hol.x402.buyCredits'),\n },\n {\n name: 'hol.memory.context',\n description: 'Fetch recent memory entries and optional summary for a scope.',\n schema: memoryContextSchema,\n handler: async (input: z.infer<typeof memoryContextSchema>) => {\n const service = ensureMemoryEnabled();\n return service.getContext({\n scope: input.scope,\n limit: input.limit,\n includeSummary: input.includeSummary ?? true,\n });\n },\n },\n {\n name: 'hol.memory.note',\n description: 'Save a free-form note into memory for the given scope.',\n schema: memoryNoteSchema,\n handler: async (input: z.infer<typeof memoryNoteSchema>) => {\n const service = ensureMemoryEnabled();\n return service.note(input.scope, input.content);\n },\n },\n {\n name: 'hol.memory.clear',\n description: 'Clear memory entries and summaries for the given scope.',\n schema: memoryClearSchema,\n handler: async (input: z.infer<typeof memoryClearSchema>) => {\n const service = ensureMemoryEnabled();\n const removed = await service.clear(input.scope);\n return { removed };\n },\n },\n {\n name: 'hol.memory.search',\n description: 'Keyword search across stored memory for a scope.',\n schema: memorySearchSchema,\n handler: async (input: z.infer<typeof memorySearchSchema>) => {\n const service = ensureMemoryEnabled();\n return service.search({ scope: input.scope, query: input.query, limit: input.limit });\n },\n },\n {\n name: 'workflow.discovery',\n description: 'Pipeline: hol.search + hol.vectorSearch',\n schema: workflowDiscoveryInput,\n handler: async (input: z.infer<typeof workflowDiscoveryInput>) =>\n formatPipelineResult(await discoveryPipeline.run(input)),\n },\n {\n name: 'workflow.registerMcp',\n description: 'Pipeline: get quote, register agent, wait for completion',\n schema: workflowRegistrationInput,\n handler: async ({ payload }: z.infer<typeof workflowRegistrationInput>) =>\n formatPipelineResult(await registrationPipeline.run({ payload })),\n },\n {\n name: 'workflow.chatSmoke',\n description: 'Pipeline: chat session smoke test for UAID',\n schema: workflowChatInput,\n handler: async (input: z.infer<typeof workflowChatInput>) =>\n formatPipelineResult(await chatPipeline.run(input)),\n },\n {\n name: 'workflow.opsCheck',\n description: 'Pipeline: stats, metrics, dashboard, protocols',\n schema: workflowOpsInput,\n handler: async () => formatPipelineResult(await opsPipeline.run({})),\n },\n {\n name: 'workflow.openrouterChat',\n description: 'Pipeline: discover OpenRouter model and run a chat message',\n schema: openRouterChatToolSchema,\n handler: async (input: z.infer<typeof openRouterChatToolSchema>) =>\n formatPipelineResult(await openRouterChatWorkflow.run(input)),\n },\n {\n name: 'workflow.registryBrokerShowcase',\n description: 'Pipeline: discovery, analytics, UAID validation, chat',\n schema: registryShowcaseToolSchema,\n handler: async (input: z.infer<typeof registryShowcaseToolSchema>) =>\n formatPipelineResult(await registryBrokerShowcaseWorkflow.run(input)),\n },\n {\n name: 'workflow.agentverseBridge',\n description: 'Pipeline: relay chat between local UAID and Agentverse UAID',\n schema: bridgePayloadSchema,\n handler: async (input: BridgePayload) =>\n formatPipelineResult(await agentverseBridgeWorkflow.run(input)),\n },\n {\n name: 'workflow.erc8004Discovery',\n description: 'Pipeline: search ERC-8004 registries',\n schema: erc8004DiscoveryToolSchema,\n handler: async (input: z.infer<typeof erc8004DiscoveryToolSchema>) =>\n formatPipelineResult(await erc8004DiscoveryWorkflow.run(input)),\n },\n {\n name: 'workflow.erc8004X402',\n description: 'Pipeline: ERC-8004 registration funded via X402 credits',\n schema: erc8004X402ToolSchema,\n handler: async (input: Erc8004X402Input) => formatPipelineResult(await erc8004X402Workflow.run(input)),\n },\n {\n name: 'workflow.x402Registration',\n description: 'Pipeline: register agent using X402 payments + chat smoke test',\n schema: x402RegistrationToolSchema,\n handler: async (input: X402RegistrationInput) => formatPipelineResult(await x402RegistrationWorkflow.run(input)),\n },\n {\n name: 'workflow.fullRegistration',\n description: 'Pipeline: discovery → register → chat → ops',\n schema: workflowFullInput,\n handler: async (input: FullWorkflowInput) => formatPipelineResult(await fullWorkflowPipeline.run(input)),\n },\n];\n\nexport const toolDefinitions: ToolDefinition[] = rawToolDefinitions as unknown as ToolDefinition[];\n\nfunction ensureMemoryEnabled() {\n if (!memoryService || !memoryService.isEnabled()) {\n throw new Error('Memory is disabled or unavailable. Set MEMORY_ENABLED=1 and ensure the configured backend is installed.');\n }\n return memoryService;\n}\n\nfunction formatPipelineResult(result: PipelineRunResult<unknown>) {\n const contextRecord =\n result.context && typeof result.context === 'object' ? (result.context as Record<string, unknown>) : {};\n const contextUaid = typeof contextRecord.uaid === 'string' ? (contextRecord.uaid as string) : undefined;\n const summaryLines = [\n `Workflow: ${result.pipeline}`,\n result.dryRun ? '(dry-run)' : undefined,\n contextUaid ? `UAID: ${contextUaid}` : undefined,\n `Steps executed: ${result.steps.length}`,\n ].filter(Boolean) as string[];\n\n return {\n content: [\n { type: 'text', text: summaryLines.join('\\n') },\n buildObjectContent('pipeline.result', result as unknown as Record<string, unknown>),\n ],\n };\n}\n\nexport function buildLoggedTool<S extends z.ZodTypeAny>(definition: ToolDefinition<S>) {\n return {\n name: definition.name,\n description: definition.description,\n parameters: definition.schema,\n execute: async (args: z.input<S>, context?: Context<SessionAuth>) => {\n const requestId = context?.requestId ?? randomUUID();\n const started = Date.now();\n try {\n const parsedInput = definition.schema.parse(args);\n logger.debug({ requestId, tool: definition.name }, 'tool.invoke');\n const result = await definition.handler(parsedInput as z.infer<S>);\n if (memoryService && memoryService.isEnabled()) {\n const scopeForMemory = deriveScopeFromArgs(parsedInput);\n if (hasScope(scopeForMemory)) {\n void memoryService\n .recordToolEvent(definition.name, scopeForMemory, { input: parsedInput, result })\n .catch((error) => logger.warn({ requestId, tool: definition.name, error }, 'memory.capture.failed'));\n }\n }\n logger.info(\n {\n requestId,\n tool: definition.name,\n durationMs: Date.now() - started,\n },\n 'tool.success',\n );\n return normalizeResult(result);\n } catch (error) {\n logger.error(\n {\n requestId,\n tool: definition.name,\n durationMs: Date.now() - started,\n error: error instanceof Error ? error.message : String(error),\n },\n 'tool.failure',\n );\n throw error;\n }\n },\n };\n}\n\nfor (const definition of toolDefinitions) {\n mcp.addTool(buildLoggedTool(definition));\n}\n\nexport const registeredTools = toolDefinitions;\n\nfunction isContentValue(value: unknown): value is Content {\n return Boolean(\n value &&\n typeof value === 'object' &&\n 'type' in (value as Record<string, unknown>) &&\n typeof (value as Record<string, unknown>).type === 'string',\n );\n}\n\nfunction normalizeResult(value: unknown): { content: Content[]; structuredContent?: Record<string, unknown>; isError?: boolean } {\n if (isResultShape(value)) {\n const record = value as Record<string, unknown>;\n return {\n content: normalizeContent(record.content),\n isError: typeof record.isError === 'boolean' ? (record.isError as boolean) : undefined,\n };\n }\n if (isPlainObject(value)) {\n return {\n content: [buildObjectContent('tool.result', value as Record<string, unknown>)],\n };\n }\n return { content: normalizeContent(value) };\n}\n\nfunction normalizeContent(result: unknown): Content[] {\n if (Array.isArray(result) && result.every(isContentValue)) {\n return result;\n }\n if (isContentValue(result)) {\n return [result];\n }\n if (result === undefined || result === null) {\n return [{ type: 'text', text: 'ok' }];\n }\n if (typeof result === 'string' || typeof result === 'number' || typeof result === 'boolean') {\n return [{ type: 'text', text: String(result) }];\n }\n if (isPlainObject(result)) {\n return [buildObjectContent('tool.result', result as Record<string, unknown>)];\n }\n return [{ type: 'text', text: JSON.stringify(result) }];\n}\n\nfunction buildObjectContent(name: string, value: Record<string, unknown>): Content {\n return {\n type: 'text',\n text: `${name}:\\n${JSON.stringify(value, null, 2)}`,\n };\n}\n\nfunction isResultShape(value: unknown): value is { content?: unknown; structuredContent?: unknown; isError?: boolean } {\n return Boolean(value && typeof value === 'object' && ('content' in (value as Record<string, unknown>) || 'structuredContent' in (value as Record<string, unknown>)));\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === 'object' && !Array.isArray(value));\n}\n\nasync function runBrokerCall<T>(label: string, fn: () => Promise<T>) {\n try {\n return await fn();\n } catch (error) {\n if (error instanceof RegistryBrokerError) {\n const body = typeof error.body === 'object' ? JSON.stringify(error.body) : String(error.body);\n throw new Error(`${label} failed (${error.status} ${error.statusText ?? ''}): ${body}`);\n }\n throw error;\n }\n}\n\nasync function safeBalanceLookup(label: 'hedera' | 'x402', accountId: string) {\n try {\n return await getCreditBalance(accountId);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { error: `${label} balance unavailable: ${message}`, accountId };\n }\n}\n\nfunction deriveScopeFromArgs(args: unknown): MemoryScope {\n if (!args || typeof args !== 'object') return {};\n const record = args as Record<string, unknown>;\n const scope: MemoryScope = {};\n // We keep this loose: whichever identifiers the tool provides, we pass along for scoping.\n if (typeof record.sessionId === 'string') scope.sessionId = record.sessionId;\n if (typeof record.uaid === 'string') scope.uaid = record.uaid;\n if (typeof record.namespace === 'string') scope.namespace = record.namespace;\n if (typeof record.userId === 'string') scope.userId = record.userId;\n return scope;\n}\n\nfunction hasScope(scope: MemoryScope) {\n return Boolean(scope.sessionId || scope.uaid || scope.namespace || scope.userId);\n}\n\nfunction stringifyForMemory(value: unknown): string {\n if (typeof value === 'string') return value;\n if (value === undefined || value === null) return '';\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nasync function recordMemory(scope: MemoryScope, role: 'user' | 'assistant' | 'note' | 'tool', content: string, toolName: string) {\n if (!memoryService || !memoryService.isEnabled()) return;\n try {\n await memoryService.recordEntry({ scope, role, content, toolName });\n } catch (error) {\n // Do not fail tool execution if memory capture fails.\n logger.warn({ scope, toolName, error }, 'memory.record.failed');\n }\n}\n\nmcp.addResource({\n name: 'hol.search.help',\n uri: 'help://rb/search',\n mimeType: 'text/markdown',\n load: async () => [\n {\n text: [\n '# hol.search',\n '',\n 'Discover registered agents or MCP servers.',\n '',\n '- `q`: keyword search',\n '- `capabilities`: filter by declared skills',\n '- `metadata`: pass `{ \\\"region\\\": [\\\"na\\\"] }` style filters',\n '- `type`: limit results to `ai-agents` or `mcp-servers`',\n ].join('\\n'),\n },\n ],\n});\n\nmcp.addResource({\n name: 'hol.tools.guide',\n uri: 'help://hol/usage',\n mimeType: 'text/markdown',\n load: async () => [\n {\n text: [\n '# Hashnet MCP quick usage',\n '',\n 'Prefer workflow.* pipelines when available—they run multiple broker calls and return both a text summary and structured results:',\n '- Discovery: workflow.discovery { query?, limit? } (or hol.search / hol.vectorSearch).',\n '- Registration: workflow.registerMcp { payload } (quote → register → wait) or workflow.fullRegistration to add discovery/chat/ops.',\n '- Chat: hol.chat.createSession { uaid, auth?, historyTtlSeconds? } → hol.chat.sendMessage { sessionId OR uaid, message, auth?, streaming? } → hol.chat.history/compact/end.',\n '- UAID validation/resets: hol.resolveUaid { uaid }, hol.closeUaidConnection { uaid }.',\n '- Ops/metrics: workflow.opsCheck or hol.stats / hol.metricsSummary / hol.dashboardStats.',\n '- Credits: hol.credits.balance first, then hol.purchaseCredits.hbar or hol.x402.buyCredits (X402 requires evmPrivateKey; call hol.x402.minimums to inspect limits).',\n '- Protocols: hol.listProtocols and hol.detectProtocol when inspecting inbound requests.',\n '',\n 'Ask the user for any missing UAID, registration payload fields, accountId, or auth tokens before calling tools. Keep sessionId/uaid strings verbatim.',\n ].join('\\n'),\n },\n ],\n});\n\nmcp.addResource({\n name: 'hol.memory.guide',\n uri: 'help://hol/memory',\n mimeType: 'text/markdown',\n load: async () => [\n {\n text: [\n '# Memory tools',\n '',\n 'Memory is optional and disabled by default. Enable with `MEMORY_ENABLED=1` (defaults to SQLite at `MEMORY_STORAGE_PATH`).',\n '',\n '- `hol.memory.context { scope, limit?, includeSummary? }`: recent entries plus optional summary for a UAID/session/namespace.',\n '- `hol.memory.note { scope, content }`: store a note in the scope.',\n '- `hol.memory.search { scope, query, limit? }`: keyword search within scoped memory.',\n '- `hol.memory.clear { scope }`: drop entries + summary for the scope.',\n '',\n 'Scopes: supply at least one of `uaid`, `sessionId`, `namespace`, or `userId`. The service bounds responses to avoid overwhelming clients.',\n ].join('\\n'),\n },\n ],\n});\n","import { RegistryBrokerClient, RegistryBrokerError } from '@hashgraphonline/standards-sdk';\nimport Bottleneck from 'bottleneck';\nimport IORedis from 'ioredis';\nimport { fetch as undiciFetch } from 'undici';\nimport type { Response as UndiciResponse } from 'undici';\nimport { config } from './config';\n\nconst autoTopUpConfig = config.autoTopUpEnabled\n ? {\n accountId: config.hederaAccountId!,\n privateKey: config.hederaPrivateKey!,\n memo: 'mcp-autotopup',\n }\n : undefined;\n\nconst broker = new RegistryBrokerClient({\n baseUrl: normalizeRegistryUrl(config.registryBrokerUrl),\n apiKey: config.registryBrokerApiKey,\n fetchImplementation: undiciFetch as unknown as typeof fetch,\n registrationAutoTopUp: autoTopUpConfig,\n historyAutoTopUp: autoTopUpConfig,\n});\n\nconst brokerLimiter = createLimiter();\n\nfunction createLimiter() {\n if (!config.rateLimit) return undefined;\n\n const redisClient = config.rateLimit.redis?.url ? new IORedis(config.rateLimit.redis.url) : undefined;\n const limiterOptions: Bottleneck.ConstructorOptions = {\n ...(config.rateLimit.maxConcurrent !== undefined\n ? { maxConcurrent: config.rateLimit.maxConcurrent }\n : {}),\n ...(config.rateLimit.minTimeMs !== undefined\n ? { minTime: config.rateLimit.minTimeMs }\n : {}),\n ...(config.rateLimit.reservoir !== undefined\n ? { reservoir: config.rateLimit.reservoir }\n : {}),\n ...(config.rateLimit.reservoirRefreshAmount !== undefined\n ? { reservoirRefreshAmount: config.rateLimit.reservoirRefreshAmount }\n : {}),\n ...(config.rateLimit.reservoirRefreshIntervalMs !== undefined\n ? { reservoirRefreshInterval: config.rateLimit.reservoirRefreshIntervalMs }\n : {}),\n ...(redisClient ? { datastore: 'ioredis' as const, connection: redisClient as unknown as Bottleneck.IORedisConnection } : {}),\n };\n\n if (\n !limiterOptions.maxConcurrent &&\n !limiterOptions.minTime &&\n !limiterOptions.reservoir &&\n !limiterOptions.datastore\n ) {\n return undefined;\n }\n\n return new Bottleneck(limiterOptions);\n}\n\ntype BrokerTask<T> = (client: RegistryBrokerClient) => Promise<T>;\n\nexport async function withBroker<T>(task: BrokerTask<T>, label?: string): Promise<T> {\n const run = async () => {\n if (!config.registryBrokerApiKey) {\n throw new Error('REGISTRY_BROKER_API_KEY is required to call the registry broker. Set it in your environment or .env file.');\n }\n try {\n return await task(broker);\n } catch (error) {\n throw formatBrokerError(error, label);\n }\n };\n if (brokerLimiter) {\n return brokerLimiter.schedule(run);\n }\n return run();\n}\n\nexport { broker, brokerLimiter };\n\nexport interface CreditBalanceResponse {\n accountId: string;\n balance: number;\n timestamp: string;\n}\n\nexport async function getCreditBalance(accountId?: string): Promise<CreditBalanceResponse> {\n if (!config.registryBrokerApiKey) {\n throw new Error('REGISTRY_BROKER_API_KEY is required to fetch credit balances.');\n }\n const base = config.registryBrokerUrl.endsWith('/') ? config.registryBrokerUrl : `${config.registryBrokerUrl}/`;\n const url = new URL('credits/balance', base);\n if (accountId) {\n url.searchParams.set('accountId', accountId);\n }\n const headers: Record<string, string> = {\n accept: 'application/json',\n 'x-api-key': config.registryBrokerApiKey,\n };\n const request = async () => {\n const response = await undiciFetch(url, { method: 'GET', headers });\n if (!response.ok) {\n const hint = await safeReadBody(response);\n throw new Error(`Failed to fetch credit balance (${response.status}): ${hint ?? response.statusText}`);\n }\n return (await response.json()) as CreditBalanceResponse;\n };\n if (brokerLimiter) {\n return brokerLimiter.schedule(request);\n }\n return request();\n}\n\nasync function safeReadBody(response: Response | UndiciResponse) {\n try {\n const text = await (response as any).text();\n return text || undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction formatBrokerError(error: unknown, label?: string): Error {\n if (error instanceof RegistryBrokerError) {\n const body =\n typeof error.body === 'object'\n ? JSON.stringify(error.body)\n : error.body\n ? String(error.body)\n : 'no response body';\n const statusText = error.statusText ? ` ${error.statusText}` : '';\n const prefix = label ? `${label} failed` : 'Registry broker request failed';\n return new Error(`${prefix} (${error.status}${statusText}): ${body}`);\n }\n return error instanceof Error ? error : new Error(String(error));\n}\n\nfunction normalizeRegistryUrl(rawUrl: string): string {\n try {\n const parsed = new URL(rawUrl);\n // Map legacy host to the canonical hol registry host.\n if (parsed.hostname === 'registry.hashgraphonline.com') {\n parsed.hostname = 'hol.org';\n parsed.pathname = '/registry/api/v1';\n parsed.search = '';\n parsed.hash = '';\n return stripTrailingSlash(parsed.toString());\n }\n // Ensure path ends with /api/v1\n const cleanPath = parsed.pathname.replace(/\\/+$/, '');\n parsed.pathname = cleanPath.endsWith('/api/v1') ? cleanPath : `${cleanPath || ''}/api/v1`;\n return stripTrailingSlash(parsed.toString());\n } catch {\n // Fallback to raw URL if parsing fails.\n return rawUrl;\n }\n}\n\nfunction stripTrailingSlash(value: string) {\n return value.endsWith('/') ? value.slice(0, -1) : value;\n}\n","import { config as loadEnv } from 'dotenv';\nimport { z } from 'zod';\n\nif (process.env.NODE_ENV !== 'test') {\n loadEnv({ quiet: true });\n}\n\nconst LOG_LEVELS = ['fatal', 'error', 'warn', 'info', 'debug', 'trace'] as const;\n\nconst envSchema = z\n .object({\n REGISTRY_BROKER_API_URL: z\n .string()\n .url()\n .default('https://hol.org/registry/api/v1'),\n REGISTRY_BROKER_API_KEY: z.string().min(1).optional(),\n HEDERA_ACCOUNT_ID: z.string().min(1).optional(),\n HEDERA_PRIVATE_KEY: z.string().min(1).optional(),\n PORT: z.coerce.number().int().positive().default(3333),\n BROKER_MAX_CONCURRENT: z.coerce.number().int().positive().optional(),\n BROKER_MIN_TIME_MS: z.coerce.number().int().nonnegative().optional(),\n BROKER_RESERVOIR: z.coerce.number().int().positive().optional(),\n BROKER_RESERVOIR_REFRESH_INTERVAL_MS: z.coerce.number().int().positive().optional(),\n BROKER_RESERVOIR_REFRESH_AMOUNT: z.coerce.number().int().positive().optional(),\n BROKER_RATE_LIMIT_REDIS_URL: z.string().url().optional(),\n LOG_LEVEL: z.enum(LOG_LEVELS).default('info'),\n WORKFLOW_DRY_RUN: z\n .enum(['0', '1'])\n .optional()\n .transform((value) => value === '1'),\n BROKER_AUTO_TOP_UP: z\n .enum(['0', '1'])\n .optional()\n .transform((value) => value === '1'),\n HTTP_STREAM_PORT: z.coerce.number().int().positive().optional(),\n MEMORY_ENABLED: z\n .enum(['0', '1'])\n .optional()\n .transform((value) => value === '1'),\n MEMORY_STORE: z.enum(['file', 'sqlite', 'rocksdb', 'memory', 'redis']).optional(),\n MEMORY_STORAGE_PATH: z.string().default('tmp/memory.json'),\n MEMORY_MAX_ENTRIES_PER_SCOPE: z.coerce.number().int().positive().optional(),\n MEMORY_DEFAULT_TTL_SECONDS: z.coerce.number().int().positive().optional(),\n MEMORY_SUMMARY_TRIGGER: z.coerce.number().int().positive().optional(),\n MEMORY_MAX_RETURN_ENTRIES: z.coerce.number().int().positive().optional(),\n MEMORY_CAPTURE_TOOLS: z\n .enum(['0', '1'])\n .optional()\n .transform((value) => value === '1'),\n })\n .superRefine((val, ctx) => {\n const hasAccount = Boolean(val.HEDERA_ACCOUNT_ID);\n const hasKey = Boolean(val.HEDERA_PRIVATE_KEY);\n if (hasAccount !== hasKey) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'HEDERA_ACCOUNT_ID and HEDERA_PRIVATE_KEY must both be set to enable registrationAutoTopUp.',\n });\n }\n });\n\nconst normalized = (value?: string) => {\n if (value === undefined) return undefined;\n const trimmed = value.trim();\n return trimmed.length === 0 ? undefined : trimmed;\n};\n\nconst parsed = envSchema.safeParse({\n REGISTRY_BROKER_API_URL: normalized(process.env.REGISTRY_BROKER_API_URL),\n REGISTRY_BROKER_API_KEY: normalized(process.env.REGISTRY_BROKER_API_KEY),\n HEDERA_ACCOUNT_ID: normalized(process.env.HEDERA_ACCOUNT_ID),\n HEDERA_PRIVATE_KEY: normalized(process.env.HEDERA_PRIVATE_KEY),\n PORT: normalized(process.env.PORT),\n BROKER_MAX_CONCURRENT: normalized(process.env.BROKER_MAX_CONCURRENT),\n BROKER_MIN_TIME_MS: normalized(process.env.BROKER_MIN_TIME_MS),\n BROKER_RESERVOIR: normalized(process.env.BROKER_RESERVOIR),\n BROKER_RESERVOIR_REFRESH_INTERVAL_MS: normalized(process.env.BROKER_RESERVOIR_REFRESH_INTERVAL_MS),\n BROKER_RESERVOIR_REFRESH_AMOUNT: normalized(process.env.BROKER_RESERVOIR_REFRESH_AMOUNT),\n BROKER_RATE_LIMIT_REDIS_URL: normalized(process.env.BROKER_RATE_LIMIT_REDIS_URL),\n LOG_LEVEL: normalized(process.env.LOG_LEVEL),\n WORKFLOW_DRY_RUN: normalized(process.env.WORKFLOW_DRY_RUN),\n BROKER_AUTO_TOP_UP: normalized(process.env.BROKER_AUTO_TOP_UP),\n HTTP_STREAM_PORT: normalized(process.env.HTTP_STREAM_PORT),\n MEMORY_ENABLED: normalized(process.env.MEMORY_ENABLED),\n MEMORY_STORE: normalized(process.env.MEMORY_STORE),\n MEMORY_STORAGE_PATH: normalized(process.env.MEMORY_STORAGE_PATH),\n MEMORY_MAX_ENTRIES_PER_SCOPE: normalized(process.env.MEMORY_MAX_ENTRIES_PER_SCOPE),\n MEMORY_DEFAULT_TTL_SECONDS: normalized(process.env.MEMORY_DEFAULT_TTL_SECONDS),\n MEMORY_SUMMARY_TRIGGER: normalized(process.env.MEMORY_SUMMARY_TRIGGER),\n MEMORY_MAX_RETURN_ENTRIES: normalized(process.env.MEMORY_MAX_RETURN_ENTRIES),\n MEMORY_CAPTURE_TOOLS: normalized(process.env.MEMORY_CAPTURE_TOOLS),\n});\n\nif (!parsed.success) {\n throw new Error(`Invalid environment configuration:\\n${parsed.error.toString()}`);\n}\n\nexport const config = {\n registryBrokerUrl: parsed.data.REGISTRY_BROKER_API_URL,\n registryBrokerApiKey: parsed.data.REGISTRY_BROKER_API_KEY,\n hederaAccountId: parsed.data.HEDERA_ACCOUNT_ID,\n hederaPrivateKey: parsed.data.HEDERA_PRIVATE_KEY,\n port: parsed.data.PORT,\n autoTopUpEnabled:\n Boolean(parsed.data.BROKER_AUTO_TOP_UP) && Boolean(parsed.data.HEDERA_ACCOUNT_ID && parsed.data.HEDERA_PRIVATE_KEY),\n rateLimit: (() => {\n const {\n BROKER_MAX_CONCURRENT,\n BROKER_MIN_TIME_MS,\n BROKER_RESERVOIR,\n BROKER_RESERVOIR_REFRESH_AMOUNT,\n BROKER_RESERVOIR_REFRESH_INTERVAL_MS,\n BROKER_RATE_LIMIT_REDIS_URL,\n } = parsed.data;\n const hasLimiter =\n BROKER_MAX_CONCURRENT ||\n BROKER_MIN_TIME_MS ||\n BROKER_RESERVOIR ||\n BROKER_RATE_LIMIT_REDIS_URL;\n if (!hasLimiter) return undefined;\n return {\n maxConcurrent: BROKER_MAX_CONCURRENT,\n minTimeMs: BROKER_MIN_TIME_MS,\n reservoir: BROKER_RESERVOIR,\n reservoirRefreshAmount: BROKER_RESERVOIR_REFRESH_AMOUNT,\n reservoirRefreshIntervalMs: BROKER_RESERVOIR_REFRESH_INTERVAL_MS,\n redis: BROKER_RATE_LIMIT_REDIS_URL\n ? {\n url: BROKER_RATE_LIMIT_REDIS_URL,\n }\n : undefined,\n };\n })(),\n workflowDryRun: parsed.data.WORKFLOW_DRY_RUN ?? false,\n httpStreamPort: parsed.data.HTTP_STREAM_PORT,\n logLevel: parsed.data.LOG_LEVEL,\n memory: {\n enabled: parsed.data.MEMORY_ENABLED ?? false,\n store: parsed.data.MEMORY_STORE ?? 'file',\n path: parsed.data.MEMORY_STORAGE_PATH ?? 'tmp/memory.json',\n maxEntriesPerScope: parsed.data.MEMORY_MAX_ENTRIES_PER_SCOPE ?? 200,\n defaultTtlSeconds: parsed.data.MEMORY_DEFAULT_TTL_SECONDS ?? 24 * 60 * 60,\n summaryTrigger: parsed.data.MEMORY_SUMMARY_TRIGGER ?? 100,\n maxReturnEntries: parsed.data.MEMORY_MAX_RETURN_ENTRIES ?? 50,\n captureTools: parsed.data.MEMORY_CAPTURE_TOOLS ?? true,\n },\n};\n\nexport type AppConfig = typeof config;\n","import pino from 'pino';\nimport { config } from './config';\n\n// Log to stderr so stdio MCP transport keeps stdout reserved for protocol traffic.\nexport const logger = pino(\n {\n level: config.logLevel,\n base: undefined,\n },\n pino.destination(2),\n);\n","import { z } from 'zod';\nimport type { RegistryBrokerClient } from '@hashgraphonline/standards-sdk';\n\ntype AgentRegistrationRequest = Parameters<RegistryBrokerClient['registerAgent']>[0];\n\nconst socialLinkSchema = z.object({\n platform: z.string(),\n handle: z.string(),\n});\n\nconst aiAgentSchema = z.object({\n type: z.union([z.literal(0), z.literal(1)]),\n capabilities: z.array(z.number().int().nonnegative()),\n model: z.string(),\n creator: z.string().optional(),\n});\n\nconst mcpServerSchema = z.object({\n version: z.string(),\n connectionInfo: z.object({\n url: z.string().url(),\n transport: z.enum(['stdio', 'sse']),\n }),\n services: z.array(z.number().int().nonnegative()),\n description: z.string(),\n capabilities: z.array(z.string()).optional(),\n resources: z\n .array(\n z.object({\n name: z.string(),\n description: z.string(),\n }),\n )\n .optional(),\n tools: z\n .array(\n z.object({\n name: z.string(),\n description: z.string(),\n }),\n )\n .optional(),\n maintainer: z.string().optional(),\n repository: z.string().optional(),\n docs: z.string().optional(),\n});\n\nconst baseProfileSchema = z.object({\n version: z.string(),\n type: z.number().int(),\n display_name: z.string(),\n alias: z.string().optional(),\n bio: z.string().optional(),\n socials: z.array(socialLinkSchema).optional(),\n profileImage: z.string().optional(),\n uaid: z.string().optional(),\n properties: z.record(z.string(), z.any()).optional(),\n inboundTopicId: z.string().optional(),\n outboundTopicId: z.string().optional(),\n base_account: z.string().optional(),\n});\n\nexport const agentProfileSchema = baseProfileSchema.extend({\n aiAgent: aiAgentSchema.optional(),\n mcpServer: mcpServerSchema.optional(),\n});\n\nconst metadataSchema = z.object({\n trustScore: z.number().min(0).max(100).optional(),\n verified: z.boolean().optional(),\n avgLatency: z.number().nonnegative().optional(),\n uptime: z.number().min(0).max(100).optional(),\n provider: z.string().optional(),\n category: z.string().optional(),\n adapter: z.string().optional(),\n openConvAICompatible: z.boolean().optional(),\n customFields: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional(),\n});\n\nexport const agentRegistrationSchema = z.object({\n profile: agentProfileSchema,\n endpoint: z.string().url().optional(),\n protocol: z.string().optional(),\n communicationProtocol: z.string().optional(),\n registry: z.string().optional(),\n additionalRegistries: z.array(z.string()).optional(),\n metadata: metadataSchema.optional(),\n}) as unknown as z.ZodType<AgentRegistrationRequest>;\n","import type { Logger } from 'pino';\n\ninterface EnsureEnvOptions {\n logger?: Logger;\n context?: string;\n}\n\nexport function ensureRequiredEnv(requiredEnv: string[] | undefined, options?: EnsureEnvOptions) {\n if (!requiredEnv?.length) return;\n\n const missing = getMissingEnvVars(requiredEnv);\n if (missing.length > 0) {\n options?.logger?.error?.({ missingEnv: missing }, 'workflow.env.missing');\n const label = options?.context ?? 'workflow';\n throw new Error(`Missing required environment variables for ${label}: ${missing.join(', ')}`);\n }\n}\n\nexport function getMissingEnvVars(requiredEnv: string[]): string[] {\n return requiredEnv.filter((variable) => {\n const value = process.env[variable];\n return value === undefined || value.length === 0;\n });\n}\n\nexport function assertEnvVars(requiredEnv: string[], context: string) {\n ensureRequiredEnv(requiredEnv, { context });\n}\n","import { config } from '../config';\nimport { logger as baseLogger } from '../logger';\nimport { ensureRequiredEnv } from './env';\nimport type {\n PipelineDefinition,\n PipelineExecutionOptions,\n PipelineRunResult,\n PipelineStep,\n PipelineStepResult,\n PipelineStepRunArgs,\n} from './types';\n\nexport function createPipeline<TInput, TContext>(definition: PipelineDefinition<TInput, TContext>) {\n async function run(input: TInput, options?: PipelineExecutionOptions<TContext>): Promise<PipelineRunResult<TContext>> {\n const pipelineLogger = baseLogger.child({ pipeline: definition.name });\n const dryRun = options?.dryRun ?? config.workflowDryRun;\n ensureRequiredEnv(definition.requiredEnv, { logger: pipelineLogger, context: definition.name });\n const context = await definition.createContext(input);\n const stepsResults: PipelineStepResult<unknown>[] = [];\n\n for (let index = 0; index < definition.steps.length; index += 1) {\n const step = definition.steps[index] as PipelineStep<TInput, TContext, unknown>;\n const stepLogger = pipelineLogger.child({ step: step.name, index });\n const stepArgs: PipelineStepRunArgs<TInput, TContext> = {\n input,\n context,\n dryRun,\n logger: stepLogger,\n };\n\n const shouldSkip = await shouldSkipStep(step, stepArgs, dryRun);\n const startedAt = Date.now();\n\n if (shouldSkip) {\n stepLogger.info({ dryRun }, 'pipeline.step.skipped');\n stepsResults.push({ name: step.name, durationMs: 0, skipped: true });\n // eslint-disable-next-line no-await-in-loop\n await options?.hooks?.onStepStart?.({ pipeline: definition.name, step: step.name, index, context });\n // eslint-disable-next-line no-await-in-loop\n await options?.hooks?.onStepSuccess?.({ pipeline: definition.name, step: step.name, index, context, output: undefined });\n continue;\n }\n\n pipelineLogger.info({ step: step.name }, 'pipeline.step.start');\n // eslint-disable-next-line no-await-in-loop\n await options?.hooks?.onStepStart?.({ pipeline: definition.name, step: step.name, index, context });\n\n try {\n // eslint-disable-next-line no-await-in-loop\n const output = await step.run(stepArgs);\n const durationMs = Date.now() - startedAt;\n stepLogger.info({ durationMs }, 'pipeline.step.success');\n stepsResults.push({ name: step.name, durationMs, skipped: false, output });\n // eslint-disable-next-line no-await-in-loop\n await options?.hooks?.onStepSuccess?.({ pipeline: definition.name, step: step.name, index, context, output });\n } catch (error) {\n const durationMs = Date.now() - startedAt;\n const message = error instanceof Error ? error.message : String(error);\n stepLogger.error({ durationMs, error: message }, 'pipeline.step.error');\n stepsResults.push({ name: step.name, durationMs, skipped: false, error: message });\n // eslint-disable-next-line no-await-in-loop\n await options?.hooks?.onStepError?.({ pipeline: definition.name, step: step.name, index, context, error });\n throw error;\n }\n }\n\n return {\n pipeline: definition.name,\n context,\n steps: stepsResults,\n dryRun,\n };\n }\n\n return { definition, run };\n}\n\nasync function shouldSkipStep<TInput, TContext>(\n step: PipelineStep<TInput, TContext, unknown>,\n args: PipelineStepRunArgs<TInput, TContext>,\n dryRun: boolean,\n): Promise<boolean> {\n if (dryRun && step.allowDuringDryRun !== true) {\n return true;\n }\n if (step.skip) {\n return Boolean(await step.skip(args));\n }\n return false;\n}\n","import { createPipeline } from './pipeline';\nimport type { PipelineDefinition } from './types';\n\nconst pipelines = new Map<string, ReturnType<typeof createPipeline<any, any>>>();\n\nexport function registerPipeline<TInput, TContext>(definition: PipelineDefinition<TInput, TContext>) {\n const pipeline = createPipeline(definition);\n pipelines.set(definition.name, pipeline);\n return pipeline;\n}\n\nexport function getPipeline(name: string) {\n return pipelines.get(name);\n}\n\nexport function listPipelines() {\n return Array.from(pipelines.values()).map((pipeline) => pipeline.definition);\n}\n","import { registerPipeline } from './registry';\nimport type { PipelineDefinition } from './types';\nimport { withBroker } from '../broker';\n\ninterface DiscoveryInput {\n query?: string;\n limit?: number;\n}\n\ninterface DiscoveryContext {\n results: {\n search?: unknown;\n vector?: unknown;\n };\n}\n\nconst discoveryDefinition: PipelineDefinition<DiscoveryInput, DiscoveryContext> = {\n name: 'workflow.discovery',\n description: 'Run hol.search and hol.vectorSearch to explore agents.',\n version: '1.0.0',\n requiredEnv: ['REGISTRY_BROKER_API_KEY'],\n createContext: () => ({ results: {} }),\n steps: [\n {\n name: 'hol.search',\n description: 'Keyword search',\n allowDuringDryRun: true,\n run: async ({ input, context }) => {\n const payload = { q: input.query, limit: input.limit ?? 5 };\n const response = await withBroker((client) => client.search(payload));\n context.results.search = response;\n return response;\n },\n },\n {\n name: 'hol.vectorSearch',\n description: 'Vector similarity search',\n allowDuringDryRun: true,\n run: async ({ input, context }) => {\n if (!input.query) {\n return undefined;\n }\n const response = await withBroker((client) => client.vectorSearch({ query: input.query, limit: input.limit ?? 5 }));\n context.results.vector = response;\n return response;\n },\n },\n ],\n};\n\nexport const discoveryPipeline = registerPipeline(discoveryDefinition);\n","import type { AgentRegistrationRequest, RegisterAgentResponse } from '@hashgraphonline/standards-sdk';\nimport { RegistryBrokerError } from '@hashgraphonline/standards-sdk';\nimport { withBroker } from '../../broker';\nimport { InsufficientCreditsError } from '../errors';\n\nexport type ShortfallResolution = 'retry' | 'abort' | void;\n\nexport interface CreditAwareRegistrationOptions {\n payload: AgentRegistrationRequest;\n onShortfall?: (quoteError: InsufficientCreditsError) => Promise<ShortfallResolution> | ShortfallResolution;\n}\n\nexport async function runCreditAwareRegistration({ payload, onShortfall }: CreditAwareRegistrationOptions) {\n while (true) {\n try {\n const response = await withBroker((client) => client.registerAgent(payload));\n return response;\n } catch (error) {\n const converted = await translateCreditError(error, payload);\n if (converted) {\n const action = (await onShortfall?.(converted)) ?? 'abort';\n if (action === 'retry') {\n continue;\n }\n throw converted;\n }\n throw error;\n }\n }\n}\n\nasync function translateCreditError(error: unknown, payload: AgentRegistrationRequest) {\n if (!(error instanceof RegistryBrokerError) || error.status !== 402) {\n return null;\n }\n const quote = await withBroker((client) => client.getRegistrationQuote(payload));\n return new InsufficientCreditsError(quote);\n}\n\nexport async function waitForRegistrationCompletion(attemptId: string) {\n return withBroker((client) =>\n client.waitForRegistrationCompletion(attemptId, {\n intervalMs: 2_000,\n timeoutMs: 5 * 60_000,\n }),\n );\n}\n\nexport async function retryWithFixedDelays<T>(fn: () => Promise<T>, attempts = 3, delayMs = 1_000) {\n let lastError: unknown;\n for (let i = 0; i < attempts; i += 1) {\n try {\n return await fn();\n } catch (error) {\n lastError = error;\n if (i < attempts - 1) {\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n }\n }\n throw lastError;\n}\n","import type { RegisterAgentQuoteResponse } from '@hashgraphonline/standards-sdk';\n\nexport interface CreditShortfallSummary {\n requiredCredits: number;\n availableCredits: number;\n shortfallCredits: number;\n estimatedHbar?: number | null;\n creditsPerHbar?: number | null;\n registry?: string;\n protocol?: string;\n accountId?: string | null;\n}\n\nexport class InsufficientCreditsError extends Error {\n readonly code = 'INSUFFICIENT_CREDITS';\n readonly summary: CreditShortfallSummary;\n\n constructor(quote: RegisterAgentQuoteResponse, hint?: string) {\n const shortfall = Math.max(0, quote.shortfallCredits ?? 0);\n const message = hint ?? `Insufficient registry credits (shortfall: ${shortfall})`;\n super(message);\n this.name = 'InsufficientCreditsError';\n this.summary = {\n requiredCredits: quote.requiredCredits ?? 0,\n availableCredits: quote.availableCredits ?? 0,\n shortfallCredits: shortfall,\n estimatedHbar: quote.estimatedHbar,\n creditsPerHbar: quote.creditsPerHbar,\n registry: quote.registry,\n protocol: quote.protocol,\n accountId: quote.accountId,\n };\n }\n}\n\nexport function isInsufficientCreditsError(error: unknown): error is InsufficientCreditsError {\n return error instanceof InsufficientCreditsError || Boolean(error && (error as { code?: string }).code === 'INSUFFICIENT_CREDITS');\n}\n","import type { AgentRegistrationRequest, RegisterAgentQuoteResponse } from '@hashgraphonline/standards-sdk';\nimport { registerPipeline } from './registry';\nimport type { PipelineDefinition } from './types';\nimport { withBroker } from '../broker';\nimport type { CreditShortfallSummary } from './errors';\nimport { runCreditAwareRegistration } from './utils/credits';\n\ninterface RegistrationInput {\n payload: AgentRegistrationRequest;\n}\n\ninterface RegistrationContext {\n payload: AgentRegistrationRequest;\n attemptId?: string;\n result?: unknown;\n uaid?: string;\n quote?: CreditShortfallSummary | RegisterAgentQuoteResponse;\n}\n\nconst registrationDefinition: PipelineDefinition<RegistrationInput, RegistrationContext> = {\n name: 'workflow.registerMcp',\n description: 'Quote, register, and wait for completion.',\n version: '1.0.0',\n requiredEnv: ['REGISTRY_BROKER_API_KEY'],\n createContext: ({ payload }) => ({ payload }),\n steps: [\n {\n name: 'hol.getRegistrationQuote',\n allowDuringDryRun: true,\n run: async ({ context }) => {\n const quote = await withBroker((client) => client.getRegistrationQuote(context.payload));\n context.quote = quote;\n return quote;\n },\n },\n {\n name: 'hol.registerAgent',\n run: async ({ context }) => {\n const response = await runCreditAwareRegistration({\n payload: context.payload,\n onShortfall: (err) => {\n context.quote = err.summary;\n return 'abort';\n },\n });\n if ('attemptId' in response && typeof response.attemptId === 'string') {\n context.attemptId = response.attemptId;\n }\n context.result = response;\n return response;\n },\n },\n {\n name: 'hol.waitForRegistrationCompletion',\n run: async ({ context }) => {\n if (!context.attemptId) {\n throw new Error('Registration attemptId missing.');\n }\n const result = await withBroker((client) =>\n client.waitForRegistrationCompletion(context.attemptId!, {\n intervalMs: 2_000,\n timeoutMs: 5 * 60_000,\n }),\n );\n if (result && typeof result === 'object' && 'result' in result) {\n const progress = result as { result?: Record<string, unknown> };\n const maybeUaid = progress.result?.uaid;\n if (typeof maybeUaid === 'string') {\n context.uaid = maybeUaid;\n }\n }\n return result;\n },\n },\n ],\n};\n\nexport const registrationPipeline = registerPipeline(registrationDefinition);\n","import { createRequire } from 'node:module';\nimport { InMemoryMemoryStore } from './in-memory-store';\nimport { FileMemoryStore } from './file-store';\nimport type { MemoryConfig, MemoryStore } from './types';\n\nexport function createMemoryStore(config: MemoryConfig): MemoryStore {\n switch (config.store) {\n case 'file':\n return new FileMemoryStore(config.path ?? 'tmp/memory.json');\n case 'sqlite':\n return loadSqliteStore(config.path ?? 'tmp/memory.db');\n case 'memory':\n return new InMemoryMemoryStore();\n case 'rocksdb':\n // Placeholder for a heavier-duty backend; keep failure explicit so DX is predictable.\n throw new Error('RocksDB backend not yet implemented. Use MEMORY_STORE=sqlite or memory for now.');\n case 'redis':\n // Redis would allow multi-process sharing; still to be implemented.\n throw new Error('Redis backend not yet implemented. Use MEMORY_STORE=sqlite or memory for now.');\n default:\n throw new Error(`Unsupported memory store \"${config.store}\".`);\n }\n}\n\nfunction loadSqliteStore(filePath: string): MemoryStore {\n const require = createRequire(import.meta.url);\n // Dynamic import keeps better-sqlite3 optional until the sqlite backend is actually enabled.\n const module = require('./sqlite-store') as typeof import('./sqlite-store');\n return new module.SqliteMemoryStore(filePath);\n}\n","import { randomUUID } from 'node:crypto';\nimport type { MemoryEntry, MemoryEntryInput, MemoryStore, MemorySummary } from './types';\nimport { scopeKey } from './types';\n\nexport class InMemoryMemoryStore implements MemoryStore {\n private entries = new Map<string, MemoryEntry[]>();\n private summaries = new Map<string, MemorySummary>();\n\n async append(entry: MemoryEntryInput): Promise<MemoryEntry> {\n const now = Date.now();\n const key = scopeKey(entry.scope);\n const record: MemoryEntry = {\n ...entry,\n id: randomUUID(),\n createdAt: now,\n };\n const existing = this.entries.get(key) ?? [];\n existing.push(record);\n this.entries.set(key, existing);\n return record;\n }\n\n async listRecent(scope: MemoryEntryInput['scope'], limit: number): Promise<MemoryEntry[]> {\n const key = scopeKey(scope);\n const items = this.entries.get(key) ?? [];\n return this.filterLive(items)\n .sort((a, b) => b.createdAt - a.createdAt)\n .slice(0, limit);\n }\n\n async trim(scope: MemoryEntryInput['scope'], maxEntries: number): Promise<number> {\n const key = scopeKey(scope);\n const items = this.filterLive(this.entries.get(key) ?? []).sort((a, b) => b.createdAt - a.createdAt);\n const toKeep = items.slice(0, maxEntries);\n const trimmed = items.length - toKeep.length;\n this.entries.set(key, toKeep);\n return trimmed;\n }\n\n async clear(scope: MemoryEntryInput['scope']): Promise<number> {\n const key = scopeKey(scope);\n const count = (this.entries.get(key) ?? []).length;\n this.entries.delete(key);\n this.summaries.delete(key);\n return count;\n }\n\n async search(scope: MemoryEntryInput['scope'], query: string, limit: number): Promise<MemoryEntry[]> {\n const key = scopeKey(scope);\n const items = this.filterLive(this.entries.get(key) ?? []);\n const normalized = query.toLowerCase();\n return items\n .filter((item) => item.content.toLowerCase().includes(normalized))\n .sort((a, b) => b.createdAt - a.createdAt)\n .slice(0, limit);\n }\n\n async getSummary(scope: MemoryEntryInput['scope']): Promise<MemorySummary | null> {\n const key = scopeKey(scope);\n return this.summaries.get(key) ?? null;\n }\n\n async upsertSummary(summary: MemorySummary): Promise<void> {\n const key = scopeKey(summary.scope);\n this.summaries.set(key, summary);\n }\n\n async purgeExpired(nowMs: number): Promise<number> {\n let removed = 0;\n for (const [key, values] of this.entries.entries()) {\n const live = values.filter((entry) => !entry.expiresAt || entry.expiresAt > nowMs);\n removed += values.length - live.length;\n this.entries.set(key, live);\n }\n return removed;\n }\n\n private filterLive(entries: MemoryEntry[]) {\n const now = Date.now();\n return entries.filter((entry) => !entry.expiresAt || entry.expiresAt > now);\n }\n}\n","export type MemoryScope = {\n uaid?: string;\n sessionId?: string;\n namespace?: string;\n userId?: string;\n};\n\nexport type MemoryRole = 'user' | 'assistant' | 'system' | 'tool' | 'event' | 'note';\n\nexport interface MemoryEntryInput {\n scope: MemoryScope;\n role: MemoryRole;\n content: string;\n toolName?: string;\n metadata?: Record<string, unknown>;\n expiresAt?: number;\n}\n\nexport interface MemoryEntry extends MemoryEntryInput {\n id: string;\n createdAt: number;\n}\n\nexport interface MemorySummary {\n scope: MemoryScope;\n content: string;\n updatedAt: number;\n}\n\nexport interface MemoryStore {\n append(entry: MemoryEntryInput): Promise<MemoryEntry>;\n listRecent(scope: MemoryScope, limit: number): Promise<MemoryEntry[]>;\n trim(scope: MemoryScope, maxEntries: number): Promise<number>;\n clear(scope: MemoryScope): Promise<number>;\n search(scope: MemoryScope, query: string, limit: number): Promise<MemoryEntry[]>;\n getSummary(scope: MemoryScope): Promise<MemorySummary | null>;\n upsertSummary(summary: MemorySummary): Promise<void>;\n purgeExpired(nowMs: number): Promise<number>;\n}\n\nexport interface MemoryConfig {\n enabled: boolean;\n store: 'sqlite' | 'rocksdb' | 'memory' | 'redis';\n path?: string;\n maxEntriesPerScope: number;\n defaultTtlSeconds?: number;\n summaryTrigger: number;\n maxReturnEntries: number;\n captureTools: boolean;\n}\n\nexport function scopeKey(scope: MemoryScope): string {\n return [scope.uaid ?? '', scope.sessionId ?? '', scope.namespace ?? '', scope.userId ?? ''].join('::');\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { randomUUID } from 'node:crypto';\nimport type { MemoryEntry, MemoryEntryInput, MemoryStore, MemorySummary } from './types';\nimport { scopeKey } from './types';\n\ntype PersistedShape = {\n entries: MemoryEntry[];\n summaries: MemorySummary[];\n};\n\nexport class FileMemoryStore implements MemoryStore {\n private filePath: string;\n private data: PersistedShape;\n\n constructor(filePath: string) {\n this.filePath = filePath;\n this.data = { entries: [], summaries: [] };\n this.ensureLoaded();\n }\n\n async append(entry: MemoryEntryInput): Promise<MemoryEntry> {\n const record: MemoryEntry = {\n ...entry,\n id: randomUUID(),\n createdAt: Date.now(),\n };\n this.data.entries.push(record);\n await this.save();\n return record;\n }\n\n async listRecent(scope: MemoryEntryInput['scope'], limit: number): Promise<MemoryEntry[]> {\n const key = scopeKey(scope);\n const now = Date.now();\n return this.data.entries\n .filter((entry) => scopeKey(entry.scope) === key)\n .filter((entry) => !entry.expiresAt || entry.expiresAt > now)\n .sort((a, b) => b.createdAt - a.createdAt)\n .slice(0, limit);\n }\n\n async trim(scope: MemoryEntryInput['scope'], maxEntries: number): Promise<number> {\n const key = scopeKey(scope);\n const scoped = this.data.entries.filter((entry) => scopeKey(entry.scope) === key).sort((a, b) => b.createdAt - a.createdAt);\n const keep = scoped.slice(0, maxEntries).map((entry) => entry.id);\n const before = this.data.entries.length;\n this.data.entries = this.data.entries.filter((entry) => scopeKey(entry.scope) !== key || keep.includes(entry.id));\n const removed = before - this.data.entries.length;\n if (removed > 0) {\n await this.save();\n }\n return removed;\n }\n\n async clear(scope: MemoryEntryInput['scope']): Promise<number> {\n const key = scopeKey(scope);\n const beforeEntries = this.data.entries.length;\n const beforeSummaries = this.data.summaries.length;\n this.data.entries = this.data.entries.filter((entry) => scopeKey(entry.scope) !== key);\n this.data.summaries = this.data.summaries.filter((summary) => scopeKey(summary.scope) !== key);\n const removed = beforeEntries - this.data.entries.length + (beforeSummaries - this.data.summaries.length);\n if (removed > 0) {\n await this.save();\n }\n return removed;\n }\n\n async search(scope: MemoryEntryInput['scope'], query: string, limit: number): Promise<MemoryEntry[]> {\n const key = scopeKey(scope);\n const normalized = query.toLowerCase();\n const now = Date.now();\n return this.data.entries\n .filter((entry) => scopeKey(entry.scope) === key)\n .filter((entry) => !entry.expiresAt || entry.expiresAt > now)\n .filter((entry) => entry.content.toLowerCase().includes(normalized))\n .sort((a, b) => b.createdAt - a.createdAt)\n .slice(0, limit);\n }\n\n async getSummary(scope: MemoryEntryInput['scope']): Promise<MemorySummary | null> {\n const key = scopeKey(scope);\n return this.data.summaries.find((summary) => scopeKey(summary.scope) === key) ?? null;\n }\n\n async upsertSummary(summary: MemorySummary): Promise<void> {\n const key = scopeKey(summary.scope);\n const existingIndex = this.data.summaries.findIndex((entry) => scopeKey(entry.scope) === key);\n if (existingIndex >= 0) {\n this.data.summaries[existingIndex] = summary;\n } else {\n this.data.summaries.push(summary);\n }\n await this.save();\n }\n\n async purgeExpired(nowMs: number): Promise<number> {\n const before = this.data.entries.length;\n this.data.entries = this.data.entries.filter((entry) => !entry.expiresAt || entry.expiresAt > nowMs);\n const removed = before - this.data.entries.length;\n if (removed > 0) {\n await this.save();\n }\n return removed;\n }\n\n private ensureLoaded() {\n const dir = path.dirname(this.filePath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n if (!fs.existsSync(this.filePath)) {\n this.saveSync();\n return;\n }\n try {\n const content = fs.readFileSync(this.filePath, 'utf8');\n const parsed = JSON.parse(content) as PersistedShape;\n this.data = {\n entries: parsed.entries ?? [],\n summaries: parsed.summaries ?? [],\n };\n } catch {\n // Corrupt file: reset to empty to keep the server running.\n this.data = { entries: [], summaries: [] };\n this.saveSync();\n }\n }\n\n private async save() {\n await fs.promises.writeFile(this.filePath, JSON.stringify(this.data, null, 2), 'utf8');\n }\n\n private saveSync() {\n fs.writeFileSync(this.filePath, JSON.stringify(this.data, null, 2), 'utf8');\n }\n}\n","import type { Logger } from 'pino';\nimport { config } from '../config';\nimport { logger as baseLogger } from '../logger';\nimport { createMemoryStore } from './factory';\nimport type { MemoryConfig, MemoryEntry, MemoryRole, MemoryScope, MemoryStore, MemorySummary } from './types';\n\ntype RecordParams = {\n scope: MemoryScope;\n role: MemoryRole;\n content: string;\n toolName?: string;\n metadata?: Record<string, unknown>;\n ttlSeconds?: number;\n};\n\ntype ContextParams = {\n scope: MemoryScope;\n limit?: number;\n includeSummary?: boolean;\n};\n\ntype SearchParams = {\n scope: MemoryScope;\n query: string;\n limit?: number;\n};\n\nconst DEFAULT_MAX_CHARS = 4000;\nconst REDACT_KEYS = ['privateKey', 'apiKey', 'token', 'authorization', 'auth', 'evmPrivateKey', 'password'];\n\nexport class MemoryService {\n private readonly store: MemoryStore;\n private readonly config: MemoryConfig;\n private readonly logger: Logger;\n\n constructor(store: MemoryStore, memoryConfig: MemoryConfig, logger: Logger) {\n this.store = store;\n this.config = memoryConfig;\n // Keep a scoped logger so memory noise does not mix with tool logs.\n this.logger = logger.child({ module: 'memory' });\n }\n\n isEnabled(): boolean {\n return this.config.enabled;\n }\n\n async recordEntry(params: RecordParams): Promise<MemoryEntry | null> {\n if (!this.config.enabled) return null;\n const content = truncate(params.content, DEFAULT_MAX_CHARS);\n const ttlSeconds = params.ttlSeconds ?? this.config.defaultTtlSeconds;\n const expiresAt = ttlSeconds ? Date.now() + ttlSeconds * 1000 : undefined;\n\n const entry = await this.store.append({\n scope: params.scope,\n role: params.role,\n content,\n toolName: params.toolName,\n metadata: params.metadata ? redact(params.metadata) : undefined,\n expiresAt,\n });\n\n await this.store.trim(params.scope, this.config.maxEntriesPerScope);\n await this.store.purgeExpired(Date.now());\n if (this.config.summaryTrigger && this.config.summaryTrigger > 0) {\n void this.maybeSummarize(params.scope).catch((error) => {\n this.logger.warn({ error }, 'memory.summarize.failed');\n });\n }\n\n return entry;\n }\n\n async recordToolEvent(toolName: string, scope: MemoryScope, payload: unknown): Promise<void> {\n if (!this.config.enabled || !this.config.captureTools) return;\n const excerpt = truncate(serialize(payload), DEFAULT_MAX_CHARS);\n await this.recordEntry({\n scope,\n role: 'tool',\n content: `[${toolName}] ${excerpt}`,\n toolName,\n });\n }\n\n async note(scope: MemoryScope, content: string): Promise<MemoryEntry | null> {\n return this.recordEntry({ scope, role: 'note', content });\n }\n\n async getContext(params: ContextParams): Promise<{ entries: MemoryEntry[]; summary?: MemorySummary | null }> {\n const limit = clamp(params.limit ?? this.config.maxReturnEntries, 1, this.config.maxReturnEntries);\n const entries = await this.store.listRecent(params.scope, limit);\n const summary = params.includeSummary ? await this.store.getSummary(params.scope) : undefined;\n return { entries, summary };\n }\n\n async search(params: SearchParams): Promise<MemoryEntry[]> {\n const limit = clamp(params.limit ?? this.config.maxReturnEntries, 1, this.config.maxReturnEntries);\n return this.store.search(params.scope, params.query, limit);\n }\n\n async clear(scope: MemoryScope): Promise<number> {\n return this.store.clear(scope);\n }\n\n async summarize(scope: MemoryScope): Promise<MemorySummary | null> {\n if (!this.config.enabled) return null;\n const entries = await this.store.listRecent(scope, this.config.summaryTrigger ?? this.config.maxReturnEntries);\n if (!entries.length) return null;\n const summary = buildHeuristicSummary(entries);\n const record = { scope, content: summary, updatedAt: Date.now() };\n await this.store.upsertSummary(record);\n return record;\n }\n\n private async maybeSummarize(scope: MemoryScope) {\n if (!this.config.summaryTrigger) return;\n const entries = await this.store.listRecent(scope, this.config.summaryTrigger + 5);\n if (entries.length < this.config.summaryTrigger) return;\n await this.summarize(scope);\n }\n}\n\nexport function createMemoryService(): MemoryService | null {\n if (!config.memory.enabled) return null;\n try {\n const store = createMemoryStore(config.memory);\n return new MemoryService(store, config.memory, baseLogger);\n } catch (error) {\n baseLogger.error({ error }, 'memory.init.failed');\n return null;\n }\n}\n\nfunction truncate(value: string, max: number) {\n if (value.length <= max) return value;\n return `${value.slice(0, max)}…`;\n}\n\nfunction clamp(value: number, min: number, max: number) {\n return Math.min(Math.max(value, min), max);\n}\n\nfunction serialize(payload: unknown) {\n if (typeof payload === 'string') return payload;\n if (payload === undefined || payload === null) return '';\n try {\n return JSON.stringify(redact(payload), null, 2);\n } catch (error) {\n return `unserializable payload: ${error instanceof Error ? error.message : String(error)}`;\n }\n}\n\nfunction redact<T>(payload: T): T {\n if (Array.isArray(payload)) {\n return payload.map((item) => redact(item)) as unknown as T;\n }\n if (payload && typeof payload === 'object') {\n const clone: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(payload as Record<string, unknown>)) {\n if (REDACT_KEYS.includes(key.toLowerCase())) {\n clone[key] = '[redacted]';\n } else {\n clone[key] = redact(value);\n }\n }\n return clone as unknown as T;\n }\n return payload;\n}\n\nfunction buildHeuristicSummary(entries: MemoryEntry[]): string {\n // Lightweight fallback: we do not call an LLM here; just condense the latest messages.\n const recent = entries\n .slice(0, 10)\n .map((entry) => `${entry.role}${entry.toolName ? `(${entry.toolName})` : ''}: ${truncate(entry.content, 512)}`);\n return ['Summary (heuristic, no LLM):', ...recent].join('\\n');\n}\n","import { createMemoryService } from './service';\n\nexport const memoryService = createMemoryService();\n\nexport * from './service';\nexport * from './types';\n","import type { MemoryScope } from '../../memory';\nimport { memoryService } from '../../memory';\nimport type { MemoryEntry, MemorySummary } from '../../memory/types';\n\nexport interface MemoryLoadOptions {\n scope: MemoryScope;\n limit?: number;\n includeSummary?: boolean;\n optOut?: boolean;\n}\n\nexport interface MemoryRecordOptions {\n scope: MemoryScope;\n role: 'user' | 'assistant' | 'note' | 'tool' | 'event';\n content: string;\n toolName: string;\n optOut?: boolean;\n}\n\nexport async function loadMemoryContext(options: MemoryLoadOptions): Promise<{ entries: MemoryEntry[]; summary?: MemorySummary | null } | null> {\n if (options.optOut) return null;\n if (!memoryService || !memoryService.isEnabled()) return null;\n // Keep reads bounded by opts + global caps inside the service.\n return memoryService.getContext({\n scope: options.scope,\n limit: options.limit,\n includeSummary: options.includeSummary ?? true,\n });\n}\n\nexport async function recordMemory(options: MemoryRecordOptions): Promise<void> {\n if (options.optOut) return;\n if (!memoryService || !memoryService.isEnabled()) return;\n await memoryService.recordEntry({\n scope: options.scope,\n role: options.role,\n content: options.content,\n toolName: options.toolName,\n });\n}\n","import type { AgentAuthConfig } from '@hashgraphonline/standards-sdk';\nimport { registerPipeline } from './registry';\nimport type { PipelineDefinition } from './types';\nimport { withBroker } from '../broker';\nimport { loadMemoryContext, recordMemory } from './utils/memory';\n\ninterface ChatInput {\n uaid: string;\n message?: string;\n auth?: AgentAuthConfig;\n disableMemory?: boolean;\n}\n\ninterface ChatContext {\n sessionId?: string;\n uaid: string;\n transcript: unknown;\n auth?: AgentAuthConfig;\n memoryContext?: unknown;\n memoryOptOut?: boolean;\n}\n\nconst chatDefinition: PipelineDefinition<ChatInput, ChatContext> = {\n name: 'workflow.chatSmoke',\n description: 'Create a chat session, send a message, read history, compact, and close.',\n version: '1.0.0',\n requiredEnv: ['REGISTRY_BROKER_API_KEY'],\n createContext: ({ uaid, auth, disableMemory }) => ({ uaid, auth, transcript: undefined, memoryOptOut: disableMemory }),\n steps: [\n {\n name: 'workflow.chatSmoke.memory.load',\n skip: ({ input }) => Boolean(input.disableMemory),\n run: async ({ context }) => {\n const scope = { uaid: context.uaid };\n const loaded = await loadMemoryContext({ scope, optOut: context.memoryOptOut });\n context.memoryContext = loaded ?? undefined;\n return loaded ?? { skipped: true };\n },\n },\n {\n name: 'hol.chat.createSession',\n run: async ({ context }) => {\n const response = await withBroker((client) =>\n client.chat.createSession({ uaid: context.uaid, historyTtlSeconds: 60, auth: context.auth }),\n );\n if (response?.sessionId) {\n context.sessionId = response.sessionId;\n }\n return response;\n },\n },\n {\n name: 'hol.chat.sendMessage',\n run: async ({ input, context }) => {\n if (!context.sessionId) throw new Error('Missing chat session');\n const message = input.message ?? 'Hello from workflow.chatSmoke';\n await recordMemory({\n scope: { uaid: context.uaid, sessionId: context.sessionId },\n role: 'user',\n content: message,\n toolName: 'workflow.chatSmoke',\n optOut: context.memoryOptOut,\n });\n const response = await withBroker((client) =>\n client.chat.sendMessage({\n sessionId: context.sessionId!,\n message,\n uaid: context.uaid,\n auth: input.auth ?? context.auth,\n }),\n );\n await recordMemory({\n scope: { uaid: context.uaid, sessionId: context.sessionId },\n role: 'assistant',\n content: JSON.stringify(response),\n toolName: 'workflow.chatSmoke',\n optOut: context.memoryOptOut,\n });\n return response;\n },\n },\n {\n name: 'hol.chat.history',\n run: async ({ context }) => {\n if (!context.sessionId) throw new Error('Missing chat session');\n const history = await withBroker((client) => client.chat.getHistory(context.sessionId!));\n context.transcript = history;\n await recordMemory({\n scope: { uaid: context.uaid, sessionId: context.sessionId },\n role: 'event',\n content: JSON.stringify({ history }),\n toolName: 'workflow.chatSmoke',\n optOut: context.memoryOptOut,\n });\n return history;\n },\n },\n {\n name: 'hol.chat.compact',\n allowDuringDryRun: true,\n run: async ({ context }) => {\n if (!context.sessionId) throw new Error('Missing chat session');\n try {\n return await withBroker((client) => client.chat.compactHistory({ sessionId: context.sessionId!, preserveEntries: 2 }));\n } catch (error) {\n const message = error instanceof Error ? error.message.toLowerCase() : '';\n if (message.includes('authenticated account required') || message.includes('insufficient credits')) {\n return { skipped: true, reason: 'history compaction requires authenticated account' };\n }\n throw error;\n }\n },\n },\n {\n name: 'hol.chat.end',\n allowDuringDryRun: true,\n run: async ({ context }) => {\n if (!context.sessionId) throw new Error('Missing chat session');\n return withBroker((client) => client.chat.endSession(context.sessionId!));\n },\n },\n ],\n};\n\nexport const chatPipeline = registerPipeline(chatDefinition);\n","import { registerPipeline } from './registry';\nimport type { PipelineDefinition } from './types';\nimport { withBroker } from '../broker';\n\ninterface OpsInput {\n inspect?: boolean;\n}\n\ninterface OpsContext {\n stats?: unknown;\n metrics?: unknown;\n dashboard?: unknown;\n}\n\nconst opsDefinition: PipelineDefinition<OpsInput, OpsContext> = {\n name: 'workflow.opsCheck',\n description: 'Run stats, metrics, dashboard, listProtocols, detectProtocol.',\n version: '1.0.0',\n requiredEnv: ['REGISTRY_BROKER_API_KEY'],\n createContext: () => ({}),\n steps: [\n {\n name: 'hol.stats',\n allowDuringDryRun: true,\n run: async ({ context }) => {\n const response = await withBroker((client) => client.stats());\n context.stats = response;\n return response;\n },\n },\n {\n name: 'hol.metricsSummary',\n allowDuringDryRun: true,\n run: async ({ context }) => {\n const response = await withBroker((client) => client.metricsSummary());\n context.metrics = response;\n return response;\n },\n },\n {\n name: 'hol.dashboardStats',\n allowDuringDryRun: true,\n run: async ({ context }) => {\n const response = await withBroker((client) => client.dashboardStats());\n context.dashboard = response;\n return response;\n },\n },\n {\n name: 'hol.listProtocols',\n allowDuringDryRun: true,\n run: async () => withBroker((client) => client.listProtocols()),\n },\n {\n name: 'hol.detectProtocol',\n allowDuringDryRun: true,\n run: async () =>\n withBroker((client) =>\n client.detectProtocol({\n headers: { 'content-type': 'application/json' },\n body: '{}',\n } as any),\n ),\n },\n ],\n};\n\nexport const opsPipeline = registerPipeline(opsDefinition);\n","import { registerPipeline } from './registry';\nimport type { PipelineDefinition } from './types';\nimport { discoveryPipeline } from './discovery';\nimport { registrationPipeline } from './registration';\nimport { chatPipeline } from './chat';\nimport { opsPipeline } from './ops';\nimport type { AgentRegistrationRequest } from '@hashgraphonline/standards-sdk';\nimport { loadMemoryContext, recordMemory } from './utils/memory';\n\ninterface FullWorkflowInput {\n registrationPayload: AgentRegistrationRequest;\n discoveryQuery?: string;\n chatMessage?: string;\n disableMemory?: boolean;\n}\n\ninterface FullWorkflowContext {\n discovery?: unknown;\n registration?: unknown;\n chat?: unknown;\n ops?: unknown;\n uaid?: string;\n memoryOptOut?: boolean;\n memoryContext?: unknown;\n}\n\nconst fullDefinition: PipelineDefinition<FullWorkflowInput, FullWorkflowContext> = {\n name: 'workflow.fullRegistration',\n description: 'Discovery → Registration → Chat → Ops health check',\n version: '1.0.0',\n requiredEnv: ['REGISTRY_BROKER_API_KEY', 'HEDERA_ACCOUNT_ID', 'HEDERA_PRIVATE_KEY'],\n createContext: (input) => ({ memoryOptOut: input.disableMemory }),\n steps: [\n {\n name: 'workflow.discovery',\n allowDuringDryRun: true,\n run: async ({ input, context }) => {\n const result = await discoveryPipeline.run({ query: input.discoveryQuery, limit: 5 });\n context.discovery = result;\n await recordMemory({\n scope: { namespace: 'workflow.fullRegistration' },\n role: 'event',\n content: JSON.stringify({ discovery: result }),\n toolName: 'workflow.fullRegistration',\n optOut: context.memoryOptOut,\n });\n return result;\n },\n },\n {\n name: 'workflow.registerMcp',\n run: async ({ input, context, dryRun }) => {\n const payload = { payload: input.registrationPayload };\n const result = await registrationPipeline.run(payload, { dryRun });\n context.registration = result;\n context.uaid = result.context.uaid;\n if (context.uaid) {\n await recordMemory({\n scope: { uaid: context.uaid },\n role: 'event',\n content: JSON.stringify({ registration: result }),\n toolName: 'workflow.fullRegistration',\n optOut: context.memoryOptOut,\n });\n }\n return result;\n },\n },\n {\n name: 'workflow.fullRegistration.memory.load',\n skip: ({ input, context }) => Boolean(input.disableMemory || !context.uaid),\n run: async ({ context }) => {\n if (!context.uaid) return { skipped: true };\n const loaded = await loadMemoryContext({ scope: { uaid: context.uaid }, optOut: context.memoryOptOut });\n context.memoryContext = loaded ?? undefined;\n return loaded ?? { skipped: true };\n },\n },\n {\n name: 'workflow.chatSmoke',\n run: async ({ input, context, dryRun }) => {\n if (!context.uaid) throw new Error('UAID missing from registration context');\n const result = await chatPipeline.run({ uaid: context.uaid, message: input.chatMessage, disableMemory: input.disableMemory }, { dryRun });\n context.chat = result;\n return result;\n },\n },\n {\n name: 'workflow.opsCheck',\n allowDuringDryRun: true,\n run: async ({ context, dryRun }) => {\n const result = await opsPipeline.run({}, { dryRun });\n context.ops = result;\n return result;\n },\n },\n ],\n};\n\nexport const fullWorkflowPipeline = registerPipeline(fullDefinition);\n","import type { PipelineDefinition } from './types';\nimport { registerPipeline } from './registry';\n\ninterface WorkflowMetadata {\n name: string;\n description: string;\n version?: string;\n requiredEnv?: string[];\n}\n\nexport function scaffoldWorkflow<TInput, TContext>(definition: PipelineDefinition<TInput, TContext>) {\n if (!definition.version) {\n definition.version = '1.0.0';\n }\n if (!definition.requiredEnv) {\n definition.requiredEnv = ['REGISTRY_BROKER_API_KEY'];\n }\n return registerPipeline(definition);\n}\n\nexport function defineWorkflow<TInput, TContext>(metadata: WorkflowMetadata, steps: PipelineDefinition<TInput, TContext>['steps'], createContext: PipelineDefinition<TInput, TContext>['createContext']) {\n return scaffoldWorkflow({ ...metadata, steps, createContext });\n}\n","import { scaffoldWorkflow } from './scaffold';\nimport type { PipelineDefinition } from './types';\nimport { withBroker } from '../broker';\nimport { loadMemoryContext, recordMemory } from './utils/memory';\n\ninterface OpenRouterChatInput {\n modelId: string;\n registry?: string;\n message: string;\n authToken?: string;\n historyTtlSeconds?: number;\n disableMemory?: boolean;\n}\n\ninterface OpenRouterChatContext {\n uaid?: string;\n sessionId?: string;\n transcript?: unknown;\n memoryOptOut?: boolean;\n}\n\nconst openRouterChatDefinition: PipelineDefinition<OpenRouterChatInput, OpenRouterChatContext> = {\n name: 'workflow.openrouterChat',\n description: 'Discover an OpenRouter model and run a chat message against it.',\n version: '1.0.0',\n requiredEnv: ['REGISTRY_BROKER_API_KEY'],\n createContext: (input) => ({ memoryOptOut: input.disableMemory }),\n steps: [\n {\n name: 'workflow.openrouterChat.memory.load',\n skip: ({ input }) => Boolean(input.disableMemory),\n run: async ({ input, context }) => {\n const scope = { namespace: 'openrouter', userId: input.modelId };\n const loaded = await loadMemoryContext({ scope, optOut: context.memoryOptOut });\n return loaded ?? { skipped: true };\n },\n },\n {\n name: 'hol.search',\n run: async ({ input, context }) => {\n const result = await withBroker((client) =>\n client.search({ q: input.modelId, registries: input.registry ? [input.registry] : ['openrouter'], limit: 1 }),\n );\n if (!result.hits?.length) {\n throw new Error(`Model ${input.modelId} not found in registry ${input.registry ?? 'openrouter'}`);\n }\n context.uaid = result.hits[0].uaid;\n return result.hits[0];\n },\n },\n {\n name: 'hol.chat.createSession',\n run: async ({ input, context }) => {\n if (!context.uaid) throw new Error('UAID missing from discovery step');\n const auth = input.authToken ? { type: 'bearer' as const, token: input.authToken } : undefined;\n const response = await withBroker((client) =>\n client.chat.createSession({\n uaid: context.uaid!,\n historyTtlSeconds: input.historyTtlSeconds ?? 900,\n auth,\n }),\n );\n context.sessionId = response.sessionId;\n return response;\n },\n },\n {\n name: 'hol.chat.sendMessage',\n run: async ({ input, context }) => {\n if (!context.sessionId) throw new Error('Missing chat session');\n const auth = input.authToken ? { type: 'bearer' as const, token: input.authToken } : undefined;\n await recordMemory({\n scope: { uaid: context.uaid, sessionId: context.sessionId },\n role: 'user',\n content: input.message,\n toolName: 'workflow.openrouterChat',\n optOut: context.memoryOptOut,\n });\n const response = await withBroker((client) =>\n client.chat.sendMessage({ sessionId: context.sessionId!, auth, message: input.message, uaid: context.uaid }),\n );\n await recordMemory({\n scope: { uaid: context.uaid, sessionId: context.sessionId },\n role: 'assistant',\n content: JSON.stringify(response),\n toolName: 'workflow.openrouterChat',\n optOut: context.memoryOptOut,\n });\n return response;\n },\n },\n {\n name: 'hol.chat.history',\n allowDuringDryRun: true,\n run: async ({ context }) => {\n if (!context.sessionId) throw new Error('Missing chat session');\n const history = await withBroker((client) => client.chat.getHistory(context.sessionId!));\n context.transcript = history;\n await recordMemory({\n scope: { uaid: context.uaid, sessionId: context.sessionId },\n role: 'event',\n content: JSON.stringify({ history }),\n toolName: 'workflow.openrouterChat',\n optOut: context.memoryOptOut,\n });\n return history;\n },\n },\n {\n name: 'hol.chat.end',\n allowDuringDryRun: true,\n run: async ({ context }) => {\n if (!context.sessionId) throw new Error('Missing chat session');\n return withBroker((client) => client.chat.endSession(context.sessionId!));\n },\n },\n ],\n};\n\nexport const openRouterChatWorkflow = scaffoldWorkflow(openRouterChatDefinition);\n","import { scaffoldWorkflow } from './scaffold';\nimport type { PipelineDefinition } from './types';\nimport { withBroker } from '../broker';\nimport { discoveryPipeline } from './discovery';\nimport { chatPipeline } from './chat';\nimport { opsPipeline } from './ops';\nimport type { AgentRegistrationRequest } from '@hashgraphonline/standards-sdk';\nimport { loadMemoryContext, recordMemory } from './utils/memory';\n\nexport interface RegistryShowcaseInput {\n query?: string;\n uaid?: string;\n message?: string;\n performCreditCheck?: boolean;\n disableMemory?: boolean;\n}\n\ninterface RegistryShowcaseContext {\n discovery?: unknown;\n uaid?: string;\n listProtocols?: unknown;\n detectProtocol?: unknown;\n stats?: unknown;\n metrics?: unknown;\n dashboard?: unknown;\n websocket?: unknown;\n chat?: unknown;\n creditQuote?: unknown;\n memoryOptOut?: boolean;\n memoryContext?: unknown;\n}\n\nconst registryShowcaseDefinition: PipelineDefinition<RegistryShowcaseInput, RegistryShowcaseContext> = {\n name: 'workflow.registryBrokerShowcase',\n description: 'Discovery + analytics + chat showcase workflow inspired by registry-broker-demo.ts.',\n version: '1.0.0',\n requiredEnv: ['REGISTRY_BROKER_API_KEY'],\n createContext: (input) => ({ memoryOptOut: input.disableMemory }),\n steps: [\n {\n name: 'workflow.discovery',\n allowDuringDryRun: true,\n run: async ({ input, context, dryRun }) => {\n const result = await discoveryPipeline.run({ query: input.query }, { dryRun });\n context.discovery = result;\n context.uaid = input.uaid ?? (result.steps[0]?.output as any)?.hits?.[0]?.uaid;\n if (context.uaid) {\n await recordMemory({\n scope: { uaid: context.uaid },\n role: 'event',\n content: JSON.stringify({ discovery: result }),\n toolName: 'workflow.registryBrokerShowcase',\n optOut: context.memoryOptOut,\n });\n }\n return result;\n },\n },\n {\n name: 'workflow.registryBrokerShowcase.memory.load',\n skip: ({ input }) => Boolean(input.disableMemory),\n run: async ({ context }) => {\n if (!context.uaid) return { skipped: true };\n const loaded = await loadMemoryContext({ scope: { uaid: context.uaid }, optOut: context.memoryOptOut });\n context.memoryContext = loaded ?? undefined;\n return loaded ?? { skipped: true };\n },\n },\n {\n name: 'hol.listProtocols',\n allowDuringDryRun: true,\n run: async ({ context }) => {\n const response = await withBroker((client) => client.listProtocols());\n context.listProtocols = response;\n return response;\n },\n },\n {\n name: 'hol.detectProtocol',\n allowDuringDryRun: true,\n run: async ({ context }) => {\n const response = await withBroker((client) => client.detectProtocol({ headers: { 'content-type': 'application/json' }, body: '{}' }));\n context.detectProtocol = response;\n await recordMemory({\n scope: { uaid: context.uaid },\n role: 'event',\n content: JSON.stringify({ detectProtocol: response }),\n toolName: 'workflow.registryBrokerShowcase',\n optOut: context.memoryOptOut,\n });\n return response;\n },\n },\n {\n name: 'hol.stats',\n allowDuringDryRun: true,\n run: async ({ context }) => {\n const response = await withBroker((client) => client.stats());\n context.stats = response;\n return response;\n },\n },\n {\n name: 'hol.metricsSummary',\n allowDuringDryRun: true,\n run: async ({ context }) => {\n const response = await withBroker((client) => client.metricsSummary());\n context.metrics = response;\n return response;\n },\n },\n {\n name: 'hol.dashboardStats',\n allowDuringDryRun: true,\n run: async ({ context }) => {\n const response = await withBroker((client) => client.dashboardStats());\n context.dashboard = response;\n return response;\n },\n },\n {\n name: 'hol.websocketStats',\n allowDuringDryRun: true,\n run: async ({ context }) => {\n const response = await withBroker((client) => client.websocketStats());\n context.websocket = response;\n return response;\n },\n },\n {\n name: 'workflow.registryBrokerShowcase.chat',\n skip: ({ input, context }) => !(input.message && context.uaid),\n run: async ({ input, context, dryRun }) => {\n if (!context.uaid) throw new Error('No UAID discovered for chat');\n const result = await chatPipeline.run({ uaid: context.uaid, message: input.message, disableMemory: input.disableMemory }, { dryRun });\n context.chat = result;\n return result;\n },\n },\n {\n name: 'hol.getRegistrationQuote',\n skip: ({ input }) => !input.performCreditCheck,\n run: async ({ context }) => {\n const discoveryRecord =\n context.discovery && typeof context.discovery === 'object'\n ? (context.discovery as { context?: Record<string, unknown> })\n : null;\n const payload = (discoveryRecord?.context as { registrationPayload?: unknown } | undefined)?.registrationPayload ?? context.discovery;\n const response = await withBroker((client) => client.getRegistrationQuote(payload as unknown as AgentRegistrationRequest));\n context.creditQuote = response;\n return response;\n },\n },\n ],\n};\n\nexport const registryBrokerShowcaseWorkflow = scaffoldWorkflow(registryShowcaseDefinition);\n","import type { AgentAuthConfig } from '@hashgraphonline/standards-sdk';\nimport { scaffoldWorkflow } from './scaffold';\nimport type { PipelineDefinition } from './types';\nimport { withBroker } from '../broker';\n\ninterface BridgeInput {\n uaid: string;\n localMessage: string;\n agentverseMessage: string;\n agentverseUaid: string;\n localAuth?: AgentAuthConfig;\n agentverseAuth?: AgentAuthConfig;\n iterations?: number;\n}\n\ninterface BridgeContext {\n localSession?: string;\n agentverseSession?: string;\n localUaid?: string;\n agentverseUaid?: string;\n transcripts: Array<{ target: 'local' | 'agentverse'; response: unknown }>;\n}\n\nconst agentverseBridgeDefinition: PipelineDefinition<BridgeInput, BridgeContext> = {\n name: 'workflow.agentverseBridge',\n description: 'Relay messages between a local UAID session and an Agentverse UAID.',\n version: '1.0.0',\n requiredEnv: ['REGISTRY_BROKER_API_KEY'],\n createContext: () => ({ transcripts: [] }),\n steps: [\n {\n name: 'workflow.agentverseBridge.createSessions',\n run: async ({ input, context }) => {\n const local = await withBroker((client) =>\n client.chat.createSession({ uaid: input.uaid, auth: input.localAuth, historyTtlSeconds: 300 }),\n );\n const agentverse = await withBroker((client) =>\n client.chat.createSession({ uaid: input.agentverseUaid, auth: input.agentverseAuth, historyTtlSeconds: 300 }),\n );\n context.localSession = local.sessionId;\n context.agentverseSession = agentverse.sessionId;\n context.localUaid = input.uaid;\n context.agentverseUaid = input.agentverseUaid;\n return { local, agentverse };\n },\n },\n {\n name: 'workflow.agentverseBridge.relay',\n run: async ({ input, context }) => {\n if (!context.localSession || !context.agentverseSession) {\n throw new Error('Sessions missing');\n }\n const iterations = input.iterations ?? 1;\n for (let i = 0; i < iterations; i += 1) {\n const localResponse = await withBroker((client) =>\n client.chat.sendMessage({\n sessionId: context.localSession!,\n auth: input.localAuth,\n message: input.localMessage,\n uaid: context.localUaid,\n }),\n );\n context.transcripts.push({ target: 'local', response: localResponse });\n const agentverseResponse = await withBroker((client) =>\n client.chat.sendMessage({\n sessionId: context.agentverseSession!,\n auth: input.agentverseAuth,\n message: input.agentverseMessage,\n uaid: context.agentverseUaid,\n }),\n );\n context.transcripts.push({ target: 'agentverse', response: agentverseResponse });\n }\n return context.transcripts;\n },\n },\n {\n name: 'workflow.agentverseBridge.history',\n allowDuringDryRun: true,\n run: async ({ context }) => {\n const localHistory = await withBroker((client) => client.chat.getHistory(context.localSession!));\n const agentverseHistory = await withBroker((client) => client.chat.getHistory(context.agentverseSession!));\n return { localHistory, agentverseHistory };\n },\n },\n {\n name: 'workflow.agentverseBridge.cleanup',\n allowDuringDryRun: true,\n run: async ({ context }) => {\n await Promise.all([\n withBroker((client) => client.chat.endSession(context.localSession!)),\n withBroker((client) => client.chat.endSession(context.agentverseSession!)),\n ]);\n return { ended: true };\n },\n },\n ],\n};\n\nexport const agentverseBridgeWorkflow = scaffoldWorkflow(agentverseBridgeDefinition);\n","import { scaffoldWorkflow } from './scaffold';\nimport type { PipelineDefinition } from './types';\nimport { withBroker } from '../broker';\n\ninterface Erc8004DiscoveryInput {\n query?: string;\n limit?: number;\n}\n\ninterface Erc8004DiscoveryContext {\n hits?: unknown;\n}\n\nconst erc8004DiscoveryDefinition: PipelineDefinition<Erc8004DiscoveryInput, Erc8004DiscoveryContext> = {\n name: 'workflow.erc8004Discovery',\n description: 'Filter search/vector/namespace lookups for ERC-8004 registries.',\n version: '1.0.0',\n requiredEnv: ['REGISTRY_BROKER_API_KEY'],\n createContext: () => ({}),\n steps: [\n {\n name: 'hol.search',\n allowDuringDryRun: true,\n run: async ({ input, context }) => {\n const response = await withBroker((client) =>\n client.search({ q: input.query, registries: ['erc-8004'], limit: input.limit ?? 10 }),\n );\n context.hits = response.hits;\n return response;\n },\n },\n {\n name: 'hol.registrySearchByNamespace',\n allowDuringDryRun: true,\n run: async ({ input }) => withBroker((client) => client.registrySearchByNamespace('erc-8004', input.query)),\n },\n ],\n};\n\nexport const erc8004DiscoveryWorkflow = scaffoldWorkflow(erc8004DiscoveryDefinition);\n","import type { AgentRegistrationRequest, AdditionalRegistryCatalogResponse } from '@hashgraphonline/standards-sdk';\nimport { scaffoldWorkflow } from './scaffold';\nimport type { PipelineDefinition } from './types';\nimport { withBroker } from '../broker';\nimport type { CreditShortfallSummary } from './errors';\nimport { runCreditAwareRegistration, waitForRegistrationCompletion } from './utils/credits';\n\ninterface CreditTopUpConfig {\n accountId: string;\n privateKey: string;\n hbarAmount?: number;\n memo?: string;\n maxRetries?: number;\n}\n\nexport interface RegisterAgentAdvancedInput {\n payload: AgentRegistrationRequest;\n additionalRegistrySelections?: string[];\n updateAdditionalRegistries?: string[];\n skipUpdate?: boolean;\n creditTopUp?: CreditTopUpConfig;\n}\n\ninterface RegisterAgentAdvancedContext {\n payload: AgentRegistrationRequest;\n resolvedRegistries: string[];\n missingRegistries: string[];\n lastQuote?: CreditShortfallSummary;\n attemptId?: string;\n uaid?: string;\n registrationResult?: unknown;\n updateResult?: unknown;\n progress?: unknown;\n catalog?: AdditionalRegistryCatalogResponse;\n}\n\nconst registerAgentAdvancedDefinition: PipelineDefinition<RegisterAgentAdvancedInput, RegisterAgentAdvancedContext> = {\n name: 'workflow.registerAgentAdvanced',\n description: 'Extended registration workflow with additional registries and optional updates.',\n version: '1.0.0',\n requiredEnv: ['REGISTRY_BROKER_API_KEY'],\n createContext: ({ payload }) => ({ payload, resolvedRegistries: [], missingRegistries: [] }),\n steps: [\n {\n name: 'hol.getAdditionalRegistries',\n allowDuringDryRun: true,\n skip: ({ input }) => !input.additionalRegistrySelections?.length && !input.updateAdditionalRegistries?.length,\n run: async ({ context }) => {\n const catalog = await withBroker((client) => client.getAdditionalRegistries());\n context.catalog = catalog;\n return catalog;\n },\n },\n {\n name: 'workflow.resolveAdditionalRegistries',\n allowDuringDryRun: true,\n run: async ({ input, context }) => {\n const catalog = context.catalog;\n if (!catalog) return null;\n const selections = input.additionalRegistrySelections ?? [];\n const { resolved, missing } = resolveAdditionalSelections(selections, catalog);\n context.resolvedRegistries = resolved;\n context.missingRegistries = missing;\n if (resolved.length > 0) {\n context.payload = {\n ...context.payload,\n additionalRegistries: resolved,\n };\n }\n return { resolved, missing };\n },\n },\n {\n name: 'hol.getRegistrationQuote',\n allowDuringDryRun: true,\n run: async ({ context }) => withBroker((client) => client.getRegistrationQuote(context.payload)),\n },\n {\n name: 'workflow.registerAgentAdvanced.register',\n run: async ({ input, context }) => {\n const response = await runCreditAwareRegistration({\n payload: context.payload,\n onShortfall: async (err) => {\n context.lastQuote = err.summary;\n if (!input.creditTopUp) {\n return 'abort';\n }\n await purchaseCreditsWithHbar(input.creditTopUp, err.summary);\n return 'retry';\n },\n });\n context.registrationResult = response;\n if ('attemptId' in response && typeof response.attemptId === 'string') {\n context.attemptId = response.attemptId;\n }\n if ('uaid' in response && typeof response.uaid === 'string') {\n context.uaid = response.uaid;\n }\n return response;\n },\n },\n {\n name: 'hol.waitForRegistrationCompletion',\n run: async ({ context }) => {\n if (!context.attemptId) throw new Error('Registration attemptId missing.');\n const result = await waitForRegistrationCompletion(context.attemptId);\n context.progress = result;\n if (result && typeof result === 'object' && 'result' in result) {\n const progress = result as { result?: Record<string, unknown> };\n const maybeUaid = progress.result?.uaid;\n if (typeof maybeUaid === 'string') {\n context.uaid = maybeUaid;\n }\n }\n return result;\n },\n },\n {\n name: 'workflow.registerAgentAdvanced.update',\n skip: ({ input }) => input.skipUpdate || !input.updateAdditionalRegistries?.length,\n run: async ({ input, context }) => {\n if (!context.uaid) throw new Error('UAID missing for update.');\n const resolved = input.updateAdditionalRegistries ?? [];\n const updatePayload: AgentRegistrationRequest = {\n ...context.payload,\n additionalRegistries: resolved,\n };\n const response = await withBroker((client) => client.updateAgent(context.uaid!, updatePayload));\n context.updateResult = response;\n return response;\n },\n },\n ],\n};\n\nexport const registerAgentAdvancedPipeline = scaffoldWorkflow(registerAgentAdvancedDefinition);\n\nfunction resolveAdditionalSelections(selections: string[], catalog: AdditionalRegistryCatalogResponse) {\n if (!catalog.registries || catalog.registries.length === 0) {\n return { resolved: [], missing: selections };\n }\n const resolved = new Set<string>();\n const missing: string[] = [];\n for (const selection of selections) {\n const matches = collectMatches(selection, catalog);\n if (matches.length === 0) {\n missing.push(selection);\n } else {\n matches.forEach((key) => resolved.add(key));\n }\n }\n return { resolved: Array.from(resolved), missing };\n}\n\nfunction collectMatches(selection: string, catalog: AdditionalRegistryCatalogResponse) {\n const target = selection.trim().toLowerCase();\n if (!target) return [];\n const matches: string[] = [];\n for (const registry of catalog.registries ?? []) {\n const registryId = registry.id?.toLowerCase();\n const networks = registry.networks ?? [];\n if (!registryId || networks.length === 0) continue;\n if (registryId === target) {\n networks.forEach((network) => {\n if (network?.key) {\n matches.push(network.key);\n }\n });\n continue;\n }\n for (const network of networks) {\n if (!network?.key) continue;\n const keyLower = network.key.toLowerCase();\n const networkIdLower = network.networkId?.toLowerCase();\n const labelLower = network.label?.toLowerCase();\n const nameLower = network.name?.toLowerCase();\n if (\n target === keyLower ||\n (networkIdLower && target === networkIdLower) ||\n (labelLower && target === labelLower) ||\n (nameLower && target === nameLower) ||\n target === `${registryId}:${networkIdLower}`\n ) {\n matches.push(network.key);\n }\n }\n }\n return matches;\n}\n\nasync function purchaseCreditsWithHbar(config: CreditTopUpConfig, summary: CreditShortfallSummary) {\n const hbarAmount = config.hbarAmount ?? Math.max(0.25, (summary.shortfallCredits ?? 1) / 100);\n await withBroker((client) =>\n client.purchaseCreditsWithHbar({\n accountId: config.accountId,\n privateKey: config.privateKey,\n hbarAmount,\n memo: config.memo ?? 'workflow.registerAgentAdvanced:topup',\n metadata: {\n shortfall: summary.shortfallCredits,\n requiredCredits: summary.requiredCredits,\n },\n }),\n );\n}\n","import type { AgentRegistrationRequest, AdditionalRegistryCatalogResponse, LedgerVerifyRequest } from '@hashgraphonline/standards-sdk';\nimport { scaffoldWorkflow } from './scaffold';\nimport type { PipelineDefinition } from './types';\nimport { withBroker } from '../broker';\nimport { registerAgentAdvancedPipeline, type RegisterAgentAdvancedInput } from './register-advanced';\n\nexport interface RegisterAgentErc8004Input extends RegisterAgentAdvancedInput {\n erc8004Networks?: string[];\n ledgerVerification?: LedgerVerifyRequest;\n}\n\ninterface RegisterAgentErc8004Context {\n resolvedNetworks: string[];\n missingNetworks: string[];\n advancedResult?: unknown;\n catalog?: AdditionalRegistryCatalogResponse;\n}\n\nconst registerAgentErc8004Definition: PipelineDefinition<RegisterAgentErc8004Input, RegisterAgentErc8004Context> = {\n name: 'workflow.registerAgentErc8004',\n description: 'ERC-8004-specific registration workflow with optional ledger verification.',\n version: '1.0.0',\n requiredEnv: ['REGISTRY_BROKER_API_KEY'],\n createContext: () => ({ resolvedNetworks: [], missingNetworks: [] }),\n steps: [\n {\n name: 'hol.getAdditionalRegistries',\n allowDuringDryRun: true,\n run: async ({ context }) => {\n const catalog = await withBroker((client) => client.getAdditionalRegistries());\n context.catalog = catalog;\n return catalog;\n },\n },\n {\n name: 'workflow.erc8004.resolveNetworks',\n allowDuringDryRun: true,\n run: async ({ input, context }) => {\n const response = context.catalog;\n if (!response) {\n context.resolvedNetworks = [];\n context.missingNetworks = [];\n return { resolved: [], missing: [] };\n }\n const selections = input.erc8004Networks?.length ? input.erc8004Networks : defaultErc8004Selections(response);\n const { resolved, missing } = resolveErc8004Selections(selections, response);\n context.resolvedNetworks = resolved;\n context.missingNetworks = missing;\n return { resolved, missing };\n },\n },\n {\n name: 'hol.ledger.authenticate',\n skip: ({ input }) => !input.ledgerVerification,\n run: async ({ input }) => withBroker((client) => client.verifyLedgerChallenge(input.ledgerVerification!)),\n },\n {\n name: 'workflow.registerAgentAdvanced',\n run: async ({ input, context, dryRun }) => {\n const advancedInput: RegisterAgentAdvancedInput = {\n payload: withAdditionalRegistries(input.payload, context.resolvedNetworks),\n additionalRegistrySelections: context.resolvedNetworks,\n updateAdditionalRegistries: input.updateAdditionalRegistries,\n skipUpdate: input.skipUpdate,\n creditTopUp: input.creditTopUp,\n };\n const result = await registerAgentAdvancedPipeline.run(advancedInput, { dryRun });\n context.advancedResult = result;\n return result;\n },\n },\n ],\n};\n\nexport const registerAgentErc8004Pipeline = scaffoldWorkflow(registerAgentErc8004Definition);\n\nfunction resolveErc8004Selections(selections: string[], catalog: AdditionalRegistryCatalogResponse) {\n if (!catalog.registries || catalog.registries.length === 0) {\n return { resolved: [], missing: selections };\n }\n const resolved = new Set<string>();\n const missing: string[] = [];\n selections.forEach((entry) => {\n const normalized = entry.trim().toLowerCase();\n if (!normalized) return;\n let matched = false;\n for (const descriptor of catalog.registries ?? []) {\n const descriptorId = descriptor.id?.toLowerCase();\n const networks = descriptor.networks ?? [];\n if (!descriptorId || !descriptorId.startsWith('erc-8004')) continue;\n for (const network of networks) {\n if (!network) continue;\n const candidates = [network.key, network.networkId, network.label, network.name]\n .map((value) => value?.toLowerCase().trim())\n .filter(Boolean);\n if (candidates.includes(normalized) || `${descriptorId}:${network.networkId?.toLowerCase()}` === normalized) {\n if (network.key) {\n resolved.add(network.key);\n }\n matched = true;\n }\n }\n }\n if (!matched) {\n missing.push(entry);\n }\n });\n return { resolved: Array.from(resolved), missing };\n}\n\nfunction defaultErc8004Selections(catalog: AdditionalRegistryCatalogResponse) {\n const defaults = catalog.registries?.find((entry) => entry.id?.toLowerCase() === 'erc-8004');\n if (!defaults || !defaults.networks) return [];\n return defaults.networks.map((network) => network?.key).filter((key): key is string => Boolean(key));\n}\n\nfunction withAdditionalRegistries(payload: AgentRegistrationRequest, networks: string[]) {\n if (networks.length === 0) return payload;\n return { ...payload, additionalRegistries: networks };\n}\n","import type { LedgerVerifyRequest, RegistryBrokerClient, JsonObject } from '@hashgraphonline/standards-sdk';\nimport { scaffoldWorkflow } from './scaffold';\nimport type { PipelineDefinition } from './types';\nimport { withBroker } from '../broker';\n\nexport interface X402TopUpInput {\n accountId: string;\n credits: number;\n usdAmount?: number;\n description?: string;\n metadata?: JsonObject;\n evmPrivateKey: string;\n network?: 'base' | 'base-sepolia';\n rpcUrl?: string;\n ledgerVerification?: LedgerVerifyRequest;\n}\n\ninterface X402TopUpContext {\n minimums?: unknown;\n ledgerVerification?: unknown;\n purchase?: unknown;\n}\n\ntype BuyCreditsWithX402Params = Parameters<RegistryBrokerClient['buyCreditsWithX402']>[0];\n\nconst x402TopUpDefinition: PipelineDefinition<X402TopUpInput, X402TopUpContext> = {\n name: 'workflow.x402TopUp',\n description: 'Buy registry credits via X402 using an EVM wallet.',\n version: '1.0.0',\n requiredEnv: ['REGISTRY_BROKER_API_KEY'],\n createContext: () => ({}),\n steps: [\n {\n name: 'hol.ledger.authenticate',\n skip: ({ input }) => !input.ledgerVerification,\n run: async ({ input, context }) => {\n const verification = await withBroker((client) => client.verifyLedgerChallenge(input.ledgerVerification!));\n context.ledgerVerification = verification;\n return verification;\n },\n },\n {\n name: 'hol.x402.minimums',\n allowDuringDryRun: true,\n run: async ({ context }) => {\n const minimums = await withBroker((client) => client.getX402Minimums());\n context.minimums = minimums;\n return minimums;\n },\n },\n {\n name: 'hol.x402.buyCredits',\n run: async ({ input, context }) => {\n const payload: BuyCreditsWithX402Params = {\n accountId: input.accountId,\n credits: input.credits,\n usdAmount: input.usdAmount,\n description: input.description,\n metadata: input.metadata,\n evmPrivateKey: input.evmPrivateKey,\n network: input.network,\n rpcUrl: input.rpcUrl,\n };\n const purchase = await withBroker((client) => client.buyCreditsWithX402(payload));\n context.purchase = purchase;\n return purchase;\n },\n },\n ],\n};\n\nexport const x402TopUpWorkflow = scaffoldWorkflow(x402TopUpDefinition);\n","import type { AgentRegistrationRequest, LedgerVerifyRequest } from '@hashgraphonline/standards-sdk';\nimport { scaffoldWorkflow } from './scaffold';\nimport type { PipelineDefinition } from './types';\nimport { registerAgentErc8004Pipeline } from './register-erc8004';\nimport { x402TopUpWorkflow } from './x402-topup';\nimport { chatPipeline } from './chat';\n\ninterface Erc8004X402Input {\n payload: AgentRegistrationRequest;\n erc8004Networks?: string[];\n creditPurchase?: {\n accountId: string;\n credits: number;\n evmPrivateKey: string;\n ledgerVerification?: LedgerVerifyRequest;\n network?: 'base' | 'base-sepolia';\n };\n chatMessage?: string;\n}\n\nconst erc8004X402Definition: PipelineDefinition<Erc8004X402Input, Record<string, unknown>> = {\n name: 'workflow.erc8004X402',\n description: 'Register on ERC-8004 networks with X402 credit purchases and chat smoke.',\n version: '1.0.0',\n requiredEnv: ['REGISTRY_BROKER_API_KEY'],\n createContext: () => ({}),\n steps: [\n {\n name: 'workflow.x402TopUp',\n skip: ({ input }) => !input.creditPurchase,\n run: async ({ input, dryRun }) =>\n x402TopUpWorkflow.run(\n {\n accountId: input.creditPurchase!.accountId,\n credits: input.creditPurchase!.credits,\n evmPrivateKey: input.creditPurchase!.evmPrivateKey,\n network: input.creditPurchase!.network,\n ledgerVerification: input.creditPurchase!.ledgerVerification,\n },\n { dryRun },\n ),\n },\n {\n name: 'workflow.registerAgentErc8004',\n run: async ({ input, dryRun }) =>\n registerAgentErc8004Pipeline.run(\n {\n payload: input.payload,\n erc8004Networks: input.erc8004Networks,\n creditTopUp: undefined,\n },\n { dryRun },\n ),\n },\n {\n name: 'workflow.erc8004X402.chat',\n skip: ({ input }) => !input.chatMessage,\n run: async ({ input, context, dryRun }) => {\n const uaid = (context?.context as any)?.registrationResult?.context?.uaid;\n if (!uaid) throw new Error('UAID missing after registration');\n return chatPipeline.run({ uaid, message: input.chatMessage }, { dryRun });\n },\n },\n ],\n};\n\nexport const erc8004X402Workflow = scaffoldWorkflow(erc8004X402Definition);\n","import type { AgentRegistrationRequest, LedgerVerifyRequest } from '@hashgraphonline/standards-sdk';\nimport { scaffoldWorkflow } from './scaffold';\nimport type { PipelineDefinition } from './types';\nimport { x402TopUpWorkflow } from './x402-topup';\nimport { registerAgentAdvancedPipeline } from './register-advanced';\nimport { chatPipeline } from './chat';\n\ninterface X402RegistrationInput {\n payload: AgentRegistrationRequest;\n x402: {\n accountId: string;\n credits: number;\n evmPrivateKey: string;\n ledgerVerification?: LedgerVerifyRequest;\n };\n chatMessage?: string;\n}\n\nconst x402RegistrationDefinition: PipelineDefinition<X402RegistrationInput, Record<string, unknown>> = {\n name: 'workflow.x402Registration',\n description: 'Full agent registration funded via X402 credits with chat validation.',\n version: '1.0.0',\n requiredEnv: ['REGISTRY_BROKER_API_KEY'],\n createContext: () => ({}),\n steps: [\n {\n name: 'workflow.x402TopUp',\n run: async ({ input, dryRun }) =>\n x402TopUpWorkflow.run(\n {\n accountId: input.x402.accountId,\n credits: input.x402.credits,\n evmPrivateKey: input.x402.evmPrivateKey,\n ledgerVerification: input.x402.ledgerVerification,\n },\n { dryRun },\n ),\n },\n {\n name: 'workflow.registerAgentAdvanced',\n run: async ({ input, dryRun }) => registerAgentAdvancedPipeline.run({ payload: input.payload }, { dryRun }),\n },\n {\n name: 'workflow.x402Registration.chat',\n skip: ({ input }) => !input.chatMessage,\n run: async ({ input, context, dryRun }) => {\n const uaid = (context.context as any)?.registrationResult?.context?.uaid;\n if (!uaid) throw new Error('UAID missing after registration');\n return chatPipeline.run({ uaid, message: input.chatMessage }, { dryRun });\n },\n },\n ],\n};\n\nexport const x402RegistrationWorkflow = scaffoldWorkflow(x402RegistrationDefinition);\n","import { runSSE, runStdio } from './transports';\nimport { logger } from './logger';\n\nconst transport = (process.env.MCP_TRANSPORT ?? 'sse').toLowerCase();\n\nif (transport === 'stdio') {\n logger.info({ transport }, 'starting MCP server');\n runStdio().catch((err) => {\n logger.error({ err }, 'Failed to start stdio transport');\n process.exitCode = 1;\n });\n} else {\n logger.info({ transport }, 'starting MCP server');\n runSSE().catch((err) => {\n logger.error({ err }, 'Failed to start SSE transport');\n process.exitCode = 1;\n });\n}\n"],"mappings":";AAAA,OAAO,UAA+C;AACtD,SAAS,cAAAA,mBAAkB;AAC3B,SAAS,mBAAmB;;;ACF5B,SAAS,cAAAC,mBAAkB;AAC3B,SAA6F,uBAAAC,4BAA2B;AACxH,SAAS,eAAe;AAExB,SAAS,KAAAC,UAAS;;;ACJlB,SAAS,sBAAsB,2BAA2B;AAC1D,OAAO,gBAAgB;AACvB,OAAO,aAAa;AACpB,SAAS,SAAS,mBAAmB;;;ACHrC,SAAS,UAAU,eAAe;AAClC,SAAS,SAAS;AAElB,IAAI,QAAQ,IAAI,aAAa,QAAQ;AACnC,UAAQ,EAAE,OAAO,KAAK,CAAC;AACzB;AAEA,IAAM,aAAa,CAAC,SAAS,SAAS,QAAQ,QAAQ,SAAS,OAAO;AAEtE,IAAM,YAAY,EACf,OAAO;AAAA,EACN,yBAAyB,EACtB,OAAO,EACP,IAAI,EACJ,QAAQ,iCAAiC;AAAA,EAC5C,yBAAyB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA,EACpD,mBAAmB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA,EAC9C,oBAAoB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA,EAC/C,MAAM,EAAE,OAAO,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,QAAQ,IAAI;AAAA,EACrD,uBAAuB,EAAE,OAAO,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,SAAS;AAAA,EACnE,oBAAoB,EAAE,OAAO,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,SAAS;AAAA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E,SAAS,IAAI,MAAM,GAAG;AAC/D,UAAM,MAAM,IAAI,YAAY;AAC5B,QAAI,UAAU;AACd,QAAI,GAAG,QAAQ,CAAC,UAAU;AACxB,UAAI,QAAQ,SAAS,KAAK;AACxB,mBAAW,MAAM,SAAS;AAAA,MAC5B;AAAA,IACF,CAAC;AACD,QAAI,GAAG,OAAO,MAAM;AAClB,UAAI,QAAQ,QAAQ;AAClB,eAAO,MAAM,EAAE,SAAS,QAAQ,MAAM,GAAG,GAAG,EAAE,GAAG,eAAe;AAAA,MAClE;AAAA,IACF,CAAC;AACD,QAAI,KAAK,GAAG,EAAE,KAAK,QAAQ;AAAA,EAC7B,OAAO;AACL,QAAI,KAAK,QAAQ;AAAA,EACnB;AACF;;;AiC5GA,IAAM,aAAa,QAAQ,IAAI,iBAAiB,OAAO,YAAY;AAEnE,IAAI,cAAc,SAAS;AACzB,SAAO,KAAK,EAAE,UAAU,GAAG,qBAAqB;AAChD,WAAS,EAAE,MAAM,CAAC,QAAQ;AACxB,WAAO,MAAM,EAAE,IAAI,GAAG,iCAAiC;AACvD,YAAQ,WAAW;AAAA,EACrB,CAAC;AACH,OAAO;AACL,SAAO,KAAK,EAAE,UAAU,GAAG,qBAAqB;AAChD,SAAO,EAAE,MAAM,CAAC,QAAQ;AACtB,WAAO,MAAM,EAAE,IAAI,GAAG,+BAA+B;AACrD,YAAQ,WAAW;AAAA,EACrB,CAAC;AACH;","names":["randomUUID","randomUUID","RegistryBrokerError","z","parsed","z","RegistryBrokerError","RegistryBrokerError","normalized","randomUUID","randomUUID","normalized","parsed","config","require","logger","config","normalized","z","payload","recordMemory","response","randomUUID","recordMemory","randomUUID"]}
|
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"profile": {
|
|
3
|
-
"version": "1.0.0",
|
|
4
|
-
"type": 2,
|
|
5
|
-
"display_name": "Hashnet MCP Server",
|
|
6
|
-
"alias": "hashnet-mcp",
|
|
7
|
-
"bio": "FastMCP wrapper around the Hashgraph Online Registry Broker.",
|
|
8
|
-
"socials": [
|
|
9
|
-
{ "platform": "github", "handle": "hashgraphonline" }
|
|
10
|
-
],
|
|
11
|
-
"mcpServer": {
|
|
12
|
-
"version": "1.0.0",
|
|
13
|
-
"connectionInfo": {
|
|
14
|
-
"url": "https://hashnet.example.com/mcp/stream",
|
|
15
|
-
"transport": "sse"
|
|
16
|
-
},
|
|
17
|
-
"services": [0, 1, 2, 6],
|
|
18
|
-
"description": "Provides hol.* registry broker tooling over MCP.",
|
|
19
|
-
"capabilities": ["registry-search", "registration", "uaid"],
|
|
20
|
-
"resources": [
|
|
21
|
-
{ "name": "hol.search.help", "description": "Search usage info" }
|
|
22
|
-
],
|
|
23
|
-
"tools": [
|
|
24
|
-
{ "name": "hol.search", "description": "Discover agents" },
|
|
25
|
-
{ "name": "hol.registerAgent", "description": "Register new agent" }
|
|
26
|
-
],
|
|
27
|
-
"maintainer": "hol",
|
|
28
|
-
"repository": "https://github.com/hol/hashnet-mcp",
|
|
29
|
-
"docs": "https://hashgraphonline.com/docs"
|
|
30
|
-
}
|
|
31
|
-
},
|
|
32
|
-
"protocol": "mcp",
|
|
33
|
-
"communicationProtocol": "sse",
|
|
34
|
-
"registry": "hashgraph-online",
|
|
35
|
-
"metadata": {
|
|
36
|
-
"trustScore": 95,
|
|
37
|
-
"verified": true,
|
|
38
|
-
"avgLatency": 120,
|
|
39
|
-
"uptime": 99.9,
|
|
40
|
-
"provider": "Hashnet",
|
|
41
|
-
"category": "infrastructure",
|
|
42
|
-
"adapter": "rb",
|
|
43
|
-
"openConvAICompatible": true,
|
|
44
|
-
"customFields": {
|
|
45
|
-
"region": "iad"
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
}
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"uaid": "uaid:registry:local-agent",
|
|
3
|
-
"agentverseUaid": "uaid:agentverse:partner",
|
|
4
|
-
"localMessage": "Relay this update to Agentverse",
|
|
5
|
-
"agentverseMessage": "Acknowledged from Agentverse",
|
|
6
|
-
"iterations": 2,
|
|
7
|
-
"localAuth": {
|
|
8
|
-
"type": "bearer",
|
|
9
|
-
"token": "LOCAL_AGENT_TOKEN"
|
|
10
|
-
},
|
|
11
|
-
"agentverseAuth": {
|
|
12
|
-
"type": "bearer",
|
|
13
|
-
"token": "AGENTVERSE_TOKEN"
|
|
14
|
-
}
|
|
15
|
-
}
|