@indexnetwork/protocol 2.0.1-rc.244.1 → 3.0.0-rc.245.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/index.d.ts +6 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/intent/intent.graph.d.ts +26 -26
- package/dist/intent/intent.inferrer.d.ts +8 -8
- package/dist/intent/intent.reconciler.d.ts +12 -12
- package/dist/intent/intent.state.d.ts +6 -6
- package/dist/mcp/mcp.server.d.ts +5 -0
- package/dist/mcp/mcp.server.d.ts.map +1 -1
- package/dist/mcp/mcp.server.js +43 -2
- package/dist/mcp/mcp.server.js.map +1 -1
- package/dist/opportunity/opportunity.evaluator.d.ts +3 -3
- package/dist/premise/premise.analyzer.d.ts +2 -2
- package/dist/premise/premise.decomposer.d.ts +2 -2
- package/dist/premise/premise.tools.js.map +1 -1
- package/dist/shared/agent/tool.factory.js.map +1 -1
- package/dist/shared/agent/tool.helpers.d.ts +1 -1
- package/dist/shared/agent/tool.helpers.d.ts.map +1 -1
- package/dist/shared/agent/tool.helpers.js.map +1 -1
- package/dist/shared/interfaces/agent-dispatcher.interface.d.ts +1 -1
- package/dist/shared/interfaces/agent-dispatcher.interface.js.map +1 -1
- package/dist/shared/interfaces/auth.interface.d.ts +16 -9
- package/dist/shared/interfaces/auth.interface.d.ts.map +1 -1
- package/dist/shared/interfaces/auth.interface.js.map +1 -1
- package/dist/shared/interfaces/database.interface.d.ts +2 -2
- 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/question-generator.interface.d.ts +1 -1
- package/dist/shared/interfaces/question-generator.interface.d.ts.map +1 -1
- package/dist/shared/interfaces/question-generator.interface.js.map +1 -1
- package/dist/shared/schemas/discovery-question.schema.d.ts +242 -0
- package/dist/shared/schemas/discovery-question.schema.d.ts.map +1 -0
- package/dist/shared/schemas/discovery-question.schema.js +49 -0
- package/dist/shared/schemas/discovery-question.schema.js.map +1 -0
- package/dist/shared/schemas/mcp-auth.schema.d.ts +18 -0
- package/dist/shared/schemas/mcp-auth.schema.d.ts.map +1 -0
- package/dist/shared/schemas/mcp-auth.schema.js +2 -0
- package/dist/shared/schemas/mcp-auth.schema.js.map +1 -0
- package/dist/shared/schemas/negotiation-digest.schema.d.ts +2 -2
- package/dist/shared/schemas/negotiation-state.schema.d.ts +118 -0
- package/dist/shared/schemas/negotiation-state.schema.d.ts.map +1 -0
- package/dist/shared/schemas/negotiation-state.schema.js +29 -0
- package/dist/shared/schemas/negotiation-state.schema.js.map +1 -0
- package/dist/shared/schemas/profile.schema.d.ts +100 -0
- package/dist/shared/schemas/profile.schema.d.ts.map +1 -0
- package/dist/shared/schemas/profile.schema.js +26 -0
- package/dist/shared/schemas/profile.schema.js.map +1 -0
- package/dist/shared/schemas/question.schema.d.ts +8 -8
- package/package.json +1 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp.server.js","sourceRoot":"/","sources":["mcp/mcp.server.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAKzE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AAErE,OAAO,EAAE,cAAc,EAAE,MAAM,sCAAsC,CAAC;AACtE,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAC;AACtE,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,wBAAwB,EAAE,MAAM,iCAAiC,CAAC;AAEhH,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAE5E,MAAM,MAAM,GAAG,cAAc,CAAC,WAAW,CAAC,CAA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AC,KAAK,CAAC,aAAa,QAAQ,UAAU,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;gBAClE,IAAI,wBAAwB,CAAC,GAAG,CAAC,EAAE,CAAC;oBAClC,UAAU,CAAC,eAAe,EAAE,CAAC,GAAG,EAAE;wBAChC,SAAS,EAAE,KAAK;wBAChB,SAAS,EAAE,UAAU;wBACrB,QAAQ;wBACR,MAAM,EAAE,YAAY;wBACpB,IAAI,EAAE;4BACJ,SAAS,EAAE,KAAK;4BAChB,QAAQ;yBACT;wBACD,OAAO,EAAE;4BACP,OAAO,EAAE,aAAa,EAAE,OAAO;4BAC/B,SAAS,EAAE,aAAa,EAAE,SAAS;4BACnC,UAAU,EAAE,aAAa,EAAE,UAAU;yBACtC;qBACF,CAAC,CAAC;gBACL,CAAC;gBACD,MAAM,aAAa,GAAG,wBAAwB,CAAC,GAAG,CAAC,CAAC;gBACpD,OAAO;oBACL,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAe,EAAE,IAAI,EAAE,aAAa,IAAI,IAAI,CAAC,SAAS,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC;oBAC/F,OAAO,EAAE,IAAI;iBACd,CAAC;YACJ,CAAC;QACH,CAAC,CACF,CAAC;IACJ,CAAC;IAED,MAAM,CAAC,OAAO,CAAC,2BAA2B,QAAQ,CAAC,IAAI,QAAQ,CAAC,CAAC;IACjE,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/**\n * MCP Server Factory — creates an McpServer instance with all protocol tools\n * registered from the existing tool registry. Each tool invocation resolves\n * auth from the HTTP request, builds a ResolvedToolContext, and delegates\n * to the raw tool handler.\n */\n\nimport { z } from 'zod';\nimport { McpServer, fromJsonSchema } from '@modelcontextprotocol/server';\nimport type { ServerContext, JsonSchemaType } from '@modelcontextprotocol/server';\n\nimport type { McpAuthResolver } from '../shared/interfaces/auth.interface.js';\nimport type { ToolDeps, ResolvedToolContext } from '../shared/agent/tool.helpers.js';\nimport { resolveChatContext } from '../shared/agent/tool.helpers.js';\nimport type { Question } from '../shared/schemas/question.schema.js';\nimport { QuestionSchema } from '../shared/schemas/question.schema.js';\nimport { dispatchElicitations } from './elicitation.dispatcher.js';\nimport { createToolRegistry } from '../shared/agent/tool.registry.js';\nimport { ToolRuntimeError, invokeToolRuntime, toolRuntimeErrorToResult } from '../shared/agent/tool.runtime.js';\nimport type { TraceEmitter } from '../shared/observability/request-context.js';\nimport { protocolLogger } from '../shared/observability/protocol.logger.js';\n\nconst logger = protocolLogger('McpServer');\n\nfunction isExpectedMcpAuthError(message: string): boolean {\n return message.includes('Authentication required') ||\n message.includes('Invalid API key') ||\n message.includes('Invalid or expired access token') ||\n message.includes('JWT payload missing user ID');\n}\n\n/**\n * Runtime/auth failures are converted into structured MCP `isError` tool\n * results for the caller. Reporting them as application exceptions produces\n * Sentry noise for expected client failures and policy-enforced timeouts.\n */\nexport function shouldReportMcpToolError(err: unknown): boolean {\n if (err instanceof ToolRuntimeError) return false;\n const message = err instanceof Error ? err.message : String(err);\n return !isExpectedMcpAuthError(message);\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// ZOD 3 → JSON SCHEMA CONVERSION\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Minimal Zod-to-JSON-Schema conversion for MCP tool registration.\n * Converts Zod 3.x schemas to plain JSON Schema objects that can be\n * wrapped with `fromJsonSchema()` for MCP SDK compatibility.\n */\nfunction zodToJsonSchema(schema: z.ZodType): Record<string, unknown> {\n if (schema instanceof z.ZodObject) {\n const shape = schema.shape;\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n for (const [key, value] of Object.entries(shape)) {\n const zodValue = value as z.ZodType;\n properties[key] = zodToJsonSchema(zodValue);\n if (!(zodValue instanceof z.ZodOptional) && !(zodValue instanceof z.ZodDefault)) {\n required.push(key);\n }\n }\n return { type: 'object', properties, ...(required.length ? { required } : {}) };\n }\n if (schema instanceof z.ZodString) {\n const result: Record<string, unknown> = { type: 'string' };\n // Detect .url(), .email(), .uuid() etc. via Zod's internal checks array\n const checks = (schema as z.ZodString & { _def: { checks: Array<{ kind: string }> } })._def?.checks;\n if (checks) {\n for (const check of checks) {\n if (check.kind === 'url') result.format = 'uri';\n else if (check.kind === 'email') result.format = 'email';\n else if (check.kind === 'uuid') result.format = 'uuid';\n else if (check.kind === 'datetime') result.format = 'date-time';\n }\n }\n return result;\n }\n if (schema instanceof z.ZodNumber) {\n const checks = (schema as z.ZodNumber & { _def: { checks: Array<{ kind: string; value?: number }> } })._def?.checks;\n const result: Record<string, unknown> = { type: 'number' };\n if (checks) {\n for (const check of checks) {\n if (check.kind === 'int') result.type = 'integer';\n else if (check.kind === 'min') result.minimum = check.value;\n else if (check.kind === 'max') result.maximum = check.value;\n }\n }\n return result;\n }\n if (schema instanceof z.ZodBoolean) return { type: 'boolean' };\n if (schema instanceof z.ZodArray) {\n return { type: 'array', items: zodToJsonSchema((schema as z.ZodArray<z.ZodType>).element) };\n }\n if (schema instanceof z.ZodOptional) {\n return zodToJsonSchema((schema as z.ZodOptional<z.ZodType>).unwrap());\n }\n if (schema instanceof z.ZodDefault) {\n return zodToJsonSchema((schema as z.ZodDefault<z.ZodType>).removeDefault());\n }\n if (schema instanceof z.ZodEnum) {\n return { type: 'string', enum: (schema as z.ZodEnum<[string, ...string[]]>).options };\n }\n if (schema instanceof z.ZodNullable) {\n const inner = zodToJsonSchema((schema as z.ZodNullable<z.ZodType>).unwrap());\n return { ...inner, nullable: true };\n }\n if (schema instanceof z.ZodRecord) {\n return { type: 'object', additionalProperties: true };\n }\n return { type: 'object' };\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// RESULT POST-PROCESSING\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Strips internal `_`-prefixed keys from `data` and promotes `isError`\n * from the inner `success: false` signal to the MCP envelope level.\n * Fail-open: if JSON parsing throws, returns the original text with isError: false.\n */\nexport function sanitizeMcpResult(text: string): { text: string; isError: boolean } {\n try {\n const parsed = JSON.parse(text);\n if (\n parsed &&\n typeof parsed === 'object' &&\n parsed.data &&\n typeof parsed.data === 'object' &&\n !Array.isArray(parsed.data)\n ) {\n for (const key of Object.keys(parsed.data)) {\n if (key.startsWith('_') || key === 'debugSteps') {\n delete parsed.data[key];\n }\n }\n }\n const isError = parsed?.success === false;\n return { text: JSON.stringify(parsed), isError };\n } catch {\n return { text, isError: false };\n }\n}\n\n/** Spec cap on the number of decision questions surfaced per turn. */\nconst MAX_DECISION_QUESTIONS = 3;\n\n/**\n * Extracts decision questions from a parsed tool-result text, if present.\n * Validates each entry against `QuestionSchema` and drops malformed items;\n * caps the array at `MAX_DECISION_QUESTIONS` (defense-in-depth — Slice 2's\n * generator already caps at 3, but we don't trust the cast here).\n *\n * Returns null when the text isn't JSON, has no `data.questions`, or\n * contains zero valid questions after validation.\n */\nexport function extractDecisionQuestions(text: string): Question[] | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return null;\n }\n\n const rawQs = (parsed as { data?: { questions?: unknown } } | null)?.data?.questions;\n if (!Array.isArray(rawQs) || rawQs.length === 0) return null;\n\n const valid: Question[] = [];\n for (const raw of rawQs) {\n const result = QuestionSchema.safeParse(raw);\n if (result.success) valid.push(result.data);\n if (valid.length === MAX_DECISION_QUESTIONS) break;\n }\n return valid.length > 0 ? valid : null;\n}\n\n/**\n * Renders the JSON-envelope text block appended to the tool result content\n * when decision questions are present. The leading sentinel string lets the\n * LLM client recognize and surface the questions in prose for clients\n * without elicitation support.\n */\nexport function renderQuestionsEnvelope(questions: Question[]): string {\n return `Decision questions (structured): ${JSON.stringify({ questions })}`;\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// MCP SERVER FACTORY\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Factory for creating per-request scoped database instances.\n * Injected from the controller/handler layer to keep the protocol layer\n * free of direct adapter imports.\n */\nexport interface ScopedDepsFactory {\n /** Creates scoped userDb and systemDb for the given user and index scope. */\n create(userId: string, indexScope: string[]): Pick<ToolDeps, 'userDb' | 'systemDb'>;\n}\n\n/**\n * Computes the index scope passed to the per-request scoped DB factory. When\n * `networkScopeId` is non-null, the agent is bound to a single network and\n * may only reach that network plus the user's personal index. Otherwise the\n * full set of the user's network memberships is returned.\n */\nexport const computeAgentIndexScope = (\n userNetworks: { networkId: string; isPersonal?: boolean | null }[],\n networkScopeId: string | null | undefined,\n): string[] => {\n if (!networkScopeId) {\n return userNetworks.map((m) => m.networkId);\n }\n return userNetworks\n .filter((m) => m.networkId === networkScopeId || m.isPersonal === true)\n .map((m) => m.networkId);\n};\n\n/**\n * Promotes a network-scoped agent's bound network into the resolved tool\n * context as the implicit chat scope. Every tool that branches on\n * `context.networkId` (read_networks, read_intents, read_user_profiles,\n * opportunity tools, etc.) then enforces scope automatically — without this\n * step the DB-level `indexScope` clamp guards cross-user data but tools that\n * shape their response off `context.networkId` (notably `read_networks`'\n * `publicNetworks` branch) would still leak the global view.\n *\n * No-op when there is no scope, or when an explicit chat scope is already\n * set (a user-driven index-scoped chat must keep precedence over the agent\n * binding — which would be a strict subset anyway, since the API key cannot\n * reach beyond its bound network).\n */\nexport const applyNetworkScopeToContext = (\n context: ResolvedToolContext,\n networkScopeId: string | null | undefined,\n): void => {\n if (!networkScopeId) return;\n if (context.networkId) return;\n\n context.networkId = networkScopeId;\n // Clamp indexScope to [boundNetwork, personalIndex] BEFORE the membership\n // check below. If the bound network is not in userNetworks (defensive case),\n // the filter still produces a safe scope (personal index only) rather than\n // leaving the unclamped scope set by resolveChatContext.\n context.indexScope = context.userNetworks\n .filter((m) => m.networkId === networkScopeId || m.isPersonal === true)\n .map((m) => m.networkId);\n\n const bound = context.userNetworks.find((m) => m.networkId === networkScopeId);\n if (!bound) return;\n\n context.indexName = bound.networkTitle;\n context.scopedIndex = {\n id: bound.networkId,\n title: bound.networkTitle,\n prompt: bound.indexPrompt ?? null,\n };\n const isOwner = bound.permissions?.includes('owner') ?? false;\n context.scopedMembershipRole = isOwner ? 'owner' : 'member';\n context.isOwner = isOwner;\n};\n\n/**\n * Tools allowed during onboarding — everything else is gated until\n * complete_onboarding is called. Includes the agent-gate-exempt tools\n * (register_agent, read_docs, scrape_url) because they are informational /\n * registration primitives needed at every lifecycle stage.\n */\nexport const ONBOARDING_ALLOWED: ReadonlySet<string> = new Set([\n 'register_agent',\n 'read_docs',\n 'scrape_url',\n 'record_onboarding_privacy_consent',\n 'preview_user_profile',\n 'get_profile_run',\n 'cancel_profile_run',\n 'confirm_user_profile',\n 'create_user_profile',\n 'complete_onboarding',\n 'import_gmail_contacts',\n 'read_networks',\n 'create_network_membership',\n 'create_intent',\n 'discover_opportunities',\n 'read_user_profiles',\n]);\n\n/**\n * Builds the onboarding gate message for MCP callers. Condensed from the\n * chat orchestrator's 8-step flow (chat.prompt.ts buildOnboarding) into a\n * 7-step tool-error guide suited for non-interactive MCP clients.\n */\nexport function buildMcpOnboardingMessage(ctx: ResolvedToolContext): string {\n const nameStep = ctx.hasName\n ? `1. Greet the user and confirm their name (\"You're ${ctx.userName}, right?\").`\n : `1. Ask the user for their name and a short self-description.`;\n\n const communityStep = ctx.networkId\n ? `5. (Skipped — user is already in \"${ctx.indexName ?? 'their community'}\".)`\n : `5. Call read_networks() and let the user pick communities to join via create_network_membership(networkId=...).`;\n\n const allowedList = Array.from(ONBOARDING_ALLOWED).join(', ');\n\n return (\n `This user has not completed onboarding. You must guide them through setup before they can use other tools. ` +\n `Only the following tools are available until onboarding is complete: ` +\n `${allowedList}.\\n\\n` +\n `Onboarding flow:\\n` +\n `${nameStep}\\n` +\n `2. Ask whether the user allows use of event/EdgeOS profile data, then call record_onboarding_privacy_consent(edgeosImportGranted=...).\\n` +\n `3. Ask separately whether the user allows public internet/profile lookup, then call record_onboarding_privacy_consent(publicProfileLookupGranted=...).\\n` +\n `4. Call preview_user_profile(...) using only allowed inputs; do not run public lookup unless consent was granted. If it returns profileRunId, poll get_profile_run(profileRunId=...) until status is succeeded, then use its result as the draft.\\n` +\n `5. Present the profile draft and ask \"Does that look right?\" On approval/correction, call confirm_user_profile(...).\\n` +\n `${communityStep}\\n` +\n `6. Ask what the user is looking for and call create_intent(description=\"...\").\\n` +\n `7. Call complete_onboarding() to finish setup. Gmail/contact import and discovery are optional after onboarding, never mandatory.`\n );\n}\n\n/**\n * Creates an MCP server with all protocol tools registered.\n * Tools resolve auth per-request via the HTTP request available in ServerContext.\n *\n * @param deps - Shared tool dependencies (graphs, database, embedder, etc.)\n * @param authResolver - Resolves authenticated identity from the HTTP request\n * @param scopedDepsFactory - Factory for creating per-request scoped databases\n * @returns A configured McpServer ready to be connected to a transport\n */\nfunction createMcpTraceEmitter(toolName: string, ctx: ServerContext): TraceEmitter | undefined {\n const token = ctx.mcpReq._meta?.progressToken;\n if (typeof token !== 'string' && typeof token !== 'number') return undefined;\n\n let progress = 0;\n return (event) => {\n progress += 1;\n const message = (() => {\n if (event.type === 'graph_start') return `${toolName}: ${event.name} started`;\n if (event.type === 'graph_end') return `${toolName}: ${event.name} finished${event.durationMs != null ? ` in ${event.durationMs}ms` : ''}`;\n if (event.type === 'agent_start') return `${toolName}: ${event.name} agent started`;\n if (event.type === 'agent_end') return `${toolName}: ${event.name} agent finished${event.durationMs != null ? ` in ${event.durationMs}ms` : ''}`;\n if (event.type === 'opportunity_draft_ready') return `${toolName}: opportunity draft ready`;\n return `${toolName}: progress`;\n })();\n\n const notification: Parameters<ServerContext['mcpReq']['notify']>[0] = {\n method: 'notifications/progress',\n params: { progressToken: token, progress, message },\n };\n void ctx.mcpReq.notify(notification).catch((err) => {\n logger.debug('Failed to send MCP progress notification', {\n toolName,\n error: err instanceof Error ? err.message : String(err),\n });\n });\n };\n}\n\nexport const MCP_INSTRUCTIONS = `\nIndex Network is a private, intent-driven discovery protocol. You help users find the right people and help the right people find them, via Index Network MCP tools.\n\n# Voice\nCalm, direct, analytical, concise. Preferred vocabulary: opportunity, overlap, signal, pattern, emerging, relevant, adjacency.\n\n# Banned vocabulary\nNEVER use \"search\" in any form. Use \"looking up\" for indexed data, \"find\" / \"look for\" for discovery, \"check\" for verification, \"discover\" for exploration. Banned: leverage, unlock, optimize, scale, disrupt, revolutionary, AI-powered, maximize value, act fast, networking, match.\n\n# Entity model\n- User — has one Profile, many Memberships, many Intents.\n- Profile — identity (bio, skills, interests, location).\n- Index — community with title, prompt (purpose), join policy. Has Members.\n- Membership — User↔Index junction. \\`isPersonal: true\\` marks the user's personal index (contacts).\n- Intent — what a user is looking for (signal). Description, summary, embedding.\n- IntentIndex — Intent↔Index junction (auto-assigned).\n- Opportunity — discovered connection between users. Roles, status, reasoning.\n\n# Output rules\n- NEVER expose internal IDs, UUIDs, field names, or tool names — EXCEPT when an ID is actionable for the user (e.g. a \\`conversationId\\` they need to open a chat). Surface such IDs verbatim when the tool returns them.\n- NEVER use internal vocabulary — say \"signal\" not \"intent\", \"community\" not \"index\".\n- NEVER dump raw JSON. Synthesize in natural language.\n- Surface top 1–3 relevant points unless asked for the full list.\n- Prefer first names; use full names only to disambiguate.\n- Translate statuses: draft/latent → \"draft\", pending → \"sent\", accepted → \"connected\".\n- NEVER fabricate data. If you don't have it, call the appropriate tool.\n\n# Tool guidance\nEach tool's description contains its own usage rules (when to call, when NOT to call, required prerequisites, post-call follow-ups). Read the description of every tool you call — that is where the per-tool workflow patterns live.\n\n# Authentication\nPass your API key in the \\`x-api-key\\` request header (not \\`Authorization: Bearer\\`).\n\n# Opportunity lifecycle\nOpportunities move through: draft → pending → accepted (or rejected).\n\n- **draft** (you created it, not yet sent): offer to send it; confirm before calling update_opportunity with pending.\n- **pending, you sent it**: waiting for the other side — nothing to do.\n- **pending, you received it**: the other person is waiting for your response. Surface it to the user and ask if they want to start a chat. Only call update_opportunity with accepted after explicit user confirmation.\n- **accepted**: both sides are connected — a direct conversation exists. Surface the conversationId to the user if available.\n\nNever accept a received opportunity without explicit user approval in the current conversation.\n\n# Decision questions after discovery\n\nAfter \\`discover_opportunities\\`, the tool result may include a second text block starting with \\`Decision questions (structured): ...\\`. This means the discovery engine ran negotiations but needs human input to sharpen the next turn — e.g. clarify timing, role, stage, or location.\n\n**When this block is present:**\n1. Parse the \\`questions\\` array from the JSON after the sentinel.\n2. Each question has \\`title\\` (decision domain, ≤12 chars), \\`prompt\\` (ends in \\`?\\`), \\`options\\` (2–4 items, each with \\`label\\` and \\`description\\`), and \\`multiSelect\\`. The safest option is labeled \\`... (Recommended)\\`.\n3. Present each question in natural language: ask the \\`prompt\\`, list options as \\`**{label}** — {description}\\`. Never expose the JSON or technical field names.\n4. Wait for the user's answer, then fold it into the next \\`discover_opportunities(searchQuery=...)\\` call.\n\n**Elicitation-capable clients** (those that declared \\`elicitation\\` support in \\`initialize\\`): the server dispatches \\`elicitation/create\\` requests directly — answers are written back to the chat session automatically. You will not see the envelope as a follow-up task in that case.\n`.trim();\n\nexport function createMcpServer(\n deps: ToolDeps,\n authResolver: McpAuthResolver,\n scopedDepsFactory: ScopedDepsFactory,\n): McpServer {\n // Tools exempt from the agent-registration gate — available before registration is complete.\n const AGENT_GATE_EXEMPT = new Set(['register_agent', 'read_docs', 'scrape_url']);\n\n const server = new McpServer(\n { name: 'index-network', version: '1.0.0' },\n { instructions: MCP_INSTRUCTIONS },\n );\n\n const registry = createToolRegistry(deps);\n\n for (const [toolName, toolDef] of registry) {\n // Convert Zod 3 schema to JSON Schema, then wrap with fromJsonSchema\n // for MCP SDK's StandardSchemaWithJSON compatibility\n const jsonSchema = zodToJsonSchema(toolDef.schema) as JsonSchemaType;\n const mcpSchema = fromJsonSchema(jsonSchema);\n\n server.registerTool(\n toolName,\n {\n description: toolDef.description,\n inputSchema: mcpSchema,\n },\n async (args: unknown, ctx: ServerContext) => {\n let reportDeps = deps;\n let reportUserId: string | undefined;\n let reportContext: ResolvedToolContext | undefined;\n\n try {\n // Extract the original HTTP request from the MCP server context\n const httpReq = ctx.http?.req;\n if (!httpReq) {\n return {\n content: [{ type: 'text' as const, text: JSON.stringify({ error: 'No HTTP request available in MCP context' }) }],\n isError: true,\n };\n }\n\n // Resolve authenticated identity (userId + optional agentId + optional network scope + optional surface)\n const { userId, agentId, isSessionAuth, networkScopeId, clientSurface } = await authResolver.resolveIdentity(httpReq);\n reportUserId = userId;\n\n // Per-principal MCP throttle. Runs BEFORE any DB work so a throttled\n // call short-circuits cheaply. The /mcp transport bypasses the\n // controller-level RateLimit guard, so this is the only volume cap on\n // tool calls — it stops an over-eager agent from cascading itself into\n // provider rate limits.\n if (deps.mcpRateLimiter) {\n // Throttling is best-effort: never let a limiter failure (or a host\n // implementation that throws instead of failing open) break tool\n // dispatch. Treat any error as \"allowed\".\n let decision: Awaited<ReturnType<NonNullable<typeof deps.mcpRateLimiter>>> | null = null;\n try {\n decision = await deps.mcpRateLimiter({\n userId,\n ...(agentId ? { agentId } : {}),\n toolName,\n });\n } catch (rlErr) {\n logger.warn(`MCP rate limiter threw for \"${toolName}\" — failing open`, {\n error: rlErr instanceof Error ? rlErr.message : String(rlErr),\n });\n }\n if (decision && !decision.allowed) {\n const retryAfterSec = decision.retryAfterSec ?? 60;\n return {\n content: [{\n type: 'text' as const,\n text: JSON.stringify({\n error: 'Rate limit exceeded',\n message:\n `Too many ${toolName} calls in a short period. Wait ${retryAfterSec}s before retrying.` +\n (toolName === 'discover_opportunities'\n ? ` If a discovery run is in progress, poll get_discovery_run instead of calling discover_opportunities again.`\n : ''),\n retryAfterSec,\n }),\n }],\n isError: true,\n };\n }\n }\n\n // Resolve chat context for the user (mark as MCP — no interactive UI available)\n const context = await resolveChatContext({ database: deps.database, userId });\n reportContext = context;\n context.isMcp = true;\n if (agentId) {\n context.agentId = agentId;\n }\n if (clientSurface) {\n context.clientSurface = clientSurface;\n }\n\n // Network-scoped agents inherit their bound network as the implicit chat\n // scope. Every tool that branches on `context.networkId` then enforces\n // the same boundary the DB-level `indexScope` clamp enforces below —\n // most importantly `read_networks`, which would otherwise return the\n // global `publicNetworks` catalog for unscoped contexts.\n applyNetworkScopeToContext(context, networkScopeId);\n\n // Gate: API-key callers (background agents) must register before using most tools.\n // OAuth/JWT session callers (human MCP clients such as Claude Code) are exempt —\n // their identity is already established via the auth flow and they have no agent entity.\n if (!isSessionAuth && !context.agentId && !AGENT_GATE_EXEMPT.has(toolName)) {\n return {\n content: [{\n type: 'text' as const,\n text: JSON.stringify({\n error: 'Agent not registered',\n message:\n 'You must register as an agent before using Index tools. ' +\n 'Call register_agent with your agent name to establish an identity. ' +\n 'The tools register_agent, read_docs, and scrape_url are available without registration.',\n }),\n }],\n isError: true,\n };\n }\n\n // Gate: non-onboarded users can only use onboarding-related tools.\n // Mirrors the chat orchestrator's ONBOARDING MODE — the MCP client must\n // walk the user through profile creation, Gmail connect, intent capture,\n // and complete_onboarding() before full tool access is granted.\n if (context.isOnboarding && !ONBOARDING_ALLOWED.has(toolName)) {\n const onboardingSteps = buildMcpOnboardingMessage(context);\n return {\n content: [{\n type: 'text' as const,\n text: JSON.stringify({\n error: 'Onboarding required',\n message: onboardingSteps,\n }),\n }],\n isError: true,\n };\n }\n\n // Build per-request scoped databases via injected factory.\n // Network-scoped agents are clamped to their bound network plus the user's\n // personal index — they cannot reach other networks even when the user is\n // a member of them. The personal-index reachability is preserved so the\n // agent can still manage its owner's profile and contacts.\n // context.indexScope is now the single source of truth: set by\n // resolveChatContext (full set) and narrowed by applyNetworkScopeToContext.\n const scopedDbs = scopedDepsFactory.create(userId, context.indexScope);\n\n // Override deps with per-request scoped databases\n const requestDeps: ToolDeps = { ...deps, ...scopedDbs };\n reportDeps = requestDeps;\n\n // Re-create registry with per-request deps for scoped database access\n const requestRegistry = createToolRegistry(requestDeps);\n const requestTool = requestRegistry.get(toolName);\n\n if (!requestTool) {\n return {\n content: [{ type: 'text' as const, text: JSON.stringify({ error: `Tool \"${toolName}\" not found` }) }],\n isError: true,\n };\n }\n\n // Validate input against the original Zod schema\n const parseResult = (toolDef.schema as z.ZodType).safeParse(args);\n if (!parseResult.success) {\n const issues = parseResult.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ');\n return {\n content: [{ type: 'text' as const, text: JSON.stringify({ success: false, error: `Invalid input: ${issues}` }) }],\n isError: true,\n };\n }\n const validatedArgs = parseResult.data;\n\n // Execute the tool handler through the shared runtime so MCP calls have\n // consistent timeout, cancellation, progress, and requestContext plumbing.\n const result = await invokeToolRuntime({\n toolName,\n tool: requestTool,\n context,\n query: validatedArgs,\n signal: ctx.mcpReq.signal,\n traceEmitter: createMcpTraceEmitter(toolName, ctx),\n });\n\n const { text: sanitizedText, isError: toolIsError } = sanitizeMcpResult(result);\n\n // Slice 5: decision questions post-processing for discover_opportunities only.\n if (toolName === \"discover_opportunities\" && !toolIsError) {\n const questions = extractDecisionQuestions(sanitizedText);\n if (questions) {\n const envelopeBlock = {\n type: \"text\" as const,\n text: renderQuestionsEnvelope(questions),\n };\n\n const supportsElicitation =\n !!server.server.getClientCapabilities()?.elicitation;\n\n // Capture into a local const so TS preserves the narrowing\n // inside the callback below. Optional chains don't survive\n // across closure boundaries under strict mode.\n const elicitInput = ctx.mcpReq?.elicitInput;\n\n if (supportsElicitation && elicitInput) {\n // Sequential — never parallel (day-one rule). We await the loop\n // before returning the tool result so test harnesses can observe\n // the dispatched calls deterministically.\n await dispatchElicitations({\n userId,\n questions,\n elicitInput: (params) => elicitInput(params),\n chatMessageWriter: deps.chatMessageWriter,\n });\n }\n\n return {\n content: [\n { type: \"text\" as const, text: sanitizedText },\n envelopeBlock,\n ],\n ...(toolIsError ? { isError: true } : {}),\n };\n }\n }\n\n return {\n content: [{ type: 'text' as const, text: sanitizedText }],\n ...(toolIsError ? { isError: true } : {}),\n };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n logger.error(`MCP tool \"${toolName}\" failed`, { error: message });\n if (shouldReportMcpToolError(err)) {\n reportDeps.reportToolError?.(err, {\n subsystem: 'mcp',\n operation: 'mcp.tool',\n toolName,\n userId: reportUserId,\n tags: {\n transport: 'mcp',\n toolName,\n },\n context: {\n agentId: reportContext?.agentId,\n networkId: reportContext?.networkId,\n indexScope: reportContext?.indexScope,\n },\n });\n }\n const runtimeResult = toolRuntimeErrorToResult(err);\n return {\n content: [{ type: 'text' as const, text: runtimeResult ?? JSON.stringify({ error: message }) }],\n isError: true,\n };\n }\n },\n );\n }\n\n logger.verbose(`MCP server created with ${registry.size} tools`);\n return server;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"mcp.server.js","sourceRoot":"/","sources":["mcp/mcp.server.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAMzE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AAErE,OAAO,EAAE,cAAc,EAAE,MAAM,sCAAsC,CAAC;AACtE,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAC;AACtE,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,wBAAwB,EAAE,MAAM,iCAAiC,CAAC;AAEhH,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAE5E,MAAM,MAAM,GAAG,cAAc,CAAC,WAAW,CAAC,CAAC;AAE3C,SAAS,sBAAsB,CAAC,OAAe;IAC7C,OAAO,OAAO,CAAC,QAAQ,CAAC,yBAAyB,CAAC;QAChD,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAC;QACnC,OAAO,CAAC,QAAQ,CAAC,iCAAiC,CAAC;QACnD,OAAO,CAAC,QAAQ,CAAC,6BAA6B,CAAC,CAAC;AACpD,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,wBAAwB,CAAC,GAAY;IACnD,IAAI,GAAG,YAAY,gBAAgB;QAAE,OAAO,KAAK,CAAC;IAClD,MAAM,OAAO,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,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;wBAChB,SAAS,EAAE,UAAU;wBACrB,QAAQ;wBACR,MAAM,EAAE,YAAY;wBACpB,IAAI,EAAE;4BACJ,SAAS,EAAE,KAAK;4BAChB,QAAQ;yBACT;wBACD,OAAO,EAAE;4BACP,OAAO,EAAE,aAAa,EAAE,OAAO;4BAC/B,SAAS,EAAE,aAAa,EAAE,SAAS;4BACnC,UAAU,EAAE,aAAa,EAAE,UAAU;yBACtC;qBACF,CAAC,CAAC;gBACL,CAAC;gBACD,MAAM,aAAa,GAAG,wBAAwB,CAAC,GAAG,CAAC,CAAC;gBACpD,OAAO;oBACL,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAe,EAAE,IAAI,EAAE,aAAa,IAAI,IAAI,CAAC,SAAS,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC;oBAC/F,OAAO,EAAE,IAAI;iBACd,CAAC;YACJ,CAAC;QACH,CAAC,CACF,CAAC;IACJ,CAAC;IAED,MAAM,CAAC,OAAO,CAAC,2BAA2B,QAAQ,CAAC,IAAI,QAAQ,CAAC,CAAC;IACjE,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/**\n * MCP Server Factory — creates an McpServer instance with all protocol tools\n * registered from the existing tool registry. Each tool invocation resolves\n * auth from the HTTP request, builds a ResolvedToolContext, and delegates\n * to the raw tool handler.\n */\n\nimport { z } from 'zod';\nimport { McpServer, fromJsonSchema } from '@modelcontextprotocol/server';\nimport type { ServerContext, JsonSchemaType } from '@modelcontextprotocol/server';\n\nimport type { McpAuthResolver } from '../shared/interfaces/auth.interface.js';\nimport type { McpAuthInput } from '../shared/schemas/mcp-auth.schema.js';\nimport type { ToolDeps, ResolvedToolContext } from '../shared/agent/tool.helpers.js';\nimport { resolveChatContext } from '../shared/agent/tool.helpers.js';\nimport type { Question } from '../shared/schemas/question.schema.js';\nimport { QuestionSchema } from '../shared/schemas/question.schema.js';\nimport { dispatchElicitations } from './elicitation.dispatcher.js';\nimport { createToolRegistry } from '../shared/agent/tool.registry.js';\nimport { ToolRuntimeError, invokeToolRuntime, toolRuntimeErrorToResult } from '../shared/agent/tool.runtime.js';\nimport type { TraceEmitter } from '../shared/observability/request-context.js';\nimport { protocolLogger } from '../shared/observability/protocol.logger.js';\n\nconst logger = protocolLogger('McpServer');\n\nfunction isExpectedMcpAuthError(message: string): boolean {\n return message.includes('Authentication required') ||\n message.includes('Invalid API key') ||\n message.includes('Invalid or expired access token') ||\n message.includes('JWT payload missing user ID');\n}\n\n/**\n * Runtime/auth failures are converted into structured MCP `isError` tool\n * results for the caller. Reporting them as application exceptions produces\n * Sentry noise for expected client failures and policy-enforced timeouts.\n */\nexport function shouldReportMcpToolError(err: unknown): boolean {\n if (err instanceof ToolRuntimeError) return false;\n const message = err instanceof Error ? err.message : String(err);\n return !isExpectedMcpAuthError(message);\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// ZOD 3 → JSON SCHEMA CONVERSION\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Minimal Zod-to-JSON-Schema conversion for MCP tool registration.\n * Converts Zod 3.x schemas to plain JSON Schema objects that can be\n * wrapped with `fromJsonSchema()` for MCP SDK compatibility.\n */\nfunction zodToJsonSchema(schema: z.ZodType): Record<string, unknown> {\n if (schema instanceof z.ZodObject) {\n const shape = schema.shape;\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n for (const [key, value] of Object.entries(shape)) {\n const zodValue = value as z.ZodType;\n properties[key] = zodToJsonSchema(zodValue);\n if (!(zodValue instanceof z.ZodOptional) && !(zodValue instanceof z.ZodDefault)) {\n required.push(key);\n }\n }\n return { type: 'object', properties, ...(required.length ? { required } : {}) };\n }\n if (schema instanceof z.ZodString) {\n const result: Record<string, unknown> = { type: 'string' };\n // Detect .url(), .email(), .uuid() etc. via Zod's internal checks array\n const checks = (schema as z.ZodString & { _def: { checks: Array<{ kind: string }> } })._def?.checks;\n if (checks) {\n for (const check of checks) {\n if (check.kind === 'url') result.format = 'uri';\n else if (check.kind === 'email') result.format = 'email';\n else if (check.kind === 'uuid') result.format = 'uuid';\n else if (check.kind === 'datetime') result.format = 'date-time';\n }\n }\n return result;\n }\n if (schema instanceof z.ZodNumber) {\n const checks = (schema as z.ZodNumber & { _def: { checks: Array<{ kind: string; value?: number }> } })._def?.checks;\n const result: Record<string, unknown> = { type: 'number' };\n if (checks) {\n for (const check of checks) {\n if (check.kind === 'int') result.type = 'integer';\n else if (check.kind === 'min') result.minimum = check.value;\n else if (check.kind === 'max') result.maximum = check.value;\n }\n }\n return result;\n }\n if (schema instanceof z.ZodBoolean) return { type: 'boolean' };\n if (schema instanceof z.ZodArray) {\n return { type: 'array', items: zodToJsonSchema((schema as z.ZodArray<z.ZodType>).element) };\n }\n if (schema instanceof z.ZodOptional) {\n return zodToJsonSchema((schema as z.ZodOptional<z.ZodType>).unwrap());\n }\n if (schema instanceof z.ZodDefault) {\n return zodToJsonSchema((schema as z.ZodDefault<z.ZodType>).removeDefault());\n }\n if (schema instanceof z.ZodEnum) {\n return { type: 'string', enum: (schema as z.ZodEnum<[string, ...string[]]>).options };\n }\n if (schema instanceof z.ZodNullable) {\n const inner = zodToJsonSchema((schema as z.ZodNullable<z.ZodType>).unwrap());\n return { ...inner, nullable: true };\n }\n if (schema instanceof z.ZodRecord) {\n return { type: 'object', additionalProperties: true };\n }\n return { type: 'object' };\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// RESULT POST-PROCESSING\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Strips internal `_`-prefixed keys from `data` and promotes `isError`\n * from the inner `success: false` signal to the MCP envelope level.\n * Fail-open: if JSON parsing throws, returns the original text with isError: false.\n */\nexport function sanitizeMcpResult(text: string): { text: string; isError: boolean } {\n try {\n const parsed = JSON.parse(text);\n if (\n parsed &&\n typeof parsed === 'object' &&\n parsed.data &&\n typeof parsed.data === 'object' &&\n !Array.isArray(parsed.data)\n ) {\n for (const key of Object.keys(parsed.data)) {\n if (key.startsWith('_') || key === 'debugSteps') {\n delete parsed.data[key];\n }\n }\n }\n const isError = parsed?.success === false;\n return { text: JSON.stringify(parsed), isError };\n } catch {\n return { text, isError: false };\n }\n}\n\n/** Spec cap on the number of decision questions surfaced per turn. */\nconst MAX_DECISION_QUESTIONS = 3;\n\n/**\n * Extracts decision questions from a parsed tool-result text, if present.\n * Validates each entry against `QuestionSchema` and drops malformed items;\n * caps the array at `MAX_DECISION_QUESTIONS` (defense-in-depth — Slice 2's\n * generator already caps at 3, but we don't trust the cast here).\n *\n * Returns null when the text isn't JSON, has no `data.questions`, or\n * contains zero valid questions after validation.\n */\nexport function extractDecisionQuestions(text: string): Question[] | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return null;\n }\n\n const rawQs = (parsed as { data?: { questions?: unknown } } | null)?.data?.questions;\n if (!Array.isArray(rawQs) || rawQs.length === 0) return null;\n\n const valid: Question[] = [];\n for (const raw of rawQs) {\n const result = QuestionSchema.safeParse(raw);\n if (result.success) valid.push(result.data);\n if (valid.length === MAX_DECISION_QUESTIONS) break;\n }\n return valid.length > 0 ? valid : null;\n}\n\n/**\n * Renders the JSON-envelope text block appended to the tool result content\n * when decision questions are present. The leading sentinel string lets the\n * LLM client recognize and surface the questions in prose for clients\n * without elicitation support.\n */\nexport function renderQuestionsEnvelope(questions: Question[]): string {\n return `Decision questions (structured): ${JSON.stringify({ questions })}`;\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// MCP SERVER FACTORY\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Factory for creating per-request scoped database instances.\n * Injected from the controller/handler layer to keep the protocol layer\n * free of direct adapter imports.\n */\nexport interface ScopedDepsFactory {\n /** Creates scoped userDb and systemDb for the given user and index scope. */\n create(userId: string, indexScope: string[]): Pick<ToolDeps, 'userDb' | 'systemDb'>;\n}\n\n/**\n * Computes the index scope passed to the per-request scoped DB factory. When\n * `networkScopeId` is non-null, the agent is bound to a single network and\n * may only reach that network plus the user's personal index. Otherwise the\n * full set of the user's network memberships is returned.\n */\nexport const computeAgentIndexScope = (\n userNetworks: { networkId: string; isPersonal?: boolean | null }[],\n networkScopeId: string | null | undefined,\n): string[] => {\n if (!networkScopeId) {\n return userNetworks.map((m) => m.networkId);\n }\n return userNetworks\n .filter((m) => m.networkId === networkScopeId || m.isPersonal === true)\n .map((m) => m.networkId);\n};\n\n/**\n * Promotes a network-scoped agent's bound network into the resolved tool\n * context as the implicit chat scope. Every tool that branches on\n * `context.networkId` (read_networks, read_intents, read_user_profiles,\n * opportunity tools, etc.) then enforces scope automatically — without this\n * step the DB-level `indexScope` clamp guards cross-user data but tools that\n * shape their response off `context.networkId` (notably `read_networks`'\n * `publicNetworks` branch) would still leak the global view.\n *\n * No-op when there is no scope, or when an explicit chat scope is already\n * set (a user-driven index-scoped chat must keep precedence over the agent\n * binding — which would be a strict subset anyway, since the API key cannot\n * reach beyond its bound network).\n */\nexport const applyNetworkScopeToContext = (\n context: ResolvedToolContext,\n networkScopeId: string | null | undefined,\n): void => {\n if (!networkScopeId) return;\n if (context.networkId) return;\n\n context.networkId = networkScopeId;\n // Clamp indexScope to [boundNetwork, personalIndex] BEFORE the membership\n // check below. If the bound network is not in userNetworks (defensive case),\n // the filter still produces a safe scope (personal index only) rather than\n // leaving the unclamped scope set by resolveChatContext.\n context.indexScope = context.userNetworks\n .filter((m) => m.networkId === networkScopeId || m.isPersonal === true)\n .map((m) => m.networkId);\n\n const bound = context.userNetworks.find((m) => m.networkId === networkScopeId);\n if (!bound) return;\n\n context.indexName = bound.networkTitle;\n context.scopedIndex = {\n id: bound.networkId,\n title: bound.networkTitle,\n prompt: bound.indexPrompt ?? null,\n };\n const isOwner = bound.permissions?.includes('owner') ?? false;\n context.scopedMembershipRole = isOwner ? 'owner' : 'member';\n context.isOwner = isOwner;\n};\n\n/**\n * Tools allowed during onboarding — everything else is gated until\n * complete_onboarding is called. Includes the agent-gate-exempt tools\n * (register_agent, read_docs, scrape_url) because they are informational /\n * registration primitives needed at every lifecycle stage.\n */\nexport const ONBOARDING_ALLOWED: ReadonlySet<string> = new Set([\n 'register_agent',\n 'read_docs',\n 'scrape_url',\n 'record_onboarding_privacy_consent',\n 'preview_user_profile',\n 'get_profile_run',\n 'cancel_profile_run',\n 'confirm_user_profile',\n 'create_user_profile',\n 'complete_onboarding',\n 'import_gmail_contacts',\n 'read_networks',\n 'create_network_membership',\n 'create_intent',\n 'discover_opportunities',\n 'read_user_profiles',\n]);\n\n/**\n * Builds the onboarding gate message for MCP callers. Condensed from the\n * chat orchestrator's 8-step flow (chat.prompt.ts buildOnboarding) into a\n * 7-step tool-error guide suited for non-interactive MCP clients.\n */\nexport function buildMcpOnboardingMessage(ctx: ResolvedToolContext): string {\n const nameStep = ctx.hasName\n ? `1. Greet the user and confirm their name (\"You're ${ctx.userName}, right?\").`\n : `1. Ask the user for their name and a short self-description.`;\n\n const communityStep = ctx.networkId\n ? `5. (Skipped — user is already in \"${ctx.indexName ?? 'their community'}\".)`\n : `5. Call read_networks() and let the user pick communities to join via create_network_membership(networkId=...).`;\n\n const allowedList = Array.from(ONBOARDING_ALLOWED).join(', ');\n\n return (\n `This user has not completed onboarding. You must guide them through setup before they can use other tools. ` +\n `Only the following tools are available until onboarding is complete: ` +\n `${allowedList}.\\n\\n` +\n `Onboarding flow:\\n` +\n `${nameStep}\\n` +\n `2. Ask whether the user allows use of event/EdgeOS profile data, then call record_onboarding_privacy_consent(edgeosImportGranted=...).\\n` +\n `3. Ask separately whether the user allows public internet/profile lookup, then call record_onboarding_privacy_consent(publicProfileLookupGranted=...).\\n` +\n `4. Call preview_user_profile(...) using only allowed inputs; do not run public lookup unless consent was granted. If it returns profileRunId, poll get_profile_run(profileRunId=...) until status is succeeded, then use its result as the draft.\\n` +\n `5. Present the profile draft and ask \"Does that look right?\" On approval/correction, call confirm_user_profile(...).\\n` +\n `${communityStep}\\n` +\n `6. Ask what the user is looking for and call create_intent(description=\"...\").\\n` +\n `7. Call complete_onboarding() to finish setup. Gmail/contact import and discovery are optional after onboarding, never mandatory.`\n );\n}\n\n/**\n * Creates an MCP server with all protocol tools registered.\n * Tools resolve auth per-request via the HTTP request available in ServerContext.\n *\n * @param deps - Shared tool dependencies (graphs, database, embedder, etc.)\n * @param authResolver - Resolves authenticated identity from the HTTP request\n * @param scopedDepsFactory - Factory for creating per-request scoped databases\n * @returns A configured McpServer ready to be connected to a transport\n */\nfunction createMcpTraceEmitter(toolName: string, ctx: ServerContext): TraceEmitter | undefined {\n const token = ctx.mcpReq._meta?.progressToken;\n if (typeof token !== 'string' && typeof token !== 'number') return undefined;\n\n let progress = 0;\n return (event) => {\n progress += 1;\n const message = (() => {\n if (event.type === 'graph_start') return `${toolName}: ${event.name} started`;\n if (event.type === 'graph_end') return `${toolName}: ${event.name} finished${event.durationMs != null ? ` in ${event.durationMs}ms` : ''}`;\n if (event.type === 'agent_start') return `${toolName}: ${event.name} agent started`;\n if (event.type === 'agent_end') return `${toolName}: ${event.name} agent finished${event.durationMs != null ? ` in ${event.durationMs}ms` : ''}`;\n if (event.type === 'opportunity_draft_ready') return `${toolName}: opportunity draft ready`;\n return `${toolName}: progress`;\n })();\n\n const notification: Parameters<ServerContext['mcpReq']['notify']>[0] = {\n method: 'notifications/progress',\n params: { progressToken: token, progress, message },\n };\n void ctx.mcpReq.notify(notification).catch((err) => {\n logger.debug('Failed to send MCP progress notification', {\n toolName,\n error: err instanceof Error ? err.message : String(err),\n });\n });\n };\n}\n\nexport const MCP_INSTRUCTIONS = `\nIndex Network is a private, intent-driven discovery protocol. You help users find the right people and help the right people find them, via Index Network MCP tools.\n\n# Voice\nCalm, direct, analytical, concise. Preferred vocabulary: opportunity, overlap, signal, pattern, emerging, relevant, adjacency.\n\n# Banned vocabulary\nNEVER use \"search\" in any form. Use \"looking up\" for indexed data, \"find\" / \"look for\" for discovery, \"check\" for verification, \"discover\" for exploration. Banned: leverage, unlock, optimize, scale, disrupt, revolutionary, AI-powered, maximize value, act fast, networking, match.\n\n# Entity model\n- User — has one Profile, many Memberships, many Intents.\n- Profile — identity (bio, skills, interests, location).\n- Index — community with title, prompt (purpose), join policy. Has Members.\n- Membership — User↔Index junction. \\`isPersonal: true\\` marks the user's personal index (contacts).\n- Intent — what a user is looking for (signal). Description, summary, embedding.\n- IntentIndex — Intent↔Index junction (auto-assigned).\n- Opportunity — discovered connection between users. Roles, status, reasoning.\n\n# Output rules\n- NEVER expose internal IDs, UUIDs, field names, or tool names — EXCEPT when an ID is actionable for the user (e.g. a \\`conversationId\\` they need to open a chat). Surface such IDs verbatim when the tool returns them.\n- NEVER use internal vocabulary — say \"signal\" not \"intent\", \"community\" not \"index\".\n- NEVER dump raw JSON. Synthesize in natural language.\n- Surface top 1–3 relevant points unless asked for the full list.\n- Prefer first names; use full names only to disambiguate.\n- Translate statuses: draft/latent → \"draft\", pending → \"sent\", accepted → \"connected\".\n- NEVER fabricate data. If you don't have it, call the appropriate tool.\n\n# Tool guidance\nEach tool's description contains its own usage rules (when to call, when NOT to call, required prerequisites, post-call follow-ups). Read the description of every tool you call — that is where the per-tool workflow patterns live.\n\n# Authentication\nPass your API key in the \\`x-api-key\\` request header (not \\`Authorization: Bearer\\`).\n\n# Opportunity lifecycle\nOpportunities move through: draft → pending → accepted (or rejected).\n\n- **draft** (you created it, not yet sent): offer to send it; confirm before calling update_opportunity with pending.\n- **pending, you sent it**: waiting for the other side — nothing to do.\n- **pending, you received it**: the other person is waiting for your response. Surface it to the user and ask if they want to start a chat. Only call update_opportunity with accepted after explicit user confirmation.\n- **accepted**: both sides are connected — a direct conversation exists. Surface the conversationId to the user if available.\n\nNever accept a received opportunity without explicit user approval in the current conversation.\n\n# Decision questions after discovery\n\nAfter \\`discover_opportunities\\`, the tool result may include a second text block starting with \\`Decision questions (structured): ...\\`. This means the discovery engine ran negotiations but needs human input to sharpen the next turn — e.g. clarify timing, role, stage, or location.\n\n**When this block is present:**\n1. Parse the \\`questions\\` array from the JSON after the sentinel.\n2. Each question has \\`title\\` (decision domain, ≤12 chars), \\`prompt\\` (ends in \\`?\\`), \\`options\\` (2–4 items, each with \\`label\\` and \\`description\\`), and \\`multiSelect\\`. The safest option is labeled \\`... (Recommended)\\`.\n3. Present each question in natural language: ask the \\`prompt\\`, list options as \\`**{label}** — {description}\\`. Never expose the JSON or technical field names.\n4. Wait for the user's answer, then fold it into the next \\`discover_opportunities(searchQuery=...)\\` call.\n\n**Elicitation-capable clients** (those that declared \\`elicitation\\` support in \\`initialize\\`): the server dispatches \\`elicitation/create\\` requests directly — answers are written back to the chat session automatically. You will not see the envelope as a follow-up task in that case.\n`.trim();\n\n/**\n * Extracts a Bearer token from an HTTP Authorization header.\n */\nexport function extractBearerToken(req: Request): string | undefined {\n const authHeader = req.headers.get('Authorization');\n if (!authHeader) return undefined;\n const [scheme, token] = authHeader.trim().split(/\\s+/, 2);\n if (scheme?.toLowerCase() === 'bearer' && token) return token;\n return undefined;\n}\n\n/**\n * Normalizes the x-index-surface header to a typed surface value.\n * Unknown or absent values collapse to 'web'.\n */\nlet hasWarnedInvalidSurface = false;\nexport function parseClientSurface(raw: string | null): 'telegram' | 'web' {\n if (raw === null || raw === '') return 'web';\n const trimmed = raw.trim().toLowerCase();\n if (trimmed === '') return 'web';\n if (trimmed === 'telegram') return 'telegram';\n if (trimmed === 'web') return 'web';\n if (!hasWarnedInvalidSurface) {\n hasWarnedInvalidSurface = true;\n logger.warn('Unknown x-index-surface value (collapsing to web; warning once per process)');\n }\n return 'web';\n}\n\nexport function createMcpServer(\n deps: ToolDeps,\n authResolver: McpAuthResolver,\n scopedDepsFactory: ScopedDepsFactory,\n): McpServer {\n // Tools exempt from the agent-registration gate — available before registration is complete.\n const AGENT_GATE_EXEMPT = new Set(['register_agent', 'read_docs', 'scrape_url']);\n\n const server = new McpServer(\n { name: 'index-network', version: '1.0.0' },\n { instructions: MCP_INSTRUCTIONS },\n );\n\n const registry = createToolRegistry(deps);\n\n for (const [toolName, toolDef] of registry) {\n // Convert Zod 3 schema to JSON Schema, then wrap with fromJsonSchema\n // for MCP SDK's StandardSchemaWithJSON compatibility\n const jsonSchema = zodToJsonSchema(toolDef.schema) as JsonSchemaType;\n const mcpSchema = fromJsonSchema(jsonSchema);\n\n server.registerTool(\n toolName,\n {\n description: toolDef.description,\n inputSchema: mcpSchema,\n },\n async (args: unknown, ctx: ServerContext) => {\n let reportDeps = deps;\n let reportUserId: string | undefined;\n let reportContext: ResolvedToolContext | undefined;\n\n try {\n // Extract the original HTTP request from the MCP server context\n const httpReq = ctx.http?.req;\n if (!httpReq) {\n return {\n content: [{ type: 'text' as const, text: JSON.stringify({ error: 'No HTTP request available in MCP context' }) }],\n isError: true,\n };\n }\n\n // Extract transport-neutral auth input DTO from the HTTP request\n const mcpAuthInput: McpAuthInput = {\n bearerToken: extractBearerToken(httpReq),\n apiKey: httpReq.headers.get('x-api-key') ?? undefined,\n clientSurface: parseClientSurface(httpReq.headers.get('x-index-surface')),\n telegramHandle: httpReq.headers.get('x-index-telegram-handle') ?? undefined,\n telegramUsername: httpReq.headers.get('x-index-telegram-username') ?? undefined,\n };\n\n // Resolve authenticated identity from the auth input DTO\n const { userId, agentId, isSessionAuth, networkScopeId, clientSurface } = await authResolver.resolveIdentity(mcpAuthInput);\n reportUserId = userId;\n\n // Per-principal MCP throttle. Runs BEFORE any DB work so a throttled\n // call short-circuits cheaply. The /mcp transport bypasses the\n // controller-level RateLimit guard, so this is the only volume cap on\n // tool calls — it stops an over-eager agent from cascading itself into\n // provider rate limits.\n if (deps.mcpRateLimiter) {\n // Throttling is best-effort: never let a limiter failure (or a host\n // implementation that throws instead of failing open) break tool\n // dispatch. Treat any error as \"allowed\".\n let decision: Awaited<ReturnType<NonNullable<typeof deps.mcpRateLimiter>>> | null = null;\n try {\n decision = await deps.mcpRateLimiter({\n userId,\n ...(agentId ? { agentId } : {}),\n toolName,\n });\n } catch (rlErr) {\n logger.warn(`MCP rate limiter threw for \"${toolName}\" — failing open`, {\n error: rlErr instanceof Error ? rlErr.message : String(rlErr),\n });\n }\n if (decision && !decision.allowed) {\n const retryAfterSec = decision.retryAfterSec ?? 60;\n return {\n content: [{\n type: 'text' as const,\n text: JSON.stringify({\n error: 'Rate limit exceeded',\n message:\n `Too many ${toolName} calls in a short period. Wait ${retryAfterSec}s before retrying.` +\n (toolName === 'discover_opportunities'\n ? ` If a discovery run is in progress, poll get_discovery_run instead of calling discover_opportunities again.`\n : ''),\n retryAfterSec,\n }),\n }],\n isError: true,\n };\n }\n }\n\n // Resolve chat context for the user (mark as MCP — no interactive UI available)\n const context = await resolveChatContext({ database: deps.database, userId });\n reportContext = context;\n context.isMcp = true;\n if (agentId) {\n context.agentId = agentId;\n }\n if (clientSurface) {\n context.clientSurface = clientSurface;\n }\n\n // Network-scoped agents inherit their bound network as the implicit chat\n // scope. Every tool that branches on `context.networkId` then enforces\n // the same boundary the DB-level `indexScope` clamp enforces below —\n // most importantly `read_networks`, which would otherwise return the\n // global `publicNetworks` catalog for unscoped contexts.\n applyNetworkScopeToContext(context, networkScopeId);\n\n // Gate: API-key callers (background agents) must register before using most tools.\n // OAuth/JWT session callers (human MCP clients such as Claude Code) are exempt —\n // their identity is already established via the auth flow and they have no agent entity.\n if (!isSessionAuth && !context.agentId && !AGENT_GATE_EXEMPT.has(toolName)) {\n return {\n content: [{\n type: 'text' as const,\n text: JSON.stringify({\n error: 'Agent not registered',\n message:\n 'You must register as an agent before using Index tools. ' +\n 'Call register_agent with your agent name to establish an identity. ' +\n 'The tools register_agent, read_docs, and scrape_url are available without registration.',\n }),\n }],\n isError: true,\n };\n }\n\n // Gate: non-onboarded users can only use onboarding-related tools.\n // Mirrors the chat orchestrator's ONBOARDING MODE — the MCP client must\n // walk the user through profile creation, Gmail connect, intent capture,\n // and complete_onboarding() before full tool access is granted.\n if (context.isOnboarding && !ONBOARDING_ALLOWED.has(toolName)) {\n const onboardingSteps = buildMcpOnboardingMessage(context);\n return {\n content: [{\n type: 'text' as const,\n text: JSON.stringify({\n error: 'Onboarding required',\n message: onboardingSteps,\n }),\n }],\n isError: true,\n };\n }\n\n // Build per-request scoped databases via injected factory.\n // Network-scoped agents are clamped to their bound network plus the user's\n // personal index — they cannot reach other networks even when the user is\n // a member of them. The personal-index reachability is preserved so the\n // agent can still manage its owner's profile and contacts.\n // context.indexScope is now the single source of truth: set by\n // resolveChatContext (full set) and narrowed by applyNetworkScopeToContext.\n const scopedDbs = scopedDepsFactory.create(userId, context.indexScope);\n\n // Override deps with per-request scoped databases\n const requestDeps: ToolDeps = { ...deps, ...scopedDbs };\n reportDeps = requestDeps;\n\n // Re-create registry with per-request deps for scoped database access\n const requestRegistry = createToolRegistry(requestDeps);\n const requestTool = requestRegistry.get(toolName);\n\n if (!requestTool) {\n return {\n content: [{ type: 'text' as const, text: JSON.stringify({ error: `Tool \"${toolName}\" not found` }) }],\n isError: true,\n };\n }\n\n // Validate input against the original Zod schema\n const parseResult = (toolDef.schema as z.ZodType).safeParse(args);\n if (!parseResult.success) {\n const issues = parseResult.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ');\n return {\n content: [{ type: 'text' as const, text: JSON.stringify({ success: false, error: `Invalid input: ${issues}` }) }],\n isError: true,\n };\n }\n const validatedArgs = parseResult.data;\n\n // Execute the tool handler through the shared runtime so MCP calls have\n // consistent timeout, cancellation, progress, and requestContext plumbing.\n const result = await invokeToolRuntime({\n toolName,\n tool: requestTool,\n context,\n query: validatedArgs,\n signal: ctx.mcpReq.signal,\n traceEmitter: createMcpTraceEmitter(toolName, ctx),\n });\n\n const { text: sanitizedText, isError: toolIsError } = sanitizeMcpResult(result);\n\n // Slice 5: decision questions post-processing for discover_opportunities only.\n if (toolName === \"discover_opportunities\" && !toolIsError) {\n const questions = extractDecisionQuestions(sanitizedText);\n if (questions) {\n const envelopeBlock = {\n type: \"text\" as const,\n text: renderQuestionsEnvelope(questions),\n };\n\n const supportsElicitation =\n !!server.server.getClientCapabilities()?.elicitation;\n\n // Capture into a local const so TS preserves the narrowing\n // inside the callback below. Optional chains don't survive\n // across closure boundaries under strict mode.\n const elicitInput = ctx.mcpReq?.elicitInput;\n\n if (supportsElicitation && elicitInput) {\n // Sequential — never parallel (day-one rule). We await the loop\n // before returning the tool result so test harnesses can observe\n // the dispatched calls deterministically.\n await dispatchElicitations({\n userId,\n questions,\n elicitInput: (params) => elicitInput(params),\n chatMessageWriter: deps.chatMessageWriter,\n });\n }\n\n return {\n content: [\n { type: \"text\" as const, text: sanitizedText },\n envelopeBlock,\n ],\n ...(toolIsError ? { isError: true } : {}),\n };\n }\n }\n\n return {\n content: [{ type: 'text' as const, text: sanitizedText }],\n ...(toolIsError ? { isError: true } : {}),\n };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n logger.error(`MCP tool \"${toolName}\" failed`, { error: message });\n if (shouldReportMcpToolError(err)) {\n reportDeps.reportToolError?.(err, {\n subsystem: 'mcp',\n operation: 'mcp.tool',\n toolName,\n userId: reportUserId,\n tags: {\n transport: 'mcp',\n toolName,\n },\n context: {\n agentId: reportContext?.agentId,\n networkId: reportContext?.networkId,\n indexScope: reportContext?.indexScope,\n },\n });\n }\n const runtimeResult = toolRuntimeErrorToResult(err);\n return {\n content: [{ type: 'text' as const, text: runtimeResult ?? JSON.stringify({ error: message }) }],\n isError: true,\n };\n }\n },\n );\n }\n\n logger.verbose(`MCP server created with ${registry.size} tools`);\n return server;\n}\n"]}
|
|
@@ -9,14 +9,14 @@ declare const OpportunitySchema: z.ZodObject<{
|
|
|
9
9
|
sourceId: z.ZodString;
|
|
10
10
|
candidateId: z.ZodString;
|
|
11
11
|
}, "strip", z.ZodTypeAny, {
|
|
12
|
-
reasoning: string;
|
|
13
12
|
sourceId: string;
|
|
13
|
+
reasoning: string;
|
|
14
14
|
score: number;
|
|
15
15
|
valencyRole: "Agent" | "Patient" | "Peer";
|
|
16
16
|
candidateId: string;
|
|
17
17
|
}, {
|
|
18
|
-
reasoning: string;
|
|
19
18
|
sourceId: string;
|
|
19
|
+
reasoning: string;
|
|
20
20
|
score: number;
|
|
21
21
|
valencyRole: "Agent" | "Patient" | "Peer";
|
|
22
22
|
candidateId: string;
|
|
@@ -244,8 +244,8 @@ export declare class OpportunityEvaluator {
|
|
|
244
244
|
minScore?: number | undefined;
|
|
245
245
|
candidatesJson?: string | undefined;
|
|
246
246
|
}, {
|
|
247
|
-
reasoning: string;
|
|
248
247
|
sourceId: string;
|
|
248
|
+
reasoning: string;
|
|
249
249
|
score: number;
|
|
250
250
|
valencyRole: "Agent" | "Patient" | "Peer";
|
|
251
251
|
candidateId: string;
|
|
@@ -7,19 +7,19 @@ declare const responseFormat: z.ZodObject<{
|
|
|
7
7
|
felicityClarity: z.ZodNumber;
|
|
8
8
|
semanticEntropy: z.ZodNumber;
|
|
9
9
|
}, "strip", z.ZodTypeAny, {
|
|
10
|
-
reasoning: string;
|
|
11
10
|
semanticEntropy: number;
|
|
12
11
|
felicityAuthority: number;
|
|
13
12
|
felicitySincerity: number;
|
|
14
13
|
felicityClarity: number;
|
|
15
14
|
speechActType: "DECLARATIVE" | "ASSERTIVE";
|
|
16
|
-
}, {
|
|
17
15
|
reasoning: string;
|
|
16
|
+
}, {
|
|
18
17
|
semanticEntropy: number;
|
|
19
18
|
felicityAuthority: number;
|
|
20
19
|
felicitySincerity: number;
|
|
21
20
|
felicityClarity: number;
|
|
22
21
|
speechActType: "DECLARATIVE" | "ASSERTIVE";
|
|
22
|
+
reasoning: string;
|
|
23
23
|
}>;
|
|
24
24
|
export type PremiseAnalyzerOutput = z.infer<typeof responseFormat>;
|
|
25
25
|
/**
|
|
@@ -22,17 +22,17 @@ declare const responseFormat: z.ZodObject<{
|
|
|
22
22
|
tier: "assertive" | "contextual";
|
|
23
23
|
}>, "many">;
|
|
24
24
|
}, "strip", z.ZodTypeAny, {
|
|
25
|
-
reasoning: string;
|
|
26
25
|
premises: {
|
|
27
26
|
text: string;
|
|
28
27
|
tier: "assertive" | "contextual";
|
|
29
28
|
}[];
|
|
30
|
-
}, {
|
|
31
29
|
reasoning: string;
|
|
30
|
+
}, {
|
|
32
31
|
premises: {
|
|
33
32
|
text: string;
|
|
34
33
|
tier: "assertive" | "contextual";
|
|
35
34
|
}[];
|
|
35
|
+
reasoning: string;
|
|
36
36
|
}>;
|
|
37
37
|
export type PremiseDecomposerOutput = z.infer<typeof responseFormat>;
|
|
38
38
|
export type DecomposedPremise = z.infer<typeof premiseItemSchema>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"premise.tools.js","sourceRoot":"/","sources":["premise/premise.tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAC7E,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAE5E,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAExE,MAAM,MAAM,GAAG,cAAc,CAAC,mBAAmB,CAAC,CAAC;AAEnD,MAAM,UAAU,kBAAkB,CAAC,UAAsB,EAAE,IAAc;IACvE,MAAM,QAAQ,GAAG,IAAI,CAAC,QAA2C,CAAC;IAClE,MAAM,YAAY,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC;IAEzC,gFAAgF;IAChF,eAAe;IACf,gFAAgF;IAEhF,MAAM,aAAa,GAAG,UAAU,CAAC;QAC/B,IAAI,EAAE,gBAAgB;QACtB,WAAW,EACT,wFAAwF;YACxF,wFAAwF;YACxF,oCAAoC;YACpC,cAAc;YACd,wGAAwG;YACxG,4DAA4D;YAC5D,yFAAyF;YACzF,+FAA+F;YAC/F,6DAA6D;YAC7D,8FAA8F;YAC9F,6FAA6F;YAC7F,8FAA8F;QAChG,WAAW,EAAE,CAAC,CAAC,MAAM,CAAC;YACpB,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,sHAAsH,CAAC;YAC/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AAS,EAAE;gBAC5C,MAAM,EAAE,WAAW;gBACnB,WAAW,EAAE,IAAI,IAAI,EAAE;aACxB,CAAC,CAAC;YAEH,MAAM,aAAa,GAAG,OAAO,CAAC;gBAC5B,EAAE,EAAE,KAAK,CAAC,SAAS;gBACnB,OAAO,EAAE,iCAAiC;aAC3C,CAAC,CAAC;YACH,IAAI,CAAC;gBAAC,IAAI,CAAC,aAAa,EAAE,WAAW,EAAE,CAAC,KAAK,CAAC,SAAS,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;YAAC,CAAC;YAC3E,OAAO,CAAC,EAAE,CAAC;gBAAC,MAAM,CAAC,KAAK,CAAC,mDAAmD,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;YAAC,CAAC;YAC9F,OAAO,aAAa,CAAC;QACvB,CAAC;KACF,CAAC,CAAC;IAEH,OAAO,CAAC,aAAa,EAAE,YAAY,EAAE,aAAa,EAAE,cAAc,CAAC,CAAC;AACtE,CAAC","sourcesContent":["import { z } from \"zod\";\n\nimport type { DefineTool, ToolDeps } from \"../shared/agent/tool.helpers.js\";\nimport { success, error, UUID_REGEX } from \"../shared/agent/tool.helpers.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport type { PremiseGraphDatabase, PremiseRecord, PremiseValidity } from \"../shared/interfaces/database.interface.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\n\nconst logger = protocolLogger(\"ChatTools:Premise\");\n\nexport function createPremiseTools(defineTool: DefineTool, deps: ToolDeps) {\n const database = deps.database as unknown as PremiseGraphDatabase;\n const premiseGraph = deps.graphs.premise;\n\n // ─────────────────────────────────────────────────────────────────────────────\n // PREMISE CRUD\n // ─────────────────────────────────────────────────────────────────────────────\n\n const createPremise = defineTool({\n name: \"create_premise\",\n description:\n \"Creates a premise — a self-descriptive proposition the user asserts about themselves. \" +\n \"Premises are the foundational facts that shape how the system understands who you are \" +\n \"and what contexts you inhabit.\\n\\n\" +\n \"**Tiers:**\\n\" +\n \"- `assertive` (default): stable identity facts (e.g. 'I am a software engineer', 'I live in Berlin'). \" +\n \"Use for things that are durably true and not time-bound.\\n\" +\n \"- `contextual`: temporal or situational facts (e.g. 'I am attending DevCon this week', \" +\n \"'I am fundraising for my Series A right now'). Use when the user shares something time-bound \" +\n \"or context-specific. These default to `volatile: true`.\\n\\n\" +\n \"**When to use:** Call this whenever the user shares a fact about themselves in first person \" +\n \"('I am', 'I work at', 'I just joined', 'I am currently'). Do not infer premises from vague \" +\n \"statements — only create them when the user is clearly asserting something about themselves.\",\n querySchema: z.object({\n text: z.string().trim().min(1).describe(\"The premise text — a self-descriptive proposition in first person, e.g. 'I am a machine learning researcher at MIT'.\"),\n tier: z.enum([\"assertive\", \"contextual\"]).default(\"assertive\").describe(\"Tier of the premise. 'assertive' = stable identity fact. 'contextual' = temporal/situational. Defaults to 'assertive'.\"),\n validFrom: z.string().datetime().optional().describe(\"ISO 8601 date-time string for when this premise becomes valid. Omit for immediate.\"),\n validUntil: z.string().datetime().optional().describe(\"ISO 8601 date-time string for when this premise expires. Recommended for contextual premises with a known end date; omit if open-ended.\"),\n volatile: z.boolean().optional().describe(\"Whether this premise should be automatically retracted when it expires. Defaults to true for contextual tier, false for assertive.\"),\n }),\n handler: async ({ context, query }) => {\n if (!premiseGraph) {\n return error(\"Premise graph not available.\");\n }\n\n const effectiveVolatile = query.volatile ?? (query.tier === \"contextual\" ? true : false);\n\n logger.verbose(`[createPremise] Creating premise for user ${context.userId}: \"${query.text.substring(0, 60)}...\"`);\n\n const result = await invokeWithAbortSignal(premiseGraph, {\n userId: context.userId,\n assertionText: query.text,\n tier: query.tier,\n validFrom: query.validFrom,\n validUntil: query.validUntil,\n volatile: effectiveVolatile,\n operationMode: \"create\",\n });\n\n if (result.error) {\n return error(result.error);\n }\n\n if (!result.premise) {\n return error(\"Premise creation failed — no premise returned.\");\n }\n\n const premise = result.premise;\n const indexesAssigned = result.networkAssignments?.length ?? 0;\n const analysisSummary = premise.analysis\n ? `speechActType: ${premise.analysis.speechActType}, clarity: ${premise.analysis.felicityClarity?.toFixed(2) ?? \"n/a\"}`\n : \"no analysis\";\n\n const createResult = success({\n id: premise.id,\n assertion: premise.assertion.text,\n tier: premise.assertion.tier,\n analysisSummary,\n indexesAssigned,\n message: `Premise created and assigned to ${indexesAssigned} index${indexesAssigned === 1 ? \"\" : \"es\"}.`,\n });\n try { deps.premiseEvents?.onCreated?.(premise.id, context.userId); }\n catch (e) { logger.error('[createPremise] premiseEvents.onCreated failed', { error: e }); }\n return createResult;\n },\n });\n\n const readPremises = defineTool({\n name: \"read_premises\",\n description:\n \"Retrieves premises — the self-descriptive propositions a user has asserted about themselves. \" +\n \"Premises represent stable identity facts (assertive) and temporal context (contextual).\\n\\n\" +\n \"**Usage modes:**\\n\" +\n \"- No parameters: returns the caller's own active premises.\\n\" +\n \"- With `userId`: returns that user's premises (use when reviewing another member's context).\\n\" +\n \"- With `includeRetracted: true`: returns all premises regardless of status (active, retracted, expired) for history review.\\n\\n\" +\n \"**When to use:** Call before creating a premise to check if it already exists. \" +\n \"Call when the user asks what they have shared about themselves, or to review their current context. \" +\n \"Each premise includes: id, text, tier, status, analysis summary, and validity range.\",\n querySchema: z.object({\n userId: z.string().optional().describe(\"User ID to fetch premises for. Omit to fetch the current user's own premises.\"),\n includeRetracted: z.boolean().default(false).describe(\"When true, returns all premises regardless of status (active, retracted, expired). Defaults to false (active only).\"),\n }),\n handler: async ({ context, query }) => {\n const targetUserId = query.userId?.trim() || context.userId;\n\n if (query.userId?.trim() && !UUID_REGEX.test(query.userId.trim())) {\n return error(\"Invalid userId format.\");\n }\n\n logger.verbose(`[readPremises] Fetching premises for user ${targetUserId}`);\n\n // Query DB directly (bypassing graph) to support status filtering.\n // The graph's query node hardcodes ACTIVE status, so includeRetracted\n // would be dead code if we routed through it.\n const statusFilter = query.includeRetracted ? undefined : \"ACTIVE\" as const;\n const premises = await database.getPremisesForUser(targetUserId, statusFilter);\n\n const mapped = premises.map((p: PremiseRecord) => ({\n id: p.id,\n text: p.assertion.text,\n tier: p.assertion.tier,\n status: p.status,\n analysisSummary: p.analysis\n ? `speechActType: ${p.analysis.speechActType ?? \"n/a\"}, clarity: ${p.analysis.felicityClarity?.toFixed(2) ?? \"n/a\"}`\n : \"no analysis\",\n validFrom: p.validity.validFrom ?? null,\n validUntil: p.validity.validUntil ?? null,\n volatile: p.validity.volatile ?? false,\n }));\n\n return success({\n premises: mapped,\n count: mapped.length,\n });\n },\n });\n\n const updatePremise = defineTool({\n name: \"update_premise\",\n description:\n \"Modifies an existing premise. Updating the text triggers re-analysis and re-embedding, \" +\n \"which may change how it influences opportunity discovery. \" +\n \"Use when the user corrects or refines something they previously stated about themselves, \" +\n \"or when validity dates need adjustment.\\n\\n\" +\n \"**When to use:** When the user says 'actually, I meant...', 'update my premise about...', \" +\n \"or provides a corrected version of a previously stated fact. \" +\n \"Requires the premise ID — call read_premises first if you don't have it.\",\n querySchema: z.object({\n premiseId: z.string().describe(\"UUID of the premise to update. Get from read_premises.\"),\n text: z.string().trim().min(1).optional().describe(\"New assertion text. Triggers re-analysis and re-embedding when provided.\"),\n validFrom: z.string().datetime().optional().describe(\"New ISO 8601 valid-from date-time.\"),\n validUntil: z.string().datetime().optional().describe(\"New ISO 8601 valid-until date-time.\"),\n volatile: z.boolean().optional().describe(\"Update the volatile flag.\"),\n }),\n handler: async ({ context, query }) => {\n if (!UUID_REGEX.test(query.premiseId)) {\n return error(\"Invalid premiseId format.\");\n }\n\n const existing = await database.getPremise(query.premiseId);\n if (!existing) {\n return error(\"Premise not found.\");\n }\n if (existing.userId !== context.userId) {\n return error(\"You can only update your own premises.\");\n }\n if (existing.status === \"RETRACTED\") {\n return error(\"Cannot update a retracted premise. Retracted premises are immutable.\");\n }\n\n logger.verbose(`[updatePremise] Updating premise ${query.premiseId} for user ${context.userId}`);\n\n // When text is unchanged, skip the graph (avoids unnecessary LLM\n // re-analysis and non-deterministic re-embedding). Only route through\n // the graph when the assertion text actually changes.\n if (query.text === undefined) {\n const hasValidityChange =\n query.validFrom !== undefined ||\n query.validUntil !== undefined ||\n query.volatile !== undefined;\n\n if (!hasValidityChange) {\n return error(\"No fields to update. Provide text, validFrom, validUntil, or volatile.\");\n }\n\n const mergedValidity: PremiseValidity = {\n ...existing.validity,\n ...(query.validFrom !== undefined && { validFrom: query.validFrom }),\n ...(query.validUntil !== undefined && { validUntil: query.validUntil }),\n ...(query.volatile !== undefined && { volatile: query.volatile }),\n };\n\n const updated = await database.updatePremise(query.premiseId, { validity: mergedValidity });\n\n const metadataResult = success({\n id: updated.id,\n assertion: updated.assertion.text,\n tier: updated.assertion.tier,\n status: updated.status,\n message: \"Premise updated successfully (metadata only, no re-analysis).\",\n });\n try { deps.premiseEvents?.onUpdated?.(query.premiseId, context.userId); }\n catch (e) { logger.error('[updatePremise] premiseEvents.onUpdated failed', { error: e }); }\n return metadataResult;\n }\n\n // Text change requires the graph for re-analysis and re-embedding\n if (!premiseGraph) {\n return error(\"Premise graph not available.\");\n }\n\n const result = await invokeWithAbortSignal(premiseGraph, {\n userId: context.userId,\n assertionText: query.text,\n tier: existing.assertion.tier,\n validFrom: query.validFrom ?? existing.validity.validFrom ?? undefined,\n validUntil: query.validUntil ?? existing.validity.validUntil ?? undefined,\n volatile: query.volatile ?? existing.validity.volatile,\n operationMode: \"update\",\n targetPremiseId: query.premiseId,\n });\n\n if (result.error) {\n return error(result.error);\n }\n\n if (!result.premise) {\n return error(\"Premise update failed — no updated premise returned.\");\n }\n\n const updated = result.premise;\n\n const updateResult = success({\n id: updated.id,\n assertion: updated.assertion.text,\n tier: updated.assertion.tier,\n status: updated.status,\n message: \"Premise updated successfully.\",\n });\n try { deps.premiseEvents?.onUpdated?.(query.premiseId, context.userId); }\n catch (e) { logger.error('[updatePremise] premiseEvents.onUpdated failed', { error: e }); }\n return updateResult;\n },\n });\n\n const retractPremise = defineTool({\n name: \"retract_premise\",\n description:\n \"Retracts a premise — a soft delete that preserves the history of what was asserted. \" +\n \"Retracted premises are no longer active but remain in the audit trail. \" +\n \"Use when the user explicitly wants to remove something they previously stated about themselves, \" +\n \"or when a contextual premise is no longer true.\\n\\n\" +\n \"**When to use:** When the user says 'remove my premise about...', 'I no longer...', \" +\n \"or 'that's not true anymore'. Do not retract premises proactively — only on explicit user instruction.\",\n querySchema: z.object({\n premiseId: z.string().describe(\"UUID of the premise to retract. Get from read_premises.\"),\n }),\n handler: async ({ context, query }) => {\n if (!UUID_REGEX.test(query.premiseId)) {\n return error(\"Invalid premiseId format.\");\n }\n\n const existing = await database.getPremise(query.premiseId);\n if (!existing) {\n return error(\"Premise not found.\");\n }\n if (existing.userId !== context.userId) {\n return error(\"You can only retract your own premises.\");\n }\n if (existing.status === \"RETRACTED\") {\n return error(\"Premise is already retracted.\");\n }\n\n logger.verbose(`[retractPremise] Retracting premise ${query.premiseId} for user ${context.userId}`);\n\n await database.updatePremise(query.premiseId, {\n status: \"RETRACTED\",\n retractedAt: new Date(),\n });\n\n const retractResult = success({\n id: query.premiseId,\n message: \"Premise retracted successfully.\",\n });\n try { deps.premiseEvents?.onRetracted?.(query.premiseId, context.userId); }\n catch (e) { logger.error('[retractPremise] premiseEvents.onRetracted failed', { error: e }); }\n return retractResult;\n },\n });\n\n return [createPremise, readPremises, updatePremise, retractPremise];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"premise.tools.js","sourceRoot":"/","sources":["premise/premise.tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAC7E,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAE5E,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAExE,MAAM,MAAM,GAAG,cAAc,CAAC,mBAAmB,CAAC,CAAC;AAEnD,MAAM,UAAU,kBAAkB,CAAC,UAAsB,EAA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DefineTool, ToolDeps } from \"../shared/agent/tool.helpers.js\";\nimport { success, error, UUID_REGEX } from \"../shared/agent/tool.helpers.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport type { PremiseRecord, PremiseValidity } from \"../shared/interfaces/database.interface.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\n\nconst logger = protocolLogger(\"ChatTools:Premise\");\n\nexport function createPremiseTools(defineTool: DefineTool, deps: ToolDeps) {\n const database = deps.database;\n const premiseGraph = deps.graphs.premise;\n\n // ─────────────────────────────────────────────────────────────────────────────\n // PREMISE CRUD\n // ─────────────────────────────────────────────────────────────────────────────\n\n const createPremise = defineTool({\n name: \"create_premise\",\n description:\n \"Creates a premise — a self-descriptive proposition the user asserts about themselves. \" +\n \"Premises are the foundational facts that shape how the system understands who you are \" +\n \"and what contexts you inhabit.\\n\\n\" +\n \"**Tiers:**\\n\" +\n \"- `assertive` (default): stable identity facts (e.g. 'I am a software engineer', 'I live in Berlin'). \" +\n \"Use for things that are durably true and not time-bound.\\n\" +\n \"- `contextual`: temporal or situational facts (e.g. 'I am attending DevCon this week', \" +\n \"'I am fundraising for my Series A right now'). Use when the user shares something time-bound \" +\n \"or context-specific. These default to `volatile: true`.\\n\\n\" +\n \"**When to use:** Call this whenever the user shares a fact about themselves in first person \" +\n \"('I am', 'I work at', 'I just joined', 'I am currently'). Do not infer premises from vague \" +\n \"statements — only create them when the user is clearly asserting something about themselves.\",\n querySchema: z.object({\n text: z.string().trim().min(1).describe(\"The premise text — a self-descriptive proposition in first person, e.g. 'I am a machine learning researcher at MIT'.\"),\n tier: z.enum([\"assertive\", \"contextual\"]).default(\"assertive\").describe(\"Tier of the premise. 'assertive' = stable identity fact. 'contextual' = temporal/situational. Defaults to 'assertive'.\"),\n validFrom: z.string().datetime().optional().describe(\"ISO 8601 date-time string for when this premise becomes valid. Omit for immediate.\"),\n validUntil: z.string().datetime().optional().describe(\"ISO 8601 date-time string for when this premise expires. Recommended for contextual premises with a known end date; omit if open-ended.\"),\n volatile: z.boolean().optional().describe(\"Whether this premise should be automatically retracted when it expires. Defaults to true for contextual tier, false for assertive.\"),\n }),\n handler: async ({ context, query }) => {\n if (!premiseGraph) {\n return error(\"Premise graph not available.\");\n }\n\n const effectiveVolatile = query.volatile ?? (query.tier === \"contextual\" ? true : false);\n\n logger.verbose(`[createPremise] Creating premise for user ${context.userId}: \"${query.text.substring(0, 60)}...\"`);\n\n const result = await invokeWithAbortSignal(premiseGraph, {\n userId: context.userId,\n assertionText: query.text,\n tier: query.tier,\n validFrom: query.validFrom,\n validUntil: query.validUntil,\n volatile: effectiveVolatile,\n operationMode: \"create\",\n });\n\n if (result.error) {\n return error(result.error);\n }\n\n if (!result.premise) {\n return error(\"Premise creation failed — no premise returned.\");\n }\n\n const premise = result.premise;\n const indexesAssigned = result.networkAssignments?.length ?? 0;\n const analysisSummary = premise.analysis\n ? `speechActType: ${premise.analysis.speechActType}, clarity: ${premise.analysis.felicityClarity?.toFixed(2) ?? \"n/a\"}`\n : \"no analysis\";\n\n const createResult = success({\n id: premise.id,\n assertion: premise.assertion.text,\n tier: premise.assertion.tier,\n analysisSummary,\n indexesAssigned,\n message: `Premise created and assigned to ${indexesAssigned} index${indexesAssigned === 1 ? \"\" : \"es\"}.`,\n });\n try { deps.premiseEvents?.onCreated?.(premise.id, context.userId); }\n catch (e) { logger.error('[createPremise] premiseEvents.onCreated failed', { error: e }); }\n return createResult;\n },\n });\n\n const readPremises = defineTool({\n name: \"read_premises\",\n description:\n \"Retrieves premises — the self-descriptive propositions a user has asserted about themselves. \" +\n \"Premises represent stable identity facts (assertive) and temporal context (contextual).\\n\\n\" +\n \"**Usage modes:**\\n\" +\n \"- No parameters: returns the caller's own active premises.\\n\" +\n \"- With `userId`: returns that user's premises (use when reviewing another member's context).\\n\" +\n \"- With `includeRetracted: true`: returns all premises regardless of status (active, retracted, expired) for history review.\\n\\n\" +\n \"**When to use:** Call before creating a premise to check if it already exists. \" +\n \"Call when the user asks what they have shared about themselves, or to review their current context. \" +\n \"Each premise includes: id, text, tier, status, analysis summary, and validity range.\",\n querySchema: z.object({\n userId: z.string().optional().describe(\"User ID to fetch premises for. Omit to fetch the current user's own premises.\"),\n includeRetracted: z.boolean().default(false).describe(\"When true, returns all premises regardless of status (active, retracted, expired). Defaults to false (active only).\"),\n }),\n handler: async ({ context, query }) => {\n const targetUserId = query.userId?.trim() || context.userId;\n\n if (query.userId?.trim() && !UUID_REGEX.test(query.userId.trim())) {\n return error(\"Invalid userId format.\");\n }\n\n logger.verbose(`[readPremises] Fetching premises for user ${targetUserId}`);\n\n // Query DB directly (bypassing graph) to support status filtering.\n // The graph's query node hardcodes ACTIVE status, so includeRetracted\n // would be dead code if we routed through it.\n const statusFilter = query.includeRetracted ? undefined : \"ACTIVE\" as const;\n const premises = await database.getPremisesForUser(targetUserId, statusFilter);\n\n const mapped = premises.map((p: PremiseRecord) => ({\n id: p.id,\n text: p.assertion.text,\n tier: p.assertion.tier,\n status: p.status,\n analysisSummary: p.analysis\n ? `speechActType: ${p.analysis.speechActType ?? \"n/a\"}, clarity: ${p.analysis.felicityClarity?.toFixed(2) ?? \"n/a\"}`\n : \"no analysis\",\n validFrom: p.validity.validFrom ?? null,\n validUntil: p.validity.validUntil ?? null,\n volatile: p.validity.volatile ?? false,\n }));\n\n return success({\n premises: mapped,\n count: mapped.length,\n });\n },\n });\n\n const updatePremise = defineTool({\n name: \"update_premise\",\n description:\n \"Modifies an existing premise. Updating the text triggers re-analysis and re-embedding, \" +\n \"which may change how it influences opportunity discovery. \" +\n \"Use when the user corrects or refines something they previously stated about themselves, \" +\n \"or when validity dates need adjustment.\\n\\n\" +\n \"**When to use:** When the user says 'actually, I meant...', 'update my premise about...', \" +\n \"or provides a corrected version of a previously stated fact. \" +\n \"Requires the premise ID — call read_premises first if you don't have it.\",\n querySchema: z.object({\n premiseId: z.string().describe(\"UUID of the premise to update. Get from read_premises.\"),\n text: z.string().trim().min(1).optional().describe(\"New assertion text. Triggers re-analysis and re-embedding when provided.\"),\n validFrom: z.string().datetime().optional().describe(\"New ISO 8601 valid-from date-time.\"),\n validUntil: z.string().datetime().optional().describe(\"New ISO 8601 valid-until date-time.\"),\n volatile: z.boolean().optional().describe(\"Update the volatile flag.\"),\n }),\n handler: async ({ context, query }) => {\n if (!UUID_REGEX.test(query.premiseId)) {\n return error(\"Invalid premiseId format.\");\n }\n\n const existing = await database.getPremise(query.premiseId);\n if (!existing) {\n return error(\"Premise not found.\");\n }\n if (existing.userId !== context.userId) {\n return error(\"You can only update your own premises.\");\n }\n if (existing.status === \"RETRACTED\") {\n return error(\"Cannot update a retracted premise. Retracted premises are immutable.\");\n }\n\n logger.verbose(`[updatePremise] Updating premise ${query.premiseId} for user ${context.userId}`);\n\n // When text is unchanged, skip the graph (avoids unnecessary LLM\n // re-analysis and non-deterministic re-embedding). Only route through\n // the graph when the assertion text actually changes.\n if (query.text === undefined) {\n const hasValidityChange =\n query.validFrom !== undefined ||\n query.validUntil !== undefined ||\n query.volatile !== undefined;\n\n if (!hasValidityChange) {\n return error(\"No fields to update. Provide text, validFrom, validUntil, or volatile.\");\n }\n\n const mergedValidity: PremiseValidity = {\n ...existing.validity,\n ...(query.validFrom !== undefined && { validFrom: query.validFrom }),\n ...(query.validUntil !== undefined && { validUntil: query.validUntil }),\n ...(query.volatile !== undefined && { volatile: query.volatile }),\n };\n\n const updated = await database.updatePremise(query.premiseId, { validity: mergedValidity });\n\n const metadataResult = success({\n id: updated.id,\n assertion: updated.assertion.text,\n tier: updated.assertion.tier,\n status: updated.status,\n message: \"Premise updated successfully (metadata only, no re-analysis).\",\n });\n try { deps.premiseEvents?.onUpdated?.(query.premiseId, context.userId); }\n catch (e) { logger.error('[updatePremise] premiseEvents.onUpdated failed', { error: e }); }\n return metadataResult;\n }\n\n // Text change requires the graph for re-analysis and re-embedding\n if (!premiseGraph) {\n return error(\"Premise graph not available.\");\n }\n\n const result = await invokeWithAbortSignal(premiseGraph, {\n userId: context.userId,\n assertionText: query.text,\n tier: existing.assertion.tier,\n validFrom: query.validFrom ?? existing.validity.validFrom ?? undefined,\n validUntil: query.validUntil ?? existing.validity.validUntil ?? undefined,\n volatile: query.volatile ?? existing.validity.volatile,\n operationMode: \"update\",\n targetPremiseId: query.premiseId,\n });\n\n if (result.error) {\n return error(result.error);\n }\n\n if (!result.premise) {\n return error(\"Premise update failed — no updated premise returned.\");\n }\n\n const updated = result.premise;\n\n const updateResult = success({\n id: updated.id,\n assertion: updated.assertion.text,\n tier: updated.assertion.tier,\n status: updated.status,\n message: \"Premise updated successfully.\",\n });\n try { deps.premiseEvents?.onUpdated?.(query.premiseId, context.userId); }\n catch (e) { logger.error('[updatePremise] premiseEvents.onUpdated failed', { error: e }); }\n return updateResult;\n },\n });\n\n const retractPremise = defineTool({\n name: \"retract_premise\",\n description:\n \"Retracts a premise — a soft delete that preserves the history of what was asserted. \" +\n \"Retracted premises are no longer active but remain in the audit trail. \" +\n \"Use when the user explicitly wants to remove something they previously stated about themselves, \" +\n \"or when a contextual premise is no longer true.\\n\\n\" +\n \"**When to use:** When the user says 'remove my premise about...', 'I no longer...', \" +\n \"or 'that's not true anymore'. Do not retract premises proactively — only on explicit user instruction.\",\n querySchema: z.object({\n premiseId: z.string().describe(\"UUID of the premise to retract. Get from read_premises.\"),\n }),\n handler: async ({ context, query }) => {\n if (!UUID_REGEX.test(query.premiseId)) {\n return error(\"Invalid premiseId format.\");\n }\n\n const existing = await database.getPremise(query.premiseId);\n if (!existing) {\n return error(\"Premise not found.\");\n }\n if (existing.userId !== context.userId) {\n return error(\"You can only retract your own premises.\");\n }\n if (existing.status === \"RETRACTED\") {\n return error(\"Premise is already retracted.\");\n }\n\n logger.verbose(`[retractPremise] Retracting premise ${query.premiseId} for user ${context.userId}`);\n\n await database.updatePremise(query.premiseId, {\n status: \"RETRACTED\",\n retractedAt: new Date(),\n });\n\n const retractResult = success({\n id: query.premiseId,\n message: \"Premise retracted successfully.\",\n });\n try { deps.premiseEvents?.onRetracted?.(query.premiseId, context.userId); }\n catch (e) { logger.error('[retractPremise] premiseEvents.onRetracted failed', { error: e }); }\n return retractResult;\n },\n });\n\n return [createPremise, readPremises, updatePremise, retractPremise];\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool.factory.js","sourceRoot":"/","sources":["shared/agent/tool.factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAG7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AACjF,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,6BAA6B,EAAE,MAAM,8CAA8C,CAAC;AAC7F,OAAO,EAAE,yBAAyB,EAAE,MAAM,wCAAwC,CAAC;AACnF,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAC/D,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AACjF,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,cAAc,EAAE,MAAM,qCAAqC,CAAC;AAIrE,OAAO,EAIL,kBAAkB,GACnB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,KAAK,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAChF,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACpE,OAAO,E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GAAG,YAAY;QACf,GAAG,gBAAgB;QACnB,GAAG,YAAY;QACf,GAAG,UAAU;QACb,GAAG,gBAAgB;QACnB,GAAG,YAAY;KAChB,CAAC;AACJ,CAAC","sourcesContent":["import { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport type { HydeGraphDatabase, PremiseGraphDatabase } from \"../interfaces/database.interface.js\";\nimport { IntentGraphFactory } from \"../../intent/intent.graph.js\";\nimport { ProfileGraphFactory } from \"../../profile/profile.graph.js\";\nimport { OpportunityGraphFactory } from \"../../opportunity/opportunity.graph.js\";\nimport { HydeGraphFactory } from \"../hyde/hyde.graph.js\";\nimport { HydeGenerator } from \"../hyde/hyde.generator.js\";\nimport { LensInferrer } from \"../hyde/lens.inferrer.js\";\nimport { NetworkGraphFactory } from \"../../network/network.graph.js\";\nimport { NetworkMembershipGraphFactory } from \"../../network/membership/membership.graph.js\";\nimport { IntentNetworkGraphFactory } from \"../../network/indexer/indexer.graph.js\";\nimport { IntentIndexer } from \"../../intent/intent.indexer.js\";\nimport { NegotiationGraphFactory } from \"../../negotiation/negotiation.graph.js\";\nimport { PremiseGraphFactory } from \"../../premise/premise.graph.js\";\nimport { protocolLogger } from \"../observability/protocol.logger.js\";\n\nimport type { QuestionerEnqueueFn } from \"../../questioner/questioner.types.js\";\n\nimport {\n type ToolContext,\n type ResolvedToolContext,\n type ToolDeps,\n resolveChatContext,\n} from \"./tool.helpers.js\";\nimport { error, redactSensitiveFields } from \"./tool.helpers.js\";\nimport { invokeToolRuntime, toolRuntimeErrorToResult } from \"./tool.runtime.js\";\nimport { createProfileTools } from \"../../profile/profile.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 { createPremiseTools } from \"../../premise/premise.tools.js\";\n\n// Re-export types for consumers\nexport type { ToolContext, ResolvedToolContext, ProtocolDeps } from \"./tool.helpers.js\";\nexport type { ToolDeps } from \"./tool.helpers.js\";\n\nconst logger = protocolLogger(\"ChatTools\");\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TOOL FACTORY\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Creates all chat tools bound to a specific user context.\n * Resolves user/index identity from DB at init time.\n * Tools are created fresh for each user session to ensure proper isolation.\n *\n * All external dependencies (cache, integration, queue, etc.) are provided\n * via the `deps` parameter — the protocol lib never imports concrete adapters.\n */\nexport async function createChatTools(\n deps: ToolContext,\n preResolvedContext?: ResolvedToolContext\n) {\n const { database, embedder, scraper } = deps;\n\n // ─── Resolve context from DB ───────────────────────────────────────────────\n const resolvedContext =\n preResolvedContext ??\n (await resolveChatContext({\n database,\n userId: deps.userId,\n networkId: deps.networkId,\n sessionId: deps.sessionId,\n }));\n\n // Allow callers (e.g. MCP server, tests) to override the computed indexScope\n // without going through a full re-resolve. The MCP path sets this via\n // applyNetworkScopeToContext; ToolContext.indexScope provides the same override\n // when no preResolvedContext is given.\n if (!preResolvedContext && deps.indexScope !== undefined) {\n resolvedContext.indexScope = deps.indexScope;\n }\n\n // ─── Tool wrapper ──────────────────────────────────────────────────────────\n /**\n * Standardized tool factory. Auto-injects resolved context and\n * provides uniform logging / error handling for every tool.\n */\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 return tool(\n async (query: z.infer<T>) => {\n logger.info(`Tool: ${opts.name}`, {\n context: { userId: resolvedContext.userId, networkId: resolvedContext.networkId },\n query: redactSensitiveFields(query),\n });\n try {\n return await invokeToolRuntime({\n toolName: opts.name,\n tool: { handler: async ({ context, query }) => opts.handler({ context, query: query as z.infer<T> }) },\n context: resolvedContext,\n query,\n });\n } catch (err) {\n logger.error(`${opts.name} failed`, {\n error: err instanceof Error ? err.message : String(err),\n });\n const runtimeResult = toolRuntimeErrorToResult(err);\n if (runtimeResult) return runtimeResult;\n const reason = err instanceof Error ? err.message : String(err);\n return error(`Failed to execute ${opts.name}: ${reason}`);\n }\n },\n { name: opts.name, description: opts.description, schema: opts.querySchema }\n );\n }\n\n // ─── Compile subgraphs ─────────────────────────────────────────────────────\n\n // Wrap questionerEnqueue to include session context when available\n const sessionAwareEnqueue: QuestionerEnqueueFn | undefined = deps.questionerEnqueue\n ? (input) => deps.questionerEnqueue!({\n ...input,\n ...(resolvedContext.sessionId && !input.conversationId ? { conversationId: resolvedContext.sessionId } : {}),\n })\n : undefined;\n\n const intentGraph = new IntentGraphFactory(database, embedder, deps.intentQueue, sessionAwareEnqueue).createGraph();\n const premiseGraph = new PremiseGraphFactory(database as unknown as PremiseGraphDatabase, embedder).createGraph();\n const profileGraph = new ProfileGraphFactory(database, scraper, deps.enricher, sessionAwareEnqueue, premiseGraph).createGraph();\n const hydeCache = deps.hydeCache;\n const lensInferrer = new LensInferrer();\n const hydeGenerator = new HydeGenerator();\n const compiledHydeGraph = new HydeGraphFactory(\n database as unknown as HydeGraphDatabase,\n embedder,\n hydeCache,\n lensInferrer,\n hydeGenerator\n ).createGraph();\n const negotiationGraph = deps.agentDispatcher\n ? new NegotiationGraphFactory(\n deps.negotiationDatabase,\n deps.agentDispatcher,\n deps.negotiationTimeoutQueue,\n sessionAwareEnqueue,\n ).createGraph()\n : undefined;\n const opportunityGraph = new OpportunityGraphFactory(\n database,\n embedder,\n compiledHydeGraph,\n undefined, // evaluator (default)\n undefined, // queueNotification\n negotiationGraph,\n deps.agentDispatcher,\n deps.queueNegotiateExisting,\n ).createGraph();\n const networkGraph = new NetworkGraphFactory(database).createGraph();\n const networkMembershipGraph = new NetworkMembershipGraphFactory(database).createGraph();\n const intentNetworkGraph = new IntentNetworkGraphFactory(database, new IntentIndexer()).createGraph();\n\n // ─── Create context-bound databases ────────────────────────────────────────\n // Use injected instances when provided (e.g. tests). Otherwise create from the same\n // database used for graphs so that scope checks (e.g. ensureScopedMembership, opportunity\n // update) use the same adapter as the rest of the tool pipeline.\n //\n // The systemDb's DB-level clamp uses `resolvedContext.indexScope` — the same\n // set tools see — so the JSDoc claim that indexScope is \"the same set used\n // to clamp the DB-level systemDb\" holds for both the MCP path (where the\n // MCP server already populated indexScope via applyNetworkScopeToContext)\n // and the web-chat path (where resolveChatContext clamps to [bound, personal]\n // when networkId is set).\n const userDb = deps.userDb ?? deps.createUserDatabase(database, resolvedContext.userId);\n const systemDb = deps.systemDb ?? deps.createSystemDatabase(database, resolvedContext.userId, resolvedContext.indexScope, embedder);\n\n // ─── Assemble dependencies ─────────────────────────────────────────────────\n const cache = deps.cache;\n const integration = deps.integration;\n const toolDeps: ToolDeps = {\n database,\n userDb,\n systemDb,\n scraper,\n embedder,\n cache,\n integration,\n contactService: deps.contactService,\n integrationImporter: deps.integrationImporter,\n enricher: deps.enricher,\n negotiationDatabase: deps.negotiationDatabase,\n negotiationTimeoutQueue: deps.negotiationTimeoutQueue,\n agentDatabase: deps.agentDatabase,\n grantDefaultSystemPermissions: deps.grantDefaultSystemPermissions,\n agentDispatcher: deps.agentDispatcher,\n deliveryLedger: deps.deliveryLedger,\n discoveryRuns: deps.discoveryRuns,\n discoveryRunQueue: deps.discoveryRunQueue,\n profileRuns: deps.profileRuns,\n profileRunQueue: deps.profileRunQueue,\n mintConnectToken: deps.mintConnectToken,\n mintConnectLink: deps.mintConnectLink,\n frontendUrl: deps.frontendUrl,\n apiBaseUrl: deps.apiBaseUrl,\n ...(deps.premiseEvents && { premiseEvents: deps.premiseEvents }),\n ...(deps.chatSummary && { chatSummary: deps.chatSummary }),\n ...(deps.questionGenerator && { questionGenerator: deps.questionGenerator }),\n ...(sessionAwareEnqueue && { questionerEnqueue: sessionAwareEnqueue }),\n ...(deps.negotiationSummary && { negotiationSummary: deps.negotiationSummary }),\n graphs: {\n profile: profileGraph,\n intent: intentGraph,\n index: networkGraph,\n networkMembership: networkMembershipGraph,\n intentIndex: intentNetworkGraph,\n opportunity: opportunityGraph,\n premise: premiseGraph,\n },\n };\n\n // ─── Create domain tools ──────────────────────────────────────────────────\n const profileTools = createProfileTools(defineTool, toolDeps);\n const intentTools = createIntentTools(defineTool, toolDeps);\n const networkTools = createNetworkTools(defineTool, toolDeps);\n const opportunityTools = createOpportunityTools(defineTool, toolDeps);\n const utilityTools = createUtilityTools(defineTool, toolDeps);\n const contactTools = createContactTools(defineTool, toolDeps);\n const agentTools = createAgentTools(defineTool, toolDeps);\n const integrationTools = createIntegrationTools(defineTool, toolDeps);\n const negotiationTools = deps.agentDispatcher\n ? createNegotiationTools(defineTool, toolDeps)\n : [];\n const premiseTools = createPremiseTools(defineTool, toolDeps);\n\n // confirm_opportunity_delivery is an OpenClaw-delivery ledger write and must not be\n // callable from regular chat sessions.\n const chatOpportunityToolExclusions = new Set([\n \"confirm_opportunity_delivery\",\n ]);\n const opportunityToolsForChat = opportunityTools.filter(\n (t) => !chatOpportunityToolExclusions.has((t as { name: string }).name)\n );\n\n return [\n ...profileTools,\n ...intentTools,\n ...networkTools,\n ...opportunityToolsForChat,\n ...utilityTools,\n ...integrationTools,\n ...contactTools,\n ...agentTools,\n ...negotiationTools,\n ...premiseTools,\n ];\n}\n\n/**\n * Type for the tools array returned by createChatTools.\n */\nexport type ChatTools = Awaited<ReturnType<typeof createChatTools>>;\n"]}
|
|
1
|
+
{"version":3,"file":"tool.factory.js","sourceRoot":"/","sources":["shared/agent/tool.factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAG7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,uBAAuB,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AAC,UAAU,EAAE,QAAQ,CAAC,CAAC;IAC9D,MAAM,YAAY,GAAG,kBAAkB,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;IAC9D,MAAM,UAAU,GAAG,gBAAgB,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;IAC1D,MAAM,gBAAgB,GAAG,sBAAsB,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;IACtE,MAAM,gBAAgB,GAAG,IAAI,CAAC,eAAe;QAC3C,CAAC,CAAC,sBAAsB,CAAC,UAAU,EAAE,QAAQ,CAAC;QAC9C,CAAC,CAAC,EAAE,CAAC;IACP,MAAM,YAAY,GAAG,kBAAkB,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;IAE9D,oFAAoF;IACpF,uCAAuC;IACvC,MAAM,6BAA6B,GAAG,IAAI,GAAG,CAAC;QAC5C,8BAA8B;KAC/B,CAAC,CAAC;IACH,MAAM,uBAAuB,GAAG,gBAAgB,CAAC,MAAM,CACrD,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,6BAA6B,CAAC,GAAG,CAAE,CAAsB,CAAC,IAAI,CAAC,CACxE,CAAC;IAEF,OAAO;QACL,GAAG,YAAY;QACf,GAAG,WAAW;QACd,GAAG,YAAY;QACf,GAAG,uBAAuB;QAC1B,GAAG,YAAY;QACf,GAAG,gBAAgB;QACnB,GAAG,YAAY;QACf,GAAG,UAAU;QACb,GAAG,gBAAgB;QACnB,GAAG,YAAY;KAChB,CAAC;AACJ,CAAC","sourcesContent":["import { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport type { HydeGraphDatabase } from \"../interfaces/database.interface.js\";\nimport { IntentGraphFactory } from \"../../intent/intent.graph.js\";\nimport { ProfileGraphFactory } from \"../../profile/profile.graph.js\";\nimport { OpportunityGraphFactory } from \"../../opportunity/opportunity.graph.js\";\nimport { HydeGraphFactory } from \"../hyde/hyde.graph.js\";\nimport { HydeGenerator } from \"../hyde/hyde.generator.js\";\nimport { LensInferrer } from \"../hyde/lens.inferrer.js\";\nimport { NetworkGraphFactory } from \"../../network/network.graph.js\";\nimport { NetworkMembershipGraphFactory } from \"../../network/membership/membership.graph.js\";\nimport { IntentNetworkGraphFactory } from \"../../network/indexer/indexer.graph.js\";\nimport { IntentIndexer } from \"../../intent/intent.indexer.js\";\nimport { NegotiationGraphFactory } from \"../../negotiation/negotiation.graph.js\";\nimport { PremiseGraphFactory } from \"../../premise/premise.graph.js\";\nimport { protocolLogger } from \"../observability/protocol.logger.js\";\n\nimport type { QuestionerEnqueueFn } from \"../../questioner/questioner.types.js\";\n\nimport {\n type ToolContext,\n type ResolvedToolContext,\n type ToolDeps,\n resolveChatContext,\n} from \"./tool.helpers.js\";\nimport { error, redactSensitiveFields } from \"./tool.helpers.js\";\nimport { invokeToolRuntime, toolRuntimeErrorToResult } from \"./tool.runtime.js\";\nimport { createProfileTools } from \"../../profile/profile.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 { createPremiseTools } from \"../../premise/premise.tools.js\";\n\n// Re-export types for consumers\nexport type { ToolContext, ResolvedToolContext, ProtocolDeps } from \"./tool.helpers.js\";\nexport type { ToolDeps } from \"./tool.helpers.js\";\n\nconst logger = protocolLogger(\"ChatTools\");\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TOOL FACTORY\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Creates all chat tools bound to a specific user context.\n * Resolves user/index identity from DB at init time.\n * Tools are created fresh for each user session to ensure proper isolation.\n *\n * All external dependencies (cache, integration, queue, etc.) are provided\n * via the `deps` parameter — the protocol lib never imports concrete adapters.\n */\nexport async function createChatTools(\n deps: ToolContext,\n preResolvedContext?: ResolvedToolContext\n) {\n const { database, embedder, scraper } = deps;\n\n // ─── Resolve context from DB ───────────────────────────────────────────────\n const resolvedContext =\n preResolvedContext ??\n (await resolveChatContext({\n database,\n userId: deps.userId,\n networkId: deps.networkId,\n sessionId: deps.sessionId,\n }));\n\n // Allow callers (e.g. MCP server, tests) to override the computed indexScope\n // without going through a full re-resolve. The MCP path sets this via\n // applyNetworkScopeToContext; ToolContext.indexScope provides the same override\n // when no preResolvedContext is given.\n if (!preResolvedContext && deps.indexScope !== undefined) {\n resolvedContext.indexScope = deps.indexScope;\n }\n\n // ─── Tool wrapper ──────────────────────────────────────────────────────────\n /**\n * Standardized tool factory. Auto-injects resolved context and\n * provides uniform logging / error handling for every tool.\n */\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 return tool(\n async (query: z.infer<T>) => {\n logger.info(`Tool: ${opts.name}`, {\n context: { userId: resolvedContext.userId, networkId: resolvedContext.networkId },\n query: redactSensitiveFields(query),\n });\n try {\n return await invokeToolRuntime({\n toolName: opts.name,\n tool: { handler: async ({ context, query }) => opts.handler({ context, query: query as z.infer<T> }) },\n context: resolvedContext,\n query,\n });\n } catch (err) {\n logger.error(`${opts.name} failed`, {\n error: err instanceof Error ? err.message : String(err),\n });\n const runtimeResult = toolRuntimeErrorToResult(err);\n if (runtimeResult) return runtimeResult;\n const reason = err instanceof Error ? err.message : String(err);\n return error(`Failed to execute ${opts.name}: ${reason}`);\n }\n },\n { name: opts.name, description: opts.description, schema: opts.querySchema }\n );\n }\n\n // ─── Compile subgraphs ─────────────────────────────────────────────────────\n\n // Wrap questionerEnqueue to include session context when available\n const sessionAwareEnqueue: QuestionerEnqueueFn | undefined = deps.questionerEnqueue\n ? (input) => deps.questionerEnqueue!({\n ...input,\n ...(resolvedContext.sessionId && !input.conversationId ? { conversationId: resolvedContext.sessionId } : {}),\n })\n : undefined;\n\n const intentGraph = new IntentGraphFactory(database, embedder, deps.intentQueue, sessionAwareEnqueue).createGraph();\n const premiseGraph = new PremiseGraphFactory(database, embedder).createGraph();\n const profileGraph = new ProfileGraphFactory(database, scraper, deps.enricher, sessionAwareEnqueue, premiseGraph).createGraph();\n const hydeCache = deps.hydeCache;\n const lensInferrer = new LensInferrer();\n const hydeGenerator = new HydeGenerator();\n const compiledHydeGraph = new HydeGraphFactory(\n database as unknown as HydeGraphDatabase,\n embedder,\n hydeCache,\n lensInferrer,\n hydeGenerator\n ).createGraph();\n const negotiationGraph = deps.agentDispatcher\n ? new NegotiationGraphFactory(\n deps.negotiationDatabase,\n deps.agentDispatcher,\n deps.negotiationTimeoutQueue,\n sessionAwareEnqueue,\n ).createGraph()\n : undefined;\n const opportunityGraph = new OpportunityGraphFactory(\n database,\n embedder,\n compiledHydeGraph,\n undefined, // evaluator (default)\n undefined, // queueNotification\n negotiationGraph,\n deps.agentDispatcher,\n deps.queueNegotiateExisting,\n ).createGraph();\n const networkGraph = new NetworkGraphFactory(database).createGraph();\n const networkMembershipGraph = new NetworkMembershipGraphFactory(database).createGraph();\n const intentNetworkGraph = new IntentNetworkGraphFactory(database, new IntentIndexer()).createGraph();\n\n // ─── Create context-bound databases ────────────────────────────────────────\n // Use injected instances when provided (e.g. tests). Otherwise create from the same\n // database used for graphs so that scope checks (e.g. ensureScopedMembership, opportunity\n // update) use the same adapter as the rest of the tool pipeline.\n //\n // The systemDb's DB-level clamp uses `resolvedContext.indexScope` — the same\n // set tools see — so the JSDoc claim that indexScope is \"the same set used\n // to clamp the DB-level systemDb\" holds for both the MCP path (where the\n // MCP server already populated indexScope via applyNetworkScopeToContext)\n // and the web-chat path (where resolveChatContext clamps to [bound, personal]\n // when networkId is set).\n const userDb = deps.userDb ?? deps.createUserDatabase(database, resolvedContext.userId);\n const systemDb = deps.systemDb ?? deps.createSystemDatabase(database, resolvedContext.userId, resolvedContext.indexScope, embedder);\n\n // ─── Assemble dependencies ─────────────────────────────────────────────────\n const cache = deps.cache;\n const integration = deps.integration;\n const toolDeps: ToolDeps = {\n database,\n userDb,\n systemDb,\n scraper,\n embedder,\n cache,\n integration,\n contactService: deps.contactService,\n integrationImporter: deps.integrationImporter,\n enricher: deps.enricher,\n negotiationDatabase: deps.negotiationDatabase,\n negotiationTimeoutQueue: deps.negotiationTimeoutQueue,\n agentDatabase: deps.agentDatabase,\n grantDefaultSystemPermissions: deps.grantDefaultSystemPermissions,\n agentDispatcher: deps.agentDispatcher,\n deliveryLedger: deps.deliveryLedger,\n discoveryRuns: deps.discoveryRuns,\n discoveryRunQueue: deps.discoveryRunQueue,\n profileRuns: deps.profileRuns,\n profileRunQueue: deps.profileRunQueue,\n mintConnectToken: deps.mintConnectToken,\n mintConnectLink: deps.mintConnectLink,\n frontendUrl: deps.frontendUrl,\n apiBaseUrl: deps.apiBaseUrl,\n ...(deps.premiseEvents && { premiseEvents: deps.premiseEvents }),\n ...(deps.chatSummary && { chatSummary: deps.chatSummary }),\n ...(deps.questionGenerator && { questionGenerator: deps.questionGenerator }),\n ...(sessionAwareEnqueue && { questionerEnqueue: sessionAwareEnqueue }),\n ...(deps.negotiationSummary && { negotiationSummary: deps.negotiationSummary }),\n graphs: {\n profile: profileGraph,\n intent: intentGraph,\n index: networkGraph,\n networkMembership: networkMembershipGraph,\n intentIndex: intentNetworkGraph,\n opportunity: opportunityGraph,\n premise: premiseGraph,\n },\n };\n\n // ─── Create domain tools ──────────────────────────────────────────────────\n const profileTools = createProfileTools(defineTool, toolDeps);\n const intentTools = createIntentTools(defineTool, toolDeps);\n const networkTools = createNetworkTools(defineTool, toolDeps);\n const opportunityTools = createOpportunityTools(defineTool, toolDeps);\n const utilityTools = createUtilityTools(defineTool, toolDeps);\n const contactTools = createContactTools(defineTool, toolDeps);\n const agentTools = createAgentTools(defineTool, toolDeps);\n const integrationTools = createIntegrationTools(defineTool, toolDeps);\n const negotiationTools = deps.agentDispatcher\n ? createNegotiationTools(defineTool, toolDeps)\n : [];\n const premiseTools = createPremiseTools(defineTool, toolDeps);\n\n // confirm_opportunity_delivery is an OpenClaw-delivery ledger write and must not be\n // callable from regular chat sessions.\n const chatOpportunityToolExclusions = new Set([\n \"confirm_opportunity_delivery\",\n ]);\n const opportunityToolsForChat = opportunityTools.filter(\n (t) => !chatOpportunityToolExclusions.has((t as { name: string }).name)\n );\n\n return [\n ...profileTools,\n ...intentTools,\n ...networkTools,\n ...opportunityToolsForChat,\n ...utilityTools,\n ...integrationTools,\n ...contactTools,\n ...agentTools,\n ...negotiationTools,\n ...premiseTools,\n ];\n}\n\n/**\n * Type for the tools array returned by createChatTools.\n */\nexport type ChatTools = Awaited<ReturnType<typeof createChatTools>>;\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import type { ModelConfig } from "./model.config.js";
|
|
3
|
-
import type { ProfileDocument } from "
|
|
3
|
+
import type { ProfileDocument } from "../schemas/profile.schema.js";
|
|
4
4
|
import type { ChatGraphCompositeDatabase, NetworkMembership, UserRecord, UserDatabase, SystemDatabase, NegotiationGraphDatabase } from "../interfaces/database.interface.js";
|
|
5
5
|
import type { Scraper } from "../interfaces/scraper.interface.js";
|
|
6
6
|
import type { Cache, HydeCache } from "../interfaces/cache.interface.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool.helpers.d.ts","sourceRoot":"/","sources":["shared/agent/tool.helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAC;AAC1E,OAAO,KAAK,EACV,0BAA0B,EAC1B,iBAAiB,EACjB,UAAU,EACV,YAAY,EACZ,cAAc,EACd,wBAAwB,EACzB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