@indexnetwork/protocol 4.3.4-rc.309.1 → 4.3.4-rc.310.1
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/IMPLEMENTATION.md +2 -2
- package/dist/chat/chat.agent.d.ts +1 -1
- package/dist/chat/chat.agent.js +1 -1
- package/dist/chat/chat.agent.js.map +1 -1
- package/dist/chat/chat.prompt.js +30 -30
- package/dist/chat/chat.prompt.js.map +1 -1
- package/dist/chat/chat.prompt.modules.js +8 -8
- package/dist/chat/chat.prompt.modules.js.map +1 -1
- package/dist/chat/chat.state.d.ts +1 -1
- package/dist/chat/chat.state.d.ts.map +1 -1
- package/dist/chat/chat.state.js.map +1 -1
- package/dist/chat/tests/chat.graph.mocks.d.ts +1 -1
- package/dist/chat/tests/chat.graph.mocks.js +1 -1
- package/dist/chat/tests/chat.graph.mocks.js.map +1 -1
- package/dist/contact/contact.tools.js +6 -6
- package/dist/contact/contact.tools.js.map +1 -1
- package/dist/enrichment/enrichment.tools.js +7 -7
- package/dist/enrichment/enrichment.tools.js.map +1 -1
- package/dist/integration/integration.tools.js +1 -1
- package/dist/integration/integration.tools.js.map +1 -1
- package/dist/intent/intent.graph.d.ts.map +1 -1
- package/dist/intent/intent.graph.js +9 -9
- package/dist/intent/intent.graph.js.map +1 -1
- package/dist/intent/intent.indexer.d.ts +1 -1
- package/dist/intent/intent.indexer.js +4 -4
- package/dist/intent/intent.indexer.js.map +1 -1
- package/dist/intent/intent.state.d.ts +7 -7
- package/dist/intent/intent.state.js +7 -7
- package/dist/intent/intent.state.js.map +1 -1
- package/dist/intent/intent.tools.js +26 -26
- package/dist/intent/intent.tools.js.map +1 -1
- package/dist/maintenance/maintenance.graph.d.ts +2 -2
- package/dist/maintenance/maintenance.graph.d.ts.map +1 -1
- package/dist/maintenance/maintenance.graph.js.map +1 -1
- package/dist/mcp/mcp.server.d.ts +2 -2
- package/dist/mcp/mcp.server.js +4 -4
- package/dist/mcp/mcp.server.js.map +1 -1
- package/dist/network/indexer/indexer.graph.d.ts +2 -2
- package/dist/network/indexer/indexer.graph.d.ts.map +1 -1
- package/dist/network/indexer/indexer.graph.js +13 -13
- package/dist/network/indexer/indexer.graph.js.map +1 -1
- package/dist/network/indexer/indexer.state.d.ts +3 -3
- package/dist/network/indexer/indexer.state.d.ts.map +1 -1
- package/dist/network/indexer/indexer.state.js +4 -4
- package/dist/network/indexer/indexer.state.js.map +1 -1
- package/dist/network/membership/membership.graph.d.ts +1 -1
- package/dist/network/membership/membership.graph.js +21 -21
- package/dist/network/membership/membership.graph.js.map +1 -1
- package/dist/network/membership/membership.state.d.ts +2 -2
- package/dist/network/membership/membership.state.js +2 -2
- package/dist/network/membership/membership.state.js.map +1 -1
- package/dist/network/network.graph.d.ts +1 -1
- package/dist/network/network.graph.d.ts.map +1 -1
- package/dist/network/network.graph.js +13 -13
- package/dist/network/network.graph.js.map +1 -1
- package/dist/network/network.state.d.ts +3 -3
- package/dist/network/network.state.d.ts.map +1 -1
- package/dist/network/network.state.js +3 -3
- package/dist/network/network.state.js.map +1 -1
- package/dist/network/network.tools.d.ts.map +1 -1
- package/dist/network/network.tools.js +95 -107
- package/dist/network/network.tools.js.map +1 -1
- package/dist/opportunity/opportunity.discover.d.ts +1 -1
- package/dist/opportunity/opportunity.discover.d.ts.map +1 -1
- package/dist/opportunity/opportunity.discover.js +1 -1
- package/dist/opportunity/opportunity.discover.js.map +1 -1
- package/dist/opportunity/opportunity.graph.js +10 -10
- package/dist/opportunity/opportunity.graph.js.map +1 -1
- package/dist/opportunity/opportunity.introducer.d.ts +3 -3
- package/dist/opportunity/opportunity.introducer.d.ts.map +1 -1
- package/dist/opportunity/opportunity.introducer.js +2 -2
- package/dist/opportunity/opportunity.introducer.js.map +1 -1
- package/dist/opportunity/opportunity.state.d.ts +1 -1
- package/dist/opportunity/opportunity.state.js +1 -1
- package/dist/opportunity/opportunity.state.js.map +1 -1
- package/dist/opportunity/opportunity.tools.js +18 -18
- package/dist/opportunity/opportunity.tools.js.map +1 -1
- package/dist/premise/premise.indexer.d.ts +1 -1
- package/dist/premise/premise.indexer.js +5 -5
- package/dist/premise/premise.indexer.js.map +1 -1
- package/dist/questioner/questioner.tools.js +1 -1
- package/dist/questioner/questioner.tools.js.map +1 -1
- package/dist/shared/agent/tool.factory.d.ts +1 -1
- package/dist/shared/agent/tool.factory.js +1 -1
- package/dist/shared/agent/tool.factory.js.map +1 -1
- package/dist/shared/agent/tool.helpers.d.ts +6 -6
- package/dist/shared/agent/tool.helpers.d.ts.map +1 -1
- package/dist/shared/agent/tool.helpers.js +2 -2
- package/dist/shared/agent/tool.helpers.js.map +1 -1
- package/dist/shared/agent/tool.scope.js +1 -1
- package/dist/shared/agent/tool.scope.js.map +1 -1
- package/dist/shared/agent/utility.tools.js +20 -20
- package/dist/shared/agent/utility.tools.js.map +1 -1
- package/dist/shared/interfaces/database.interface.d.ts +59 -59
- package/dist/shared/interfaces/database.interface.d.ts.map +1 -1
- package/dist/shared/interfaces/database.interface.js.map +1 -1
- package/dist/shared/interfaces/embedder.interface.d.ts +2 -2
- package/dist/shared/interfaces/embedder.interface.d.ts.map +1 -1
- package/dist/shared/interfaces/embedder.interface.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp.server.js","sourceRoot":"/","sources":["mcp/mcp.server.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAMzE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AACrE,OAAO,EAAE,uBAAuB,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAE5F,OAAO,EAAE,cAAc,EAAE,MAAM,sCAAsC,CAAC;AACtE,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACnE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AAG,wBAAwB,CAAC,GAAG,CAAC,CAAC;gBACpD,OAAO;oBACL,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAe,EAAE,IAAI,EAAE,aAAa,IAAI,IAAI,CAAC,SAAS,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC;oBAC/F,OAAO,EAAE,IAAI;iBACd,CAAC;YACJ,CAAC;QACH,CAAC,CACF,CAAC;IACJ,CAAC;IAED,MAAM,CAAC,OAAO,CAAC,2BAA2B,YAAY,CAAC,MAAM,QAAQ,CAAC,CAAC;IACvE,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/**\n * MCP Server Factory — creates an McpServer instance with all protocol tools\n * registered from the existing tool registry. Each tool invocation resolves\n * auth from the HTTP request, builds a ResolvedToolContext, and delegates\n * to the raw tool handler.\n */\n\nimport { z } from 'zod';\nimport { McpServer, fromJsonSchema } from '@modelcontextprotocol/server';\nimport type { ServerContext, JsonSchemaType } from '@modelcontextprotocol/server';\n\nimport type { McpAuthResolver } from '../shared/interfaces/auth.interface.js';\nimport type { McpAuthInput } from '../shared/schemas/mcp-auth.schema.js';\nimport type { ToolDeps, ResolvedToolContext, RawToolDefinition } from '../shared/agent/tool.helpers.js';\nimport { resolveChatContext } from '../shared/agent/tool.helpers.js';\nimport { deriveAllowedNetworkIds, scopeFromNetworkId } from '../shared/agent/tool.scope.js';\nimport type { Question } from '../shared/schemas/question.schema.js';\nimport { QuestionSchema } from '../shared/schemas/question.schema.js';\nimport { dispatchElicitations } from './elicitation.dispatcher.js';\nimport { createToolRegistry } from '../shared/agent/tool.registry.js';\nimport { ToolRuntimeError, invokeToolRuntime, toolRuntimeErrorToResult } from '../shared/agent/tool.runtime.js';\nimport type { TraceEmitter } from '../shared/observability/request-context.js';\nimport { protocolLogger } from '../shared/observability/protocol.logger.js';\n\nconst logger = protocolLogger('McpServer');\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// STATIC TOOL METADATA CACHE\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Static registration metadata for one MCP tool — schema conversion artifacts\n * that depend only on registry-shaping feature flags, not on per-request\n * database scope.\n */\ntype McpToolRegistrationMetadata = Pick<RawToolDefinition, 'name' | 'description' | 'schema'> & {\n jsonSchema: JsonSchemaType;\n inputSchema: ReturnType<typeof fromJsonSchema>;\n};\n\nconst mcpToolMetadataCache = new Map<string, McpToolRegistrationMetadata[]>();\n\n/**\n * Builds a cache key from registry-shaping dependency booleans.\n * When a feature flag changes the tool set, the cache key changes so\n * the cached metadata set is automatically invalidated.\n */\nexport function getMcpToolMetadataCacheKey(deps: Pick<ToolDeps,\n 'contactsEnabled' | 'chatSession' | 'agentDatabase' | 'agentDispatcher' | 'questionerEnqueue'\n>): string {\n return [\n `contacts:${deps.contactsEnabled === true ? '1' : '0'}`,\n `chat:${deps.chatSession ? '1' : '0'}`,\n `agent:${deps.agentDatabase ? '1' : '0'}`,\n `negotiation:${deps.agentDispatcher ? '1' : '0'}`,\n `questioner:${deps.questionerEnqueue ? '1' : '0'}`,\n ].join('|');\n}\n\n/**\n * Clears the metadata cache. Used in tests to ensure fresh state between cases.\n */\nexport function clearMcpToolMetadataCacheForTests(): void {\n mcpToolMetadataCache.clear();\n}\n\n/**\n * Returns cached (or builds and caches) static MCP tool registration metadata.\n * The first call per cache key runs the full registry creation + schema\n * conversion; subsequent calls return the cached metadata array for the same\n * registry-shaping dependency profile.\n *\n * Does NOT store tool handlers — those remain request-scoped because they\n * capture per-request userDb/systemDb.\n */\nexport function getCachedMcpToolMetadata(deps: ToolDeps): readonly McpToolRegistrationMetadata[] {\n const cacheKey = getMcpToolMetadataCacheKey(deps);\n const cached = mcpToolMetadataCache.get(cacheKey);\n if (cached) return cached;\n\n const registry = createToolRegistry(deps);\n const metadata = Array.from(registry.values()).map((toolDef): McpToolRegistrationMetadata => {\n const jsonSchema = zodToJsonSchema(toolDef.schema) as JsonSchemaType;\n return {\n name: toolDef.name,\n description: toolDef.description,\n schema: toolDef.schema,\n jsonSchema,\n inputSchema: fromJsonSchema(jsonSchema),\n };\n });\n\n mcpToolMetadataCache.set(cacheKey, metadata);\n logger.verbose(`MCP tool metadata cached with ${metadata.length} tools`, { cacheKey });\n return metadata;\n}\n\nfunction isExpectedMcpAuthError(message: string): boolean {\n return message.includes('Authentication required') ||\n message.includes('Invalid API key') ||\n message.includes('Invalid or expired access token') ||\n message.includes('JWT payload missing user ID');\n}\n\n/**\n * Runtime/auth failures are converted into structured MCP `isError` tool\n * results for the caller. Reporting them as application exceptions produces\n * Sentry noise for expected client failures and policy-enforced timeouts.\n */\nexport function shouldReportMcpToolError(err: unknown): boolean {\n if (err instanceof ToolRuntimeError) return false;\n const message = err instanceof Error ? err.message : String(err);\n return !isExpectedMcpAuthError(message);\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// ZOD 3 → JSON SCHEMA CONVERSION\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Minimal Zod-to-JSON-Schema conversion for MCP tool registration.\n * Converts Zod 3.x schemas to plain JSON Schema objects that can be\n * wrapped with `fromJsonSchema()` for MCP SDK compatibility.\n */\nfunction zodToJsonSchema(schema: z.ZodType): Record<string, unknown> {\n if (schema instanceof z.ZodObject) {\n const shape = schema.shape;\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n for (const [key, value] of Object.entries(shape)) {\n const zodValue = value as z.ZodType;\n properties[key] = zodToJsonSchema(zodValue);\n if (!(zodValue instanceof z.ZodOptional) && !(zodValue instanceof z.ZodDefault)) {\n required.push(key);\n }\n }\n return { type: 'object', properties, ...(required.length ? { required } : {}) };\n }\n if (schema instanceof z.ZodString) {\n const result: Record<string, unknown> = { type: 'string' };\n // Detect .url(), .email(), .uuid() etc. via Zod's internal checks array\n const checks = (schema as z.ZodString & { _def: { checks: Array<{ kind: string }> } })._def?.checks;\n if (checks) {\n for (const check of checks) {\n if (check.kind === 'url') result.format = 'uri';\n else if (check.kind === 'email') result.format = 'email';\n else if (check.kind === 'uuid') result.format = 'uuid';\n else if (check.kind === 'datetime') result.format = 'date-time';\n }\n }\n return result;\n }\n if (schema instanceof z.ZodNumber) {\n const checks = (schema as z.ZodNumber & { _def: { checks: Array<{ kind: string; value?: number }> } })._def?.checks;\n const result: Record<string, unknown> = { type: 'number' };\n if (checks) {\n for (const check of checks) {\n if (check.kind === 'int') result.type = 'integer';\n else if (check.kind === 'min') result.minimum = check.value;\n else if (check.kind === 'max') result.maximum = check.value;\n }\n }\n return result;\n }\n if (schema instanceof z.ZodBoolean) return { type: 'boolean' };\n if (schema instanceof z.ZodArray) {\n return { type: 'array', items: zodToJsonSchema((schema as z.ZodArray<z.ZodType>).element) };\n }\n if (schema instanceof z.ZodOptional) {\n return zodToJsonSchema((schema as z.ZodOptional<z.ZodType>).unwrap());\n }\n if (schema instanceof z.ZodDefault) {\n return zodToJsonSchema((schema as z.ZodDefault<z.ZodType>).removeDefault());\n }\n if (schema instanceof z.ZodEnum) {\n return { type: 'string', enum: (schema as z.ZodEnum<[string, ...string[]]>).options };\n }\n if (schema instanceof z.ZodNullable) {\n const inner = zodToJsonSchema((schema as z.ZodNullable<z.ZodType>).unwrap());\n return { ...inner, nullable: true };\n }\n if (schema instanceof z.ZodRecord) {\n return { type: 'object', additionalProperties: true };\n }\n return { type: 'object' };\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// RESULT POST-PROCESSING\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Strips internal `_`-prefixed keys from `data` and promotes `isError`\n * from the inner `success: false` signal to the MCP envelope level.\n * Fail-open: if JSON parsing throws, returns the original text with isError: false.\n */\nexport function sanitizeMcpResult(text: string): { text: string; isError: boolean } {\n try {\n const parsed = JSON.parse(text);\n if (\n parsed &&\n typeof parsed === 'object' &&\n parsed.data &&\n typeof parsed.data === 'object' &&\n !Array.isArray(parsed.data)\n ) {\n for (const key of Object.keys(parsed.data)) {\n if (key.startsWith('_') || key === 'debugSteps') {\n delete parsed.data[key];\n }\n }\n }\n const isError = parsed?.success === false;\n return { text: JSON.stringify(parsed), isError };\n } catch {\n return { text, isError: false };\n }\n}\n\n/** Spec cap on the number of decision questions surfaced per turn. */\nconst MAX_DECISION_QUESTIONS = 3;\n\n/**\n * Extracts decision questions from a parsed tool-result text, if present.\n * Validates each entry against `QuestionSchema` and drops malformed items;\n * caps the array at `MAX_DECISION_QUESTIONS` (defense-in-depth — Slice 2's\n * generator already caps at 3, but we don't trust the cast here).\n *\n * Returns null when the text isn't JSON, has no `data.questions`, or\n * contains zero valid questions after validation.\n */\nexport function extractDecisionQuestions(text: string): Question[] | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return null;\n }\n\n const rawQs = (parsed as { data?: { questions?: unknown } } | null)?.data?.questions;\n if (!Array.isArray(rawQs) || rawQs.length === 0) return null;\n\n const valid: Question[] = [];\n for (const raw of rawQs) {\n const result = QuestionSchema.safeParse(raw);\n if (result.success) valid.push(result.data);\n if (valid.length === MAX_DECISION_QUESTIONS) break;\n }\n return valid.length > 0 ? valid : null;\n}\n\n/**\n * Renders the JSON-envelope text block appended to the tool result content\n * when decision questions are present. The leading sentinel string lets the\n * LLM client recognize and surface the questions in prose for clients\n * without elicitation support.\n */\nexport function renderQuestionsEnvelope(questions: Question[]): string {\n return `Decision questions (structured): ${JSON.stringify({ questions })}`;\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// MCP SERVER FACTORY\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Factory for creating per-request scoped database instances.\n * Injected from the controller/handler layer to keep the protocol layer\n * free of direct adapter imports.\n */\nexport interface ScopedDepsFactory {\n /** Creates scoped userDb and systemDb for the given user and allowed network IDs. */\n create(userId: string, allowedNetworkIds: string[]): Pick<ToolDeps, 'userDb' | 'systemDb'>;\n}\n\n/**\n * Computes the concrete network IDs passed to the per-request scoped DB factory.\n * When a network scope is present, the agent reaches that network plus the\n * user's personal index. Otherwise the full membership set is returned.\n */\nexport const computeAgentAllowedNetworkIds = (\n userNetworks: { networkId: string; isPersonal?: boolean | null }[],\n scopeType: 'network' | undefined,\n scopeId: string | null | undefined,\n): string[] => deriveAllowedNetworkIds({\n memberships: userNetworks,\n ...(scopeType && scopeId ? { scopeType, scopeId } : {}),\n});\n\n/**\n * Promotes a network-scoped agent's bound network into the resolved tool\n * context as the implicit chat scope. Every tool derives its focused network\n * from the `scopeType`/`scopeId` envelope; without this step scoped API-key\n * calls would still resolve an unscoped/global view.\n *\n * No-op when there is no scope, or when an explicit scope is already set\n * (a user-driven index-scoped chat must keep precedence over the agent\n * binding — which would be a strict subset anyway, since the API key cannot\n * reach beyond its bound network).\n */\nexport const applyNetworkScopeToContext = (\n context: ResolvedToolContext,\n networkScopeId: string | null | undefined,\n): void => {\n if (!networkScopeId) return;\n if (context.scopeType && context.scopeId) return;\n\n const scope = scopeFromNetworkId(networkScopeId);\n context.scopeType = scope.scopeType;\n context.scopeId = scope.scopeId;\n\n const bound = context.userNetworks.find((m) => m.networkId === networkScopeId);\n if (!bound) return;\n\n context.indexName = bound.networkTitle;\n context.scopedIndex = {\n id: bound.networkId,\n title: bound.networkTitle,\n prompt: bound.indexPrompt ?? null,\n };\n const isOwner = bound.permissions?.includes('owner') ?? false;\n context.scopedMembershipRole = isOwner ? 'owner' : 'member';\n context.isOwner = isOwner;\n};\n\n/**\n * Tools allowed during onboarding — everything else is gated until\n * complete_onboarding is called. Includes the agent-gate-exempt tools\n * (register_agent, read_docs, scrape_url) because they are informational /\n * registration primitives needed at every lifecycle stage.\n */\nexport const ONBOARDING_ALLOWED: ReadonlySet<string> = new Set([\n 'register_agent',\n 'read_docs',\n 'scrape_url',\n 'record_onboarding_privacy_consent',\n // Canonical *_user_context / *_enrichment_run names (IND-371)\n 'preview_user_context',\n 'get_enrichment_run',\n 'cancel_enrichment_run',\n 'confirm_user_context',\n 'create_user_context',\n 'read_user_contexts',\n // Deprecated aliases retained so mid-migration clients can still onboard (IND-373 removes them)\n 'preview_user_profile',\n 'get_profile_run',\n 'cancel_profile_run',\n 'confirm_user_profile',\n 'create_user_profile',\n 'read_user_profiles',\n 'complete_onboarding',\n 'import_gmail_contacts',\n 'read_networks',\n 'create_network_membership',\n 'create_intent',\n]);\n\n/**\n * Builds the onboarding gate message for MCP callers. Condensed from the\n * chat orchestrator's 8-step flow (chat.prompt.ts buildOnboarding) into a\n * 7-step tool-error guide suited for non-interactive MCP clients.\n */\nexport function buildMcpOnboardingMessage(ctx: ResolvedToolContext): string {\n const nameStep = ctx.hasName\n ? `1. Greet the user and confirm their name (\"You're ${ctx.userName}, right?\").`\n : `1. Ask the user for their name and a short self-description.`;\n\n const communityStep = ctx.networkId\n ? `5. (Skipped — user is already in \"${ctx.indexName ?? 'their community'}\".)`\n : `5. Call read_networks() and let the user pick communities to join via create_network_membership(networkId=...).`;\n\n const allowedList = Array.from(ONBOARDING_ALLOWED).join(', ');\n\n return (\n `This user has not completed onboarding. You must guide them through setup before they can use other tools. ` +\n `Only the following tools are available until onboarding is complete: ` +\n `${allowedList}.\\n\\n` +\n `Onboarding flow:\\n` +\n `${nameStep}\\n` +\n `2. Ask whether the user allows use of event/EdgeOS profile data, then call record_onboarding_privacy_consent(edgeosImportGranted=...).\\n` +\n `3. Ask separately whether the user allows public internet/profile lookup, then call record_onboarding_privacy_consent(publicProfileLookupGranted=...).\\n` +\n `4. Call preview_user_context(...) using only allowed inputs; do not run public lookup unless consent was granted. If it returns profileRunId, poll get_enrichment_run(profileRunId=...) until status is succeeded, then use its result as the draft.\\n` +\n `5. Present the profile draft and ask \"Does that look right?\" On approval/correction, call confirm_user_context(...).\\n` +\n `${communityStep}\\n` +\n `6. Ask what the user is looking for and call create_intent(description=\"...\", autoApprove=true) so the first signal is persisted.\\n` +\n `7. Call complete_onboarding() to finish setup. Gmail/contact import and discovery are optional after onboarding, never mandatory.`\n );\n}\n\n/**\n * Creates an MCP server with all protocol tools registered.\n * Tools resolve auth per-request via the HTTP request available in ServerContext.\n *\n * @param deps - Shared tool dependencies (graphs, database, embedder, etc.)\n * @param authResolver - Resolves authenticated identity from the HTTP request\n * @param scopedDepsFactory - Factory for creating per-request scoped databases\n * @returns A configured McpServer ready to be connected to a transport\n */\nfunction createMcpTraceEmitter(toolName: string, ctx: ServerContext): TraceEmitter | undefined {\n const token = ctx.mcpReq._meta?.progressToken;\n if (typeof token !== 'string' && typeof token !== 'number') return undefined;\n\n let progress = 0;\n return (event) => {\n progress += 1;\n const message = (() => {\n if (event.type === 'graph_start') return `${toolName}: ${event.name} started`;\n if (event.type === 'graph_end') return `${toolName}: ${event.name} finished${event.durationMs != null ? ` in ${event.durationMs}ms` : ''}`;\n if (event.type === 'agent_start') return `${toolName}: ${event.name} agent started`;\n if (event.type === 'agent_end') return `${toolName}: ${event.name} agent finished${event.durationMs != null ? ` in ${event.durationMs}ms` : ''}`;\n if (event.type === 'opportunity_draft_ready') return `${toolName}: opportunity draft ready`;\n return `${toolName}: progress`;\n })();\n\n const notification: Parameters<ServerContext['mcpReq']['notify']>[0] = {\n method: 'notifications/progress',\n params: { progressToken: token, progress, message },\n };\n void ctx.mcpReq.notify(notification).catch((err) => {\n logger.debug('Failed to send MCP progress notification', {\n toolName,\n error: err instanceof Error ? err.message : String(err),\n });\n });\n };\n}\n\nexport const MCP_INSTRUCTIONS = `\nIndex Network is a private, intent-driven discovery protocol. You help users find the right people and help the right people find them, via Index Network MCP tools.\n\n# Voice\nCalm, direct, analytical, concise. Preferred vocabulary: opportunity, overlap, signal, pattern, emerging, relevant, adjacency.\n\n# Banned vocabulary\nNEVER use \"search\" in any form. Use \"looking up\" for indexed data, \"find\" / \"look for\" for discovery, \"check\" for verification, \"discover\" for exploration. Banned: leverage, unlock, optimize, scale, disrupt, revolutionary, AI-powered, maximize value, act fast, networking, match.\n\n# Entity model\n- User — has one Profile, many Memberships, many Intents.\n- Profile — identity (bio, skills, interests, location).\n- Index — community with title, prompt (purpose), join policy. Has Members.\n- Membership — User↔Index junction. \\`isPersonal: true\\` marks the user's personal index (contacts).\n- Intent — what a user is looking for (signal). Description, summary, embedding.\n- IntentIndex — Intent↔Index junction (auto-assigned).\n- Opportunity — discovered connection between users. Roles, status, reasoning.\n\n# Output rules\n- NEVER expose internal IDs, UUIDs, field names, or tool names — EXCEPT when an ID is actionable for the user (e.g. a \\`conversationId\\` they need to open a chat). Surface such IDs verbatim when the tool returns them.\n- NEVER use internal vocabulary — say \"signal\" not \"intent\", \"community\" not \"index\".\n- NEVER dump raw JSON. Synthesize in natural language.\n- Surface top 1–3 relevant points unless asked for the full list.\n- Prefer first names; use full names only to disambiguate.\n- Translate statuses: draft/latent → \"draft\", pending → \"sent\", accepted → \"connected\".\n- NEVER fabricate data. If you don't have it, call the appropriate tool.\n\n# Tool guidance\nEach tool's description contains its own usage rules (when to call, when NOT to call, required prerequisites, post-call follow-ups). Read the description of every tool you call — that is where the per-tool workflow patterns live.\n\n# Authentication\nPass your API key in the \\`x-api-key\\` request header (not \\`Authorization: Bearer\\`).\n\n# Opportunity lifecycle\nOpportunities move through: draft → pending → accepted (or rejected).\n\n- **draft** (you created it, not yet sent): offer to send it; confirm before calling update_opportunity with pending.\n- **pending, you sent it**: waiting for the other side — nothing to do.\n- **pending, you received it**: the other person is waiting for your response. Surface it to the user and ask if they want to start a chat. Only call update_opportunity with accepted after explicit user confirmation.\n- **accepted**: both sides are connected — a direct conversation exists. Surface the conversationId to the user if available.\n\nNever accept a received opportunity without explicit user approval in the current conversation.\n\n# Decision questions after discovery\n\nAfter \\`discover_opportunities\\`, the tool result may include a second text block starting with \\`Decision questions (structured): ...\\`. This means the discovery engine ran negotiations but needs human input to sharpen the next turn — e.g. clarify timing, role, stage, or location.\n\n**When this block is present:**\n1. Parse the \\`questions\\` array from the JSON after the sentinel.\n2. Each question has \\`title\\` (decision domain, ≤12 chars), \\`prompt\\` (ends in \\`?\\`), \\`options\\` (2–4 items, each with \\`label\\` and \\`description\\`), and \\`multiSelect\\`. The safest option is labeled \\`... (Recommended)\\`.\n3. Present each question in natural language: ask the \\`prompt\\`, list options as \\`**{label}** — {description}\\`. Never expose the JSON or technical field names.\n4. Wait for the user's answer, then fold it into the next \\`discover_opportunities(searchQuery=...)\\` call.\n\n**Elicitation-capable clients** (those that declared \\`elicitation\\` support in \\`initialize\\`): the server dispatches \\`elicitation/create\\` requests directly — answers are written back to the chat session automatically. You will not see the envelope as a follow-up task in that case.\n`.trim();\n\n/**\n * Extracts a Bearer token from an HTTP Authorization header.\n */\nexport function extractBearerToken(req: Request): string | undefined {\n const authHeader = req.headers.get('Authorization');\n if (!authHeader) return undefined;\n const [scheme, token] = authHeader.trim().split(/\\s+/, 2);\n if (scheme?.toLowerCase() === 'bearer' && token) return token;\n return undefined;\n}\n\n/**\n * Normalizes the x-index-surface header to a typed surface value.\n * Unknown or absent values collapse to 'web'.\n */\nlet hasWarnedInvalidSurface = false;\nexport function parseClientSurface(raw: string | null): 'telegram' | 'web' {\n if (raw === null || raw === '') return 'web';\n const trimmed = raw.trim().toLowerCase();\n if (trimmed === '') return 'web';\n if (trimmed === 'telegram') return 'telegram';\n if (trimmed === 'web') return 'web';\n if (!hasWarnedInvalidSurface) {\n hasWarnedInvalidSurface = true;\n logger.warn('Unknown x-index-surface value (collapsing to web; warning once per process)');\n }\n return 'web';\n}\n\nexport function createMcpServer(\n deps: ToolDeps,\n authResolver: McpAuthResolver,\n scopedDepsFactory: ScopedDepsFactory,\n): McpServer {\n // Tools exempt from the agent-registration gate — available before registration is complete.\n const AGENT_GATE_EXEMPT = new Set(['register_agent', 'read_docs', 'scrape_url']);\n\n const server = new McpServer(\n { name: 'index-network', version: '1.0.0' },\n { instructions: MCP_INSTRUCTIONS },\n );\n\n const toolMetadata = getCachedMcpToolMetadata(deps);\n\n for (const toolDef of toolMetadata) {\n const toolName = toolDef.name;\n\n server.registerTool(\n toolName,\n {\n description: toolDef.description,\n inputSchema: toolDef.inputSchema,\n },\n async (args: unknown, ctx: ServerContext) => {\n let reportDeps = deps;\n let reportUserId: string | undefined;\n let reportContext: ResolvedToolContext | undefined;\n\n try {\n // Extract the original HTTP request from the MCP server context\n const httpReq = ctx.http?.req;\n if (!httpReq) {\n return {\n content: [{ type: 'text' as const, text: JSON.stringify({ error: 'No HTTP request available in MCP context' }) }],\n isError: true,\n };\n }\n\n // Extract transport-neutral auth input DTO from the HTTP request\n const mcpAuthInput: McpAuthInput = {\n bearerToken: extractBearerToken(httpReq),\n apiKey: httpReq.headers.get('x-api-key') ?? undefined,\n clientSurface: parseClientSurface(httpReq.headers.get('x-index-surface')),\n telegramHandle: httpReq.headers.get('x-index-telegram-handle') ?? undefined,\n telegramUsername: httpReq.headers.get('x-index-telegram-username') ?? undefined,\n };\n\n // Resolve authenticated identity from the auth input DTO\n const { userId, agentId, isSessionAuth, networkScopeId, clientSurface } = await authResolver.resolveIdentity(mcpAuthInput);\n reportUserId = userId;\n\n // Per-principal MCP throttle. Runs BEFORE any DB work so a throttled\n // call short-circuits cheaply. The /mcp transport bypasses the\n // controller-level RateLimit guard, so this is the only volume cap on\n // tool calls — it stops an over-eager agent from cascading itself into\n // provider rate limits.\n if (deps.mcpRateLimiter) {\n // Throttling is best-effort: never let a limiter failure (or a host\n // implementation that throws instead of failing open) break tool\n // dispatch. Treat any error as \"allowed\".\n let decision: Awaited<ReturnType<NonNullable<typeof deps.mcpRateLimiter>>> | null = null;\n try {\n decision = await deps.mcpRateLimiter({\n userId,\n ...(agentId ? { agentId } : {}),\n toolName,\n });\n } catch (rlErr) {\n logger.warn(`MCP rate limiter threw for \"${toolName}\" — failing open`, {\n error: rlErr instanceof Error ? rlErr.message : String(rlErr),\n });\n }\n if (decision && !decision.allowed) {\n const retryAfterSec = decision.retryAfterSec ?? 60;\n return {\n content: [{\n type: 'text' as const,\n text: JSON.stringify({\n error: 'Rate limit exceeded',\n message:\n `Too many ${toolName} calls in a short period. Wait ${retryAfterSec}s before retrying.` +\n (toolName === 'discover_opportunities'\n ? ` If a discovery run is in progress, poll get_discovery_run instead of calling discover_opportunities again.`\n : ''),\n retryAfterSec,\n }),\n }],\n isError: true,\n };\n }\n }\n\n // Resolve chat context for the user (mark as MCP — no interactive UI available)\n const context = await resolveChatContext({ database: deps.database, userId, contactsEnabled: deps.contactsEnabled });\n reportContext = context;\n context.isMcp = true;\n if (agentId) {\n context.agentId = agentId;\n }\n if (clientSurface) {\n context.clientSurface = clientSurface;\n }\n\n // Network-scoped agents inherit their bound network as the implicit chat\n // scope. Tools consume the scope envelope and derive any concrete\n // allowed network IDs from it plus the user's memberships.\n applyNetworkScopeToContext(context, networkScopeId);\n\n // Gate: API-key callers (background agents) must register before using most tools.\n // OAuth/JWT session callers (human MCP clients such as Claude Code) are exempt —\n // their identity is already established via the auth flow and they have no agent entity.\n if (!isSessionAuth && !context.agentId && !AGENT_GATE_EXEMPT.has(toolName)) {\n return {\n content: [{\n type: 'text' as const,\n text: JSON.stringify({\n error: 'Agent not registered',\n message:\n 'You must register as an agent before using Index tools. ' +\n 'Call register_agent with your agent name to establish an identity. ' +\n 'The tools register_agent, read_docs, and scrape_url are available without registration.',\n }),\n }],\n isError: true,\n };\n }\n\n // Gate: non-onboarded users can only use onboarding-related tools.\n // Mirrors the chat orchestrator's ONBOARDING MODE — the MCP client must\n // walk the user through profile creation, Gmail connect, intent capture,\n // and complete_onboarding() before full tool access is granted.\n if (context.isOnboarding && !ONBOARDING_ALLOWED.has(toolName)) {\n const onboardingSteps = buildMcpOnboardingMessage(context);\n return {\n content: [{\n type: 'text' as const,\n text: JSON.stringify({\n error: 'Onboarding required',\n message: onboardingSteps,\n }),\n }],\n isError: true,\n };\n }\n\n // Build per-request scoped databases via injected factory.\n // Network-scoped agents are clamped to their bound network plus the user's\n // personal index — they cannot reach other networks even when the user is\n // a member of them. The personal-index reachability is preserved so the\n // agent can still manage its owner's profile and contacts.\n const allowedNetworkIds = deriveAllowedNetworkIds({\n memberships: context.userNetworks,\n ...(context.scopeType && context.scopeId\n ? { scopeType: context.scopeType, scopeId: context.scopeId }\n : {}),\n });\n const scopedDbs = scopedDepsFactory.create(userId, allowedNetworkIds);\n\n // Override deps with per-request scoped databases\n const requestDeps: ToolDeps = { ...deps, ...scopedDbs };\n reportDeps = requestDeps;\n\n // Re-create registry with per-request deps for scoped database access.\n // Do not use cached registration metadata handlers here: tool handlers\n // close over userDb/systemDb when the registry is created.\n const requestRegistry = createToolRegistry(requestDeps);\n const requestTool = requestRegistry.get(toolName);\n\n if (!requestTool) {\n return {\n content: [{ type: 'text' as const, text: JSON.stringify({ error: `Tool \"${toolName}\" not found` }) }],\n isError: true,\n };\n }\n\n // Validate input against the original Zod schema\n const parseResult = (toolDef.schema as z.ZodType).safeParse(args);\n if (!parseResult.success) {\n const issues = parseResult.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ');\n return {\n content: [{ type: 'text' as const, text: JSON.stringify({ success: false, error: `Invalid input: ${issues}` }) }],\n isError: true,\n };\n }\n const validatedArgs = parseResult.data;\n\n // Execute the tool handler through the shared runtime so MCP calls have\n // consistent timeout, cancellation, progress, and requestContext plumbing.\n const result = await invokeToolRuntime({\n toolName,\n tool: requestTool,\n context,\n query: validatedArgs,\n signal: ctx.mcpReq.signal,\n traceEmitter: createMcpTraceEmitter(toolName, ctx),\n });\n\n const { text: sanitizedText, isError: toolIsError } = sanitizeMcpResult(result);\n\n // Slice 5: decision questions post-processing for discover_opportunities only.\n if (toolName === \"discover_opportunities\" && !toolIsError) {\n const questions = extractDecisionQuestions(sanitizedText);\n if (questions) {\n const envelopeBlock = {\n type: \"text\" as const,\n text: renderQuestionsEnvelope(questions),\n };\n\n const supportsElicitation =\n !!server.server.getClientCapabilities()?.elicitation;\n\n // Capture into a local const so TS preserves the narrowing\n // inside the callback below. Optional chains don't survive\n // across closure boundaries under strict mode.\n const elicitInput = ctx.mcpReq?.elicitInput;\n\n if (supportsElicitation && elicitInput) {\n // Sequential — never parallel (day-one rule). We await the loop\n // before returning the tool result so test harnesses can observe\n // the dispatched calls deterministically.\n await dispatchElicitations({\n userId,\n questions,\n elicitInput: (params) => elicitInput(params),\n chatMessageWriter: deps.chatMessageWriter,\n });\n }\n\n return {\n content: [\n { type: \"text\" as const, text: sanitizedText },\n envelopeBlock,\n ],\n ...(toolIsError ? { isError: true } : {}),\n };\n }\n }\n\n return {\n content: [{ type: 'text' as const, text: sanitizedText }],\n ...(toolIsError ? { isError: true } : {}),\n };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n logger.error(`MCP tool \"${toolName}\" failed`, { error: message });\n if (shouldReportMcpToolError(err)) {\n reportDeps.reportToolError?.(err, {\n subsystem: 'mcp',\n operation: 'mcp.tool',\n toolName,\n userId: reportUserId,\n tags: {\n transport: 'mcp',\n toolName,\n },\n context: {\n agentId: reportContext?.agentId,\n scopeType: reportContext?.scopeType,\n scopeId: reportContext?.scopeId,\n },\n });\n }\n const runtimeResult = toolRuntimeErrorToResult(err);\n return {\n content: [{ type: 'text' as const, text: runtimeResult ?? JSON.stringify({ error: message }) }],\n isError: true,\n };\n }\n },\n );\n }\n\n logger.verbose(`MCP server created with ${toolMetadata.length} tools`);\n return server;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"mcp.server.js","sourceRoot":"/","sources":["mcp/mcp.server.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAMzE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AACrE,OAAO,EAAE,uBAAuB,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAE5F,OAAO,EAAE,cAAc,EAAE,MAAM,sCAAsC,CAAC;AACtE,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAC;AACtE,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,wBAAwB,EAAE,MAAM,iCAAiC,CAAC;AAEhH,OA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,SAAS,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC;oBAC/F,OAAO,EAAE,IAAI;iBACd,CAAC;YACJ,CAAC;QACH,CAAC,CACF,CAAC;IACJ,CAAC;IAED,MAAM,CAAC,OAAO,CAAC,2BAA2B,YAAY,CAAC,MAAM,QAAQ,CAAC,CAAC;IACvE,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/**\n * MCP Server Factory — creates an McpServer instance with all protocol tools\n * registered from the existing tool registry. Each tool invocation resolves\n * auth from the HTTP request, builds a ResolvedToolContext, and delegates\n * to the raw tool handler.\n */\n\nimport { z } from 'zod';\nimport { McpServer, fromJsonSchema } from '@modelcontextprotocol/server';\nimport type { ServerContext, JsonSchemaType } from '@modelcontextprotocol/server';\n\nimport type { McpAuthResolver } from '../shared/interfaces/auth.interface.js';\nimport type { McpAuthInput } from '../shared/schemas/mcp-auth.schema.js';\nimport type { ToolDeps, ResolvedToolContext, RawToolDefinition } from '../shared/agent/tool.helpers.js';\nimport { resolveChatContext } from '../shared/agent/tool.helpers.js';\nimport { deriveAllowedNetworkIds, scopeFromNetworkId } from '../shared/agent/tool.scope.js';\nimport type { Question } from '../shared/schemas/question.schema.js';\nimport { QuestionSchema } from '../shared/schemas/question.schema.js';\nimport { dispatchElicitations } from './elicitation.dispatcher.js';\nimport { createToolRegistry } from '../shared/agent/tool.registry.js';\nimport { ToolRuntimeError, invokeToolRuntime, toolRuntimeErrorToResult } from '../shared/agent/tool.runtime.js';\nimport type { TraceEmitter } from '../shared/observability/request-context.js';\nimport { protocolLogger } from '../shared/observability/protocol.logger.js';\n\nconst logger = protocolLogger('McpServer');\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// STATIC TOOL METADATA CACHE\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Static registration metadata for one MCP tool — schema conversion artifacts\n * that depend only on registry-shaping feature flags, not on per-request\n * database scope.\n */\ntype McpToolRegistrationMetadata = Pick<RawToolDefinition, 'name' | 'description' | 'schema'> & {\n jsonSchema: JsonSchemaType;\n inputSchema: ReturnType<typeof fromJsonSchema>;\n};\n\nconst mcpToolMetadataCache = new Map<string, McpToolRegistrationMetadata[]>();\n\n/**\n * Builds a cache key from registry-shaping dependency booleans.\n * When a feature flag changes the tool set, the cache key changes so\n * the cached metadata set is automatically invalidated.\n */\nexport function getMcpToolMetadataCacheKey(deps: Pick<ToolDeps,\n 'contactsEnabled' | 'chatSession' | 'agentDatabase' | 'agentDispatcher' | 'questionerEnqueue'\n>): string {\n return [\n `contacts:${deps.contactsEnabled === true ? '1' : '0'}`,\n `chat:${deps.chatSession ? '1' : '0'}`,\n `agent:${deps.agentDatabase ? '1' : '0'}`,\n `negotiation:${deps.agentDispatcher ? '1' : '0'}`,\n `questioner:${deps.questionerEnqueue ? '1' : '0'}`,\n ].join('|');\n}\n\n/**\n * Clears the metadata cache. Used in tests to ensure fresh state between cases.\n */\nexport function clearMcpToolMetadataCacheForTests(): void {\n mcpToolMetadataCache.clear();\n}\n\n/**\n * Returns cached (or builds and caches) static MCP tool registration metadata.\n * The first call per cache key runs the full registry creation + schema\n * conversion; subsequent calls return the cached metadata array for the same\n * registry-shaping dependency profile.\n *\n * Does NOT store tool handlers — those remain request-scoped because they\n * capture per-request userDb/systemDb.\n */\nexport function getCachedMcpToolMetadata(deps: ToolDeps): readonly McpToolRegistrationMetadata[] {\n const cacheKey = getMcpToolMetadataCacheKey(deps);\n const cached = mcpToolMetadataCache.get(cacheKey);\n if (cached) return cached;\n\n const registry = createToolRegistry(deps);\n const metadata = Array.from(registry.values()).map((toolDef): McpToolRegistrationMetadata => {\n const jsonSchema = zodToJsonSchema(toolDef.schema) as JsonSchemaType;\n return {\n name: toolDef.name,\n description: toolDef.description,\n schema: toolDef.schema,\n jsonSchema,\n inputSchema: fromJsonSchema(jsonSchema),\n };\n });\n\n mcpToolMetadataCache.set(cacheKey, metadata);\n logger.verbose(`MCP tool metadata cached with ${metadata.length} tools`, { cacheKey });\n return metadata;\n}\n\nfunction isExpectedMcpAuthError(message: string): boolean {\n return message.includes('Authentication required') ||\n message.includes('Invalid API key') ||\n message.includes('Invalid or expired access token') ||\n message.includes('JWT payload missing user ID');\n}\n\n/**\n * Runtime/auth failures are converted into structured MCP `isError` tool\n * results for the caller. Reporting them as application exceptions produces\n * Sentry noise for expected client failures and policy-enforced timeouts.\n */\nexport function shouldReportMcpToolError(err: unknown): boolean {\n if (err instanceof ToolRuntimeError) return false;\n const message = err instanceof Error ? err.message : String(err);\n return !isExpectedMcpAuthError(message);\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// ZOD 3 → JSON SCHEMA CONVERSION\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Minimal Zod-to-JSON-Schema conversion for MCP tool registration.\n * Converts Zod 3.x schemas to plain JSON Schema objects that can be\n * wrapped with `fromJsonSchema()` for MCP SDK compatibility.\n */\nfunction zodToJsonSchema(schema: z.ZodType): Record<string, unknown> {\n if (schema instanceof z.ZodObject) {\n const shape = schema.shape;\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n for (const [key, value] of Object.entries(shape)) {\n const zodValue = value as z.ZodType;\n properties[key] = zodToJsonSchema(zodValue);\n if (!(zodValue instanceof z.ZodOptional) && !(zodValue instanceof z.ZodDefault)) {\n required.push(key);\n }\n }\n return { type: 'object', properties, ...(required.length ? { required } : {}) };\n }\n if (schema instanceof z.ZodString) {\n const result: Record<string, unknown> = { type: 'string' };\n // Detect .url(), .email(), .uuid() etc. via Zod's internal checks array\n const checks = (schema as z.ZodString & { _def: { checks: Array<{ kind: string }> } })._def?.checks;\n if (checks) {\n for (const check of checks) {\n if (check.kind === 'url') result.format = 'uri';\n else if (check.kind === 'email') result.format = 'email';\n else if (check.kind === 'uuid') result.format = 'uuid';\n else if (check.kind === 'datetime') result.format = 'date-time';\n }\n }\n return result;\n }\n if (schema instanceof z.ZodNumber) {\n const checks = (schema as z.ZodNumber & { _def: { checks: Array<{ kind: string; value?: number }> } })._def?.checks;\n const result: Record<string, unknown> = { type: 'number' };\n if (checks) {\n for (const check of checks) {\n if (check.kind === 'int') result.type = 'integer';\n else if (check.kind === 'min') result.minimum = check.value;\n else if (check.kind === 'max') result.maximum = check.value;\n }\n }\n return result;\n }\n if (schema instanceof z.ZodBoolean) return { type: 'boolean' };\n if (schema instanceof z.ZodArray) {\n return { type: 'array', items: zodToJsonSchema((schema as z.ZodArray<z.ZodType>).element) };\n }\n if (schema instanceof z.ZodOptional) {\n return zodToJsonSchema((schema as z.ZodOptional<z.ZodType>).unwrap());\n }\n if (schema instanceof z.ZodDefault) {\n return zodToJsonSchema((schema as z.ZodDefault<z.ZodType>).removeDefault());\n }\n if (schema instanceof z.ZodEnum) {\n return { type: 'string', enum: (schema as z.ZodEnum<[string, ...string[]]>).options };\n }\n if (schema instanceof z.ZodNullable) {\n const inner = zodToJsonSchema((schema as z.ZodNullable<z.ZodType>).unwrap());\n return { ...inner, nullable: true };\n }\n if (schema instanceof z.ZodRecord) {\n return { type: 'object', additionalProperties: true };\n }\n return { type: 'object' };\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// RESULT POST-PROCESSING\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Strips internal `_`-prefixed keys from `data` and promotes `isError`\n * from the inner `success: false` signal to the MCP envelope level.\n * Fail-open: if JSON parsing throws, returns the original text with isError: false.\n */\nexport function sanitizeMcpResult(text: string): { text: string; isError: boolean } {\n try {\n const parsed = JSON.parse(text);\n if (\n parsed &&\n typeof parsed === 'object' &&\n parsed.data &&\n typeof parsed.data === 'object' &&\n !Array.isArray(parsed.data)\n ) {\n for (const key of Object.keys(parsed.data)) {\n if (key.startsWith('_') || key === 'debugSteps') {\n delete parsed.data[key];\n }\n }\n }\n const isError = parsed?.success === false;\n return { text: JSON.stringify(parsed), isError };\n } catch {\n return { text, isError: false };\n }\n}\n\n/** Spec cap on the number of decision questions surfaced per turn. */\nconst MAX_DECISION_QUESTIONS = 3;\n\n/**\n * Extracts decision questions from a parsed tool-result text, if present.\n * Validates each entry against `QuestionSchema` and drops malformed items;\n * caps the array at `MAX_DECISION_QUESTIONS` (defense-in-depth — Slice 2's\n * generator already caps at 3, but we don't trust the cast here).\n *\n * Returns null when the text isn't JSON, has no `data.questions`, or\n * contains zero valid questions after validation.\n */\nexport function extractDecisionQuestions(text: string): Question[] | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return null;\n }\n\n const rawQs = (parsed as { data?: { questions?: unknown } } | null)?.data?.questions;\n if (!Array.isArray(rawQs) || rawQs.length === 0) return null;\n\n const valid: Question[] = [];\n for (const raw of rawQs) {\n const result = QuestionSchema.safeParse(raw);\n if (result.success) valid.push(result.data);\n if (valid.length === MAX_DECISION_QUESTIONS) break;\n }\n return valid.length > 0 ? valid : null;\n}\n\n/**\n * Renders the JSON-envelope text block appended to the tool result content\n * when decision questions are present. The leading sentinel string lets the\n * LLM client recognize and surface the questions in prose for clients\n * without elicitation support.\n */\nexport function renderQuestionsEnvelope(questions: Question[]): string {\n return `Decision questions (structured): ${JSON.stringify({ questions })}`;\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// MCP SERVER FACTORY\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Factory for creating per-request scoped database instances.\n * Injected from the controller/handler layer to keep the protocol layer\n * free of direct adapter imports.\n */\nexport interface ScopedDepsFactory {\n /** Creates scoped userDb and systemDb for the given user and allowed network IDs. */\n create(userId: string, allowedNetworkIds: string[]): Pick<ToolDeps, 'userDb' | 'systemDb'>;\n}\n\n/**\n * Computes the concrete network IDs passed to the per-request scoped DB factory.\n * When a network scope is present, the agent reaches that network plus the\n * user's personal network. Otherwise the full membership set is returned.\n */\nexport const computeAgentAllowedNetworkIds = (\n userNetworks: { networkId: string; isPersonal?: boolean | null }[],\n scopeType: 'network' | undefined,\n scopeId: string | null | undefined,\n): string[] => deriveAllowedNetworkIds({\n memberships: userNetworks,\n ...(scopeType && scopeId ? { scopeType, scopeId } : {}),\n});\n\n/**\n * Promotes a network-scoped agent's bound network into the resolved tool\n * context as the implicit chat scope. Every tool derives its focused network\n * from the `scopeType`/`scopeId` envelope; without this step scoped API-key\n * calls would still resolve an unscoped/global view.\n *\n * No-op when there is no scope, or when an explicit scope is already set\n * (a user-driven network-scoped chat must keep precedence over the agent\n * binding — which would be a strict subset anyway, since the API key cannot\n * reach beyond its bound network).\n */\nexport const applyNetworkScopeToContext = (\n context: ResolvedToolContext,\n networkScopeId: string | null | undefined,\n): void => {\n if (!networkScopeId) return;\n if (context.scopeType && context.scopeId) return;\n\n const scope = scopeFromNetworkId(networkScopeId);\n context.scopeType = scope.scopeType;\n context.scopeId = scope.scopeId;\n\n const bound = context.userNetworks.find((m) => m.networkId === networkScopeId);\n if (!bound) return;\n\n context.indexName = bound.networkTitle;\n context.scopedIndex = {\n id: bound.networkId,\n title: bound.networkTitle,\n prompt: bound.indexPrompt ?? null,\n };\n const isOwner = bound.permissions?.includes('owner') ?? false;\n context.scopedMembershipRole = isOwner ? 'owner' : 'member';\n context.isOwner = isOwner;\n};\n\n/**\n * Tools allowed during onboarding — everything else is gated until\n * complete_onboarding is called. Includes the agent-gate-exempt tools\n * (register_agent, read_docs, scrape_url) because they are informational /\n * registration primitives needed at every lifecycle stage.\n */\nexport const ONBOARDING_ALLOWED: ReadonlySet<string> = new Set([\n 'register_agent',\n 'read_docs',\n 'scrape_url',\n 'record_onboarding_privacy_consent',\n // Canonical *_user_context / *_enrichment_run names (IND-371)\n 'preview_user_context',\n 'get_enrichment_run',\n 'cancel_enrichment_run',\n 'confirm_user_context',\n 'create_user_context',\n 'read_user_contexts',\n // Deprecated aliases retained so mid-migration clients can still onboard (IND-373 removes them)\n 'preview_user_profile',\n 'get_profile_run',\n 'cancel_profile_run',\n 'confirm_user_profile',\n 'create_user_profile',\n 'read_user_profiles',\n 'complete_onboarding',\n 'import_gmail_contacts',\n 'read_networks',\n 'create_network_membership',\n 'create_intent',\n]);\n\n/**\n * Builds the onboarding gate message for MCP callers. Condensed from the\n * chat orchestrator's 8-step flow (chat.prompt.ts buildOnboarding) into a\n * 7-step tool-error guide suited for non-interactive MCP clients.\n */\nexport function buildMcpOnboardingMessage(ctx: ResolvedToolContext): string {\n const nameStep = ctx.hasName\n ? `1. Greet the user and confirm their name (\"You're ${ctx.userName}, right?\").`\n : `1. Ask the user for their name and a short self-description.`;\n\n const communityStep = ctx.networkId\n ? `5. (Skipped — user is already in \"${ctx.indexName ?? 'their community'}\".)`\n : `5. Call read_networks() and let the user pick communities to join via create_network_membership(networkId=...).`;\n\n const allowedList = Array.from(ONBOARDING_ALLOWED).join(', ');\n\n return (\n `This user has not completed onboarding. You must guide them through setup before they can use other tools. ` +\n `Only the following tools are available until onboarding is complete: ` +\n `${allowedList}.\\n\\n` +\n `Onboarding flow:\\n` +\n `${nameStep}\\n` +\n `2. Ask whether the user allows use of event/EdgeOS profile data, then call record_onboarding_privacy_consent(edgeosImportGranted=...).\\n` +\n `3. Ask separately whether the user allows public internet/profile lookup, then call record_onboarding_privacy_consent(publicProfileLookupGranted=...).\\n` +\n `4. Call preview_user_context(...) using only allowed inputs; do not run public lookup unless consent was granted. If it returns profileRunId, poll get_enrichment_run(profileRunId=...) until status is succeeded, then use its result as the draft.\\n` +\n `5. Present the profile draft and ask \"Does that look right?\" On approval/correction, call confirm_user_context(...).\\n` +\n `${communityStep}\\n` +\n `6. Ask what the user is looking for and call create_intent(description=\"...\", autoApprove=true) so the first signal is persisted.\\n` +\n `7. Call complete_onboarding() to finish setup. Gmail/contact import and discovery are optional after onboarding, never mandatory.`\n );\n}\n\n/**\n * Creates an MCP server with all protocol tools registered.\n * Tools resolve auth per-request via the HTTP request available in ServerContext.\n *\n * @param deps - Shared tool dependencies (graphs, database, embedder, etc.)\n * @param authResolver - Resolves authenticated identity from the HTTP request\n * @param scopedDepsFactory - Factory for creating per-request scoped databases\n * @returns A configured McpServer ready to be connected to a transport\n */\nfunction createMcpTraceEmitter(toolName: string, ctx: ServerContext): TraceEmitter | undefined {\n const token = ctx.mcpReq._meta?.progressToken;\n if (typeof token !== 'string' && typeof token !== 'number') return undefined;\n\n let progress = 0;\n return (event) => {\n progress += 1;\n const message = (() => {\n if (event.type === 'graph_start') return `${toolName}: ${event.name} started`;\n if (event.type === 'graph_end') return `${toolName}: ${event.name} finished${event.durationMs != null ? ` in ${event.durationMs}ms` : ''}`;\n if (event.type === 'agent_start') return `${toolName}: ${event.name} agent started`;\n if (event.type === 'agent_end') return `${toolName}: ${event.name} agent finished${event.durationMs != null ? ` in ${event.durationMs}ms` : ''}`;\n if (event.type === 'opportunity_draft_ready') return `${toolName}: opportunity draft ready`;\n return `${toolName}: progress`;\n })();\n\n const notification: Parameters<ServerContext['mcpReq']['notify']>[0] = {\n method: 'notifications/progress',\n params: { progressToken: token, progress, message },\n };\n void ctx.mcpReq.notify(notification).catch((err) => {\n logger.debug('Failed to send MCP progress notification', {\n toolName,\n error: err instanceof Error ? err.message : String(err),\n });\n });\n };\n}\n\nexport const MCP_INSTRUCTIONS = `\nIndex Network is a private, intent-driven discovery protocol. You help users find the right people and help the right people find them, via Index Network MCP tools.\n\n# Voice\nCalm, direct, analytical, concise. Preferred vocabulary: opportunity, overlap, signal, pattern, emerging, relevant, adjacency.\n\n# Banned vocabulary\nNEVER use \"search\" in any form. Use \"looking up\" for indexed data, \"find\" / \"look for\" for discovery, \"check\" for verification, \"discover\" for exploration. Banned: leverage, unlock, optimize, scale, disrupt, revolutionary, AI-powered, maximize value, act fast, networking, match.\n\n# Entity model\n- User — has one Profile, many Memberships, many Intents.\n- Profile — identity (bio, skills, interests, location).\n- Index — community with title, prompt (purpose), join policy. Has Members.\n- Membership — User↔Index junction. \\`isPersonal: true\\` marks the user's personal network (contacts).\n- Intent — what a user is looking for (signal). Description, summary, embedding.\n- IntentIndex — Intent↔Index junction (auto-assigned).\n- Opportunity — discovered connection between users. Roles, status, reasoning.\n\n# Output rules\n- NEVER expose internal IDs, UUIDs, field names, or tool names — EXCEPT when an ID is actionable for the user (e.g. a \\`conversationId\\` they need to open a chat). Surface such IDs verbatim when the tool returns them.\n- NEVER use internal vocabulary — say \"signal\" not \"intent\", \"community\" not \"index\".\n- NEVER dump raw JSON. Synthesize in natural language.\n- Surface top 1–3 relevant points unless asked for the full list.\n- Prefer first names; use full names only to disambiguate.\n- Translate statuses: draft/latent → \"draft\", pending → \"sent\", accepted → \"connected\".\n- NEVER fabricate data. If you don't have it, call the appropriate tool.\n\n# Tool guidance\nEach tool's description contains its own usage rules (when to call, when NOT to call, required prerequisites, post-call follow-ups). Read the description of every tool you call — that is where the per-tool workflow patterns live.\n\n# Authentication\nPass your API key in the \\`x-api-key\\` request header (not \\`Authorization: Bearer\\`).\n\n# Opportunity lifecycle\nOpportunities move through: draft → pending → accepted (or rejected).\n\n- **draft** (you created it, not yet sent): offer to send it; confirm before calling update_opportunity with pending.\n- **pending, you sent it**: waiting for the other side — nothing to do.\n- **pending, you received it**: the other person is waiting for your response. Surface it to the user and ask if they want to start a chat. Only call update_opportunity with accepted after explicit user confirmation.\n- **accepted**: both sides are connected — a direct conversation exists. Surface the conversationId to the user if available.\n\nNever accept a received opportunity without explicit user approval in the current conversation.\n\n# Decision questions after discovery\n\nAfter \\`discover_opportunities\\`, the tool result may include a second text block starting with \\`Decision questions (structured): ...\\`. This means the discovery engine ran negotiations but needs human input to sharpen the next turn — e.g. clarify timing, role, stage, or location.\n\n**When this block is present:**\n1. Parse the \\`questions\\` array from the JSON after the sentinel.\n2. Each question has \\`title\\` (decision domain, ≤12 chars), \\`prompt\\` (ends in \\`?\\`), \\`options\\` (2–4 items, each with \\`label\\` and \\`description\\`), and \\`multiSelect\\`. The safest option is labeled \\`... (Recommended)\\`.\n3. Present each question in natural language: ask the \\`prompt\\`, list options as \\`**{label}** — {description}\\`. Never expose the JSON or technical field names.\n4. Wait for the user's answer, then fold it into the next \\`discover_opportunities(searchQuery=...)\\` call.\n\n**Elicitation-capable clients** (those that declared \\`elicitation\\` support in \\`initialize\\`): the server dispatches \\`elicitation/create\\` requests directly — answers are written back to the chat session automatically. You will not see the envelope as a follow-up task in that case.\n`.trim();\n\n/**\n * Extracts a Bearer token from an HTTP Authorization header.\n */\nexport function extractBearerToken(req: Request): string | undefined {\n const authHeader = req.headers.get('Authorization');\n if (!authHeader) return undefined;\n const [scheme, token] = authHeader.trim().split(/\\s+/, 2);\n if (scheme?.toLowerCase() === 'bearer' && token) return token;\n return undefined;\n}\n\n/**\n * Normalizes the x-index-surface header to a typed surface value.\n * Unknown or absent values collapse to 'web'.\n */\nlet hasWarnedInvalidSurface = false;\nexport function parseClientSurface(raw: string | null): 'telegram' | 'web' {\n if (raw === null || raw === '') return 'web';\n const trimmed = raw.trim().toLowerCase();\n if (trimmed === '') return 'web';\n if (trimmed === 'telegram') return 'telegram';\n if (trimmed === 'web') return 'web';\n if (!hasWarnedInvalidSurface) {\n hasWarnedInvalidSurface = true;\n logger.warn('Unknown x-index-surface value (collapsing to web; warning once per process)');\n }\n return 'web';\n}\n\nexport function createMcpServer(\n deps: ToolDeps,\n authResolver: McpAuthResolver,\n scopedDepsFactory: ScopedDepsFactory,\n): McpServer {\n // Tools exempt from the agent-registration gate — available before registration is complete.\n const AGENT_GATE_EXEMPT = new Set(['register_agent', 'read_docs', 'scrape_url']);\n\n const server = new McpServer(\n { name: 'index-network', version: '1.0.0' },\n { instructions: MCP_INSTRUCTIONS },\n );\n\n const toolMetadata = getCachedMcpToolMetadata(deps);\n\n for (const toolDef of toolMetadata) {\n const toolName = toolDef.name;\n\n server.registerTool(\n toolName,\n {\n description: toolDef.description,\n inputSchema: toolDef.inputSchema,\n },\n async (args: unknown, ctx: ServerContext) => {\n let reportDeps = deps;\n let reportUserId: string | undefined;\n let reportContext: ResolvedToolContext | undefined;\n\n try {\n // Extract the original HTTP request from the MCP server context\n const httpReq = ctx.http?.req;\n if (!httpReq) {\n return {\n content: [{ type: 'text' as const, text: JSON.stringify({ error: 'No HTTP request available in MCP context' }) }],\n isError: true,\n };\n }\n\n // Extract transport-neutral auth input DTO from the HTTP request\n const mcpAuthInput: McpAuthInput = {\n bearerToken: extractBearerToken(httpReq),\n apiKey: httpReq.headers.get('x-api-key') ?? undefined,\n clientSurface: parseClientSurface(httpReq.headers.get('x-index-surface')),\n telegramHandle: httpReq.headers.get('x-index-telegram-handle') ?? undefined,\n telegramUsername: httpReq.headers.get('x-index-telegram-username') ?? undefined,\n };\n\n // Resolve authenticated identity from the auth input DTO\n const { userId, agentId, isSessionAuth, networkScopeId, clientSurface } = await authResolver.resolveIdentity(mcpAuthInput);\n reportUserId = userId;\n\n // Per-principal MCP throttle. Runs BEFORE any DB work so a throttled\n // call short-circuits cheaply. The /mcp transport bypasses the\n // controller-level RateLimit guard, so this is the only volume cap on\n // tool calls — it stops an over-eager agent from cascading itself into\n // provider rate limits.\n if (deps.mcpRateLimiter) {\n // Throttling is best-effort: never let a limiter failure (or a host\n // implementation that throws instead of failing open) break tool\n // dispatch. Treat any error as \"allowed\".\n let decision: Awaited<ReturnType<NonNullable<typeof deps.mcpRateLimiter>>> | null = null;\n try {\n decision = await deps.mcpRateLimiter({\n userId,\n ...(agentId ? { agentId } : {}),\n toolName,\n });\n } catch (rlErr) {\n logger.warn(`MCP rate limiter threw for \"${toolName}\" — failing open`, {\n error: rlErr instanceof Error ? rlErr.message : String(rlErr),\n });\n }\n if (decision && !decision.allowed) {\n const retryAfterSec = decision.retryAfterSec ?? 60;\n return {\n content: [{\n type: 'text' as const,\n text: JSON.stringify({\n error: 'Rate limit exceeded',\n message:\n `Too many ${toolName} calls in a short period. Wait ${retryAfterSec}s before retrying.` +\n (toolName === 'discover_opportunities'\n ? ` If a discovery run is in progress, poll get_discovery_run instead of calling discover_opportunities again.`\n : ''),\n retryAfterSec,\n }),\n }],\n isError: true,\n };\n }\n }\n\n // Resolve chat context for the user (mark as MCP — no interactive UI available)\n const context = await resolveChatContext({ database: deps.database, userId, contactsEnabled: deps.contactsEnabled });\n reportContext = context;\n context.isMcp = true;\n if (agentId) {\n context.agentId = agentId;\n }\n if (clientSurface) {\n context.clientSurface = clientSurface;\n }\n\n // Network-scoped agents inherit their bound network as the implicit chat\n // scope. Tools consume the scope envelope and derive any concrete\n // allowed network IDs from it plus the user's memberships.\n applyNetworkScopeToContext(context, networkScopeId);\n\n // Gate: API-key callers (background agents) must register before using most tools.\n // OAuth/JWT session callers (human MCP clients such as Claude Code) are exempt —\n // their identity is already established via the auth flow and they have no agent entity.\n if (!isSessionAuth && !context.agentId && !AGENT_GATE_EXEMPT.has(toolName)) {\n return {\n content: [{\n type: 'text' as const,\n text: JSON.stringify({\n error: 'Agent not registered',\n message:\n 'You must register as an agent before using Index tools. ' +\n 'Call register_agent with your agent name to establish an identity. ' +\n 'The tools register_agent, read_docs, and scrape_url are available without registration.',\n }),\n }],\n isError: true,\n };\n }\n\n // Gate: non-onboarded users can only use onboarding-related tools.\n // Mirrors the chat orchestrator's ONBOARDING MODE — the MCP client must\n // walk the user through profile creation, Gmail connect, intent capture,\n // and complete_onboarding() before full tool access is granted.\n if (context.isOnboarding && !ONBOARDING_ALLOWED.has(toolName)) {\n const onboardingSteps = buildMcpOnboardingMessage(context);\n return {\n content: [{\n type: 'text' as const,\n text: JSON.stringify({\n error: 'Onboarding required',\n message: onboardingSteps,\n }),\n }],\n isError: true,\n };\n }\n\n // Build per-request scoped databases via injected factory.\n // Network-scoped agents are clamped to their bound network plus the user's\n // personal network — they cannot reach other networks even when the user is\n // a member of them. The personal-index reachability is preserved so the\n // agent can still manage its owner's profile and contacts.\n const allowedNetworkIds = deriveAllowedNetworkIds({\n memberships: context.userNetworks,\n ...(context.scopeType && context.scopeId\n ? { scopeType: context.scopeType, scopeId: context.scopeId }\n : {}),\n });\n const scopedDbs = scopedDepsFactory.create(userId, allowedNetworkIds);\n\n // Override deps with per-request scoped databases\n const requestDeps: ToolDeps = { ...deps, ...scopedDbs };\n reportDeps = requestDeps;\n\n // Re-create registry with per-request deps for scoped database access.\n // Do not use cached registration metadata handlers here: tool handlers\n // close over userDb/systemDb when the registry is created.\n const requestRegistry = createToolRegistry(requestDeps);\n const requestTool = requestRegistry.get(toolName);\n\n if (!requestTool) {\n return {\n content: [{ type: 'text' as const, text: JSON.stringify({ error: `Tool \"${toolName}\" not found` }) }],\n isError: true,\n };\n }\n\n // Validate input against the original Zod schema\n const parseResult = (toolDef.schema as z.ZodType).safeParse(args);\n if (!parseResult.success) {\n const issues = parseResult.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ');\n return {\n content: [{ type: 'text' as const, text: JSON.stringify({ success: false, error: `Invalid input: ${issues}` }) }],\n isError: true,\n };\n }\n const validatedArgs = parseResult.data;\n\n // Execute the tool handler through the shared runtime so MCP calls have\n // consistent timeout, cancellation, progress, and requestContext plumbing.\n const result = await invokeToolRuntime({\n toolName,\n tool: requestTool,\n context,\n query: validatedArgs,\n signal: ctx.mcpReq.signal,\n traceEmitter: createMcpTraceEmitter(toolName, ctx),\n });\n\n const { text: sanitizedText, isError: toolIsError } = sanitizeMcpResult(result);\n\n // Slice 5: decision questions post-processing for discover_opportunities only.\n if (toolName === \"discover_opportunities\" && !toolIsError) {\n const questions = extractDecisionQuestions(sanitizedText);\n if (questions) {\n const envelopeBlock = {\n type: \"text\" as const,\n text: renderQuestionsEnvelope(questions),\n };\n\n const supportsElicitation =\n !!server.server.getClientCapabilities()?.elicitation;\n\n // Capture into a local const so TS preserves the narrowing\n // inside the callback below. Optional chains don't survive\n // across closure boundaries under strict mode.\n const elicitInput = ctx.mcpReq?.elicitInput;\n\n if (supportsElicitation && elicitInput) {\n // Sequential — never parallel (day-one rule). We await the loop\n // before returning the tool result so test harnesses can observe\n // the dispatched calls deterministically.\n await dispatchElicitations({\n userId,\n questions,\n elicitInput: (params) => elicitInput(params),\n chatMessageWriter: deps.chatMessageWriter,\n });\n }\n\n return {\n content: [\n { type: \"text\" as const, text: sanitizedText },\n envelopeBlock,\n ],\n ...(toolIsError ? { isError: true } : {}),\n };\n }\n }\n\n return {\n content: [{ type: 'text' as const, text: sanitizedText }],\n ...(toolIsError ? { isError: true } : {}),\n };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n logger.error(`MCP tool \"${toolName}\" failed`, { error: message });\n if (shouldReportMcpToolError(err)) {\n reportDeps.reportToolError?.(err, {\n subsystem: 'mcp',\n operation: 'mcp.tool',\n toolName,\n userId: reportUserId,\n tags: {\n transport: 'mcp',\n toolName,\n },\n context: {\n agentId: reportContext?.agentId,\n scopeType: reportContext?.scopeType,\n scopeId: reportContext?.scopeId,\n },\n });\n }\n const runtimeResult = toolRuntimeErrorToResult(err);\n return {\n content: [{ type: 'text' as const, text: runtimeResult ?? JSON.stringify({ error: message }) }],\n isError: true,\n };\n }\n },\n );\n }\n\n logger.verbose(`MCP server created with ${toolMetadata.length} tools`);\n return server;\n}\n"]}
|
|
@@ -7,10 +7,10 @@ import { type AssignmentResult } from "./indexer.state.js";
|
|
|
7
7
|
*
|
|
8
8
|
* Handles CRUD for the intent_indexes junction table:
|
|
9
9
|
* - create: Assign an intent to an index (direct or evaluated via IntentIndexer agent)
|
|
10
|
-
* - read: List intent-
|
|
10
|
+
* - read: List intent-network links (by intentId or by networkId)
|
|
11
11
|
* - delete: Unassign an intent from an index
|
|
12
12
|
*
|
|
13
|
-
* The evaluate-based assignment flow is migrated from the old
|
|
13
|
+
* The evaluate-based assignment flow is migrated from the old Network Graph.
|
|
14
14
|
*/
|
|
15
15
|
export declare class IntentNetworkGraphFactory {
|
|
16
16
|
private database;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"indexer.graph.d.ts","sourceRoot":"/","sources":["network/indexer/indexer.graph.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAE/D,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,+CAA+C,CAAC;AAIhG,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AAGzE,OAAO,EAA2B,KAAK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A4B,CAAC;;;;;;;;;2BAHxB,CAAC;4BACF,CAAP;sBAAsB,CAAC;wBACf,CAAC;yBACF,CAAJ;8BAA4B,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2BAHxB,CAAC;4BACF,CAAP;sBAAsB,CAAC;wBACf,CAAC;yBACF,CAAJ;8BAA4B,CAAC;;;;;;;;;2BAHxB,CAAC;4BACF,CAAP;sBAAsB,CAAC;wBACf,CAAC;yBACF,CAAJ;8BAA4B,CAAC;;;;;;;;;2BAHxB,CAAC;4BACF,CAAP;sBAAsB,CAAC;wBACf,CAAC;yBACF,CAAJ;8BAA4B,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;8BAOyC,gBAAgB;;;;;;;;;;;8BAed,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;8BA0FlB,gBAAgB;;;;;;;;;;;;;;;8BAUjB,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqM9F"}
|
|
@@ -11,10 +11,10 @@ const logger = protocolLogger("IntentNetworkGraphFactory");
|
|
|
11
11
|
*
|
|
12
12
|
* Handles CRUD for the intent_indexes junction table:
|
|
13
13
|
* - create: Assign an intent to an index (direct or evaluated via IntentIndexer agent)
|
|
14
|
-
* - read: List intent-
|
|
14
|
+
* - read: List intent-network links (by intentId or by networkId)
|
|
15
15
|
* - delete: Unassign an intent from an index
|
|
16
16
|
*
|
|
17
|
-
* The evaluate-based assignment flow is migrated from the old
|
|
17
|
+
* The evaluate-based assignment flow is migrated from the old Network Graph.
|
|
18
18
|
*/
|
|
19
19
|
export class IntentNetworkGraphFactory {
|
|
20
20
|
constructor(database, intentNetworker) {
|
|
@@ -77,7 +77,7 @@ export class IntentNetworkGraphFactory {
|
|
|
77
77
|
mutationResult: { success: true, message: "Intent saved to the network." },
|
|
78
78
|
};
|
|
79
79
|
}
|
|
80
|
-
// Evaluated assignment (migrated from old
|
|
80
|
+
// Evaluated assignment (migrated from old Network Graph)
|
|
81
81
|
const intentForIndexing = await this.database.getIntentForIndexing(intentId);
|
|
82
82
|
if (!intentForIndexing) {
|
|
83
83
|
return { agentTimings: agentTimingsAccum, mutationResult: { success: false, error: "Intent not found for networking." } };
|
|
@@ -100,7 +100,7 @@ export class IntentNetworkGraphFactory {
|
|
|
100
100
|
scope: "network",
|
|
101
101
|
indexPrompt,
|
|
102
102
|
memberPrompt,
|
|
103
|
-
evaluator: "intent-
|
|
103
|
+
evaluator: "intent-networker",
|
|
104
104
|
source: "intent-network-graph",
|
|
105
105
|
createdAt: new Date().toISOString(),
|
|
106
106
|
});
|
|
@@ -127,7 +127,7 @@ export class IntentNetworkGraphFactory {
|
|
|
127
127
|
: null;
|
|
128
128
|
const _traceEmitterIndexer = requestContext.getStore()?.traceEmitter;
|
|
129
129
|
const _indexerStart = Date.now();
|
|
130
|
-
_traceEmitterIndexer?.({ type: "agent_start", name: "intent-
|
|
130
|
+
_traceEmitterIndexer?.({ type: "agent_start", name: "intent-networker" });
|
|
131
131
|
let result = null;
|
|
132
132
|
try {
|
|
133
133
|
result = await indexer.evaluate(intentForIndexing.payload, indexPrompt, memberPrompt, sourceName, renderedContext);
|
|
@@ -135,7 +135,7 @@ export class IntentNetworkGraphFactory {
|
|
|
135
135
|
finally {
|
|
136
136
|
const _indexerMs = Date.now() - _indexerStart;
|
|
137
137
|
agentTimingsAccum.push({ name: 'intent.indexer', durationMs: _indexerMs });
|
|
138
|
-
_traceEmitterIndexer?.({ type: "agent_end", name: "intent-
|
|
138
|
+
_traceEmitterIndexer?.({ type: "agent_end", name: "intent-networker", durationMs: _indexerMs, summary: result ? `Scored: index=${result.indexScore.toFixed(2)}, member=${result.memberScore.toFixed(2)}` : "intent-networker failed" });
|
|
139
139
|
}
|
|
140
140
|
if (!result) {
|
|
141
141
|
return {
|
|
@@ -153,7 +153,7 @@ export class IntentNetworkGraphFactory {
|
|
|
153
153
|
indexPrompt,
|
|
154
154
|
memberPrompt,
|
|
155
155
|
rawScores: { indexScore: result.indexScore, memberScore: result.memberScore },
|
|
156
|
-
evaluator: "intent-
|
|
156
|
+
evaluator: "intent-networker",
|
|
157
157
|
source: "intent-network-graph",
|
|
158
158
|
reason: result.reasoning,
|
|
159
159
|
createdAt: new Date().toISOString(),
|
|
@@ -185,8 +185,8 @@ export class IntentNetworkGraphFactory {
|
|
|
185
185
|
});
|
|
186
186
|
};
|
|
187
187
|
/**
|
|
188
|
-
* Read Node: Query intent-
|
|
189
|
-
* - By intentId only: list all
|
|
188
|
+
* Read Node: Query intent-network relationships.
|
|
189
|
+
* - By intentId only: list all networks the intent is in (owner only)
|
|
190
190
|
* - By networkId only: list intents in the index (member only)
|
|
191
191
|
* - By both intentId and networkId: check if specific link exists (owner only)
|
|
192
192
|
*/
|
|
@@ -194,9 +194,9 @@ export class IntentNetworkGraphFactory {
|
|
|
194
194
|
return timed("IntentNetworkGraph.read", async () => {
|
|
195
195
|
const intentId = state.intentId;
|
|
196
196
|
const networkId = state.networkId;
|
|
197
|
-
logger.verbose("Read intent-
|
|
197
|
+
logger.verbose("Read intent-network links", { userId: state.userId, intentId, networkId, queryUserId: state.queryUserId });
|
|
198
198
|
try {
|
|
199
|
-
// By both: check if specific intent-
|
|
199
|
+
// By both: check if specific intent-network link exists
|
|
200
200
|
if (intentId && networkId) {
|
|
201
201
|
const intent = await this.database.getIntent(intentId);
|
|
202
202
|
if (!intent) {
|
|
@@ -215,7 +215,7 @@ export class IntentNetworkGraphFactory {
|
|
|
215
215
|
},
|
|
216
216
|
};
|
|
217
217
|
}
|
|
218
|
-
// By intent only: list all
|
|
218
|
+
// By intent only: list all networks for this intent
|
|
219
219
|
if (intentId) {
|
|
220
220
|
const intent = await this.database.getIntent(intentId);
|
|
221
221
|
if (!intent) {
|
|
@@ -289,7 +289,7 @@ export class IntentNetworkGraphFactory {
|
|
|
289
289
|
};
|
|
290
290
|
}
|
|
291
291
|
catch (err) {
|
|
292
|
-
logger.error("Read intent-
|
|
292
|
+
logger.error("Read intent-network failed", { error: err });
|
|
293
293
|
return { error: "Failed to fetch intent-network links." };
|
|
294
294
|
}
|
|
295
295
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"indexer.graph.js","sourceRoot":"/","sources":["network/indexer/indexer.graph.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAG9D,OAAO,EAAE,8BAA8B,EAAE,MAAM,sDAAsD,CAAC;AAEtG,OAAO,EAAE,cAAc,EAAE,MAAM,+CAA+C,CAAC;AAC/E,OAAO,EAAE,KAAK,EAAE,MAAM,2CAA2C,CAAC;AAClE,OAAO,EAAE,cAAc,EAAE,MAAM,+CAA+C,CAAC;AAE/E,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AAEjF,OAAO,EAAE,uBAAuB,EAAyB,MAAM,oBAAoB,CAAC;AAEpF,MAAM,MAAM,GAAG,cAAc,CAAC,2BAA2B,CAAC,CAAC;AAE3D;;;;;;;;;GASG;AACH,MAAM,OAAO,yBAAyB;IACpC,YACU,QAAoC,EACpC,eAA8B;QAD9B,aAAQ,GAAR,QAAQ,CAA4B;QACpC,oBAAe,GAAf,eAAe,CAAe;IACrC,CAAC;IAEG,WAAW;QAChB,MAAM,OAAO,GAAG,IAAI,CAAC,eAAe,CAAC;QAErC,2BAA2B;QAE3B;;;;;WAKG;QACH,MAAM,UAAU,GAAG,KAAK,EAAE,KAA2C,EAAE,EAAE;YACvE,OAAO,KAAK,CAAC,2BAA2B,EAAE,KAAK,IAAI,EAAE;gBACnD,MAAM,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;gBAChC,MAAM,SAAS,GAAG,KAAK,CAAC,SAAS,CAAC;gBAClC,MAAM,CAAC,OAAO,CAAC,wBAAwB,EAAE,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAA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F","sourcesContent":["import { StateGraph, START, END } from \"@langchain/langgraph\";\n\nimport { IntentIndexer } from \"../../intent/intent.indexer.js\";\nimport { buildNetworkAssignmentDecision } from \"../../shared/assignment/network-assignment.policy.js\";\nimport type { IntentNetworkGraphDatabase } from \"../../shared/interfaces/database.interface.js\";\nimport { protocolLogger } from \"../../shared/observability/protocol.logger.js\";\nimport { timed } from \"../../shared/observability/performance.js\";\nimport { requestContext } from \"../../shared/observability/request-context.js\";\nimport type { DebugMetaAgent } from \"../../chat/chat-streaming.types.js\";\nimport { renderNetworkContext } from \"../../shared/network/metadata.renderer.js\";\n\nimport { IntentNetworkGraphState, type AssignmentResult } from \"./indexer.state.js\";\n\nconst logger = protocolLogger(\"IntentNetworkGraphFactory\");\n\n/**\n * Factory class to build and compile the Intent Index Graph.\n *\n * Handles CRUD for the intent_indexes junction table:\n * - create: Assign an intent to an index (direct or evaluated via IntentIndexer agent)\n * - read: List intent-index links (by intentId or by networkId)\n * - delete: Unassign an intent from an index\n *\n * The evaluate-based assignment flow is migrated from the old Index Graph.\n */\nexport class IntentNetworkGraphFactory {\n constructor(\n private database: IntentNetworkGraphDatabase,\n private intentNetworker: IntentIndexer,\n ) {}\n\n public createGraph() {\n const indexer = this.intentNetworker;\n\n // --- NODE DEFINITIONS ---\n\n /**\n * Assign Node: Assign an intent to an index.\n * Two sub-paths:\n * - Direct assignment (skipEvaluation=true): assign immediately\n * - Evaluated assignment (skipEvaluation=false): load intent + index context, evaluate via IntentIndexer\n */\n const assignNode = async (state: typeof IntentNetworkGraphState.State) => {\n return timed(\"IntentNetworkGraph.assign\", async () => {\n const intentId = state.intentId;\n const networkId = state.networkId;\n logger.verbose(\"Assign intent to index\", { userId: state.userId, intentId, networkId, skipEvaluation: state.skipEvaluation });\n\n const agentTimingsAccum: DebugMetaAgent[] = [];\n\n if (!intentId || !networkId) {\n return { agentTimings: agentTimingsAccum, mutationResult: { success: false, error: \"Both intentId and networkId are required.\" } };\n }\n\n try {\n // Validate ownership and membership\n const intent = await this.database.getIntent(intentId);\n if (!intent) {\n return { agentTimings: agentTimingsAccum, mutationResult: { success: false, error: \"Intent not found.\" } };\n }\n if (intent.userId !== state.userId) {\n return { agentTimings: agentTimingsAccum, mutationResult: { success: false, error: \"You can only add your own intents to a network.\" } };\n }\n const [isMember, isOwner] = await Promise.all([\n this.database.isNetworkMember(networkId, state.userId),\n this.database.isIndexOwner(networkId, state.userId),\n ]);\n if (!isMember && !isOwner) {\n return { agentTimings: agentTimingsAccum, mutationResult: { success: false, error: \"You are not a member of that network.\" } };\n }\n\n // Check if already assigned\n const alreadyAssigned = await this.database.isIntentAssignedToIndex(intentId, networkId);\n if (alreadyAssigned) {\n return { agentTimings: agentTimingsAccum, mutationResult: { success: true, message: \"That intent is already in this network.\" } };\n }\n\n // Direct assignment (skip evaluation)\n if (state.skipEvaluation) {\n const decision = buildNetworkAssignmentDecision({\n resourceType: \"intent\",\n mode: \"manual_override\",\n scope: \"network\",\n evaluator: \"intent-network-graph\",\n source: \"manual-index-assignment\",\n createdAt: new Date().toISOString(),\n });\n await this.database.assignIntentToNetwork(intentId, networkId, decision.finalScore, decision.metadata);\n return {\n agentTimings: agentTimingsAccum,\n assignmentResult: { networkId, assigned: true, success: true } as AssignmentResult,\n mutationResult: { success: true, message: \"Intent saved to the network.\" },\n };\n }\n\n // Evaluated assignment (migrated from old Index Graph)\n const intentForIndexing = await this.database.getIntentForIndexing(intentId);\n if (!intentForIndexing) {\n return { agentTimings: agentTimingsAccum, mutationResult: { success: false, error: \"Intent not found for networking.\" } };\n }\n\n const indexContext = await this.database.getNetworkAssignmentContext(networkId, intentForIndexing.userId);\n if (!indexContext) {\n return {\n agentTimings: agentTimingsAccum,\n assignmentResult: { networkId, assigned: false, success: false } as AssignmentResult,\n mutationResult: { success: false, error: \"Network assignment context not found.\" },\n };\n }\n const indexPrompt = indexContext.indexPrompt ?? null;\n const memberPrompt = indexContext.memberPrompt ?? null;\n const hasNoPrompts = !indexPrompt?.trim() && !memberPrompt?.trim();\n if (hasNoPrompts) {\n const decision = buildNetworkAssignmentDecision({\n resourceType: \"intent\",\n mode: \"automatic\",\n scope: \"network\",\n indexPrompt,\n memberPrompt,\n evaluator: \"intent-indexer\",\n source: \"intent-network-graph\",\n createdAt: new Date().toISOString(),\n });\n await this.database.assignIntentToNetwork(intentId, networkId, decision.finalScore, decision.metadata);\n return {\n agentTimings: agentTimingsAccum,\n assignmentResult: { networkId, assigned: true, success: true } as AssignmentResult,\n mutationResult: { success: true, message: \"Intent assigned to network (no prompts).\" },\n };\n }\n\n // Run IntentIndexer evaluation\n const sourceName = intentForIndexing.sourceType\n ? `${intentForIndexing.sourceType}:${intentForIndexing.sourceId ?? \"\"}`\n : undefined;\n\n // Render network context (type, metadata) for the evaluator\n const network = await this.database.getNetwork(networkId);\n const renderedContext = network\n ? renderNetworkContext({\n type: network.type ?? 'community',\n title: network.title,\n prompt: network.prompt,\n metadata: network.metadata ?? {},\n })\n : null;\n\n const _traceEmitterIndexer = requestContext.getStore()?.traceEmitter;\n const _indexerStart = Date.now();\n _traceEmitterIndexer?.({ type: \"agent_start\", name: \"intent-indexer\" });\n let result: Awaited<ReturnType<typeof indexer.evaluate>> | null = null;\n try {\n result = await indexer.evaluate(\n intentForIndexing.payload,\n indexPrompt,\n memberPrompt,\n sourceName,\n renderedContext\n );\n } finally {\n const _indexerMs = Date.now() - _indexerStart;\n agentTimingsAccum.push({ name: 'intent.indexer', durationMs: _indexerMs });\n _traceEmitterIndexer?.({ type: \"agent_end\", name: \"intent-indexer\", durationMs: _indexerMs, summary: result ? `Scored: index=${result.indexScore.toFixed(2)}, member=${result.memberScore.toFixed(2)}` : \"intent-indexer failed\" });\n }\n\n if (!result) {\n return {\n agentTimings: agentTimingsAccum,\n evaluation: null,\n shouldAssign: false,\n finalScore: 0,\n mutationResult: { success: false, error: \"Evaluation returned no result.\" },\n };\n }\n\n const decision = buildNetworkAssignmentDecision({\n resourceType: \"intent\",\n mode: \"automatic\",\n scope: \"network\",\n indexPrompt,\n memberPrompt,\n rawScores: { indexScore: result.indexScore, memberScore: result.memberScore },\n evaluator: \"intent-indexer\",\n source: \"intent-network-graph\",\n reason: result.reasoning,\n createdAt: new Date().toISOString(),\n });\n\n if (decision.assigned) {\n await this.database.assignIntentToNetwork(intentId, networkId, decision.finalScore, decision.metadata);\n return {\n agentTimings: agentTimingsAccum,\n evaluation: result,\n shouldAssign: true,\n finalScore: decision.finalScore,\n assignmentResult: { networkId, assigned: true, success: true } as AssignmentResult,\n mutationResult: { success: true, message: `Intent assigned to network (score: ${decision.finalScore.toFixed(2)}).` },\n };\n }\n\n return {\n agentTimings: agentTimingsAccum,\n evaluation: result,\n shouldAssign: false,\n finalScore: decision.finalScore,\n assignmentResult: { networkId, assigned: false, success: true } as AssignmentResult,\n mutationResult: { success: false, error: `Intent did not qualify for this network (score: ${decision.finalScore.toFixed(2)}).` },\n };\n } catch (err) {\n logger.error(\"Assign failed\", { error: err });\n return { agentTimings: agentTimingsAccum, mutationResult: { success: false, error: \"Failed to assign intent to network.\" } };\n }\n });\n };\n\n /**\n * Read Node: Query intent-index relationships.\n * - By intentId only: list all indexes the intent is in (owner only)\n * - By networkId only: list intents in the index (member only)\n * - By both intentId and networkId: check if specific link exists (owner only)\n */\n const readNode = async (state: typeof IntentNetworkGraphState.State) => {\n return timed(\"IntentNetworkGraph.read\", async () => {\n const intentId = state.intentId;\n const networkId = state.networkId;\n logger.verbose(\"Read intent-index links\", { userId: state.userId, intentId, networkId, queryUserId: state.queryUserId });\n\n try {\n // By both: check if specific intent-index link exists\n if (intentId && networkId) {\n const intent = await this.database.getIntent(intentId);\n if (!intent) {\n return { readResult: { links: [], count: 0, mode: \"check_link\" }, error: \"Intent not found.\" };\n }\n if (intent.userId !== state.userId) {\n return { readResult: { links: [], count: 0, mode: \"check_link\" }, error: \"You can only check links for your own intents.\" };\n }\n const isLinked = await this.database.isIntentAssignedToIndex(intentId, networkId);\n return {\n readResult: {\n links: isLinked ? [{ intentId, networkId }] : [],\n count: isLinked ? 1 : 0,\n mode: \"check_link\",\n note: isLinked ? \"Intent is linked to this network.\" : \"Intent is not linked to this network.\",\n },\n };\n }\n\n // By intent only: list all indexes for this intent\n if (intentId) {\n const intent = await this.database.getIntent(intentId);\n if (!intent) {\n return { readResult: { links: [], count: 0, mode: \"networks_for_intent\" }, error: \"Intent not found.\" };\n }\n if (intent.userId !== state.userId) {\n return { readResult: { links: [], count: 0, mode: \"networks_for_intent\" }, error: \"You can only list networks for your own intents.\" };\n }\n const networkIds = await this.database.getNetworkIdsForIntent(intentId);\n return {\n readResult: {\n links: networkIds.map((id) => ({ intentId, networkId: id })),\n count: networkIds.length,\n mode: \"networks_for_intent\",\n note: \"To show network titles, use read_networks.\",\n },\n };\n }\n\n // By index: list intents in the index\n if (!networkId) {\n return {\n readResult: { links: [], count: 0, mode: \"unknown\" },\n error: \"Provide networkId or intentId.\",\n };\n }\n\n const [isMember, isOwner] = await Promise.all([\n this.database.isNetworkMember(networkId, state.userId),\n this.database.isIndexOwner(networkId, state.userId),\n ]);\n if (!isMember && !isOwner) {\n return {\n readResult: { links: [], count: 0, mode: \"intents_in_network\" },\n error: \"Network not found or you are not a member.\",\n };\n }\n\n // All intents or filtered by user\n if (!state.queryUserId) {\n const intents = await this.database.getNetworkIntentsForMember(networkId, state.userId, { limit: 50, offset: 0 });\n return {\n readResult: {\n links: intents.map((i) => ({\n intentId: i.id,\n networkId,\n intentTitle: i.payload,\n userId: i.userId,\n userName: i.userName,\n createdAt: i.createdAt,\n relevancyScore: i.relevancyScore,\n })),\n count: intents.length,\n mode: \"intents_in_network\",\n note: \"To show network title and full intent details, use read_networks and read_intents.\",\n },\n };\n }\n\n // Specific user's intents\n const intents = await this.database.getIntentsInIndexForMember(state.queryUserId, networkId);\n return {\n readResult: {\n links: intents.map((i) => ({\n intentId: i.id,\n networkId,\n intentTitle: i.payload,\n createdAt: i.createdAt,\n relevancyScore: i.relevancyScore,\n })),\n count: intents.length,\n mode: \"intents_in_network\",\n note: \"To show network title and full intent details, use read_networks and read_intents.\",\n },\n };\n } catch (err) {\n logger.error(\"Read intent-index failed\", { error: err });\n return { error: \"Failed to fetch intent-network links.\" };\n }\n });\n };\n\n /**\n * Unassign Node: Remove an intent from an index.\n */\n const unassignNode = async (state: typeof IntentNetworkGraphState.State) => {\n return timed(\"IntentNetworkGraph.unassign\", async () => {\n const intentId = state.intentId;\n const networkId = state.networkId;\n logger.verbose(\"Unassign intent from index\", { userId: state.userId, intentId, networkId });\n\n if (!intentId || !networkId) {\n return { mutationResult: { success: false, error: \"Both intentId and networkId are required.\" } };\n }\n\n try {\n const intent = await this.database.getIntent(intentId);\n if (!intent) {\n return { mutationResult: { success: false, error: \"Intent not found.\" } };\n }\n if (intent.userId !== state.userId) {\n return { mutationResult: { success: false, error: \"You can only remove your own intents from a network.\" } };\n }\n const [isMember, isOwner] = await Promise.all([\n this.database.isNetworkMember(networkId, state.userId),\n this.database.isIndexOwner(networkId, state.userId),\n ]);\n if (!isMember && !isOwner) {\n return { mutationResult: { success: false, error: \"You are not a member of that network.\" } };\n }\n\n const assigned = await this.database.isIntentAssignedToIndex(intentId, networkId);\n if (!assigned) {\n return { mutationResult: { success: true, message: \"That intent is not in this network.\" } };\n }\n\n await this.database.unassignIntentFromIndex(intentId, networkId);\n return { mutationResult: { success: true, message: \"Intent removed from the index.\" } };\n } catch (err) {\n logger.error(\"Unassign failed\", { error: err });\n return { mutationResult: { success: false, error: \"Failed to remove intent from network.\" } };\n }\n });\n };\n\n // --- CONDITIONAL ROUTING ---\n\n const routeByMode = (state: typeof IntentNetworkGraphState.State): string => {\n switch (state.operationMode) {\n case 'create': return 'assign';\n case 'read': return 'read';\n case 'delete': return 'unassign';\n default: return 'read';\n }\n };\n\n // --- GRAPH ASSEMBLY ---\n\n const workflow = new StateGraph(IntentNetworkGraphState)\n .addNode(\"assign\", assignNode)\n .addNode(\"read\", readNode)\n .addNode(\"unassign\", unassignNode)\n .addConditionalEdges(START, routeByMode, {\n assign: \"assign\",\n read: \"read\",\n unassign: \"unassign\",\n })\n .addEdge(\"assign\", END)\n .addEdge(\"read\", END)\n .addEdge(\"unassign\", END);\n\n return workflow.compile();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"indexer.graph.js","sourceRoot":"/","sources":["network/indexer/indexer.graph.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAG9D,OAAO,EAAE,8BAA8B,EAAE,MAAM,sDAAsD,CAAC;AAEtG,OAAO,EAAE,cAAc,EAAE,MAAM,+CAA+C,CAAC;AAC/E,OAAO,EAAE,KAAK,EAAE,MAAM,2CAA2C,CAAC;AAClE,OAAO,EAAE,cAAc,EAAE,MAAM,+CAA+C,CAAC;AAE/E,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AAEjF,OAAO,EAAE,uBAAuB,EAAyB,MAAM,oBAAoB,CAAC;AAEpF,MAAM,MAAM,GAAG,cAAc,CAAC,2BAA2B,CAAC,CAAC;AAE3D;;;;;;;;;GASG;AACH,MAAM,OAAO,yBAAyB;IACpC,YACU,QAAoC,EACpC,eAA8B;QAD9B,aAAQ,GAAR,QAAQ,CAA4B;QACpC,oBAAe,GAAf,eAAe,CAAe;IACrC,CAAC;IAEG,WAAW;QAChB,MAAM,OAAO,GAAG,IAAI,CAAC,eAAe,CAAC;QAErC,2BAA2B;QAE3B;;;;;WAKG;QACH,MAAM,UAAU,GAAG,KAAK,EAAE,KAA2C,EAAE,EAAE;YACvE,OAAO,KAAK,CAAC,2BAA2B,EAAE,KAAK,IAAI,EAAE;gBACnD,MAAM,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;gBAChC,MAAM,SAAS,GAAG,KAAK,CAAC,SAAS,CAAC;gBAClC,MAAM,CAAC,OAAO,CAAC,wBAAwB,EAAE,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,QAAQ,EAAE,SAAS,E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ph, START, END } from \"@langchain/langgraph\";\n\nimport { IntentIndexer } from \"../../intent/intent.indexer.js\";\nimport { buildNetworkAssignmentDecision } from \"../../shared/assignment/network-assignment.policy.js\";\nimport type { IntentNetworkGraphDatabase } from \"../../shared/interfaces/database.interface.js\";\nimport { protocolLogger } from \"../../shared/observability/protocol.logger.js\";\nimport { timed } from \"../../shared/observability/performance.js\";\nimport { requestContext } from \"../../shared/observability/request-context.js\";\nimport type { DebugMetaAgent } from \"../../chat/chat-streaming.types.js\";\nimport { renderNetworkContext } from \"../../shared/network/metadata.renderer.js\";\n\nimport { IntentNetworkGraphState, type AssignmentResult } from \"./indexer.state.js\";\n\nconst logger = protocolLogger(\"IntentNetworkGraphFactory\");\n\n/**\n * Factory class to build and compile the Intent Index Graph.\n *\n * Handles CRUD for the intent_indexes junction table:\n * - create: Assign an intent to an index (direct or evaluated via IntentIndexer agent)\n * - read: List intent-network links (by intentId or by networkId)\n * - delete: Unassign an intent from an index\n *\n * The evaluate-based assignment flow is migrated from the old Network Graph.\n */\nexport class IntentNetworkGraphFactory {\n constructor(\n private database: IntentNetworkGraphDatabase,\n private intentNetworker: IntentIndexer,\n ) {}\n\n public createGraph() {\n const indexer = this.intentNetworker;\n\n // --- NODE DEFINITIONS ---\n\n /**\n * Assign Node: Assign an intent to an index.\n * Two sub-paths:\n * - Direct assignment (skipEvaluation=true): assign immediately\n * - Evaluated assignment (skipEvaluation=false): load intent + index context, evaluate via IntentIndexer\n */\n const assignNode = async (state: typeof IntentNetworkGraphState.State) => {\n return timed(\"IntentNetworkGraph.assign\", async () => {\n const intentId = state.intentId;\n const networkId = state.networkId;\n logger.verbose(\"Assign intent to index\", { userId: state.userId, intentId, networkId, skipEvaluation: state.skipEvaluation });\n\n const agentTimingsAccum: DebugMetaAgent[] = [];\n\n if (!intentId || !networkId) {\n return { agentTimings: agentTimingsAccum, mutationResult: { success: false, error: \"Both intentId and networkId are required.\" } };\n }\n\n try {\n // Validate ownership and membership\n const intent = await this.database.getIntent(intentId);\n if (!intent) {\n return { agentTimings: agentTimingsAccum, mutationResult: { success: false, error: \"Intent not found.\" } };\n }\n if (intent.userId !== state.userId) {\n return { agentTimings: agentTimingsAccum, mutationResult: { success: false, error: \"You can only add your own intents to a network.\" } };\n }\n const [isMember, isOwner] = await Promise.all([\n this.database.isNetworkMember(networkId, state.userId),\n this.database.isIndexOwner(networkId, state.userId),\n ]);\n if (!isMember && !isOwner) {\n return { agentTimings: agentTimingsAccum, mutationResult: { success: false, error: \"You are not a member of that network.\" } };\n }\n\n // Check if already assigned\n const alreadyAssigned = await this.database.isIntentAssignedToIndex(intentId, networkId);\n if (alreadyAssigned) {\n return { agentTimings: agentTimingsAccum, mutationResult: { success: true, message: \"That intent is already in this network.\" } };\n }\n\n // Direct assignment (skip evaluation)\n if (state.skipEvaluation) {\n const decision = buildNetworkAssignmentDecision({\n resourceType: \"intent\",\n mode: \"manual_override\",\n scope: \"network\",\n evaluator: \"intent-network-graph\",\n source: \"manual-index-assignment\",\n createdAt: new Date().toISOString(),\n });\n await this.database.assignIntentToNetwork(intentId, networkId, decision.finalScore, decision.metadata);\n return {\n agentTimings: agentTimingsAccum,\n assignmentResult: { networkId, assigned: true, success: true } as AssignmentResult,\n mutationResult: { success: true, message: \"Intent saved to the network.\" },\n };\n }\n\n // Evaluated assignment (migrated from old Network Graph)\n const intentForIndexing = await this.database.getIntentForIndexing(intentId);\n if (!intentForIndexing) {\n return { agentTimings: agentTimingsAccum, mutationResult: { success: false, error: \"Intent not found for networking.\" } };\n }\n\n const indexContext = await this.database.getNetworkAssignmentContext(networkId, intentForIndexing.userId);\n if (!indexContext) {\n return {\n agentTimings: agentTimingsAccum,\n assignmentResult: { networkId, assigned: false, success: false } as AssignmentResult,\n mutationResult: { success: false, error: \"Network assignment context not found.\" },\n };\n }\n const indexPrompt = indexContext.indexPrompt ?? null;\n const memberPrompt = indexContext.memberPrompt ?? null;\n const hasNoPrompts = !indexPrompt?.trim() && !memberPrompt?.trim();\n if (hasNoPrompts) {\n const decision = buildNetworkAssignmentDecision({\n resourceType: \"intent\",\n mode: \"automatic\",\n scope: \"network\",\n indexPrompt,\n memberPrompt,\n evaluator: \"intent-networker\",\n source: \"intent-network-graph\",\n createdAt: new Date().toISOString(),\n });\n await this.database.assignIntentToNetwork(intentId, networkId, decision.finalScore, decision.metadata);\n return {\n agentTimings: agentTimingsAccum,\n assignmentResult: { networkId, assigned: true, success: true } as AssignmentResult,\n mutationResult: { success: true, message: \"Intent assigned to network (no prompts).\" },\n };\n }\n\n // Run IntentIndexer evaluation\n const sourceName = intentForIndexing.sourceType\n ? `${intentForIndexing.sourceType}:${intentForIndexing.sourceId ?? \"\"}`\n : undefined;\n\n // Render network context (type, metadata) for the evaluator\n const network = await this.database.getNetwork(networkId);\n const renderedContext = network\n ? renderNetworkContext({\n type: network.type ?? 'community',\n title: network.title,\n prompt: network.prompt,\n metadata: network.metadata ?? {},\n })\n : null;\n\n const _traceEmitterIndexer = requestContext.getStore()?.traceEmitter;\n const _indexerStart = Date.now();\n _traceEmitterIndexer?.({ type: \"agent_start\", name: \"intent-networker\" });\n let result: Awaited<ReturnType<typeof indexer.evaluate>> | null = null;\n try {\n result = await indexer.evaluate(\n intentForIndexing.payload,\n indexPrompt,\n memberPrompt,\n sourceName,\n renderedContext\n );\n } finally {\n const _indexerMs = Date.now() - _indexerStart;\n agentTimingsAccum.push({ name: 'intent.indexer', durationMs: _indexerMs });\n _traceEmitterIndexer?.({ type: \"agent_end\", name: \"intent-networker\", durationMs: _indexerMs, summary: result ? `Scored: index=${result.indexScore.toFixed(2)}, member=${result.memberScore.toFixed(2)}` : \"intent-networker failed\" });\n }\n\n if (!result) {\n return {\n agentTimings: agentTimingsAccum,\n evaluation: null,\n shouldAssign: false,\n finalScore: 0,\n mutationResult: { success: false, error: \"Evaluation returned no result.\" },\n };\n }\n\n const decision = buildNetworkAssignmentDecision({\n resourceType: \"intent\",\n mode: \"automatic\",\n scope: \"network\",\n indexPrompt,\n memberPrompt,\n rawScores: { indexScore: result.indexScore, memberScore: result.memberScore },\n evaluator: \"intent-networker\",\n source: \"intent-network-graph\",\n reason: result.reasoning,\n createdAt: new Date().toISOString(),\n });\n\n if (decision.assigned) {\n await this.database.assignIntentToNetwork(intentId, networkId, decision.finalScore, decision.metadata);\n return {\n agentTimings: agentTimingsAccum,\n evaluation: result,\n shouldAssign: true,\n finalScore: decision.finalScore,\n assignmentResult: { networkId, assigned: true, success: true } as AssignmentResult,\n mutationResult: { success: true, message: `Intent assigned to network (score: ${decision.finalScore.toFixed(2)}).` },\n };\n }\n\n return {\n agentTimings: agentTimingsAccum,\n evaluation: result,\n shouldAssign: false,\n finalScore: decision.finalScore,\n assignmentResult: { networkId, assigned: false, success: true } as AssignmentResult,\n mutationResult: { success: false, error: `Intent did not qualify for this network (score: ${decision.finalScore.toFixed(2)}).` },\n };\n } catch (err) {\n logger.error(\"Assign failed\", { error: err });\n return { agentTimings: agentTimingsAccum, mutationResult: { success: false, error: \"Failed to assign intent to network.\" } };\n }\n });\n };\n\n /**\n * Read Node: Query intent-network relationships.\n * - By intentId only: list all networks the intent is in (owner only)\n * - By networkId only: list intents in the index (member only)\n * - By both intentId and networkId: check if specific link exists (owner only)\n */\n const readNode = async (state: typeof IntentNetworkGraphState.State) => {\n return timed(\"IntentNetworkGraph.read\", async () => {\n const intentId = state.intentId;\n const networkId = state.networkId;\n logger.verbose(\"Read intent-network links\", { userId: state.userId, intentId, networkId, queryUserId: state.queryUserId });\n\n try {\n // By both: check if specific intent-network link exists\n if (intentId && networkId) {\n const intent = await this.database.getIntent(intentId);\n if (!intent) {\n return { readResult: { links: [], count: 0, mode: \"check_link\" }, error: \"Intent not found.\" };\n }\n if (intent.userId !== state.userId) {\n return { readResult: { links: [], count: 0, mode: \"check_link\" }, error: \"You can only check links for your own intents.\" };\n }\n const isLinked = await this.database.isIntentAssignedToIndex(intentId, networkId);\n return {\n readResult: {\n links: isLinked ? [{ intentId, networkId }] : [],\n count: isLinked ? 1 : 0,\n mode: \"check_link\",\n note: isLinked ? \"Intent is linked to this network.\" : \"Intent is not linked to this network.\",\n },\n };\n }\n\n // By intent only: list all networks for this intent\n if (intentId) {\n const intent = await this.database.getIntent(intentId);\n if (!intent) {\n return { readResult: { links: [], count: 0, mode: \"networks_for_intent\" }, error: \"Intent not found.\" };\n }\n if (intent.userId !== state.userId) {\n return { readResult: { links: [], count: 0, mode: \"networks_for_intent\" }, error: \"You can only list networks for your own intents.\" };\n }\n const networkIds = await this.database.getNetworkIdsForIntent(intentId);\n return {\n readResult: {\n links: networkIds.map((id) => ({ intentId, networkId: id })),\n count: networkIds.length,\n mode: \"networks_for_intent\",\n note: \"To show network titles, use read_networks.\",\n },\n };\n }\n\n // By index: list intents in the index\n if (!networkId) {\n return {\n readResult: { links: [], count: 0, mode: \"unknown\" },\n error: \"Provide networkId or intentId.\",\n };\n }\n\n const [isMember, isOwner] = await Promise.all([\n this.database.isNetworkMember(networkId, state.userId),\n this.database.isIndexOwner(networkId, state.userId),\n ]);\n if (!isMember && !isOwner) {\n return {\n readResult: { links: [], count: 0, mode: \"intents_in_network\" },\n error: \"Network not found or you are not a member.\",\n };\n }\n\n // All intents or filtered by user\n if (!state.queryUserId) {\n const intents = await this.database.getNetworkIntentsForMember(networkId, state.userId, { limit: 50, offset: 0 });\n return {\n readResult: {\n links: intents.map((i) => ({\n intentId: i.id,\n networkId,\n intentTitle: i.payload,\n userId: i.userId,\n userName: i.userName,\n createdAt: i.createdAt,\n relevancyScore: i.relevancyScore,\n })),\n count: intents.length,\n mode: \"intents_in_network\",\n note: \"To show network title and full intent details, use read_networks and read_intents.\",\n },\n };\n }\n\n // Specific user's intents\n const intents = await this.database.getIntentsInIndexForMember(state.queryUserId, networkId);\n return {\n readResult: {\n links: intents.map((i) => ({\n intentId: i.id,\n networkId,\n intentTitle: i.payload,\n createdAt: i.createdAt,\n relevancyScore: i.relevancyScore,\n })),\n count: intents.length,\n mode: \"intents_in_network\",\n note: \"To show network title and full intent details, use read_networks and read_intents.\",\n },\n };\n } catch (err) {\n logger.error(\"Read intent-network failed\", { error: err });\n return { error: \"Failed to fetch intent-network links.\" };\n }\n });\n };\n\n /**\n * Unassign Node: Remove an intent from an index.\n */\n const unassignNode = async (state: typeof IntentNetworkGraphState.State) => {\n return timed(\"IntentNetworkGraph.unassign\", async () => {\n const intentId = state.intentId;\n const networkId = state.networkId;\n logger.verbose(\"Unassign intent from index\", { userId: state.userId, intentId, networkId });\n\n if (!intentId || !networkId) {\n return { mutationResult: { success: false, error: \"Both intentId and networkId are required.\" } };\n }\n\n try {\n const intent = await this.database.getIntent(intentId);\n if (!intent) {\n return { mutationResult: { success: false, error: \"Intent not found.\" } };\n }\n if (intent.userId !== state.userId) {\n return { mutationResult: { success: false, error: \"You can only remove your own intents from a network.\" } };\n }\n const [isMember, isOwner] = await Promise.all([\n this.database.isNetworkMember(networkId, state.userId),\n this.database.isIndexOwner(networkId, state.userId),\n ]);\n if (!isMember && !isOwner) {\n return { mutationResult: { success: false, error: \"You are not a member of that network.\" } };\n }\n\n const assigned = await this.database.isIntentAssignedToIndex(intentId, networkId);\n if (!assigned) {\n return { mutationResult: { success: true, message: \"That intent is not in this network.\" } };\n }\n\n await this.database.unassignIntentFromIndex(intentId, networkId);\n return { mutationResult: { success: true, message: \"Intent removed from the index.\" } };\n } catch (err) {\n logger.error(\"Unassign failed\", { error: err });\n return { mutationResult: { success: false, error: \"Failed to remove intent from network.\" } };\n }\n });\n };\n\n // --- CONDITIONAL ROUTING ---\n\n const routeByMode = (state: typeof IntentNetworkGraphState.State): string => {\n switch (state.operationMode) {\n case 'create': return 'assign';\n case 'read': return 'read';\n case 'delete': return 'unassign';\n default: return 'read';\n }\n };\n\n // --- GRAPH ASSEMBLY ---\n\n const workflow = new StateGraph(IntentNetworkGraphState)\n .addNode(\"assign\", assignNode)\n .addNode(\"read\", readNode)\n .addNode(\"unassign\", unassignNode)\n .addConditionalEdges(START, routeByMode, {\n assign: \"assign\",\n read: \"read\",\n unassign: \"unassign\",\n })\n .addEdge(\"assign\", END)\n .addEdge(\"read\", END)\n .addEdge(\"unassign\", END);\n\n return workflow.compile();\n }\n}\n"]}
|
|
@@ -32,7 +32,7 @@ export interface AssignmentResult {
|
|
|
32
32
|
/**
|
|
33
33
|
* Intent Index Graph State.
|
|
34
34
|
* Handles CRUD for the intent_indexes junction table (linking intents to indexes).
|
|
35
|
-
* Absorbs the old
|
|
35
|
+
* Absorbs the old Network Graph's evaluate-based assignment flow.
|
|
36
36
|
*
|
|
37
37
|
* Flow:
|
|
38
38
|
* START → router → {
|
|
@@ -56,7 +56,7 @@ export declare const IntentNetworkGraphState: import("@langchain/langgraph").Ann
|
|
|
56
56
|
operationMode: import("@langchain/langgraph").BaseChannel<"create" | "delete" | "read", "create" | "delete" | "read" | import("@langchain/langgraph").OverwriteValue<"create" | "delete" | "read">, unknown>;
|
|
57
57
|
/**
|
|
58
58
|
* When true, skip LLM evaluation and assign directly.
|
|
59
|
-
* (Migrated from old
|
|
59
|
+
* (Migrated from old Network Graph.)
|
|
60
60
|
*/
|
|
61
61
|
skipEvaluation: import("@langchain/langgraph").BaseChannel<boolean, boolean | import("@langchain/langgraph").OverwriteValue<boolean>, unknown>;
|
|
62
62
|
/** Intent payload and metadata. Null if intent not found. */
|
|
@@ -77,7 +77,7 @@ export declare const IntentNetworkGraphState: import("@langchain/langgraph").Ann
|
|
|
77
77
|
memberScore: number;
|
|
78
78
|
reasoning: string;
|
|
79
79
|
} | null> | null, unknown>;
|
|
80
|
-
/** Final decision: should intent be in this
|
|
80
|
+
/** Final decision: should intent be in this network? */
|
|
81
81
|
shouldAssign: import("@langchain/langgraph").BaseChannel<boolean | undefined, boolean | import("@langchain/langgraph").OverwriteValue<boolean | undefined> | undefined, unknown>;
|
|
82
82
|
/** Final score used for decision (0–1). */
|
|
83
83
|
finalScore: import("@langchain/langgraph").BaseChannel<number | undefined, number | import("@langchain/langgraph").OverwriteValue<number | undefined> | undefined, unknown>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"indexer.state.d.ts","sourceRoot":"/","sources":["network/indexer/indexer.state.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AAEzE;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;CACzB;AAED;;;GAGG;AACH,MAAM,WAAW,kBAAkB;IACjC,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;CAC7B;AAED;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAC/B,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,OAAO,CAAC;IAClB,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,uBAAuB;IAGlC,mDAAmD;;;;;;IAGnD,yEAAyE;;IAMzE,8DAA8D;;IAM9D,sBAAsB;;IAQtB;;;OAGG;;IAQH,6DAA6D;;IAM7D,yDAAyD;;IAMzD,8CAA8C;;;;;;;;;;;;;;IAM9C,
|
|
1
|
+
{"version":3,"file":"indexer.state.d.ts","sourceRoot":"/","sources":["network/indexer/indexer.state.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AAEzE;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1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