@indexnetwork/protocol 4.3.2 → 4.3.4-rc.309.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/dist/chat/chat.agent.d.ts.map +1 -1
- package/dist/chat/chat.agent.js +11 -1
- package/dist/chat/chat.agent.js.map +1 -1
- package/dist/chat/chat.graph.d.ts +16 -0
- package/dist/chat/chat.graph.d.ts.map +1 -1
- package/dist/chat/chat.graph.js +5 -2
- package/dist/chat/chat.graph.js.map +1 -1
- package/dist/chat/chat.prompt.d.ts.map +1 -1
- package/dist/chat/chat.prompt.js +20 -13
- package/dist/chat/chat.prompt.js.map +1 -1
- package/dist/chat/chat.state.d.ts +6 -3
- package/dist/chat/chat.state.d.ts.map +1 -1
- package/dist/chat/chat.state.js +12 -3
- package/dist/chat/chat.state.js.map +1 -1
- package/dist/chat/chat.streamer.d.ts +5 -0
- package/dist/chat/chat.streamer.d.ts.map +1 -1
- package/dist/chat/chat.streamer.js +13 -4
- package/dist/chat/chat.streamer.js.map +1 -1
- package/dist/enrichment/enrichment.tools.d.ts.map +1 -1
- package/dist/enrichment/enrichment.tools.js +16 -19
- package/dist/enrichment/enrichment.tools.js.map +1 -1
- package/dist/index.d.ts +5 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/intent/intent.graph.d.ts +10 -0
- package/dist/intent/intent.graph.d.ts.map +1 -1
- package/dist/intent/intent.graph.js +6 -2
- package/dist/intent/intent.graph.js.map +1 -1
- package/dist/intent/intent.state.d.ts +5 -1
- package/dist/intent/intent.state.d.ts.map +1 -1
- package/dist/intent/intent.state.js +11 -1
- package/dist/intent/intent.state.js.map +1 -1
- package/dist/intent/intent.tools.d.ts.map +1 -1
- package/dist/intent/intent.tools.js +63 -39
- package/dist/intent/intent.tools.js.map +1 -1
- package/dist/mcp/mcp.server.d.ts +45 -18
- package/dist/mcp/mcp.server.d.ts.map +1 -1
- package/dist/mcp/mcp.server.js +86 -45
- package/dist/mcp/mcp.server.js.map +1 -1
- package/dist/negotiation/negotiation.tools.d.ts.map +1 -1
- package/dist/negotiation/negotiation.tools.js +11 -7
- package/dist/negotiation/negotiation.tools.js.map +1 -1
- package/dist/network/network.graph.js +2 -2
- package/dist/network/network.graph.js.map +1 -1
- package/dist/network/network.tools.d.ts.map +1 -1
- package/dist/network/network.tools.js +50 -38
- package/dist/network/network.tools.js.map +1 -1
- package/dist/opportunity/opportunity.discover.d.ts +5 -0
- package/dist/opportunity/opportunity.discover.d.ts.map +1 -1
- package/dist/opportunity/opportunity.discover.js +3 -0
- package/dist/opportunity/opportunity.discover.js.map +1 -1
- package/dist/opportunity/opportunity.graph.d.ts +6 -6
- package/dist/opportunity/opportunity.graph.js +1 -1
- package/dist/opportunity/opportunity.graph.js.map +1 -1
- package/dist/opportunity/opportunity.pending-questions.d.ts +3 -0
- package/dist/opportunity/opportunity.pending-questions.d.ts.map +1 -1
- package/dist/opportunity/opportunity.pending-questions.js +7 -2
- package/dist/opportunity/opportunity.pending-questions.js.map +1 -1
- package/dist/opportunity/opportunity.state.d.ts +1 -1
- package/dist/opportunity/opportunity.tools.d.ts.map +1 -1
- package/dist/opportunity/opportunity.tools.js +46 -36
- package/dist/opportunity/opportunity.tools.js.map +1 -1
- package/dist/premise/premise.graph.d.ts +13 -1
- package/dist/premise/premise.graph.d.ts.map +1 -1
- package/dist/premise/premise.graph.js +11 -6
- package/dist/premise/premise.graph.js.map +1 -1
- package/dist/premise/premise.state.d.ts +5 -0
- package/dist/premise/premise.state.d.ts.map +1 -1
- package/dist/premise/premise.state.js +11 -0
- package/dist/premise/premise.state.js.map +1 -1
- package/dist/premise/premise.tools.d.ts.map +1 -1
- package/dist/premise/premise.tools.js +5 -0
- package/dist/premise/premise.tools.js.map +1 -1
- package/dist/questioner/questioner.tools.d.ts +1 -1
- package/dist/questioner/questioner.tools.d.ts.map +1 -1
- package/dist/questioner/questioner.tools.js +24 -13
- package/dist/questioner/questioner.tools.js.map +1 -1
- package/dist/questioner/questioner.types.d.ts +5 -0
- package/dist/questioner/questioner.types.d.ts.map +1 -1
- package/dist/questioner/questioner.types.js.map +1 -1
- package/dist/shared/agent/tool.factory.d.ts.map +1 -1
- package/dist/shared/agent/tool.factory.js +25 -16
- package/dist/shared/agent/tool.factory.js.map +1 -1
- package/dist/shared/agent/tool.helpers.d.ts +17 -18
- package/dist/shared/agent/tool.helpers.d.ts.map +1 -1
- package/dist/shared/agent/tool.helpers.js +10 -11
- package/dist/shared/agent/tool.helpers.js.map +1 -1
- package/dist/shared/agent/tool.registry.js +1 -1
- package/dist/shared/agent/tool.registry.js.map +1 -1
- package/dist/shared/agent/tool.scope.d.ts +39 -0
- package/dist/shared/agent/tool.scope.d.ts.map +1 -0
- package/dist/shared/agent/tool.scope.js +41 -0
- package/dist/shared/agent/tool.scope.js.map +1 -0
- package/dist/shared/assignment/network-assignment.policy.d.ts +8 -5
- package/dist/shared/assignment/network-assignment.policy.d.ts.map +1 -1
- package/dist/shared/assignment/network-assignment.policy.js +11 -6
- package/dist/shared/assignment/network-assignment.policy.js.map +1 -1
- package/dist/shared/hyde/hyde.graph.d.ts +6 -6
- package/dist/shared/hyde/hyde.state.d.ts +2 -2
- package/dist/shared/interfaces/auth.interface.d.ts +3 -3
- package/dist/shared/interfaces/auth.interface.js.map +1 -1
- package/dist/shared/interfaces/database.interface.d.ts +15 -3
- 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/discovery-run.interface.d.ts +1 -1
- package/dist/shared/interfaces/discovery-run.interface.d.ts.map +1 -1
- package/dist/shared/interfaces/discovery-run.interface.js.map +1 -1
- package/dist/shared/interfaces/enrichment-run.interface.d.ts +1 -1
- package/dist/shared/interfaces/enrichment-run.interface.d.ts.map +1 -1
- package/dist/shared/interfaces/enrichment-run.interface.js.map +1 -1
- package/dist/shared/interfaces/queue.interface.d.ts +8 -2
- package/dist/shared/interfaces/queue.interface.d.ts.map +1 -1
- package/dist/shared/interfaces/queue.interface.js.map +1 -1
- package/dist/shared/schemas/network-assignment.schema.d.ts +2 -2
- package/dist/shared/schemas/pending-question.schema.d.ts +5 -0
- package/dist/shared/schemas/pending-question.schema.d.ts.map +1 -1
- package/dist/shared/schemas/pending-question.schema.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool.helpers.js","sourceRoot":"/","sources":["shared/agent/tool.helpers.ts"],"names":[],"mappings":"AAyQA;;;GAGG;AACH,MAAM,OAAO,sBAAuB,SAAQ,KAAK;IAC/C,YACE,OAAe,EACC,UAAkB,EAClB,IAAwE;QAExF,KAAK,CAAC,OAAO,CAAC,CAAC;QAHC,eAAU,GAAV,UAAU,CAAQ;QAClB,SAAI,GAAJ,IAAI,CAAoE;QAGxF,IAAI,CAAC,IAAI,GAAG,wBAAwB,CAAC;IACvC,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,kBAAkB,CAAC,MAWxC;IACC,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,eAAe,EAAE,GAAG,MAAM,CAAC;IAE3E,MAAM,CAAC,IAAI,EAAE,UAAU,EAAE,YAAY,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;QACzD,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC;QACxB,QAAQ,CAAC,UAAU,CAAC,MAAM,CAAC;QAC3B,QAAQ,CAAC,qBAAqB,CAAC,MAAM,CAAC;KACvC,CAAC,CAAC;IAEH,MAAM,WAAW,GAAoB,UAAU,IAAI,IAAI,CAAC;IAExD,IAAI,CAAC,IAAI,EAAE,CAAC;QACV,MAAM,IAAI,sBAAsB,CAC9B,gBAAgB,EAChB,GAAG,EACH,gBAAgB,CACjB,CAAC;IACJ,CAAC;IAED,IAAI,WAAW,GAAuC,SAAS,CAAC;IAChE,IAAI,oBA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} from \"zod\";\nimport type { ModelConfig } from \"./model.config.js\";\nimport type { UserIdentity } from \"../schemas/identity.schema.js\";\nimport type { ChatGraphCompositeDatabase, NetworkMembership, UserRecord, UserDatabase, SystemDatabase, NegotiationGraphDatabase } from \"../interfaces/database.interface.js\";\nimport type { Scraper } from \"../interfaces/scraper.interface.js\";\nimport type { Cache, HydeCache } from \"../interfaces/cache.interface.js\";\nimport type { CompiledOpportunityGraph } from \"../../opportunity/opportunity.discover.js\";\nimport type { IntegrationAdapter } from \"../interfaces/integration.interface.js\";\nimport type { ContactServiceAdapter } from \"../interfaces/contact.interface.js\";\nimport type { ProfileEnricher } from \"../interfaces/enrichment.interface.js\";\nimport type { IntentGraphQueue } from \"../interfaces/queue.interface.js\";\nimport type { ChatSessionReader } from \"../interfaces/chat-session.interface.js\";\nimport type { ChatSummaryReader } from \"../interfaces/chat-summary.interface.js\";\nimport type { ChatMessageWriter } from \"../interfaces/chat-message-writer.interface.js\";\nimport type { QuestionGeneratorReader } from \"../interfaces/question-generator.interface.js\";\nimport type { NegotiationSummaryReader } from \"../interfaces/negotiation-summary.interface.js\";\nimport type { Embedder } from \"../interfaces/embedder.interface.js\";\nimport type { AgentDatabase } from \"../interfaces/agent.interface.js\";\nimport type { NegotiationTimeoutQueue } from \"../interfaces/negotiation-events.interface.js\";\nimport type { AgentDispatcher } from \"../interfaces/agent-dispatcher.interface.js\";\nimport type { DeliveryLedger } from \"../interfaces/delivery-ledger.interface.js\";\nimport type { MintConnectLink } from \"../interfaces/connect-link.interface.js\";\nimport type { QuestionerDatabase } from \"../interfaces/questioner.interface.js\";\nimport type { QuestionerEnqueueFn } from \"../../questioner/questioner.types.js\";\nimport type { PendingQuestionSummary } from \"../schemas/pending-question.schema.js\";\nimport type { QuestionMode } from \"../schemas/question.schema.js\";\nimport type { DiscoveryRunQueue, DiscoveryRunStore } from \"../interfaces/discovery-run.interface.js\";\nimport type { EnrichmentRunQueue, EnrichmentRunStore } from \"../interfaces/enrichment-run.interface.js\";\n\nexport type IdentityContext = UserIdentity | null;\n\nexport interface ToolErrorReport {\n operation: string;\n subsystem?: string;\n toolName?: string;\n userId?: string;\n tags?: Record<string, string | number | boolean | null | undefined>;\n context?: Record<string, unknown>;\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// COMPILED GRAPH TYPE\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/** Minimal interface for an invokable compiled LangGraph. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type CompiledGraph = { invoke: (input: any) => Promise<any> };\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TOOL CONTEXT TYPES\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Resolved context available to every tool handler.\n * Contains the current user and optional index identity, resolved from DB at init.\n * The LLM can see this context (via system prompt) but cannot change it.\n */\nexport interface ResolvedToolContext {\n // Legacy flat fields (kept for backwards compatibility in tools/prompts).\n userId: string;\n userName: string;\n userEmail: string;\n networkId?: string;\n indexName?: string;\n /** True when chat is index-scoped and the user owns the index. */\n isOwner?: boolean;\n // Rich identity context for prompt/tool orchestration.\n user: UserRecord;\n userProfile: IdentityContext;\n userNetworks: NetworkMembership[];\n /**\n * The set of index IDs this caller can reach in the current request.\n * For unscoped chats: every index the user is a member of.\n * For network-scoped agents: `[boundNetwork, personalIndex]`.\n * This is the same set used to clamp the DB-level systemDb.\n * Tools that filter intents/profiles default to this set; `networkId` is\n * the \"primary focus\" hint, not a read filter.\n */\n indexScope: string[];\n scopedIndex?: {\n id: string;\n title: string;\n prompt: string | null;\n type?: string;\n metadata?: Record<string, unknown>;\n permissions?: Record<string, unknown>;\n };\n scopedMembershipRole?: \"owner\" | \"member\";\n /** True when user has not completed onboarding (onboarding.completedAt is null). */\n isOnboarding: boolean;\n /** True when the user has a non-empty name. */\n hasName: boolean;\n /** Chat session ID when tools are used in a chat; used for draft opportunities (context.conversationId). */\n sessionId?: string;\n /** True when the request originates from an MCP transport (no interactive UI available). */\n isMcp?: boolean;\n /** Agent ID when the request originates from an API key linked to an agent. */\n agentId?: string;\n /**\n * Receiver's rendering surface declared by the MCP client via the\n * `x-index-surface` request header. `'telegram'` means the MCP response is\n * being rendered inside a Telegram chat; anything\n * else (including `undefined`) is treated as web. Forwarded into\n * `mintConnectLink` so the click-time redirect can branch.\n */\n clientSurface?: 'telegram' | 'web';\n /**\n * True when the CONTACTS_ENABLED feature flag is on. Carried from the\n * composition root so prompt modules can gate contact-import guidance —\n * when false/unset, the contacts prompt module is not injected, so the\n * orchestrator never advertises Gmail import / add_contact (whose tools\n * are also de-registered). Fail-closed: treat only `true` as enabled.\n */\n contactsEnabled?: boolean;\n}\n\n/**\n * Dependencies passed when creating tools for a user session.\n * Includes DB adapters, embedder, and scraper.\n *\n * Note: userDb and systemDb are optional inputs - if not provided, createChatTools\n * will create them internally from the chatDatabaseAdapter singleton.\n */\nexport interface ToolContext {\n userId: string;\n /** @deprecated Use userDb or systemDb instead. Kept for backwards compatibility. */\n database: ChatGraphCompositeDatabase;\n /** Context-bound database for accessing the authenticated user's own resources. Created internally if not provided. */\n userDb?: UserDatabase;\n /** Context-bound database for LLM/system operations on cross-user resources within shared indexes. Created internally if not provided. */\n systemDb?: SystemDatabase;\n embedder: Embedder;\n scraper: Scraper;\n /** When set, chat is scoped to this index; tools use it as default for read_intents and create_intent. */\n networkId?: string;\n /**\n * Optional override of the resolved `indexScope`. `resolveChatContext` always\n * computes `indexScope` from the user's memberships (clamped to [bound,\n * personal] when `networkId` is set). When the caller has already computed\n * a clamped scope — notably the MCP server, which clamps via\n * `applyNetworkScopeToContext` for network-scoped agents — passing it on\n * `ToolContext.indexScope` causes `createChatTools` (in tool.factory.ts) to\n * override `resolvedContext.indexScope` with this value rather than the\n * freshly computed one. See ResolvedToolContext.indexScope for the\n * resolved-side semantics.\n */\n indexScope?: string[];\n /** Chat session ID when creating tools for a chat; enables draft opportunities with context.conversationId. */\n sessionId?: string;\n\n // ─── Protocol-level dependencies (injected by composition root) ──────────\n /** General-purpose cache (e.g. for tool results). */\n cache: Cache;\n /** Dedicated cache for HyDE graph (may be same instance as cache). */\n hydeCache: HydeCache;\n /** External integration platform adapter (OAuth, tool actions). */\n integration: IntegrationAdapter;\n /** Queue for enqueuing follow-up intent processing (HyDE generation/deletion). */\n intentQueue: IntentGraphQueue;\n /** Contact management operations. */\n contactService: ContactServiceAdapter;\n /**\n * When false (or unset), the contact import / manual-add tools\n * (import_contacts, add_contact, import_gmail_contacts) are not registered.\n * Injected by the composition root from CONTACTS_ENABLED. Read/remove/search\n * contact tools are always registered.\n */\n contactsEnabled?: boolean;\n /** Chat session reader for loading conversation history. */\n chatSession: ChatSessionReader;\n /** Read-through chat-session digest. Optional; consumers fall back to undefined `chatContext`. */\n chatSummary?: ChatSummaryReader;\n /** Writes user messages into the user's most-recent chat session (Slice 5 MCP elicitation). */\n chatMessageWriter?: ChatMessageWriter;\n /** Decision-question generator. Optional; consumers fall back to no `questions`. */\n questionGenerator?: QuestionGeneratorReader;\n /**\n * Optional async question enqueue callback. When provided, question generation\n * is dispatched asynchronously to the QuestionerQueue instead of running inline.\n * Injected by the composition root when QUESTIONER_ENABLED=true.\n */\n questionerEnqueue?: QuestionerEnqueueFn;\n /** Negotiation-digest summarizer. Optional; consumers fall back to deterministic digests. */\n negotiationSummary?: NegotiationSummaryReader;\n /** Profile enrichment from external data sources. */\n enricher: ProfileEnricher;\n /** Database adapter for negotiation/conversation operations. */\n negotiationDatabase: NegotiationGraphDatabase;\n /** Integration importer for bulk contact import from toolkits. */\n integrationImporter: {\n importContacts(userId: string, toolkit: string): Promise<{\n imported: number;\n skipped: number;\n newContacts: number;\n existingContacts: number;\n }>;\n };\n /** Factory for user-scoped database access. */\n createUserDatabase: (db: ChatGraphCompositeDatabase, userId: string) => UserDatabase;\n /** Factory for system-scoped database access. */\n createSystemDatabase: (db: ChatGraphCompositeDatabase, userId: string, indexScope: string[], embedder?: Embedder) => SystemDatabase;\n /** Optional runtime LLM config. Pass to override env vars for API key, model, etc. */\n modelConfig?: ModelConfig;\n /** Manages negotiation timeout jobs (optional — enables AI fallback on external agent timeout). */\n negotiationTimeoutQueue?: NegotiationTimeoutQueue;\n /** Agent registry database adapter (optional — absent when host does not support agents). */\n agentDatabase?: AgentDatabase;\n /** Grants the default system-agent permissions after onboarding (optional). */\n grantDefaultSystemPermissions?: (userId: string) => Promise<void>;\n /** Dispatcher for routing negotiation turns to personal agents (optional — falls back to system AI). */\n agentDispatcher?: AgentDispatcher;\n /** Enqueue a negotiate_existing job after introducer approval (optional). */\n queueNegotiateExisting?: (opportunityId: string, userId: string) => Promise<void>;\n /** Delivery ledger for committing opportunity delivery rows (optional — absent in chat context). */\n deliveryLedger?: DeliveryLedger;\n /** Persistence for async MCP discovery runs (optional — absent in non-MCP/test contexts). */\n discoveryRuns?: DiscoveryRunStore;\n /** Queue for async MCP discovery run execution (optional — absent in non-MCP/test contexts). */\n discoveryRunQueue?: DiscoveryRunQueue;\n /** Persistence for async MCP profile runs (optional — absent in non-MCP/test contexts). */\n enrichmentRuns?: EnrichmentRunStore;\n /** Queue for async MCP profile run execution (optional — absent in non-MCP/test contexts). */\n enrichmentRunQueue?: EnrichmentRunQueue;\n /**\n * Legacy direct-token minting for opportunity accept redirects.\n * Prefer `mintConnectLink` for user-facing links.\n */\n mintConnectToken?: (userId: string, opportunityId: string) => Promise<string>;\n /** Mints (or reuses) a short connect link, snapshotting the greeting (optional — absent in non-MCP contexts). */\n mintConnectLink?: MintConnectLink;\n /** Frontend base URL for building profile links (e.g. https://index.network, optional). */\n frontendUrl?: string;\n /** API base URL for building opportunity accept links (e.g. https://protocol.index.network, optional). */\n apiBaseUrl?: string;\n /** Persistence for structured questions generated by the QuestionerAgent (optional). */\n questionerDatabase?: QuestionerDatabase;\n /** Optional host-side error reporter for swallowed protocol/tool errors. */\n reportToolError?: (error: unknown, report: ToolErrorReport) => void;\n /**\n * Optional host-side per-principal MCP call throttle. Invoked once per MCP\n * tool dispatch (after identity resolves, before any DB work). When the\n * returned decision is `allowed: false`, the dispatch short-circuits with a\n * rate-limit error carrying `retryAfterSec`. Absent in chat/test contexts.\n */\n mcpRateLimiter?: (input: { userId: string; agentId?: string; toolName: string }) => Promise<{\n allowed: boolean;\n retryAfterSec?: number;\n limit?: number;\n scope?: 'tool' | 'principal';\n }>;\n /** Optional premise lifecycle event callbacks. Fired by premise tools after successful operations. */\n premiseEvents?: {\n onCreated?: (premiseId: string, userId: string) => void;\n onUpdated?: (premiseId: string, userId: string) => void;\n onRetracted?: (premiseId: string, userId: string) => void;\n };\n}\n\n/**\n * All external dependencies needed to initialize the protocol tool engine.\n * The host application (composition root) must provide concrete implementations.\n * This is the subset of ToolContext that is NOT per-request (no userId, indexId, sessionId).\n */\nexport type ProtocolDeps = Omit<ToolContext, 'userId' | 'indexId' | 'sessionId' | 'userDb' | 'systemDb'>;\n\n/**\n * Thrown when a requested chat scope is invalid for the authenticated user.\n * Controllers can map this to an HTTP status code.\n */\nexport class ChatContextAccessError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number,\n public readonly code: \"USER_NOT_FOUND\" | \"INDEX_NOT_FOUND\" | \"INDEX_MEMBERSHIP_REQUIRED\"\n ) {\n super(message);\n this.name = \"ChatContextAccessError\";\n }\n}\n\n/**\n * Resolve the canonical context used by chat tools and system prompt.\n * This preloads user identity, profile, index memberships, and scoped index role.\n */\nexport async function resolveChatContext(params: {\n database: Pick<\n ChatGraphCompositeDatabase,\n \"getUser\" | \"getProfile\" | \"getNetworkMemberships\" | \"getNetworkMembership\" | \"getNetwork\" | \"isIndexOwner\" | \"isNetworkMember\"\n >;\n userId: string;\n networkId?: string;\n /** Chat session ID for draft opportunities (stored as context.conversationId). */\n sessionId?: string;\n /** CONTACTS_ENABLED flag, forwarded onto the resolved context for prompt gating. */\n contactsEnabled?: boolean;\n}): Promise<ResolvedToolContext> {\n const { database, userId, networkId, sessionId, contactsEnabled } = params;\n\n const [user, rawProfile, userNetworks] = await Promise.all([\n database.getUser(userId),\n database.getProfile(userId),\n database.getNetworkMemberships(userId),\n ]);\n\n const userProfile: IdentityContext = rawProfile ?? null;\n\n if (!user) {\n throw new ChatContextAccessError(\n \"User not found\",\n 404,\n \"USER_NOT_FOUND\"\n );\n }\n\n let scopedIndex: ResolvedToolContext[\"scopedIndex\"] = undefined;\n let scopedMembershipRole: ResolvedToolContext[\"scopedMembershipRole\"] = undefined;\n let isOwner = false;\n let indexName: string | undefined;\n\n if (networkId) {\n const [index, isMember, owner] = await Promise.all([\n database.getNetwork(networkId),\n database.isNetworkMember(networkId, userId),\n database.isIndexOwner(networkId, userId),\n ]);\n\n if (!index) {\n throw new ChatContextAccessError(\n \"Index not found\",\n 404,\n \"INDEX_NOT_FOUND\"\n );\n }\n\n if (!isMember) {\n throw new ChatContextAccessError(\n \"You are not a member of this index\",\n 403,\n \"INDEX_MEMBERSHIP_REQUIRED\"\n );\n }\n\n let membership = userNetworks.find((m) => m.networkId === index.id);\n if (membership === undefined) {\n membership = (await database.getNetworkMembership(index.id, userId)) ?? undefined;\n }\n scopedIndex = {\n id: index.id,\n title: index.title,\n prompt: membership?.indexPrompt ?? null,\n type: index.type ?? 'community',\n metadata: index.metadata ?? {},\n permissions: index.permissions ?? {},\n };\n isOwner = owner;\n indexName = index.title;\n scopedMembershipRole = owner ? \"owner\" : \"member\";\n }\n\n const userName = user.name ?? \"Unknown\";\n const userEmail = user.email ?? \"\";\n const hasName = !!user.name?.trim();\n\n // When scoped to an index, clamp the caller's reach to [scopedIndex, personalIndex]\n // so the chat's data model matches its \"focus\" semantic: a chat scoped to a\n // community sees that community plus the user's personal index, not their\n // other unrelated memberships. Mirrors the MCP path's clamp for network-scoped\n // agents (see applyNetworkScopeToContext / computeAgentIndexScope).\n const indexScope = networkId\n ? userNetworks\n .filter((m) => m.networkId === networkId || m.isPersonal === true)\n .map((m) => m.networkId)\n : userNetworks.map((m) => m.networkId);\n\n return {\n userId,\n userName,\n userEmail,\n networkId,\n indexName,\n isOwner,\n user,\n userProfile,\n userNetworks,\n indexScope,\n scopedIndex,\n scopedMembershipRole,\n isOnboarding: !(user.onboarding?.completedAt),\n hasName,\n contactsEnabled,\n ...(sessionId !== undefined ? { sessionId } : {}),\n };\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// DEFINE TOOL TYPE\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Type for the `defineTool` closure created in `createChatTools`.\n * Auto-injects resolved context and provides uniform logging / error handling.\n */\nexport type DefineTool = <T extends z.ZodType>(opts: {\n name: string;\n description: string;\n querySchema: T;\n handler: (input: { context: ResolvedToolContext; query: z.infer<T> }) => Promise<string>;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n}) => any;\n\n/**\n * A raw tool definition before LangChain wrapping.\n * Used by the tool registry for direct HTTP invocation.\n */\nexport interface RawToolDefinition {\n name: string;\n description: string;\n schema: z.ZodType;\n handler: (input: { context: ResolvedToolContext; query: unknown }) => Promise<string>;\n}\n\n/**\n * Registry mapping tool names to their raw definitions.\n */\nexport type ToolRegistry = Map<string, RawToolDefinition>;\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TOOL DEPENDENCIES\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Shared dependencies available to all tool domain factories.\n * Passed by `createChatTools` after compiling all subgraphs.\n */\nexport interface ToolDeps {\n /** @deprecated Use userDb or systemDb instead. Kept for backwards compatibility. */\n database: ChatGraphCompositeDatabase;\n /** Context-bound database for accessing the authenticated user's own resources. */\n userDb: UserDatabase;\n /** Context-bound database for LLM/system operations on cross-user resources within shared indexes. */\n systemDb: SystemDatabase;\n scraper: Scraper;\n embedder: import('../interfaces/embedder.interface.js').Embedder;\n cache: Cache;\n integration: IntegrationAdapter;\n contactService: ContactServiceAdapter;\n /**\n * When false (or unset), the contact import / manual-add tools\n * (import_contacts, add_contact, import_gmail_contacts) are not registered.\n * Injected by the composition root from CONTACTS_ENABLED. Read/remove/search\n * contact tools are always registered.\n */\n contactsEnabled?: boolean;\n integrationImporter: {\n importContacts(userId: string, toolkit: string): Promise<{\n imported: number;\n skipped: number;\n newContacts: number;\n existingContacts: number;\n }>;\n };\n enricher: ProfileEnricher;\n /** Database adapter for negotiation/conversation operations. */\n negotiationDatabase: NegotiationGraphDatabase;\n /** Chat session reader for exposing the caller's past conversations as MCP tools. */\n chatSession?: ChatSessionReader;\n /** Read-through chat-session digest. Optional; consumers fall back to undefined `chatContext`. */\n chatSummary?: ChatSummaryReader;\n /**\n * Test seam for opportunity discovery helpers. Production compositions leave\n * this unset so tools call the real discovery module directly.\n */\n opportunityDiscovery?: {\n runDiscoverFromQuery?: (input: unknown) => Promise<unknown>;\n continueDiscovery?: (input: unknown) => Promise<unknown>;\n };\n /**\n * Test seam for opportunity card presentation helpers. Production\n * compositions leave this unset so tools construct the real presenter.\n */\n opportunityPresentation?: {\n createPresenter?: () => { presentHomeCard(input: unknown): Promise<unknown> };\n gatherPresenterContext?: (...args: unknown[]) => Promise<unknown>;\n };\n /** Writes user messages into the user's most-recent chat session (Slice 5 MCP elicitation). */\n chatMessageWriter?: ChatMessageWriter;\n /** Decision-question generator. Optional; consumers fall back to no `questions`. */\n questionGenerator?: QuestionGeneratorReader;\n /**\n * Optional async question enqueue callback. When provided, question generation\n * is dispatched asynchronously to the QuestionerQueue instead of running inline\n * via the `questionGenerator`. Injected by the composition root when\n * QUESTIONER_ENABLED=true.\n */\n questionerEnqueue?: QuestionerEnqueueFn;\n /**\n * Lookup pending questions for a user, optionally filtered by source,\n * detection mode, or capped by count (hosts apply `limit` SQL-side).\n * Used by tools to attach contextually relevant questions to their results.\n * Injected by the composition root — absent when question delivery is disabled.\n */\n findPendingQuestions?: (\n userId: string,\n filters?: {\n sourceType?: string;\n sourceId?: string;\n /** Restrict to questions whose detection mode is in this set. */\n modes?: QuestionMode[];\n /** Maximum rows to return; hosts should apply this in the query. */\n limit?: number;\n },\n ) => Promise<PendingQuestionSummary[]>;\n /** Negotiation-digest summarizer. Optional; consumers fall back to deterministic digests. */\n negotiationSummary?: NegotiationSummaryReader;\n /** Manages negotiation timeout jobs (optional — enables AI fallback on external agent timeout). */\n negotiationTimeoutQueue?: NegotiationTimeoutQueue;\n /** Agent registry database adapter (optional — absent when host does not support agents). */\n agentDatabase?: AgentDatabase;\n /** Grants the default system-agent permissions after onboarding (optional). */\n grantDefaultSystemPermissions?: (userId: string) => Promise<void>;\n /** Dispatcher for routing negotiation turns to personal agents (optional — falls back to system AI). */\n agentDispatcher?: AgentDispatcher;\n /** Delivery ledger for committing opportunity delivery rows (optional — absent in chat context). */\n deliveryLedger?: DeliveryLedger;\n /** Persistence for async MCP discovery runs (optional — absent in non-MCP/test contexts). */\n discoveryRuns?: DiscoveryRunStore;\n /** Queue for async MCP discovery run execution (optional — absent in non-MCP/test contexts). */\n discoveryRunQueue?: DiscoveryRunQueue;\n /** Persistence for async MCP profile runs (optional — absent in non-MCP/test contexts). */\n enrichmentRuns?: EnrichmentRunStore;\n /** Queue for async MCP profile run execution (optional — absent in non-MCP/test contexts). */\n enrichmentRunQueue?: EnrichmentRunQueue;\n /**\n * Legacy direct-token minting for opportunity accept redirects.\n * Prefer `mintConnectLink` for user-facing links.\n */\n mintConnectToken?: (userId: string, opportunityId: string) => Promise<string>;\n /** Mints (or reuses) a short connect link, snapshotting the greeting (optional — absent in non-MCP contexts). */\n mintConnectLink?: MintConnectLink;\n /** Frontend base URL for building profile links (e.g. https://index.network, optional). */\n frontendUrl?: string;\n /** API base URL for building opportunity accept links (e.g. https://protocol.index.network, optional). */\n apiBaseUrl?: string;\n /** Optional host-side error reporter for swallowed protocol/tool errors. */\n reportToolError?: (error: unknown, report: ToolErrorReport) => void;\n /**\n * Optional host-side per-principal MCP call throttle. Invoked once per MCP\n * tool dispatch (after identity resolves, before any DB work). When the\n * returned decision is `allowed: false`, the dispatch short-circuits with a\n * rate-limit error carrying `retryAfterSec`. Absent in chat/test contexts.\n */\n mcpRateLimiter?: (input: { userId: string; agentId?: string; toolName: string }) => Promise<{\n allowed: boolean;\n retryAfterSec?: number;\n limit?: number;\n scope?: 'tool' | 'principal';\n }>;\n /** Optional premise lifecycle event callbacks. Fired by premise tools after successful operations. */\n premiseEvents?: {\n onCreated?: (premiseId: string, userId: string) => void;\n onUpdated?: (premiseId: string, userId: string) => void;\n onRetracted?: (premiseId: string, userId: string) => void;\n };\n graphs: {\n profile: CompiledGraph;\n intent: CompiledGraph;\n index: CompiledGraph;\n networkMembership: CompiledGraph;\n intentIndex: CompiledGraph;\n opportunity: CompiledOpportunityGraph;\n premise: CompiledGraph;\n };\n /**\n * Optional network ranking override for `read_networks`. Injected by tests or custom compositions.\n * When absent, defaults to `NetworkRecommender.invoke()` with a lazy module-level singleton.\n */\n networkRanker?: (input: {\n userContext: string;\n networks: Array<{ networkId: string; renderedContext: string }>;\n }) => Promise<{ rankedNetworkIds: string[] } | null>;\n /**\n * Resolve a user's global user_context paragraph (profile-replacing identity text),\n * generating it on demand when absent. Injected by the backend composition root\n * (`ensureGlobalUserContext`). When absent, onboarding network ranking is skipped.\n */\n getUserContextText?: (userId: string) => Promise<string>;\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TOOL RESULT HELPERS\n// ═══════════════════════════════════════════════════════════════════════════════\n\nexport function success<T>(data: T): string {\n return JSON.stringify({ success: true, data });\n}\n\nexport function error(\n message: string,\n debugSteps?: Array<{ step: string; detail?: string; data?: Record<string, unknown> }>\n): string {\n return JSON.stringify({\n success: false,\n error: message,\n ...(debugSteps?.length ? { debugSteps } : {}),\n });\n}\n\n/** Return needsClarification for missing required fields. */\nexport function needsClarification(params: {\n missingFields: string[];\n message: string;\n}): string {\n return JSON.stringify({\n success: false,\n needsClarification: true,\n ...params,\n });\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// CONSTANTS & UTILITIES\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/** Matches http/https URLs in text; captures full URL. */\nconst URL_IN_TEXT_REGEX = /https?:\\/\\/[^\\s\"'<>)\\]]+/gi;\n\n/**\n * Matches bare domain URLs without protocol (e.g. github.com/foo, www.example.com).\n * Requires at least a SLD.TLD pattern followed by optional path.\n * Negative lookbehind ensures we don't double-match URLs already caught by URL_IN_TEXT_REGEX.\n */\nconst BARE_URL_REGEX = /(?<!\\w:\\/\\/)(?<![/\\w])(?:www\\.)?[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.(?:com|org|net|io|dev|co|ai|app|xyz|me|info|gg|so|sh|cc|ly|fm|tv|to|tech|design|network|world|edu|gov|mil|int|us|uk|eu|de|fr|ca|au|jp|cn|in|br|nl|se|no|fi|dk|ch|at|be|it|es|pt|pl|cz|ru|kr|tw|hk|sg|nz|za|mx|ar|cl|id|ph|th|vn|my|ie)(?:\\/[^\\s\"'<>)\\]]*)?/gi;\n\n/** UUID v4 format: 8-4-4-4-12 hex chars (e.g. c2505011-2e45-426e-81dd-b9abb9b72023) */\nexport const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/**\n * Resolves an array of network IDs to their display titles.\n * Skips any IDs that don't resolve (deleted or invalid networks).\n */\nexport async function resolveIndexNames(\n database: { getNetwork(id: string): Promise<{ id: string; title: string } | null> },\n networkIds: string[]\n): Promise<string[]> {\n if (networkIds.length === 0) return [];\n const results = await Promise.all(\n networkIds.map(id => database.getNetwork(id))\n );\n return results.filter(Boolean).map(idx => idx!.title);\n}\n\n/**\n * Normalize a URL string: if it lacks a protocol, prepend \"https://\".\n * Returns the normalized URL or null if the result is not a valid URL.\n */\nexport function normalizeUrl(raw: string): string | null {\n let url = raw.replace(/[.,;:!?)]+$/, \"\").trim();\n if (!/^https?:\\/\\//i.test(url)) {\n url = `https://${url}`;\n }\n try {\n new URL(url);\n return url;\n } catch {\n return null;\n }\n}\n\n/**\n * Extract unique, valid URLs from a string (e.g. user message or details).\n * Handles both full URLs (https://...) and bare domains (github.com/...).\n */\nexport function extractUrls(text: string): string[] {\n if (!text || typeof text !== \"string\") return [];\n\n const seen = new Set<string>();\n const out: string[] = [];\n\n // Pass 1: full protocol URLs\n const fullMatches = text.match(URL_IN_TEXT_REGEX) ?? [];\n for (const raw of fullMatches) {\n const url = normalizeUrl(raw);\n if (url && !seen.has(url)) {\n seen.add(url);\n out.push(url);\n }\n }\n\n // Pass 2: bare domain URLs (e.g. github.com/foo)\n const bareMatches = text.match(BARE_URL_REGEX) ?? [];\n for (const raw of bareMatches) {\n const url = normalizeUrl(raw);\n if (url && !seen.has(url)) {\n seen.add(url);\n out.push(url);\n }\n }\n\n return out;\n}\n\nconst SENSITIVE_FIELD_KEYS = new Set([\n \"secret\",\n \"webhooksecret\",\n \"password\",\n \"apikey\",\n \"token\",\n \"accesstoken\",\n \"refreshtoken\",\n \"privatekey\",\n \"authtoken\",\n \"bearertoken\",\n \"clientsecret\",\n]);\n\n/**\n * Recursively redacts sensitive field values from an arbitrary payload before\n * it is passed to a structured logger. Matches field names case-insensitively\n * and ignoring underscores, so `api_key`, `apiKey`, and `API_KEY` all match.\n * Non-sensitive fields are passed through unchanged. Never mutates the input —\n * returns a new value.\n *\n * Intended for structured-log redaction only. Do NOT use as a security\n * boundary for data in motion.\n *\n * @param value - Arbitrary JSON-like payload (query object, config blob, etc.)\n * @returns A new value with sensitive fields replaced by `\"[redacted]\"`.\n */\nexport function redactSensitiveFields(value: unknown): unknown {\n if (value === null || typeof value !== \"object\") return value;\n if (Array.isArray(value)) {\n return value.map((item) => redactSensitiveFields(item));\n }\n const out: Record<string, unknown> = {};\n for (const [key, inner] of Object.entries(value as Record<string, unknown>)) {\n const normalized = key.toLowerCase().replace(/_/g, \"\");\n if (SENSITIVE_FIELD_KEYS.has(normalized)) {\n out[key] = \"[redacted]\";\n } else {\n out[key] = redactSensitiveFields(inner);\n }\n }\n return out;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"tool.helpers.js","sourceRoot":"/","sources":["shared/agent/tool.helpers.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,uBAAuB,EAAE,kBAAkB,EAAE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,OAAO,KAAK,CAAC;IAC9D,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACzB,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAC,CAAC;IAC1D,CAAC;IACD,MAAM,GAAG,GAA4B,EAAE,CAAC;IACxC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAgC,CAAC,EAAE,CAAC;QAC5E,MAAM,UAAU,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;QACvD,IAAI,oBAAoB,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,CAAC;YACzC,GAAG,CAAC,GAAG,CAAC,GAAG,YAAY,CAAC;QAC1B,CAAC;aAAM,CAAC;YACN,GAAG,CAAC,GAAG,CAAC,GAAG,qBAAqB,CAAC,KAAK,CAAC,CAAC;QAC1C,CAAC;IACH,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import { z } from \"zod\";\nimport type { ModelConfig } from \"./model.config.js\";\nimport { deriveAllowedNetworkIds, scopeFromNetworkId } from \"./tool.scope.js\";\nimport type { ToolScopeType } from \"./tool.scope.js\";\nimport type { UserIdentity } from \"../schemas/identity.schema.js\";\nimport type { ChatGraphCompositeDatabase, NetworkMembership, UserRecord, UserDatabase, SystemDatabase, NegotiationGraphDatabase } from \"../interfaces/database.interface.js\";\nimport type { Scraper } from \"../interfaces/scraper.interface.js\";\nimport type { Cache, HydeCache } from \"../interfaces/cache.interface.js\";\nimport type { CompiledOpportunityGraph } from \"../../opportunity/opportunity.discover.js\";\nimport type { IntegrationAdapter } from \"../interfaces/integration.interface.js\";\nimport type { ContactServiceAdapter } from \"../interfaces/contact.interface.js\";\nimport type { ProfileEnricher } from \"../interfaces/enrichment.interface.js\";\nimport type { IntentGraphQueue } from \"../interfaces/queue.interface.js\";\nimport type { ChatSessionReader } from \"../interfaces/chat-session.interface.js\";\nimport type { ChatSummaryReader } from \"../interfaces/chat-summary.interface.js\";\nimport type { ChatMessageWriter } from \"../interfaces/chat-message-writer.interface.js\";\nimport type { QuestionGeneratorReader } from \"../interfaces/question-generator.interface.js\";\nimport type { NegotiationSummaryReader } from \"../interfaces/negotiation-summary.interface.js\";\nimport type { Embedder } from \"../interfaces/embedder.interface.js\";\nimport type { AgentDatabase } from \"../interfaces/agent.interface.js\";\nimport type { NegotiationTimeoutQueue } from \"../interfaces/negotiation-events.interface.js\";\nimport type { AgentDispatcher } from \"../interfaces/agent-dispatcher.interface.js\";\nimport type { DeliveryLedger } from \"../interfaces/delivery-ledger.interface.js\";\nimport type { MintConnectLink } from \"../interfaces/connect-link.interface.js\";\nimport type { QuestionerDatabase } from \"../interfaces/questioner.interface.js\";\nimport type { QuestionerEnqueueFn } from \"../../questioner/questioner.types.js\";\nimport type { PendingQuestionSummary } from \"../schemas/pending-question.schema.js\";\nimport type { QuestionMode } from \"../schemas/question.schema.js\";\nimport type { DiscoveryRunQueue, DiscoveryRunStore } from \"../interfaces/discovery-run.interface.js\";\nimport type { EnrichmentRunQueue, EnrichmentRunStore } from \"../interfaces/enrichment-run.interface.js\";\n\nexport type IdentityContext = UserIdentity | null;\n\nexport interface ToolErrorReport {\n operation: string;\n subsystem?: string;\n toolName?: string;\n userId?: string;\n tags?: Record<string, string | number | boolean | null | undefined>;\n context?: Record<string, unknown>;\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// COMPILED GRAPH TYPE\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/** Minimal interface for an invokable compiled LangGraph. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type CompiledGraph = { invoke: (input: any) => Promise<any> };\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TOOL CONTEXT TYPES\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Resolved context available to every tool handler.\n * Contains the current user and optional index identity, resolved from DB at init.\n * The LLM can see this context (via system prompt) but cannot change it.\n */\nexport interface ResolvedToolContext {\n // Legacy flat fields (kept for backwards compatibility in tools/prompts).\n userId: string;\n userName: string;\n userEmail: string;\n /** Focused network for scoped chats/agents. Prefer `scopeType`/`scopeId` in new code. */\n networkId?: string;\n /** Focused request scope type. Currently only network scopes exist. */\n scopeType?: ToolScopeType;\n /** Focused request scope id. When `scopeType === 'network'`, this is the focused network id. */\n scopeId?: string;\n indexName?: string;\n /** True when chat is index-scoped and the user owns the index. */\n isOwner?: boolean;\n // Rich identity context for prompt/tool orchestration.\n user: UserRecord;\n userProfile: IdentityContext;\n userNetworks: NetworkMembership[];\n /**\n * @deprecated indexScope is legacy concrete network reach. New code should derive reach\n * from `scopeType`/`scopeId` plus `userNetworks` via `tool.scope.ts`.\n * Removed after call sites are migrated in this plan.\n */\n indexScope: string[];\n scopedIndex?: {\n id: string;\n title: string;\n prompt: string | null;\n type?: string;\n metadata?: Record<string, unknown>;\n permissions?: Record<string, unknown>;\n };\n scopedMembershipRole?: \"owner\" | \"member\";\n /** True when user has not completed onboarding (onboarding.completedAt is null). */\n isOnboarding: boolean;\n /** True when the user has a non-empty name. */\n hasName: boolean;\n /** Chat session ID when tools are used in a chat; used for draft opportunities (context.conversationId). */\n sessionId?: string;\n /** True when the request originates from an MCP transport (no interactive UI available). */\n isMcp?: boolean;\n /** Agent ID when the request originates from an API key linked to an agent. */\n agentId?: string;\n /**\n * Receiver's rendering surface declared by the MCP client via the\n * `x-index-surface` request header. `'telegram'` means the MCP response is\n * being rendered inside a Telegram chat; anything\n * else (including `undefined`) is treated as web. Forwarded into\n * `mintConnectLink` so the click-time redirect can branch.\n */\n clientSurface?: 'telegram' | 'web';\n /**\n * True when the CONTACTS_ENABLED feature flag is on. Carried from the\n * composition root so prompt modules can gate contact-import guidance —\n * when false/unset, the contacts prompt module is not injected, so the\n * orchestrator never advertises Gmail import / add_contact (whose tools\n * are also de-registered). Fail-closed: treat only `true` as enabled.\n */\n contactsEnabled?: boolean;\n}\n\n/**\n * Dependencies passed when creating tools for a user session.\n * Includes DB adapters, embedder, and scraper.\n *\n * Note: userDb and systemDb are optional inputs - if not provided, createChatTools\n * will create them internally from the chatDatabaseAdapter singleton.\n */\nexport interface ToolContext {\n userId: string;\n /** @deprecated Use userDb or systemDb instead. Kept for backwards compatibility. */\n database: ChatGraphCompositeDatabase;\n /** Context-bound database for accessing the authenticated user's own resources. Created internally if not provided. */\n userDb?: UserDatabase;\n /** Context-bound database for LLM/system operations on cross-user resources within shared indexes. Created internally if not provided. */\n systemDb?: SystemDatabase;\n embedder: Embedder;\n scraper: Scraper;\n /** When set, chat is scoped to this index; tools use it as the default focused network. */\n networkId?: string;\n /** Focused request scope type. Currently only `network` is supported. */\n scopeType?: ToolScopeType;\n /** Focused request scope id. When omitted, `networkId` is converted to a network scope. */\n scopeId?: string;\n /** @deprecated indexScope is legacy; use `scopeType`/`scopeId`, retained until wiring phases migrate call sites. */\n indexScope?: string[];\n /** Chat session ID when creating tools for a chat; enables draft opportunities with context.conversationId. */\n sessionId?: string;\n\n // ─── Protocol-level dependencies (injected by composition root) ──────────\n /** General-purpose cache (e.g. for tool results). */\n cache: Cache;\n /** Dedicated cache for HyDE graph (may be same instance as cache). */\n hydeCache: HydeCache;\n /** External integration platform adapter (OAuth, tool actions). */\n integration: IntegrationAdapter;\n /** Queue for enqueuing follow-up intent processing (HyDE generation/deletion). */\n intentQueue: IntentGraphQueue;\n /** Contact management operations. */\n contactService: ContactServiceAdapter;\n /**\n * When false (or unset), the contact import / manual-add tools\n * (import_contacts, add_contact, import_gmail_contacts) are not registered.\n * Injected by the composition root from CONTACTS_ENABLED. Read/remove/search\n * contact tools are always registered.\n */\n contactsEnabled?: boolean;\n /** Chat session reader for loading conversation history. */\n chatSession: ChatSessionReader;\n /** Read-through chat-session digest. Optional; consumers fall back to undefined `chatContext`. */\n chatSummary?: ChatSummaryReader;\n /** Writes user messages into the user's most-recent chat session (Slice 5 MCP elicitation). */\n chatMessageWriter?: ChatMessageWriter;\n /** Decision-question generator. Optional; consumers fall back to no `questions`. */\n questionGenerator?: QuestionGeneratorReader;\n /**\n * Optional async question enqueue callback. When provided, question generation\n * is dispatched asynchronously to the QuestionerQueue instead of running inline.\n * Injected by the composition root when QUESTIONER_ENABLED=true.\n */\n questionerEnqueue?: QuestionerEnqueueFn;\n /** Negotiation-digest summarizer. Optional; consumers fall back to deterministic digests. */\n negotiationSummary?: NegotiationSummaryReader;\n /** Profile enrichment from external data sources. */\n enricher: ProfileEnricher;\n /** Database adapter for negotiation/conversation operations. */\n negotiationDatabase: NegotiationGraphDatabase;\n /** Integration importer for bulk contact import from toolkits. */\n integrationImporter: {\n importContacts(userId: string, toolkit: string): Promise<{\n imported: number;\n skipped: number;\n newContacts: number;\n existingContacts: number;\n }>;\n };\n /** Factory for user-scoped database access. */\n createUserDatabase: (db: ChatGraphCompositeDatabase, userId: string) => UserDatabase;\n /** Factory for system-scoped database access. */\n createSystemDatabase: (db: ChatGraphCompositeDatabase, userId: string, indexScope: string[], embedder?: Embedder) => SystemDatabase;\n /** Optional runtime LLM config. Pass to override env vars for API key, model, etc. */\n modelConfig?: ModelConfig;\n /** Manages negotiation timeout jobs (optional — enables AI fallback on external agent timeout). */\n negotiationTimeoutQueue?: NegotiationTimeoutQueue;\n /** Agent registry database adapter (optional — absent when host does not support agents). */\n agentDatabase?: AgentDatabase;\n /** Grants the default system-agent permissions after onboarding (optional). */\n grantDefaultSystemPermissions?: (userId: string) => Promise<void>;\n /** Dispatcher for routing negotiation turns to personal agents (optional — falls back to system AI). */\n agentDispatcher?: AgentDispatcher;\n /** Enqueue a negotiate_existing job after introducer approval (optional). */\n queueNegotiateExisting?: (opportunityId: string, userId: string) => Promise<void>;\n /** Delivery ledger for committing opportunity delivery rows (optional — absent in chat context). */\n deliveryLedger?: DeliveryLedger;\n /** Persistence for async MCP discovery runs (optional — absent in non-MCP/test contexts). */\n discoveryRuns?: DiscoveryRunStore;\n /** Queue for async MCP discovery run execution (optional — absent in non-MCP/test contexts). */\n discoveryRunQueue?: DiscoveryRunQueue;\n /** Persistence for async MCP profile runs (optional — absent in non-MCP/test contexts). */\n enrichmentRuns?: EnrichmentRunStore;\n /** Queue for async MCP profile run execution (optional — absent in non-MCP/test contexts). */\n enrichmentRunQueue?: EnrichmentRunQueue;\n /**\n * Legacy direct-token minting for opportunity accept redirects.\n * Prefer `mintConnectLink` for user-facing links.\n */\n mintConnectToken?: (userId: string, opportunityId: string) => Promise<string>;\n /** Mints (or reuses) a short connect link, snapshotting the greeting (optional — absent in non-MCP contexts). */\n mintConnectLink?: MintConnectLink;\n /** Frontend base URL for building profile links (e.g. https://index.network, optional). */\n frontendUrl?: string;\n /** API base URL for building opportunity accept links (e.g. https://protocol.index.network, optional). */\n apiBaseUrl?: string;\n /** Persistence for structured questions generated by the QuestionerAgent (optional). */\n questionerDatabase?: QuestionerDatabase;\n /** Optional host-side error reporter for swallowed protocol/tool errors. */\n reportToolError?: (error: unknown, report: ToolErrorReport) => void;\n /**\n * Optional host-side per-principal MCP call throttle. Invoked once per MCP\n * tool dispatch (after identity resolves, before any DB work). When the\n * returned decision is `allowed: false`, the dispatch short-circuits with a\n * rate-limit error carrying `retryAfterSec`. Absent in chat/test contexts.\n */\n mcpRateLimiter?: (input: { userId: string; agentId?: string; toolName: string }) => Promise<{\n allowed: boolean;\n retryAfterSec?: number;\n limit?: number;\n scope?: 'tool' | 'principal';\n }>;\n /** Optional premise lifecycle event callbacks. Fired by premise tools after successful operations. */\n premiseEvents?: {\n onCreated?: (premiseId: string, userId: string) => void;\n onUpdated?: (premiseId: string, userId: string) => void;\n onRetracted?: (premiseId: string, userId: string) => void;\n };\n}\n\n/**\n * All external dependencies needed to initialize the protocol tool engine.\n * The host application (composition root) must provide concrete implementations.\n * This is the subset of ToolContext that is NOT per-request (no userId, indexId, sessionId).\n */\nexport type ProtocolDeps = Omit<ToolContext, 'userId' | 'indexId' | 'sessionId' | 'userDb' | 'systemDb'>;\n\n/**\n * Thrown when a requested chat scope is invalid for the authenticated user.\n * Controllers can map this to an HTTP status code.\n */\nexport class ChatContextAccessError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number,\n public readonly code: \"USER_NOT_FOUND\" | \"INDEX_NOT_FOUND\" | \"INDEX_MEMBERSHIP_REQUIRED\"\n ) {\n super(message);\n this.name = \"ChatContextAccessError\";\n }\n}\n\n/**\n * Resolve the canonical context used by chat tools and system prompt.\n * This preloads user identity, profile, index memberships, and scoped index role.\n */\nexport async function resolveChatContext(params: {\n database: Pick<\n ChatGraphCompositeDatabase,\n \"getUser\" | \"getProfile\" | \"getNetworkMemberships\" | \"getNetworkMembership\" | \"getNetwork\" | \"isIndexOwner\" | \"isNetworkMember\"\n >;\n userId: string;\n networkId?: string;\n /** Chat session ID for draft opportunities (stored as context.conversationId). */\n sessionId?: string;\n /** CONTACTS_ENABLED flag, forwarded onto the resolved context for prompt gating. */\n contactsEnabled?: boolean;\n}): Promise<ResolvedToolContext> {\n const { database, userId, networkId, sessionId, contactsEnabled } = params;\n\n const [user, rawProfile, userNetworks] = await Promise.all([\n database.getUser(userId),\n database.getProfile(userId),\n database.getNetworkMemberships(userId),\n ]);\n\n const userProfile: IdentityContext = rawProfile ?? null;\n\n if (!user) {\n throw new ChatContextAccessError(\n \"User not found\",\n 404,\n \"USER_NOT_FOUND\"\n );\n }\n\n let scopedIndex: ResolvedToolContext[\"scopedIndex\"] = undefined;\n let scopedMembershipRole: ResolvedToolContext[\"scopedMembershipRole\"] = undefined;\n let isOwner = false;\n let indexName: string | undefined;\n\n if (networkId) {\n const [index, isMember, owner] = await Promise.all([\n database.getNetwork(networkId),\n database.isNetworkMember(networkId, userId),\n database.isIndexOwner(networkId, userId),\n ]);\n\n if (!index) {\n throw new ChatContextAccessError(\n \"Index not found\",\n 404,\n \"INDEX_NOT_FOUND\"\n );\n }\n\n if (!isMember) {\n throw new ChatContextAccessError(\n \"You are not a member of this index\",\n 403,\n \"INDEX_MEMBERSHIP_REQUIRED\"\n );\n }\n\n let membership = userNetworks.find((m) => m.networkId === index.id);\n if (membership === undefined) {\n membership = (await database.getNetworkMembership(index.id, userId)) ?? undefined;\n }\n scopedIndex = {\n id: index.id,\n title: index.title,\n prompt: membership?.indexPrompt ?? null,\n type: index.type ?? 'community',\n metadata: index.metadata ?? {},\n permissions: index.permissions ?? {},\n };\n isOwner = owner;\n indexName = index.title;\n scopedMembershipRole = owner ? \"owner\" : \"member\";\n }\n\n const userName = user.name ?? \"Unknown\";\n const userEmail = user.email ?? \"\";\n const hasName = !!user.name?.trim();\n\n const scope = scopeFromNetworkId(networkId);\n\n // Deprecated compatibility reach. New call sites should call\n // deriveAllowedNetworkIds({ memberships: userNetworks, ...scope }) directly.\n const allowedNetworkIds = deriveAllowedNetworkIds({\n memberships: userNetworks,\n ...scope,\n });\n\n return {\n userId,\n userName,\n userEmail,\n networkId,\n ...scope,\n indexName,\n isOwner,\n user,\n userProfile,\n userNetworks,\n indexScope: allowedNetworkIds,\n scopedIndex,\n scopedMembershipRole,\n isOnboarding: !(user.onboarding?.completedAt),\n hasName,\n contactsEnabled,\n ...(sessionId !== undefined ? { sessionId } : {}),\n };\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// DEFINE TOOL TYPE\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Type for the `defineTool` closure created in `createChatTools`.\n * Auto-injects resolved context and provides uniform logging / error handling.\n */\nexport type DefineTool = <T extends z.ZodType>(opts: {\n name: string;\n description: string;\n querySchema: T;\n handler: (input: { context: ResolvedToolContext; query: z.infer<T> }) => Promise<string>;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n}) => any;\n\n/**\n * A raw tool definition before LangChain wrapping.\n * Used by the tool registry for direct HTTP invocation.\n */\nexport interface RawToolDefinition {\n name: string;\n description: string;\n schema: z.ZodType;\n handler: (input: { context: ResolvedToolContext; query: unknown }) => Promise<string>;\n}\n\n/**\n * Registry mapping tool names to their raw definitions.\n */\nexport type ToolRegistry = Map<string, RawToolDefinition>;\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TOOL DEPENDENCIES\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Shared dependencies available to all tool domain factories.\n * Passed by `createChatTools` after compiling all subgraphs.\n */\nexport interface ToolDeps {\n /** @deprecated Use userDb or systemDb instead. Kept for backwards compatibility. */\n database: ChatGraphCompositeDatabase;\n /** Context-bound database for accessing the authenticated user's own resources. */\n userDb: UserDatabase;\n /** Context-bound database for LLM/system operations on cross-user resources within shared indexes. */\n systemDb: SystemDatabase;\n scraper: Scraper;\n embedder: import('../interfaces/embedder.interface.js').Embedder;\n cache: Cache;\n integration: IntegrationAdapter;\n contactService: ContactServiceAdapter;\n /**\n * When false (or unset), the contact import / manual-add tools\n * (import_contacts, add_contact, import_gmail_contacts) are not registered.\n * Injected by the composition root from CONTACTS_ENABLED. Read/remove/search\n * contact tools are always registered.\n */\n contactsEnabled?: boolean;\n integrationImporter: {\n importContacts(userId: string, toolkit: string): Promise<{\n imported: number;\n skipped: number;\n newContacts: number;\n existingContacts: number;\n }>;\n };\n enricher: ProfileEnricher;\n /** Database adapter for negotiation/conversation operations. */\n negotiationDatabase: NegotiationGraphDatabase;\n /** Chat session reader for exposing the caller's past conversations as MCP tools. */\n chatSession?: ChatSessionReader;\n /** Read-through chat-session digest. Optional; consumers fall back to undefined `chatContext`. */\n chatSummary?: ChatSummaryReader;\n /**\n * Test seam for opportunity discovery helpers. Production compositions leave\n * this unset so tools call the real discovery module directly.\n */\n opportunityDiscovery?: {\n runDiscoverFromQuery?: (input: unknown) => Promise<unknown>;\n continueDiscovery?: (input: unknown) => Promise<unknown>;\n };\n /**\n * Test seam for opportunity card presentation helpers. Production\n * compositions leave this unset so tools construct the real presenter.\n */\n opportunityPresentation?: {\n createPresenter?: () => { presentHomeCard(input: unknown): Promise<unknown> };\n gatherPresenterContext?: (...args: unknown[]) => Promise<unknown>;\n };\n /** Writes user messages into the user's most-recent chat session (Slice 5 MCP elicitation). */\n chatMessageWriter?: ChatMessageWriter;\n /** Decision-question generator. Optional; consumers fall back to no `questions`. */\n questionGenerator?: QuestionGeneratorReader;\n /**\n * Optional async question enqueue callback. When provided, question generation\n * is dispatched asynchronously to the QuestionerQueue instead of running inline\n * via the `questionGenerator`. Injected by the composition root when\n * QUESTIONER_ENABLED=true.\n */\n questionerEnqueue?: QuestionerEnqueueFn;\n /**\n * Lookup pending questions for a user, optionally filtered by source,\n * detection mode, or capped by count (hosts apply `limit` SQL-side).\n * Used by tools to attach contextually relevant questions to their results.\n * Injected by the composition root — absent when question delivery is disabled.\n */\n findPendingQuestions?: (\n userId: string,\n filters?: {\n sourceType?: string;\n sourceId?: string;\n /** Restrict to questions whose actor carries this network id. */\n networkId?: string;\n /** Restrict to questions whose detection mode is in this set. */\n modes?: QuestionMode[];\n /** Maximum rows to return; hosts should apply this in the query. */\n limit?: number;\n },\n ) => Promise<PendingQuestionSummary[]>;\n /** Negotiation-digest summarizer. Optional; consumers fall back to deterministic digests. */\n negotiationSummary?: NegotiationSummaryReader;\n /** Manages negotiation timeout jobs (optional — enables AI fallback on external agent timeout). */\n negotiationTimeoutQueue?: NegotiationTimeoutQueue;\n /** Agent registry database adapter (optional — absent when host does not support agents). */\n agentDatabase?: AgentDatabase;\n /** Grants the default system-agent permissions after onboarding (optional). */\n grantDefaultSystemPermissions?: (userId: string) => Promise<void>;\n /** Dispatcher for routing negotiation turns to personal agents (optional — falls back to system AI). */\n agentDispatcher?: AgentDispatcher;\n /** Delivery ledger for committing opportunity delivery rows (optional — absent in chat context). */\n deliveryLedger?: DeliveryLedger;\n /** Persistence for async MCP discovery runs (optional — absent in non-MCP/test contexts). */\n discoveryRuns?: DiscoveryRunStore;\n /** Queue for async MCP discovery run execution (optional — absent in non-MCP/test contexts). */\n discoveryRunQueue?: DiscoveryRunQueue;\n /** Persistence for async MCP profile runs (optional — absent in non-MCP/test contexts). */\n enrichmentRuns?: EnrichmentRunStore;\n /** Queue for async MCP profile run execution (optional — absent in non-MCP/test contexts). */\n enrichmentRunQueue?: EnrichmentRunQueue;\n /**\n * Legacy direct-token minting for opportunity accept redirects.\n * Prefer `mintConnectLink` for user-facing links.\n */\n mintConnectToken?: (userId: string, opportunityId: string) => Promise<string>;\n /** Mints (or reuses) a short connect link, snapshotting the greeting (optional — absent in non-MCP contexts). */\n mintConnectLink?: MintConnectLink;\n /** Frontend base URL for building profile links (e.g. https://index.network, optional). */\n frontendUrl?: string;\n /** API base URL for building opportunity accept links (e.g. https://protocol.index.network, optional). */\n apiBaseUrl?: string;\n /** Optional host-side error reporter for swallowed protocol/tool errors. */\n reportToolError?: (error: unknown, report: ToolErrorReport) => void;\n /**\n * Optional host-side per-principal MCP call throttle. Invoked once per MCP\n * tool dispatch (after identity resolves, before any DB work). When the\n * returned decision is `allowed: false`, the dispatch short-circuits with a\n * rate-limit error carrying `retryAfterSec`. Absent in chat/test contexts.\n */\n mcpRateLimiter?: (input: { userId: string; agentId?: string; toolName: string }) => Promise<{\n allowed: boolean;\n retryAfterSec?: number;\n limit?: number;\n scope?: 'tool' | 'principal';\n }>;\n /** Optional premise lifecycle event callbacks. Fired by premise tools after successful operations. */\n premiseEvents?: {\n onCreated?: (premiseId: string, userId: string) => void;\n onUpdated?: (premiseId: string, userId: string) => void;\n onRetracted?: (premiseId: string, userId: string) => void;\n };\n graphs: {\n profile: CompiledGraph;\n intent: CompiledGraph;\n index: CompiledGraph;\n networkMembership: CompiledGraph;\n intentIndex: CompiledGraph;\n opportunity: CompiledOpportunityGraph;\n premise: CompiledGraph;\n };\n /**\n * Optional network ranking override for `read_networks`. Injected by tests or custom compositions.\n * When absent, defaults to `NetworkRecommender.invoke()` with a lazy module-level singleton.\n */\n networkRanker?: (input: {\n userContext: string;\n networks: Array<{ networkId: string; renderedContext: string }>;\n }) => Promise<{ rankedNetworkIds: string[] } | null>;\n /**\n * Resolve a user's global user_context paragraph (profile-replacing identity text),\n * generating it on demand when absent. Injected by the backend composition root\n * (`ensureGlobalUserContext`). When absent, onboarding network ranking is skipped.\n */\n getUserContextText?: (userId: string) => Promise<string>;\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TOOL RESULT HELPERS\n// ═══════════════════════════════════════════════════════════════════════════════\n\nexport function success<T>(data: T): string {\n return JSON.stringify({ success: true, data });\n}\n\nexport function error(\n message: string,\n debugSteps?: Array<{ step: string; detail?: string; data?: Record<string, unknown> }>\n): string {\n return JSON.stringify({\n success: false,\n error: message,\n ...(debugSteps?.length ? { debugSteps } : {}),\n });\n}\n\n/** Return needsClarification for missing required fields. */\nexport function needsClarification(params: {\n missingFields: string[];\n message: string;\n}): string {\n return JSON.stringify({\n success: false,\n needsClarification: true,\n ...params,\n });\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// CONSTANTS & UTILITIES\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/** Matches http/https URLs in text; captures full URL. */\nconst URL_IN_TEXT_REGEX = /https?:\\/\\/[^\\s\"'<>)\\]]+/gi;\n\n/**\n * Matches bare domain URLs without protocol (e.g. github.com/foo, www.example.com).\n * Requires at least a SLD.TLD pattern followed by optional path.\n * Negative lookbehind ensures we don't double-match URLs already caught by URL_IN_TEXT_REGEX.\n */\nconst BARE_URL_REGEX = /(?<!\\w:\\/\\/)(?<![/\\w])(?:www\\.)?[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.(?:com|org|net|io|dev|co|ai|app|xyz|me|info|gg|so|sh|cc|ly|fm|tv|to|tech|design|network|world|edu|gov|mil|int|us|uk|eu|de|fr|ca|au|jp|cn|in|br|nl|se|no|fi|dk|ch|at|be|it|es|pt|pl|cz|ru|kr|tw|hk|sg|nz|za|mx|ar|cl|id|ph|th|vn|my|ie)(?:\\/[^\\s\"'<>)\\]]*)?/gi;\n\n/** UUID v4 format: 8-4-4-4-12 hex chars (e.g. c2505011-2e45-426e-81dd-b9abb9b72023) */\nexport const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/**\n * Resolves an array of network IDs to their display titles.\n * Skips any IDs that don't resolve (deleted or invalid networks).\n */\nexport async function resolveIndexNames(\n database: { getNetwork(id: string): Promise<{ id: string; title: string } | null> },\n networkIds: string[]\n): Promise<string[]> {\n if (networkIds.length === 0) return [];\n const results = await Promise.all(\n networkIds.map(id => database.getNetwork(id))\n );\n return results.filter(Boolean).map(idx => idx!.title);\n}\n\n/**\n * Normalize a URL string: if it lacks a protocol, prepend \"https://\".\n * Returns the normalized URL or null if the result is not a valid URL.\n */\nexport function normalizeUrl(raw: string): string | null {\n let url = raw.replace(/[.,;:!?)]+$/, \"\").trim();\n if (!/^https?:\\/\\//i.test(url)) {\n url = `https://${url}`;\n }\n try {\n new URL(url);\n return url;\n } catch {\n return null;\n }\n}\n\n/**\n * Extract unique, valid URLs from a string (e.g. user message or details).\n * Handles both full URLs (https://...) and bare domains (github.com/...).\n */\nexport function extractUrls(text: string): string[] {\n if (!text || typeof text !== \"string\") return [];\n\n const seen = new Set<string>();\n const out: string[] = [];\n\n // Pass 1: full protocol URLs\n const fullMatches = text.match(URL_IN_TEXT_REGEX) ?? [];\n for (const raw of fullMatches) {\n const url = normalizeUrl(raw);\n if (url && !seen.has(url)) {\n seen.add(url);\n out.push(url);\n }\n }\n\n // Pass 2: bare domain URLs (e.g. github.com/foo)\n const bareMatches = text.match(BARE_URL_REGEX) ?? [];\n for (const raw of bareMatches) {\n const url = normalizeUrl(raw);\n if (url && !seen.has(url)) {\n seen.add(url);\n out.push(url);\n }\n }\n\n return out;\n}\n\nconst SENSITIVE_FIELD_KEYS = new Set([\n \"secret\",\n \"webhooksecret\",\n \"password\",\n \"apikey\",\n \"token\",\n \"accesstoken\",\n \"refreshtoken\",\n \"privatekey\",\n \"authtoken\",\n \"bearertoken\",\n \"clientsecret\",\n]);\n\n/**\n * Recursively redacts sensitive field values from an arbitrary payload before\n * it is passed to a structured logger. Matches field names case-insensitively\n * and ignoring underscores, so `api_key`, `apiKey`, and `API_KEY` all match.\n * Non-sensitive fields are passed through unchanged. Never mutates the input —\n * returns a new value.\n *\n * Intended for structured-log redaction only. Do NOT use as a security\n * boundary for data in motion.\n *\n * @param value - Arbitrary JSON-like payload (query object, config blob, etc.)\n * @returns A new value with sensitive fields replaced by `\"[redacted]\"`.\n */\nexport function redactSensitiveFields(value: unknown): unknown {\n if (value === null || typeof value !== \"object\") return value;\n if (Array.isArray(value)) {\n return value.map((item) => redactSensitiveFields(item));\n }\n const out: Record<string, unknown> = {};\n for (const [key, inner] of Object.entries(value as Record<string, unknown>)) {\n const normalized = key.toLowerCase().replace(/_/g, \"\");\n if (SENSITIVE_FIELD_KEYS.has(normalized)) {\n out[key] = \"[redacted]\";\n } else {\n out[key] = redactSensitiveFields(inner);\n }\n }\n return out;\n}\n"]}
|
|
@@ -33,7 +33,7 @@ export function createToolRegistry(deps) {
|
|
|
33
33
|
schema: opts.querySchema,
|
|
34
34
|
handler: async (input) => {
|
|
35
35
|
logger.verbose(`Tool: ${opts.name}`, {
|
|
36
|
-
context: { userId: input.context.userId,
|
|
36
|
+
context: { userId: input.context.userId, scopeType: input.context.scopeType, scopeId: input.context.scopeId },
|
|
37
37
|
query: redactSensitiveFields(input.query),
|
|
38
38
|
});
|
|
39
39
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool.registry.js","sourceRoot":"/","sources":["shared/agent/tool.registry.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AACjE,OAAO,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAC7E,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACpE,OAAO,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AAChF,OAAO,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AAI,CAAC,oCAAoC,OAAO,eAAe,aAAa,YAAY,CAAC,CAAC;YACjG,SAAS;QACX,CAAC;QACD,QAAQ,CAAC,GAAG,CAAC,OAAO,EAAE;YACpB,GAAG,SAAS;YACZ,IAAI,EAAE,OAAO;YACb,WAAW,EAAE,uBAAuB,aAAa,uFAAuF,SAAS,CAAC,WAAW,EAAE;SAChK,CAAC,CAAC;IACL,CAAC;IAED,MAAM,CAAC,OAAO,CAAC,8BAA8B,QAAQ,CAAC,IAAI,QAAQ,CAAC,CAAC;IACpE,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import { z } from 'zod';\n\nimport type { DefineTool, ResolvedToolContext, ToolDeps, RawToolDefinition, ToolRegistry } from './tool.helpers.js';\nimport { error, redactSensitiveFields } from './tool.helpers.js';\nimport { createEnrichmentTools } from '../../enrichment/enrichment.tools.js';\nimport { createIntentTools } from '../../intent/intent.tools.js';\nimport { createNetworkTools } from '../../network/network.tools.js';\nimport { createOpportunityTools } from '../../opportunity/opportunity.tools.js';\nimport { createUtilityTools } from './utility.tools.js';\nimport { createIntegrationTools } from '../../integration/integration.tools.js';\nimport { createContactTools } from '../../contact/contact.tools.js';\nimport { createAgentTools } from '../../agent/agent.tools.js';\nimport { createNegotiationTools } from '../../negotiation/negotiation.tools.js';\nimport { createChatTools } from '../../chat/chat.tools.js';\nimport { createPremiseTools } from '../../premise/premise.tools.js';\nimport { createQuestionerTools } from '../../questioner/questioner.tools.js';\nimport { protocolLogger } from '../observability/protocol.logger.js';\nimport { requestContext } from '../observability/request-context.js';\n\nconst logger = protocolLogger('ToolRegistry');\n\n/**\n * Creates a tool registry containing all tool handlers indexed by name.\n * Handlers are raw async functions (not LangChain tool() wrappers) that\n * accept { context, query } and return a JSON string.\n *\n * @param deps - Shared tool dependencies (graphs, database, embedder, etc.)\n * @param context - Resolved user context for this request.\n * @returns Map of tool name to raw tool definition.\n */\nexport function createToolRegistry(deps: ToolDeps): ToolRegistry {\n const registry: ToolRegistry = new Map();\n\n // defineTool that captures raw handlers into the registry\n function defineTool<T extends z.ZodType>(opts: {\n name: string;\n description: string;\n querySchema: T;\n handler: (input: { context: ResolvedToolContext; query: z.infer<T> }) => Promise<string>;\n }) {\n const entry: RawToolDefinition = {\n name: opts.name,\n description: opts.description,\n schema: opts.querySchema,\n handler: async (input: { context: ResolvedToolContext; query: unknown }) => {\n logger.verbose(`Tool: ${opts.name}`, {\n context: { userId: input.context.userId, scopeType: input.context.scopeType, scopeId: input.context.scopeId },\n query: redactSensitiveFields(input.query),\n });\n try {\n return await opts.handler({ context: input.context, query: input.query as z.infer<T> });\n } catch (err) {\n const abortSignal = requestContext.getStore()?.abortSignal;\n if (abortSignal?.aborted) {\n throw err;\n }\n logger.error(`${opts.name} failed`, {\n error: err instanceof Error ? err.message : String(err),\n });\n return error(`Failed to execute ${opts.name}: ${err instanceof Error ? err.message : String(err)}`);\n }\n },\n };\n\n registry.set(opts.name, entry);\n\n // Return a dummy — create*Tools functions collect return values into arrays,\n // but for the registry path we only need the side-effect on the Map.\n return null as unknown;\n }\n\n // Create all tool domains -- each one calls defineTool() which populates the registry.\n // The local defineTool is compatible with DefineTool (which returns any).\n const dt = defineTool as DefineTool;\n createEnrichmentTools(dt, deps);\n createIntentTools(dt, deps);\n createNetworkTools(dt, deps);\n createOpportunityTools(dt, deps);\n createUtilityTools(dt, deps);\n createIntegrationTools(dt, deps);\n createContactTools(dt, deps);\n createAgentTools(dt, deps);\n createNegotiationTools(dt, deps);\n createPremiseTools(dt, deps);\n createQuestionerTools(dt, deps);\n if (deps.chatSession) {\n createChatTools(dt, deps);\n }\n\n // Deprecated tool-name aliases (IND-371). The canonical implementations are now\n // registered under their *_user_context / *_enrichment_run names; we expose the\n // legacy *_user_profile / *_profile_run names as thin aliases that delegate to the\n // exact same handler + schema, so existing MCP clients keep working while they\n // migrate. The old names are removed in IND-373.\n const DEPRECATED_TOOL_ALIASES: ReadonlyArray<readonly [oldName: string, canonicalName: string]> = [\n [\"read_user_profiles\", \"read_user_contexts\"],\n [\"create_user_profile\", \"create_user_context\"],\n [\"update_user_profile\", \"update_user_context\"],\n [\"confirm_user_profile\", \"confirm_user_context\"],\n [\"preview_user_profile\", \"preview_user_context\"],\n [\"get_profile_run\", \"get_enrichment_run\"],\n [\"cancel_profile_run\", \"cancel_enrichment_run\"],\n ];\n for (const [oldName, canonicalName] of DEPRECATED_TOOL_ALIASES) {\n const canonical = registry.get(canonicalName);\n if (!canonical) {\n logger.warn(`Cannot register deprecated alias ${oldName}: canonical ${canonicalName} not found`);\n continue;\n }\n registry.set(oldName, {\n ...canonical,\n name: oldName,\n description: `[DEPRECATED — use \\`${canonicalName}\\` instead; this alias is retained for backward compatibility and will be removed.] ${canonical.description}`,\n });\n }\n\n logger.verbose(`Tool registry created with ${registry.size} tools`);\n return registry;\n}\n"]}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Request scope primitives for protocol tools.
|
|
3
|
+
*
|
|
4
|
+
* `scopeType`/`scopeId` describe the user's focused scope, not the full set of
|
|
5
|
+
* networks a caller may read or write. Helper functions derive concrete network
|
|
6
|
+
* id sets from the focused scope plus the caller's memberships.
|
|
7
|
+
*/
|
|
8
|
+
export type ToolScopeType = 'network';
|
|
9
|
+
export interface ToolScopeEnvelope {
|
|
10
|
+
scopeType?: ToolScopeType;
|
|
11
|
+
scopeId?: string;
|
|
12
|
+
}
|
|
13
|
+
export interface ScopeMembership {
|
|
14
|
+
networkId: string;
|
|
15
|
+
isPersonal?: boolean | null;
|
|
16
|
+
}
|
|
17
|
+
export interface DeriveNetworkScopeInput extends ToolScopeEnvelope {
|
|
18
|
+
memberships: ScopeMembership[];
|
|
19
|
+
}
|
|
20
|
+
export declare function scopeFromNetworkId(networkId: string | null | undefined): ToolScopeEnvelope;
|
|
21
|
+
export declare function hasNetworkScope(scope: ToolScopeEnvelope): scope is {
|
|
22
|
+
scopeType: 'network';
|
|
23
|
+
scopeId: string;
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Returns the focused network id from the canonical scope envelope.
|
|
27
|
+
*
|
|
28
|
+
* This intentionally does not inspect legacy `networkId` fields; callers that
|
|
29
|
+
* still need a transition fallback should pass `scopeFromNetworkId(networkId)`
|
|
30
|
+
* at the boundary so tool logic remains envelope-driven.
|
|
31
|
+
*/
|
|
32
|
+
export declare function focusedNetworkId(scope: ToolScopeEnvelope): string | undefined;
|
|
33
|
+
/** Human-readable label for a focused scope, used in scope-restriction notes. */
|
|
34
|
+
export declare function focusedNetworkLabel(scope: ToolScopeEnvelope & {
|
|
35
|
+
indexName?: string;
|
|
36
|
+
}): string;
|
|
37
|
+
export declare function deriveAllowedNetworkIds(input: DeriveNetworkScopeInput): string[];
|
|
38
|
+
export declare function deriveDiscoveryNetworkIds(input: DeriveNetworkScopeInput): string[];
|
|
39
|
+
//# sourceMappingURL=tool.scope.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tool.scope.d.ts","sourceRoot":"/","sources":["shared/agent/tool.scope.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,MAAM,MAAM,aAAa,GAAG,SAAS,CAAC;AAEtC,MAAM,WAAW,iBAAiB;IAChC,SAAS,CAAC,EAAE,aAAa,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,eAAe;IAC9B,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,OAAO,GAAG,IAAI,CAAC;CAC7B;AAED,MAAM,WAAW,uBAAwB,SAAQ,iBAAiB;IAChE,WAAW,EAAE,eAAe,EAAE,CAAC;CAChC;AAMD,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,iBAAiB,CAG1F;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,iBAAiB,GAAG,KAAK,IAAI;IAAE,SAAS,EAAE,SAAS,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAE5G;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,iBAAiB,GAAG,MAAM,GAAG,SAAS,CAE7E;AAED,iFAAiF;AACjF,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,iBAAiB,GAAG;IAAE,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,MAAM,CAE7F;AAED,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,uBAAuB,GAAG,MAAM,EAAE,CAUhF;AAED,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,uBAAuB,GAAG,MAAM,EAAE,CAQlF"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
function uniqueNetworkIds(ids) {
|
|
2
|
+
return [...new Set(ids.map((id) => id.trim()).filter(Boolean))];
|
|
3
|
+
}
|
|
4
|
+
export function scopeFromNetworkId(networkId) {
|
|
5
|
+
const scopeId = networkId?.trim();
|
|
6
|
+
return scopeId ? { scopeType: 'network', scopeId } : {};
|
|
7
|
+
}
|
|
8
|
+
export function hasNetworkScope(scope) {
|
|
9
|
+
return scope.scopeType === 'network' && typeof scope.scopeId === 'string' && scope.scopeId.trim().length > 0;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Returns the focused network id from the canonical scope envelope.
|
|
13
|
+
*
|
|
14
|
+
* This intentionally does not inspect legacy `networkId` fields; callers that
|
|
15
|
+
* still need a transition fallback should pass `scopeFromNetworkId(networkId)`
|
|
16
|
+
* at the boundary so tool logic remains envelope-driven.
|
|
17
|
+
*/
|
|
18
|
+
export function focusedNetworkId(scope) {
|
|
19
|
+
return hasNetworkScope(scope) ? scope.scopeId.trim() : undefined;
|
|
20
|
+
}
|
|
21
|
+
/** Human-readable label for a focused scope, used in scope-restriction notes. */
|
|
22
|
+
export function focusedNetworkLabel(scope) {
|
|
23
|
+
return scope.indexName ?? focusedNetworkId(scope) ?? 'this index';
|
|
24
|
+
}
|
|
25
|
+
export function deriveAllowedNetworkIds(input) {
|
|
26
|
+
if (!hasNetworkScope(input)) {
|
|
27
|
+
return uniqueNetworkIds(input.memberships.map((membership) => membership.networkId));
|
|
28
|
+
}
|
|
29
|
+
return uniqueNetworkIds(input.memberships
|
|
30
|
+
.filter((membership) => membership.networkId === input.scopeId || membership.isPersonal === true)
|
|
31
|
+
.map((membership) => membership.networkId));
|
|
32
|
+
}
|
|
33
|
+
export function deriveDiscoveryNetworkIds(input) {
|
|
34
|
+
if (!hasNetworkScope(input)) {
|
|
35
|
+
return uniqueNetworkIds(input.memberships.map((membership) => membership.networkId));
|
|
36
|
+
}
|
|
37
|
+
return input.memberships.some((membership) => membership.networkId === input.scopeId)
|
|
38
|
+
? [input.scopeId]
|
|
39
|
+
: [];
|
|
40
|
+
}
|
|
41
|
+
//# sourceMappingURL=tool.scope.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tool.scope.js","sourceRoot":"/","sources":["shared/agent/tool.scope.ts"],"names":[],"mappings":"AAuBA,SAAS,gBAAgB,CAAC,GAAa;IACrC,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;AAClE,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,SAAoC;IACrE,MAAM,OAAO,GAAG,SAAS,EAAE,IAAI,EAAE,CAAC;IAClC,OAAO,OAAO,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;AAC1D,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,KAAwB;IACtD,OAAO,KAAK,CAAC,SAAS,KAAK,SAAS,IAAI,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,MA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C;QACnF,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC;QACjB,CAAC,CAAC,EAAE,CAAC;AACT,CAAC","sourcesContent":["/**\n * Request scope primitives for protocol tools.\n *\n * `scopeType`/`scopeId` describe the user's focused scope, not the full set of\n * networks a caller may read or write. Helper functions derive concrete network\n * id sets from the focused scope plus the caller's memberships.\n */\nexport type ToolScopeType = 'network';\n\nexport interface ToolScopeEnvelope {\n scopeType?: ToolScopeType;\n scopeId?: string;\n}\n\nexport interface ScopeMembership {\n networkId: string;\n isPersonal?: boolean | null;\n}\n\nexport interface DeriveNetworkScopeInput extends ToolScopeEnvelope {\n memberships: ScopeMembership[];\n}\n\nfunction uniqueNetworkIds(ids: string[]): string[] {\n return [...new Set(ids.map((id) => id.trim()).filter(Boolean))];\n}\n\nexport function scopeFromNetworkId(networkId: string | null | undefined): ToolScopeEnvelope {\n const scopeId = networkId?.trim();\n return scopeId ? { scopeType: 'network', scopeId } : {};\n}\n\nexport function hasNetworkScope(scope: ToolScopeEnvelope): scope is { scopeType: 'network'; scopeId: string } {\n return scope.scopeType === 'network' && typeof scope.scopeId === 'string' && scope.scopeId.trim().length > 0;\n}\n\n/**\n * Returns the focused network id from the canonical scope envelope.\n *\n * This intentionally does not inspect legacy `networkId` fields; callers that\n * still need a transition fallback should pass `scopeFromNetworkId(networkId)`\n * at the boundary so tool logic remains envelope-driven.\n */\nexport function focusedNetworkId(scope: ToolScopeEnvelope): string | undefined {\n return hasNetworkScope(scope) ? scope.scopeId.trim() : undefined;\n}\n\n/** Human-readable label for a focused scope, used in scope-restriction notes. */\nexport function focusedNetworkLabel(scope: ToolScopeEnvelope & { indexName?: string }): string {\n return scope.indexName ?? focusedNetworkId(scope) ?? 'this index';\n}\n\nexport function deriveAllowedNetworkIds(input: DeriveNetworkScopeInput): string[] {\n if (!hasNetworkScope(input)) {\n return uniqueNetworkIds(input.memberships.map((membership) => membership.networkId));\n }\n\n return uniqueNetworkIds(\n input.memberships\n .filter((membership) => membership.networkId === input.scopeId || membership.isPersonal === true)\n .map((membership) => membership.networkId),\n );\n}\n\nexport function deriveDiscoveryNetworkIds(input: DeriveNetworkScopeInput): string[] {\n if (!hasNetworkScope(input)) {\n return uniqueNetworkIds(input.memberships.map((membership) => membership.networkId));\n }\n\n return input.memberships.some((membership) => membership.networkId === input.scopeId)\n ? [input.scopeId]\n : [];\n}\n"]}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { ScopeMembership, ToolScopeEnvelope } from "../agent/tool.scope.js";
|
|
1
2
|
import type { NetworkAssignmentMetadata, NetworkAssignmentMode, NetworkAssignmentPromptPresence, NetworkAssignmentRawScores, NetworkAssignmentResourceType, NetworkAssignmentScope } from "../schemas/network-assignment.schema.js";
|
|
2
3
|
/** Centralized default for unified premise/intent network assignment. */
|
|
3
4
|
export declare const DEFAULT_NETWORK_ASSIGNMENT_THRESHOLD = 0.7;
|
|
@@ -5,8 +6,10 @@ export interface PromptPresenceInput {
|
|
|
5
6
|
indexPrompt?: string | null;
|
|
6
7
|
memberPrompt?: string | null;
|
|
7
8
|
}
|
|
8
|
-
export
|
|
9
|
-
|
|
9
|
+
export type AssignmentScopeMembership = ScopeMembership | string;
|
|
10
|
+
export interface ResolveAssignmentNetworkScopeArgs extends ToolScopeEnvelope {
|
|
11
|
+
memberships: AssignmentScopeMembership[];
|
|
12
|
+
/** @deprecated Use `scopeType: 'network'` + `scopeId`. */
|
|
10
13
|
networkScopeId?: string;
|
|
11
14
|
}
|
|
12
15
|
export interface BuildNetworkAssignmentDecisionArgs extends PromptPresenceInput {
|
|
@@ -33,9 +36,9 @@ export interface NetworkAssignmentDecision {
|
|
|
33
36
|
*/
|
|
34
37
|
export declare function classifyPromptPresence(input: PromptPresenceInput): NetworkAssignmentPromptPresence;
|
|
35
38
|
/**
|
|
36
|
-
* Resolves the networks to evaluate: all memberships in global scope,
|
|
37
|
-
*
|
|
38
|
-
* membership to avoid broadening scope accidentally.
|
|
39
|
+
* Resolves the networks to evaluate: all memberships in global scope, or the
|
|
40
|
+
* focused network plus personal memberships in network scope. The focused
|
|
41
|
+
* network must also be a membership to avoid broadening scope accidentally.
|
|
39
42
|
*
|
|
40
43
|
* @param args - User memberships plus optional active network scope.
|
|
41
44
|
* @returns Network IDs that assignment should evaluate.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network-assignment.policy.d.ts","sourceRoot":"/","sources":["shared/assignment/network-assignment.policy.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"network-assignment.policy.d.ts","sourceRoot":"/","sources":["shared/assignment/network-assignment.policy.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AACjF,OAAO,KAAK,EAAE,yBAAyB,EAAE,qBAAqB,EAAE,+BAA+B,EAAE,0BAA0B,EAAE,6BAA6B,EAAE,sBAAsB,EAAE,MAAM,yCAAyC,CAAC;AAEpO,yEAAyE;AACzE,eAAO,MAAM,oCAAoC,MAAM,CAAC;AAExD,MAAM,WAAW,mBAAmB;IAClC,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC9B;AAED,MAAM,MAAM,yBAAyB,GAAG,eAAe,GAAG,MAAM,CAAC;AAEjE,MAAM,WAAW,iCAAkC,SAAQ,iBAAiB;IAC1E,WAAW,EAAE,yBAAyB,EAAE,CAAC;IACzC,0DAA0D;IAC1D,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,MAAM,WAAW,kCAAmC,SAAQ,mBAAmB;IAC7E,YAAY,EAAE,6BAA6B,CAAC;IAC5C,IAAI,EAAE,qBAAqB,CAAC;IAC5B,KAAK,EAAE,sBAAsB,CAAC;IAC9B,SAAS,CAAC,EAAE,0BAA0B,GAAG,IAAI,CAAC;IAC9C,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,yBAAyB;IACxC,QAAQ,EAAE,OAAO,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,yBAAyB,CAAC;CACrC;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,mBAAmB,GAAG,+BAA+B,CAOlG;AAED;;;;;;;GAOG;AACH,wBAAgB,6BAA6B,CAAC,IAAI,EAAE,iCAAiC,GAAG,MAAM,EAAE,CAW/F;AAED;;;;;GAKG;AACH,wBAAgB,8BAA8B,CAAC,IAAI,EAAE,kCAAkC,GAAG,yBAAyB,CAiBlH;AAED;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CACrC,SAAS,EAAE,0BAA0B,EACrC,cAAc,EAAE,+BAA+B,GAC9C,MAAM,CAcR"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { deriveAllowedNetworkIds, scopeFromNetworkId } from "../agent/tool.scope.js";
|
|
1
2
|
/** Centralized default for unified premise/intent network assignment. */
|
|
2
3
|
export const DEFAULT_NETWORK_ASSIGNMENT_THRESHOLD = 0.7;
|
|
3
4
|
/**
|
|
@@ -18,17 +19,21 @@ export function classifyPromptPresence(input) {
|
|
|
18
19
|
return "none";
|
|
19
20
|
}
|
|
20
21
|
/**
|
|
21
|
-
* Resolves the networks to evaluate: all memberships in global scope,
|
|
22
|
-
*
|
|
23
|
-
* membership to avoid broadening scope accidentally.
|
|
22
|
+
* Resolves the networks to evaluate: all memberships in global scope, or the
|
|
23
|
+
* focused network plus personal memberships in network scope. The focused
|
|
24
|
+
* network must also be a membership to avoid broadening scope accidentally.
|
|
24
25
|
*
|
|
25
26
|
* @param args - User memberships plus optional active network scope.
|
|
26
27
|
* @returns Network IDs that assignment should evaluate.
|
|
27
28
|
*/
|
|
28
29
|
export function resolveAssignmentNetworkScope(args) {
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
30
|
+
const memberships = args.memberships.map((membership) => (typeof membership === "string"
|
|
31
|
+
? { networkId: membership, isPersonal: false }
|
|
32
|
+
: membership));
|
|
33
|
+
const scope = args.scopeType && args.scopeId
|
|
34
|
+
? { scopeType: args.scopeType, scopeId: args.scopeId }
|
|
35
|
+
: scopeFromNetworkId(args.networkScopeId);
|
|
36
|
+
return deriveAllowedNetworkIds({ memberships, ...scope });
|
|
32
37
|
}
|
|
33
38
|
/**
|
|
34
39
|
* Builds a unified assignment decision and metadata envelope.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network-assignment.policy.js","sourceRoot":"/","sources":["shared/assignment/network-assignment.policy.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"network-assignment.policy.js","sourceRoot":"/","sources":["shared/assignment/network-assignment.policy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAIrF,yEAAyE;AACzE,MAAM,CAAC,MAAM,oCAAoC,GAAG,GAAG,CAAC;AAiCxD;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB,CAAC,KAA0B;IAC/D,MAAM,QAAQ,GAAG,CAAC,CAAC,KAAK,CAAC,WAAW,EAAE,IAAI,EAAE,CAAC;IAC7C,MAAM,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC,YAAY,EAAE,IAAI,EAAE,CAAC;IAC/C,IAAI,QAAQ,IAAI,SAAS;QAAE,OAAO,MAAM,CAAC;IACzC,IAAI,QAAQ;QAAE,OAAO,OAAO,CAAC;IAC7B,IAAI,SAAS;QAAE,OAAO,QAAQ,CAAC;IAC/B,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,6BAA6B,CAAC,IAAuC;IACnF,MAAM,WAAW,GAAG,IAAI,CAAC,W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AAE,CAAC;YAC7B,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACxD,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YAC/C,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACzD;KACF,CAAC;AACJ,CAAC;AAED,SAAS,UAAU,CAAC,KAAa;IAC/B,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,OAAO,CAAC,CAAC;IACtC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC;AACzC,CAAC","sourcesContent":["import { deriveAllowedNetworkIds, scopeFromNetworkId } from \"../agent/tool.scope.js\";\nimport type { ScopeMembership, ToolScopeEnvelope } from \"../agent/tool.scope.js\";\nimport type { NetworkAssignmentMetadata, NetworkAssignmentMode, NetworkAssignmentPromptPresence, NetworkAssignmentRawScores, NetworkAssignmentResourceType, NetworkAssignmentScope } from \"../schemas/network-assignment.schema.js\";\n\n/** Centralized default for unified premise/intent network assignment. */\nexport const DEFAULT_NETWORK_ASSIGNMENT_THRESHOLD = 0.7;\n\nexport interface PromptPresenceInput {\n indexPrompt?: string | null;\n memberPrompt?: string | null;\n}\n\nexport type AssignmentScopeMembership = ScopeMembership | string;\n\nexport interface ResolveAssignmentNetworkScopeArgs extends ToolScopeEnvelope {\n memberships: AssignmentScopeMembership[];\n /** @deprecated Use `scopeType: 'network'` + `scopeId`. */\n networkScopeId?: string;\n}\n\nexport interface BuildNetworkAssignmentDecisionArgs extends PromptPresenceInput {\n resourceType: NetworkAssignmentResourceType;\n mode: NetworkAssignmentMode;\n scope: NetworkAssignmentScope;\n rawScores?: NetworkAssignmentRawScores | null;\n threshold?: number;\n evaluator?: string;\n source?: string;\n reason?: string;\n createdAt?: string;\n}\n\nexport interface NetworkAssignmentDecision {\n assigned: boolean;\n finalScore: number;\n metadata: NetworkAssignmentMetadata;\n}\n\n/**\n * Classifies whether a network/member prompt pair can filter a resource.\n *\n * @param input - Network and member prompt values to inspect.\n * @returns Prompt-presence classification for assignment policy decisions.\n */\nexport function classifyPromptPresence(input: PromptPresenceInput): NetworkAssignmentPromptPresence {\n const hasIndex = !!input.indexPrompt?.trim();\n const hasMember = !!input.memberPrompt?.trim();\n if (hasIndex && hasMember) return \"both\";\n if (hasIndex) return \"index\";\n if (hasMember) return \"member\";\n return \"none\";\n}\n\n/**\n * Resolves the networks to evaluate: all memberships in global scope, or the\n * focused network plus personal memberships in network scope. The focused\n * network must also be a membership to avoid broadening scope accidentally.\n *\n * @param args - User memberships plus optional active network scope.\n * @returns Network IDs that assignment should evaluate.\n */\nexport function resolveAssignmentNetworkScope(args: ResolveAssignmentNetworkScopeArgs): string[] {\n const memberships = args.memberships.map((membership) => (\n typeof membership === \"string\"\n ? { networkId: membership, isPersonal: false }\n : membership\n ));\n const scope = args.scopeType && args.scopeId\n ? { scopeType: args.scopeType, scopeId: args.scopeId }\n : scopeFromNetworkId(args.networkScopeId);\n\n return deriveAllowedNetworkIds({ memberships, ...scope });\n}\n\n/**\n * Builds a unified assignment decision and metadata envelope.\n *\n * @param args - Assignment resource, scope, prompt, score, and provenance inputs.\n * @returns Assignment decision and explainability metadata.\n */\nexport function buildNetworkAssignmentDecision(args: BuildNetworkAssignmentDecisionArgs): NetworkAssignmentDecision {\n const threshold = clampScore(args.threshold ?? DEFAULT_NETWORK_ASSIGNMENT_THRESHOLD);\n const promptPresence = classifyPromptPresence(args);\n\n if (args.mode === \"manual_override\") {\n const finalScore = 1.0;\n return buildDecision(args, promptPresence, threshold, finalScore, true, args.reason ?? \"Explicit manual override.\");\n }\n\n if (promptPresence === \"none\") {\n const finalScore = 1.0;\n return buildDecision(args, promptPresence, threshold, finalScore, true, args.reason ?? \"No prompts configured; network has no dynamic filtration.\");\n }\n\n const finalScore = combineAssignmentScores(args.rawScores ?? {}, promptPresence);\n const assigned = finalScore >= threshold;\n return buildDecision(args, promptPresence, threshold, finalScore, assigned, args.reason);\n}\n\n/**\n * Combines index/member scores according to available prompt filtration.\n *\n * @param rawScores - Optional normalized index and member scores.\n * @param promptPresence - Which prompts are present for this assignment decision.\n * @returns Final normalized score in the 0..1 range.\n */\nexport function combineAssignmentScores(\n rawScores: NetworkAssignmentRawScores,\n promptPresence: NetworkAssignmentPromptPresence,\n): number {\n const indexScore = clampScore(rawScores.indexScore ?? 0);\n const memberScore = clampScore(rawScores.memberScore ?? 0);\n\n switch (promptPresence) {\n case \"both\":\n return clampScore(indexScore * 0.6 + memberScore * 0.4);\n case \"index\":\n return indexScore;\n case \"member\":\n return memberScore;\n case \"none\":\n return 1.0;\n }\n}\n\nfunction buildDecision(\n args: BuildNetworkAssignmentDecisionArgs,\n promptPresence: NetworkAssignmentPromptPresence,\n threshold: number,\n finalScore: number,\n assigned: boolean,\n reason?: string,\n): NetworkAssignmentDecision {\n return {\n assigned,\n finalScore,\n metadata: {\n resourceType: args.resourceType,\n mode: args.mode,\n scope: args.scope,\n policy: \"unified-threshold-v1\",\n threshold,\n promptPresence,\n ...(args.rawScores ? { rawScores: args.rawScores } : {}),\n finalScore,\n assigned,\n ...(reason ? { reason } : {}),\n ...(args.evaluator ? { evaluator: args.evaluator } : {}),\n ...(args.source ? { source: args.source } : {}),\n ...(args.createdAt ? { createdAt: args.createdAt } : {}),\n },\n };\n}\n\nfunction clampScore(score: number): number {\n if (!Number.isFinite(score)) return 0;\n return Math.max(0, Math.min(1, score));\n}\n"]}
|
|
@@ -23,7 +23,7 @@ export declare class HydeGraphFactory {
|
|
|
23
23
|
private generator;
|
|
24
24
|
constructor(database: HydeGraphDatabase, embedder: EmbeddingGenerator, cache: HydeCache, inferrer: LensInferrer, generator: HydeGenerator);
|
|
25
25
|
createGraph(): import("@langchain/langgraph").CompiledStateGraph<{
|
|
26
|
-
sourceType: "
|
|
26
|
+
sourceType: "context" | "intent" | "query";
|
|
27
27
|
sourceId: import("../interfaces/database.interface.js").Id<"users"> | import("../interfaces/database.interface.js").Id<"intents"> | undefined;
|
|
28
28
|
sourceText: string;
|
|
29
29
|
profileContext: string | undefined;
|
|
@@ -35,7 +35,7 @@ export declare class HydeGraphFactory {
|
|
|
35
35
|
error: string | undefined;
|
|
36
36
|
agentTimings: DebugMetaAgent[];
|
|
37
37
|
}, {
|
|
38
|
-
sourceType?: "
|
|
38
|
+
sourceType?: "context" | "intent" | "query" | undefined;
|
|
39
39
|
sourceId?: import("../interfaces/database.interface.js").Id<"users"> | import("../interfaces/database.interface.js").Id<"intents"> | import("@langchain/langgraph").OverwriteValue<import("../interfaces/database.interface.js").Id<"users"> | import("../interfaces/database.interface.js").Id<"intents"> | undefined> | undefined;
|
|
40
40
|
sourceText?: string | undefined;
|
|
41
41
|
profileContext?: string | import("@langchain/langgraph").OverwriteValue<string | undefined> | undefined;
|
|
@@ -48,8 +48,8 @@ export declare class HydeGraphFactory {
|
|
|
48
48
|
agentTimings?: DebugMetaAgent[] | import("@langchain/langgraph").OverwriteValue<DebugMetaAgent[]> | undefined;
|
|
49
49
|
}, "__start__" | "infer_lenses" | "check_cache" | "generate_missing" | "embed" | "cache_results", {
|
|
50
50
|
sourceType: {
|
|
51
|
-
(annotation: import("@langchain/langgraph").SingleReducer<"
|
|
52
|
-
(): import("@langchain/langgraph").LastValue<"
|
|
51
|
+
(annotation: import("@langchain/langgraph").SingleReducer<"context" | "intent" | "query", "context" | "intent" | "query">): import("@langchain/langgraph").BaseChannel<"context" | "intent" | "query", "context" | "intent" | "query" | import("@langchain/langgraph").OverwriteValue<"context" | "intent" | "query">, unknown>;
|
|
52
|
+
(): import("@langchain/langgraph").LastValue<"context" | "intent" | "query">;
|
|
53
53
|
Root: <S extends import("@langchain/langgraph").StateDefinition>(sd: S) => import("@langchain/langgraph").AnnotationRoot<S>;
|
|
54
54
|
};
|
|
55
55
|
sourceId: import("@langchain/langgraph").BaseChannel<import("../interfaces/database.interface.js").Id<"users"> | import("../interfaces/database.interface.js").Id<"intents"> | undefined, import("../interfaces/database.interface.js").Id<"users"> | import("../interfaces/database.interface.js").Id<"intents"> | import("@langchain/langgraph").OverwriteValue<import("../interfaces/database.interface.js").Id<"users"> | import("../interfaces/database.interface.js").Id<"intents"> | undefined> | undefined, unknown>;
|
|
@@ -68,8 +68,8 @@ export declare class HydeGraphFactory {
|
|
|
68
68
|
agentTimings: import("@langchain/langgraph").BaseChannel<DebugMetaAgent[], DebugMetaAgent[] | import("@langchain/langgraph").OverwriteValue<DebugMetaAgent[]>, unknown>;
|
|
69
69
|
}, {
|
|
70
70
|
sourceType: {
|
|
71
|
-
(annotation: import("@langchain/langgraph").SingleReducer<"
|
|
72
|
-
(): import("@langchain/langgraph").LastValue<"
|
|
71
|
+
(annotation: import("@langchain/langgraph").SingleReducer<"context" | "intent" | "query", "context" | "intent" | "query">): import("@langchain/langgraph").BaseChannel<"context" | "intent" | "query", "context" | "intent" | "query" | import("@langchain/langgraph").OverwriteValue<"context" | "intent" | "query">, unknown>;
|
|
72
|
+
(): import("@langchain/langgraph").LastValue<"context" | "intent" | "query">;
|
|
73
73
|
Root: <S extends import("@langchain/langgraph").StateDefinition>(sd: S) => import("@langchain/langgraph").AnnotationRoot<S>;
|
|
74
74
|
};
|
|
75
75
|
sourceId: import("@langchain/langgraph").BaseChannel<import("../interfaces/database.interface.js").Id<"users"> | import("../interfaces/database.interface.js").Id<"intents"> | undefined, import("../interfaces/database.interface.js").Id<"users"> | import("../interfaces/database.interface.js").Id<"intents"> | import("@langchain/langgraph").OverwriteValue<import("../interfaces/database.interface.js").Id<"users"> | import("../interfaces/database.interface.js").Id<"intents"> | undefined> | undefined, unknown>;
|
|
@@ -16,8 +16,8 @@ export interface HydeDocumentState {
|
|
|
16
16
|
export declare const HydeGraphState: import("@langchain/langgraph").AnnotationRoot<{
|
|
17
17
|
/** Source type: intent, profile, user context, or ad-hoc query. */
|
|
18
18
|
sourceType: {
|
|
19
|
-
(annotation: import("@langchain/langgraph").SingleReducer<"
|
|
20
|
-
(): import("@langchain/langgraph").LastValue<"
|
|
19
|
+
(annotation: import("@langchain/langgraph").SingleReducer<"context" | "intent" | "query", "context" | "intent" | "query">): import("@langchain/langgraph").BaseChannel<"context" | "intent" | "query", "context" | "intent" | "query" | import("@langchain/langgraph").OverwriteValue<"context" | "intent" | "query">, unknown>;
|
|
20
|
+
(): import("@langchain/langgraph").LastValue<"context" | "intent" | "query">;
|
|
21
21
|
Root: <S extends import("@langchain/langgraph").StateDefinition>(sd: S) => import("@langchain/langgraph").AnnotationRoot<S>;
|
|
22
22
|
};
|
|
23
23
|
/** Source entity ID (e.g. intent ID, user ID). Omitted for ad-hoc query. */
|
|
@@ -17,9 +17,9 @@ export interface McpAuthResolver {
|
|
|
17
17
|
* agent, and `clientSurface` declaring which kind of UI is rendering the
|
|
18
18
|
* MCP response (drives connect-link redirect choice at click time).
|
|
19
19
|
*
|
|
20
|
-
* When `networkScopeId` is set, the MCP server
|
|
21
|
-
*
|
|
22
|
-
*
|
|
20
|
+
* When `networkScopeId` is set, the MCP server promotes it into the
|
|
21
|
+
* canonical `{ scopeType: 'network', scopeId }` envelope. Downstream tools
|
|
22
|
+
* derive concrete allowed network IDs from that envelope plus memberships.
|
|
23
23
|
*
|
|
24
24
|
* `isSessionAuth` is true for OAuth/JWT bearer sessions — the agent-
|
|
25
25
|
* registration gate in the MCP server is skipped for these callers.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.interface.js","sourceRoot":"/","sources":["shared/interfaces/auth.interface.ts"],"names":[],"mappings":"","sourcesContent":["import type { McpAuthInput } from '../schemas/mcp-auth.schema.js';\n\n/**\n * Resolves the authenticated MCP identity from an auth input DTO.\n * The DTO is extracted from the transport at the edge (e.g. from HTTP Request\n * headers) before the protocol layer is called. New auth paths stay free of\n * platform-specific `Request` coupling; `resolveUserId` remains only as a\n * deprecated compatibility bridge while callers migrate to `resolveIdentity`.\n */\nexport interface McpAuthResolver {\n /**\n * Extracts and validates the authenticated identity from the auth input.\n *\n * @param input - Transport-neutral auth input DTO with credential fields\n * extracted at the MCP transport edge.\n * @returns The authenticated user's UUID, optional agent UUID, auth method,\n * `networkScopeId` if the caller's API key is bound to a network-scoped\n * agent, and `clientSurface` declaring which kind of UI is rendering the\n * MCP response (drives connect-link redirect choice at click time).\n *\n * When `networkScopeId` is set, the MCP server
|
|
1
|
+
{"version":3,"file":"auth.interface.js","sourceRoot":"/","sources":["shared/interfaces/auth.interface.ts"],"names":[],"mappings":"","sourcesContent":["import type { McpAuthInput } from '../schemas/mcp-auth.schema.js';\n\n/**\n * Resolves the authenticated MCP identity from an auth input DTO.\n * The DTO is extracted from the transport at the edge (e.g. from HTTP Request\n * headers) before the protocol layer is called. New auth paths stay free of\n * platform-specific `Request` coupling; `resolveUserId` remains only as a\n * deprecated compatibility bridge while callers migrate to `resolveIdentity`.\n */\nexport interface McpAuthResolver {\n /**\n * Extracts and validates the authenticated identity from the auth input.\n *\n * @param input - Transport-neutral auth input DTO with credential fields\n * extracted at the MCP transport edge.\n * @returns The authenticated user's UUID, optional agent UUID, auth method,\n * `networkScopeId` if the caller's API key is bound to a network-scoped\n * agent, and `clientSurface` declaring which kind of UI is rendering the\n * MCP response (drives connect-link redirect choice at click time).\n *\n * When `networkScopeId` is set, the MCP server promotes it into the\n * canonical `{ scopeType: 'network', scopeId }` envelope. Downstream tools\n * derive concrete allowed network IDs from that envelope plus memberships.\n *\n * `isSessionAuth` is true for OAuth/JWT bearer sessions — the agent-\n * registration gate in the MCP server is skipped for these callers.\n *\n * `clientSurface` is passed through from the DTO. Only `'telegram'`\n * activates the t.me redirect path on `/c/{code}` clicks.\n *\n * @throws Error if authentication fails (no token, invalid token, etc.)\n */\n resolveIdentity(input: McpAuthInput): Promise<{\n userId: string;\n agentId?: string;\n isSessionAuth?: boolean;\n networkScopeId?: string | null;\n clientSurface?: 'telegram' | 'web';\n }>;\n\n /**\n * Deprecated HTTP Request bridge retained for compatibility with older\n * callers. New transport code must extract `McpAuthInput` at the edge and\n * call `resolveIdentity` instead.\n *\n * @deprecated Use resolveIdentity instead.\n */\n resolveUserId(request: Request): Promise<string>;\n}\n"]}
|