@indexnetwork/protocol 3.7.0-rc.276.1 → 3.7.1-rc.278.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/agent/agent.tools.js +1 -1
- package/dist/agent/agent.tools.js.map +1 -1
- package/dist/chat/chat.agent.d.ts +6 -6
- package/dist/chat/chat.agent.d.ts.map +1 -1
- package/dist/chat/chat.agent.js +9 -9
- package/dist/chat/chat.agent.js.map +1 -1
- package/dist/chat/chat.graph.d.ts.map +1 -1
- package/dist/chat/chat.graph.js +3 -12
- package/dist/chat/chat.graph.js.map +1 -1
- package/dist/chat/chat.interrupt.classifier.d.ts.map +1 -1
- package/dist/chat/chat.interrupt.classifier.js +1 -3
- package/dist/chat/chat.interrupt.classifier.js.map +1 -1
- package/dist/chat/chat.suggester.js.map +1 -1
- package/dist/contact/contact.tools.d.ts.map +1 -1
- package/dist/contact/contact.tools.js +17 -5
- package/dist/contact/contact.tools.js.map +1 -1
- package/dist/context/context.generator.d.ts +2 -0
- package/dist/context/context.generator.d.ts.map +1 -1
- package/dist/context/context.generator.js +8 -6
- package/dist/context/context.generator.js.map +1 -1
- package/dist/integration/integration.tools.d.ts.map +1 -1
- package/dist/integration/integration.tools.js +6 -0
- package/dist/integration/integration.tools.js.map +1 -1
- package/dist/intent/intent.clarifier.d.ts +2 -0
- package/dist/intent/intent.clarifier.d.ts.map +1 -1
- package/dist/intent/intent.clarifier.js +9 -23
- package/dist/intent/intent.clarifier.js.map +1 -1
- package/dist/intent/intent.graph.d.ts.map +1 -1
- package/dist/intent/intent.graph.js +29 -26
- package/dist/intent/intent.graph.js.map +1 -1
- package/dist/intent/intent.tools.d.ts.map +1 -1
- package/dist/intent/intent.tools.js +18 -48
- package/dist/intent/intent.tools.js.map +1 -1
- package/dist/maintenance/maintenance.graph.d.ts.map +1 -1
- package/dist/maintenance/maintenance.graph.js +1 -2
- package/dist/maintenance/maintenance.graph.js.map +1 -1
- package/dist/mcp/mcp.server.d.ts.map +1 -1
- package/dist/mcp/mcp.server.js +2 -4
- package/dist/mcp/mcp.server.js.map +1 -1
- package/dist/negotiation/negotiation.graph.d.ts.map +1 -1
- package/dist/negotiation/negotiation.graph.js +13 -20
- package/dist/negotiation/negotiation.graph.js.map +1 -1
- package/dist/negotiation/negotiation.tools.d.ts.map +1 -1
- package/dist/negotiation/negotiation.tools.js +12 -12
- package/dist/negotiation/negotiation.tools.js.map +1 -1
- package/dist/network/indexer/indexer.graph.d.ts +9 -9
- package/dist/network/indexer/indexer.graph.d.ts.map +1 -1
- package/dist/network/indexer/indexer.graph.js.map +1 -1
- package/dist/network/network.graph.d.ts.map +1 -1
- package/dist/network/network.graph.js +19 -25
- package/dist/network/network.graph.js.map +1 -1
- package/dist/opportunity/feed/feed.categorizer.d.ts.map +1 -1
- package/dist/opportunity/feed/feed.categorizer.js +15 -20
- package/dist/opportunity/feed/feed.categorizer.js.map +1 -1
- package/dist/opportunity/feed/feed.graph.d.ts.map +1 -1
- package/dist/opportunity/feed/feed.graph.js +8 -10
- package/dist/opportunity/feed/feed.graph.js.map +1 -1
- package/dist/opportunity/opportunity.introducer.d.ts.map +1 -1
- package/dist/opportunity/opportunity.introducer.js +1 -2
- package/dist/opportunity/opportunity.introducer.js.map +1 -1
- package/dist/opportunity/opportunity.tools.d.ts.map +1 -1
- package/dist/opportunity/opportunity.tools.js +3 -2
- package/dist/opportunity/opportunity.tools.js.map +1 -1
- package/dist/profile/profile.enricher.d.ts +5 -7
- package/dist/profile/profile.enricher.d.ts.map +1 -1
- package/dist/profile/profile.enricher.js +8 -10
- package/dist/profile/profile.enricher.js.map +1 -1
- package/dist/profile/profile.generator.d.ts.map +1 -1
- package/dist/profile/profile.generator.js +1 -2
- package/dist/profile/profile.generator.js.map +1 -1
- package/dist/profile/profile.tools.js +1 -1
- package/dist/profile/profile.tools.js.map +1 -1
- package/dist/questioner/questioner.presets.d.ts.map +1 -1
- package/dist/questioner/questioner.presets.js +24 -38
- package/dist/questioner/questioner.presets.js.map +1 -1
- package/dist/shared/agent/tool.factory.d.ts.map +1 -1
- package/dist/shared/agent/tool.factory.js +2 -2
- package/dist/shared/agent/tool.factory.js.map +1 -1
- package/dist/shared/agent/tool.helpers.d.ts +14 -0
- package/dist/shared/agent/tool.helpers.d.ts.map +1 -1
- package/dist/shared/agent/tool.helpers.js.map +1 -1
- package/dist/shared/agent/tool.runtime.d.ts.map +1 -1
- package/dist/shared/agent/tool.runtime.js +20 -13
- package/dist/shared/agent/tool.runtime.js.map +1 -1
- package/dist/shared/hyde/hyde.graph.d.ts.map +1 -1
- package/dist/shared/hyde/hyde.graph.js +3 -2
- package/dist/shared/hyde/hyde.graph.js.map +1 -1
- package/dist/shared/hyde/hyde.strategies.d.ts +2 -1
- package/dist/shared/hyde/hyde.strategies.d.ts.map +1 -1
- package/dist/shared/hyde/hyde.strategies.js.map +1 -1
- package/dist/shared/observability/trace.d.ts +3 -3
- package/dist/shared/observability/trace.d.ts.map +1 -1
- package/dist/shared/observability/trace.js +19 -33
- package/dist/shared/observability/trace.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat.agent.js","sourceRoot":"/","sources":["chat/chat.agent.ts"],"names":[],"mappings":";;;;;;;;;AACA,OAAO,EAAE,SAAS,EAAe,aAAa,EAAE,WAAW,EAAkB,MAAM,0BAA0B,CAAC;AAC9G,OAAO,EAAE,eAAe,EAA8C,MAAM,iCAAiC,CAAC;AAC9G,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AACrE,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AACvE,OAAO,EAAE,sBAAsB,EAAyB,MAAM,0BAA0B,CAAC;AACzF,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,WAAW,EAAoB,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAAE,qBAAqB,EAAE,M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oBACzC,wBAAwB,EAAE,EAAE,cAAc,EAAE,CAAC,GAAG,0BAA0B,CAAC,EAAE;iBAC9E,CAAC;gBACF,GAAG,CAAC,6BAA6B,IAAI,EAAE,kBAAkB,EAAE,6BAA6B,EAAE,CAAC;aAC5F;SACF,CAAC;IACJ,CAAC;;AAryBD,4EAA4E;AAEpD,gCAAsB,GAAG;IAC/C,6GAA6G;IAC7G,gGAAgG;IAChG,0GAA0G;IAC1G,oEAAoE;IACpE,iIAAiI;CAClI,CAAC;AAcF,6EAA6E;AACrD,yBAAe,GAAG,GAAG,CAAC;AAEtB,uBAAa,GAAG,GAAG,CAAC;AAxVtC;IADL,KAAK,EAAE;;;;6CAgGP;AA0XK;IADL,KAAK,EAAE;;;;oCAgDP;AAmBK;IADL,KAAK,EAAE;;sDAIG,WAAW;;0CAskBrB","sourcesContent":["import type { ChatOpenAI } from \"@langchain/openai\";\nimport { AIMessage, BaseMessage, SystemMessage, ToolMessage, AIMessageChunk } from \"@langchain/core/messages\";\nimport { createChatTools, type ToolContext, type ResolvedToolContext } from \"../shared/agent/tool.factory.js\";\nimport { resolveChatContext } from \"../shared/agent/tool.helpers.js\";\nimport { ITERATION_NUDGE, buildSystemContent } from \"./chat.prompt.js\";\nimport { extractRecentToolCalls, type IterationContext } from \"./chat.prompt.modules.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport { createModel, type ModelConfig } from \"../shared/agent/model.config.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\nimport { sanitizeForDebugMeta } from \"../shared/observability/debug-meta.sanitizer.js\";\nimport type { DebugMetaToolCall, DebugMetaLlm, DebugMetaOrchestratorNegotiations, DebugMetaDiscoveryQuestions } from \"./chat-streaming.types.js\";\nimport type { Question, QuestionStrategy } from \"../shared/schemas/question.schema.js\";\nimport type { Opportunity } from \"../shared/interfaces/database.interface.js\";\nimport { Timed } from \"../shared/observability/performance.js\";\nimport { requestContext } from \"../shared/observability/request-context.js\";\nimport { deduplicateQuestions } from \"./chat.question-dedup.js\";\n\nconst logger = protocolLogger(\"ChatAgent\");\n\n// Re-export for external consumers\nexport { ITERATION_NUDGE } from \"./chat.prompt.js\";\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TYPES\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Writer callback for streaming custom data out of the graph node.\n * Matches the `config.writer` signature from LangGraphRunnableConfig.\n */\nexport type StreamWriter = (data: unknown) => void;\n\n/**\n * Events emitted by `streamRun()` via the writer callback.\n *\n * - `iteration_start` — new agent loop iteration begins\n * - `llm_start` — LLM begins generating response\n * - `text_chunk` — a token (or group of tokens) of model text\n * - `llm_end` — LLM finished generating (may have tool calls)\n * - `tool_activity` — tool starts or finishes execution\n * - `graph_start` — a LangGraph sub-graph begins inside a tool\n * - `graph_end` — a LangGraph sub-graph completes\n * - `agent_start` — an LLM agent begins inside a graph node\n * - `agent_end` — an LLM agent completes\n * - `opportunity_draft_ready` — an orchestrator-triggered negotiation finalized\n * to `draft` and the card is ready to render inline\n */\nexport type AgentStreamEvent =\n | { type: \"iteration_start\"; iteration: number }\n | { type: \"llm_start\"; iteration: number }\n | { type: \"text_chunk\"; content: string }\n | { type: \"llm_end\"; iteration: number; hasToolCalls: boolean; toolNames?: string[] }\n | { type: \"tool_activity\"; phase: \"start\"; name: string }\n | {\n type: \"tool_activity\";\n phase: \"end\";\n name: string;\n success: boolean;\n summary?: string;\n steps?: Array<{ step: string; detail?: string; data?: Record<string, unknown> }>;\n }\n | { type: \"response_reset\"; reason: string }\n | { type: \"hallucination_detected\"; blockType: string; tool: string }\n | { type: \"graph_start\"; name: string }\n | { type: \"graph_end\"; name: string; durationMs: number }\n | { type: \"phase_start\"; name: string }\n | { type: \"phase_end\"; name: string; durationMs: number }\n | { type: \"agent_start\"; name: string }\n | { type: \"agent_end\"; name: string; durationMs: number; summary: string }\n | {\n // Emitted from the orchestrator branch of OpportunityGraph.negotiateNode\n // each time a per-candidate negotiation resolves to an accepted draft.\n // Carries the opportunity row plus the counterparty's display basics so\n // the frontend can append an inline card to the chat timeline without a\n // second round-trip user lookup.\n type: \"opportunity_draft_ready\";\n opportunityId: string;\n opportunity: Opportunity;\n /** Viewer-centric summary derived from interpretation.reasoning via viewerCentricCardSummary. */\n personalizedSummary?: string;\n counterparty: {\n userId: string;\n name?: string;\n };\n }\n | {\n type: \"negotiation_session_start\";\n opportunityId: string;\n negotiationConversationId: string;\n sourceUserId: string;\n candidateUserId: string;\n candidateName?: string;\n trigger: \"orchestrator\" | \"ambient\";\n startedAt: number;\n }\n | {\n type: \"negotiation_session_end\";\n opportunityId: string;\n negotiationConversationId: string;\n durationMs: number;\n }\n | {\n type: \"negotiation_turn\";\n opportunityId: string;\n negotiationConversationId: string;\n turnIndex: number;\n actor: \"source\" | \"candidate\";\n action: \"propose\" | \"accept\" | \"reject\" | \"counter\" | \"question\";\n reasoning?: string;\n message?: string;\n suggestedRoles?: { ownUser?: string; otherUser?: string };\n durationMs: number;\n }\n | {\n type: \"negotiation_outcome\";\n opportunityId: string;\n outcome:\n | \"accepted\"\n | \"rejected_stalled\"\n | \"waiting_for_agent\"\n | \"timed_out\"\n | \"turn_cap\";\n turnCount: number;\n reasoning?: string;\n agreedRoles?: { ownUser?: string; otherUser?: string };\n }\n | { type: \"decision_questions\"; questions: Question[] }\n | { type: \"chat_summarizer_start\"; payload: { sessionId: string } }\n | { type: \"chat_summarizer_end\"; payload: { durationMs: number } }\n | { type: \"question_generator_start\"; payload: { inputMode: \"transcripts\" | \"insights\"; negotiationCount: number; hasChatContext: boolean; truncated?: { originalCount: number; keptCount: number } } }\n | { type: \"question_generator_end\"; payload: { finalCount: number; strategies: QuestionStrategy[]; durationMs: number; inputMode: \"transcripts\" | \"insights\" } };\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// CONFIGURATION\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Soft limit: After this many iterations, inject a nudge message.\n */\nexport const SOFT_ITERATION_LIMIT = 8;\n\n/**\n * Hard limit: Force exit after this many iterations to prevent infinite loops.\n */\nexport const HARD_ITERATION_LIMIT = 12;\n\n/**\n * Extract plain text from message content (string or structured block array).\n * Filters to only `type: \"text\"` blocks, discarding tool metadata.\n */\nfunction extractTextContent(content: string | Array<Record<string, unknown>>): string {\n if (typeof content === \"string\") return content;\n if (Array.isArray(content)) {\n return content\n .filter((b): b is { type: \"text\"; text?: string } => (b as { type?: string }).type === \"text\")\n .map((b) => b.text ?? \"\")\n .join(\"\");\n }\n return \"\";\n}\n\n/**\n * Extract plain text from an AIMessageChunk (string content or text blocks).\n */\nfunction extractTextFromChunk(chunk: AIMessageChunk): string {\n return extractTextContent(chunk.content as string | Array<Record<string, unknown>>);\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// CHAT AGENT CLASS\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Result of a single agent iteration.\n */\nexport interface AgentIterationResult {\n /** Whether the agent wants to continue (made tool calls) or stop (produced final response) */\n shouldContinue: boolean;\n /** Tool calls made in this iteration (if any) */\n toolCalls?: Array<{\n id: string;\n name: string;\n args: Record<string, unknown>;\n }>;\n /** Tool results from executing the tool calls */\n toolResults?: Array<{\n toolCallId: string;\n name: string;\n result: string;\n }>;\n /** Final response text (if agent is done) */\n responseText?: string;\n /** Updated messages array */\n messages: BaseMessage[];\n}\n\n/**\n * ChatAgent: ReAct-style agent that uses tools to help users.\n *\n * The agent operates in a loop:\n * 1. Receive messages (conversation history + tool results)\n * 2. Decide: call tools OR respond to user\n * 3. If tools called: execute them, add results, loop back\n * 4. If response: return final text\n *\n * Use `ChatAgent.create(context)` to construct (async factory).\n */\nexport class ChatAgent {\n private model: ChatOpenAI;\n private tools: Awaited<ReturnType<typeof createChatTools>>;\n private toolsByName: Map<string, any>;\n\n /**\n * Private constructor — use `ChatAgent.create()` instead.\n */\n private constructor(\n private resolvedContext: ResolvedToolContext,\n tools: Awaited<ReturnType<typeof createChatTools>>,\n modelConfig?: ModelConfig,\n ) {\n this.model = createModel(\"chat\", modelConfig);\n\n // Store tools and index by name\n this.tools = tools;\n this.toolsByName = new Map();\n for (const tool of this.tools) {\n this.toolsByName.set(tool.name, tool);\n }\n\n // Bind tools to model\n this.model = this.model.bindTools(this.tools) as ChatOpenAI;\n }\n\n /**\n * Extracts the text content of the most recent HumanMessage.\n */\n private static getCurrentUserMessage(messages: BaseMessage[]): string | undefined {\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]._getType() === \"human\") {\n const content = messages[i].content;\n return typeof content === \"string\" ? content : undefined;\n }\n }\n return undefined;\n }\n\n /**\n * Async factory: creates a ChatAgent with resolved user/index context.\n * Resolves user/index identity from DB during tool initialization.\n */\n static async create(context: ToolContext): Promise<ChatAgent> {\n const resolved: ResolvedToolContext = await resolveChatContext({\n database: context.database,\n userId: context.userId,\n networkId: context.networkId,\n sessionId: context.sessionId,\n });\n const tools = await createChatTools(context, resolved);\n return new ChatAgent(resolved, tools, context.modelConfig);\n }\n\n /**\n * Run a single iteration of the agent loop.\n *\n * @param messages - Current conversation including any tool results\n * @param iterationCount - Current iteration number (for soft limit)\n * @returns Result indicating whether to continue and any tool calls/response\n */\n @Timed()\n async runIteration(\n messages: BaseMessage[],\n iterationCount: number,\n ): Promise<AgentIterationResult> {\n const iterCtx: IterationContext = {\n recentTools: extractRecentToolCalls(messages),\n currentMessage: ChatAgent.getCurrentUserMessage(messages),\n ctx: this.resolvedContext,\n };\n const systemContent = buildSystemContent(this.resolvedContext, iterCtx);\n\n const fullMessages: BaseMessage[] = [\n new SystemMessage(systemContent),\n ...messages,\n ];\n\n // Add nudge if past soft limit\n if (iterationCount >= SOFT_ITERATION_LIMIT) {\n fullMessages.push(new SystemMessage(ITERATION_NUDGE));\n }\n\n logger.verbose(\"Agent iteration\", {\n iteration: iterationCount,\n messageCount: messages.length,\n pastSoftLimit: iterationCount >= SOFT_ITERATION_LIMIT,\n });\n\n // Invoke model\n const response = await invokeWithAbortSignal(this.model, fullMessages);\n logger.debug(\"Chat model response\", {\n content:\n typeof response.content === \"string\"\n ? response.content\n : JSON.stringify(response.content),\n toolCalls: response.tool_calls?.length ?? 0,\n toolCallNames: response.tool_calls?.map((tc) => tc.name) ?? [],\n });\n\n // Check if model made tool calls\n const toolCalls = response.tool_calls || [];\n\n if (toolCalls.length > 0) {\n logger.verbose(\"Agent made tool calls\", {\n iteration: iterationCount,\n toolCount: toolCalls.length,\n tools: toolCalls.map((tc) => tc.name),\n });\n\n // Execute tools (can be parallelized if independent)\n const toolResults = await this.executeToolCalls(toolCalls);\n\n // Build updated messages\n const updatedMessages = [\n ...messages,\n response, // AIMessage with tool_calls\n ...toolResults.map(\n (tr) =>\n new ToolMessage({\n tool_call_id: tr.toolCallId,\n content: tr.result,\n name: tr.name,\n }),\n ),\n ];\n\n return {\n shouldContinue: true,\n toolCalls: toolCalls.map((tc) => ({\n id: tc.id!,\n name: tc.name,\n args: tc.args as Record<string, unknown>,\n })),\n toolResults,\n messages: updatedMessages,\n };\n }\n\n // No tool calls - agent is responding\n const responseText = extractTextContent(\n response.content as string | Array<Record<string, unknown>>,\n );\n logger.debug(\"Agent produced response (raw)\", {\n iteration: iterationCount,\n responseText,\n });\n logger.verbose(\"Agent produced response\", {\n iteration: iterationCount,\n responseLength: responseText.length,\n });\n\n return {\n shouldContinue: false,\n responseText,\n messages: [...messages, response],\n };\n }\n\n /**\n * Execute tool calls, potentially in parallel.\n */\n private async executeToolCalls(\n toolCalls: Array<{\n id?: string;\n name: string;\n args: Record<string, unknown>;\n }>,\n ): Promise<Array<{ toolCallId: string; name: string; result: string }>> {\n // Execute all tool calls in parallel\n const results = await Promise.all(\n toolCalls.map(async (tc) => {\n const tool = this.toolsByName.get(tc.name);\n\n if (!tool) {\n logger.error(\"Unknown tool\", { name: tc.name });\n return {\n toolCallId: tc.id || `unknown-${Date.now()}`,\n name: tc.name,\n result: JSON.stringify({\n success: false,\n error: `Unknown tool: ${tc.name}`,\n }),\n };\n }\n\n try {\n logger.verbose(\"Executing tool\", { name: tc.name, args: tc.args });\n let result = await tool.invoke(tc.args);\n let resultStr =\n typeof result === \"string\" ? result : JSON.stringify(result);\n\n if (tc.name === \"discover_opportunities\") {\n const newResult = await this.handleCreateIntentCallback(resultStr, tc.args);\n if (newResult !== null) {\n resultStr = newResult;\n result = newResult;\n }\n }\n\n logger.debug(\"Tool response\", { name: tc.name, result: resultStr });\n logger.verbose(\"Tool completed\", {\n name: tc.name,\n resultLength: resultStr.length,\n });\n\n return {\n toolCallId: tc.id || `${tc.name}-${Date.now()}`,\n name: tc.name,\n result: resultStr,\n };\n } catch (error) {\n logger.error(\"Tool execution failed\", {\n name: tc.name,\n error: error instanceof Error ? error.message : String(error),\n });\n\n return {\n toolCallId: tc.id || `${tc.name}-${Date.now()}`,\n name: tc.name,\n result: JSON.stringify({\n success: false,\n error: `Tool execution failed: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n }),\n };\n }\n }),\n );\n\n return results;\n }\n\n /**\n * When discover_opportunities returned createIntentSuggested, call create_intent then discover_opportunities.\n * Returns the new discover_opportunities result string or null if no callback / create_intent failed.\n */\n private async handleCreateIntentCallback(\n resultStr: string,\n originalArgs: Record<string, unknown>\n ): Promise<string | null> {\n let parsed: { success?: boolean; error?: string; data?: { createIntentSuggested?: boolean; suggestedIntentDescription?: string } };\n try {\n parsed = JSON.parse(resultStr) as typeof parsed;\n } catch {\n return null;\n }\n if (\n !parsed?.data?.createIntentSuggested ||\n typeof parsed.data.suggestedIntentDescription !== \"string\"\n ) {\n return null;\n }\n // Never auto-create intents during introducer flows — signals are personal\n if ((originalArgs as { introTargetUserId?: string }).introTargetUserId) {\n return null;\n }\n const createIntentTool = this.toolsByName.get(\"create_intent\");\n const discoverOpportunitiesTool = this.toolsByName.get(\"discover_opportunities\");\n if (!createIntentTool || !discoverOpportunitiesTool) return null;\n\n logger.verbose(\"Create-intent signal: auto-calling create_intent then discover_opportunities\");\n const createIntentResult = await createIntentTool.invoke({\n description: parsed.data.suggestedIntentDescription,\n networkId: (originalArgs as { networkId?: string }).networkId,\n });\n const createIntentStr =\n typeof createIntentResult === \"string\" ? createIntentResult : JSON.stringify(createIntentResult);\n let createIntentParsed: { success?: boolean; error?: string };\n try {\n createIntentParsed = JSON.parse(createIntentStr) as { success?: boolean; error?: string };\n } catch {\n createIntentParsed = {};\n }\n if (createIntentParsed.success === false) {\n logger.warn(\"Create-intent failed; not re-running discover_opportunities\", {\n error: createIntentParsed.error,\n });\n return null;\n }\n\n const newResult = await discoverOpportunitiesTool.invoke(originalArgs);\n return typeof newResult === \"string\" ? newResult : JSON.stringify(newResult);\n }\n\n /**\n * Detect hallucinated ```intent_proposal or ```opportunity blocks in model text\n * that were NOT generated by the corresponding tool call.\n *\n * A tool call that returned 0 cards (e.g. \"Found 0 match(es)\") counts as\n * NOT having produced valid blocks — the LLM must not fabricate them.\n *\n * @returns Block info if hallucination detected, null otherwise\n */\n /**\n * Check whether any tool call produced valid opportunity blocks.\n * Both `discover_opportunities` and `list_opportunities` can return\n * ```opportunity code blocks — either one counts as a valid source.\n */\n private static hasOpportunitySource(\n toolsUsed: Array<{ name: string; success: boolean; resultSummary?: string }>,\n ): boolean {\n return toolsUsed.some(\n (t) =>\n (t.name === \"discover_opportunities\" || t.name === \"list_opportunities\") &&\n t.success &&\n !t.resultSummary?.startsWith(\"Found 0\") &&\n !t.resultSummary?.startsWith(\"No matches\") &&\n !t.resultSummary?.startsWith(\"No opportunities\"),\n );\n }\n\n private detectHallucinatedBlock(\n text: string,\n toolsUsed: Array<{ name: string; success: boolean; resultSummary?: string }>,\n userMessage?: string,\n ): { type: string; tool: string; description: string } | null {\n const hasSuccessfulCreateIntent = toolsUsed.some(\n (t) => t.name === \"create_intent\" && t.success,\n );\n\n // Check for hallucinated intent_proposal\n if (text.includes(\"```intent_proposal\") && !hasSuccessfulCreateIntent) {\n const match = text.match(/```intent_proposal\\s*\\n\\s*\\{[^}]*\"description\"\\s*:\\s*\"([^\"]+)\"/);\n if (match) {\n return { type: \"intent_proposal\", tool: \"create_intent\", description: match[1] };\n }\n }\n\n // Check for hallucinated opportunity blocks\n if (text.includes(\"```opportunity\") && !ChatAgent.hasOpportunitySource(toolsUsed)) {\n // Use the user's original message as the search query — NOT fields from the\n // hallucinated JSON. The model fabricates person names and reasoning that have\n // nothing to do with the user's actual request, leading to wrong results and\n // the model re-calling the tool with the correct query (doubling negotiation cost).\n const description = userMessage?.trim() || \"find connections\";\n return { type: \"opportunity\", tool: \"discover_opportunities\", description };\n }\n\n return null;\n }\n\n /**\n * Strip ```opportunity and ```intent_proposal code blocks from text\n * when no corresponding successful tool call was made.\n * Defense-in-depth: catches hallucinated blocks that slip past detectHallucinatedBlock\n * (e.g. after a correction iteration that still hallucinates).\n *\n * @param text - The response text to sanitize\n * @param toolsUsed - Tool call records from the agent loop\n * @returns Sanitized text with unbacked blocks removed\n */\n private stripUnbackedBlocks(\n text: string,\n toolsUsed: Array<{ name: string; success: boolean; resultSummary?: string }>,\n ): string {\n let result = text;\n let removedBlock = false;\n\n const hasSuccessfulCreateIntent = toolsUsed.some(\n (t) => t.name === \"create_intent\" && t.success,\n );\n\n if (!ChatAgent.hasOpportunitySource(toolsUsed) && result.includes(\"```opportunity\")) {\n const next = result.replace(/```opportunity\\s*\\n[\\s\\S]*?```/g, \"\");\n removedBlock ||= next !== result;\n result = next;\n }\n if (!hasSuccessfulCreateIntent && result.includes(\"```intent_proposal\")) {\n const next = result.replace(/```intent_proposal\\s*\\n[\\s\\S]*?```/g, \"\");\n removedBlock ||= next !== result;\n result = next;\n }\n\n // Clean up leftover double blank lines only when a block was actually removed\n if (removedBlock) {\n result = result.replace(/\\n{3,}/g, \"\\n\\n\").trim();\n }\n\n return result;\n }\n\n // ─── Phantom write detection ─────────────────────────────────────────────\n\n private static readonly PHANTOM_WRITE_PATTERNS = [\n /\\bI(?:'ve| have) (?:updated|adjusted|changed|modified|edited|created|added|removed|deleted|saved|set up)\\b/i,\n /\\bI (?:updated|adjusted|changed|modified|edited|created|added|removed|deleted|saved|set up)\\b/i,\n /\\b(?:Updated|Adjusted|Changed|Modified|Edited|Created|Added|Removed|Deleted|Saved) (?:your|the|their)\\b/i,\n /\\bEverything is (?:now )?(?:updated|changed|adjusted|saved|set)\\b/i,\n /\\b(?:profile|bio|premise|signal|intent|membership|narrative) (?:has been|is now) (?:updated|changed|modified|adjusted|saved)\\b/i,\n ];\n\n /**\n * Detect when the model claims to have performed a write action\n * without having called any tools in the turn.\n */\n private static detectPhantomWrite(\n responseText: string,\n toolsUsed: Array<{ name: string }>,\n ): boolean {\n if (toolsUsed.length > 0) return false;\n return ChatAgent.PHANTOM_WRITE_PATTERNS.some(pattern => pattern.test(responseText));\n }\n\n // ─── Shared tool-result post-processing types ─────────────────────────────\n private static readonly STEP_DETAIL_MAX = 300;\n\n private static readonly STEP_NAME_MAX = 100;\n\n /**\n * Post-process a tool result: strip _graphTimings, extract summary/debugSteps,\n * and optionally run discover_opportunities → create_intent callback.\n *\n * Returns the normalized result string and extracted debug metadata so both\n * the normal streaming tool loop and the hallucination-recovery branch\n * produce identical LLM-facing payloads.\n */\n private async normalizeToolResult(\n toolName: string,\n resultStr: string,\n toolArgs: Record<string, unknown>,\n ): Promise<{\n resultStr: string;\n summary: string;\n debugSteps?: Array<{ step: string; detail?: string; data?: Record<string, unknown> }>;\n graphTimings?: Array<{ name: string; durationMs: number; agents: Array<{ name: string; durationMs: number }> }>;\n decisionQuestions?: Question[];\n discoveryQuestionsDebug?: DebugMetaDiscoveryQuestions;\n }> {\n let normalized = resultStr;\n\n // Run create_intent callback for discover_opportunities results\n if (toolName === \"discover_opportunities\") {\n const callbackResult = await this.handleCreateIntentCallback(normalized, toolArgs);\n if (callbackResult !== null) {\n normalized = callbackResult;\n }\n }\n\n type StepData = Record<string, unknown>;\n type DebugStep = { step: string; detail?: string; data?: StepData };\n type GraphTiming = { name: string; durationMs: number; agents: Array<{ name: string; durationMs: number }> };\n\n let summary = \"Done\";\n let debugSteps: DebugStep[] | undefined;\n let graphTimings: GraphTiming[] | undefined;\n let decisionQuestions: Question[] | undefined;\n let discoveryQuestionsDebug: DebugMetaDiscoveryQuestions | undefined;\n\n try {\n const parsed = JSON.parse(normalized) as {\n success?: boolean;\n data?: {\n summary?: string;\n debugSteps?: DebugStep[];\n _graphTimings?: GraphTiming[];\n };\n summary?: string;\n debugSteps?: DebugStep[];\n _graphTimings?: GraphTiming[];\n };\n const payload = parsed.success && parsed.data != null ? parsed.data : parsed;\n summary = payload.summary ?? parsed.summary ?? \"Done\";\n\n const rawSteps = payload.debugSteps ?? parsed.debugSteps;\n if (Array.isArray(rawSteps) && rawSteps.length > 0) {\n debugSteps = rawSteps.map((s) => ({\n step: String(s.step ?? \"\").slice(0, ChatAgent.STEP_NAME_MAX),\n detail:\n s.detail != null\n ? String(s.detail).slice(0, ChatAgent.STEP_DETAIL_MAX)\n : undefined,\n ...(s.data && typeof s.data === \"object\" ? { data: s.data } : {}),\n }));\n }\n\n const rawGraphTimings = payload._graphTimings ?? parsed._graphTimings;\n if (Array.isArray(rawGraphTimings) && rawGraphTimings.length > 0) {\n graphTimings = rawGraphTimings as GraphTiming[];\n // Strip _graphTimings from the result string sent back to the LLM\n try {\n const cleanedResult = JSON.parse(normalized) as Record<string, unknown>;\n delete cleanedResult._graphTimings;\n if (cleanedResult.data && typeof cleanedResult.data === \"object\") {\n delete (cleanedResult.data as Record<string, unknown>)._graphTimings;\n }\n normalized = JSON.stringify(cleanedResult);\n } catch { /* keep original if can't clean */ }\n }\n\n const rawQuestions = (payload as { questions?: unknown }).questions ?? (parsed as { questions?: unknown }).questions;\n const rawQuestionDebug = (payload as { _discoveryQuestionsDebug?: unknown })._discoveryQuestionsDebug\n ?? (parsed as { _discoveryQuestionsDebug?: unknown })._discoveryQuestionsDebug;\n if (Array.isArray(rawQuestions)) {\n decisionQuestions = rawQuestions as Question[];\n }\n if (rawQuestionDebug && typeof rawQuestionDebug === \"object\") {\n discoveryQuestionsDebug = rawQuestionDebug as DebugMetaDiscoveryQuestions;\n }\n // `_discoveryQuestionsDebug` is internal trace data — strip from the LLM-facing\n // tool result. `questions` is intentionally kept visible so the agent can\n // follow the prompt addendum and reference the decision prompts in its reply.\n if (discoveryQuestionsDebug !== undefined) {\n try {\n const cleaned = JSON.parse(normalized) as Record<string, unknown>;\n const stripFrom = (obj: Record<string, unknown>) => {\n delete obj._discoveryQuestionsDebug;\n };\n stripFrom(cleaned);\n if (cleaned.data && typeof cleaned.data === \"object\") {\n stripFrom(cleaned.data as Record<string, unknown>);\n }\n normalized = JSON.stringify(cleaned);\n } catch { /* keep original */ }\n }\n } catch {\n /* not JSON, keep default */\n }\n\n return {\n resultStr: normalized,\n summary,\n debugSteps,\n graphTimings,\n ...(decisionQuestions !== undefined ? { decisionQuestions } : {}),\n ...(discoveryQuestionsDebug !== undefined ? { discoveryQuestionsDebug } : {}),\n };\n }\n\n /**\n * Run the full agent loop until completion or hard limit.\n *\n * @param initialMessages - Starting conversation messages\n * @returns Final response text and full message history\n */\n @Timed()\n async run(initialMessages: BaseMessage[]): Promise<{\n responseText: string;\n messages: BaseMessage[];\n iterationCount: number;\n }> {\n let messages = initialMessages;\n let iterationCount = 0;\n\n while (iterationCount < HARD_ITERATION_LIMIT) {\n const result = await this.runIteration(messages, iterationCount);\n iterationCount++;\n messages = result.messages;\n\n if (!result.shouldContinue) {\n const responseText =\n result.responseText ||\n \"I apologize, but I couldn't generate a response.\";\n logger.debug(\"Agent final response\", { responseText });\n return {\n responseText,\n messages,\n iterationCount,\n };\n }\n }\n\n // Hit hard limit - force a response\n logger.warn(\"Hit hard iteration limit\", { iterationCount });\n\n const forceResponseMessages = [\n ...messages,\n new SystemMessage(\n \"You have reached the maximum number of tool calls. You MUST provide a final response now. Summarize what you've accomplished and what might still be needed.\",\n ),\n ];\n\n const forcedResponse = await invokeWithAbortSignal(this.model, forceResponseMessages);\n const responseText = extractTextContent(\n forcedResponse.content as string | Array<Record<string, unknown>>,\n );\n logger.debug(\"Agent forced response\", { responseText });\n\n return {\n responseText,\n messages: [...messages, forcedResponse],\n iterationCount,\n };\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // STREAMING RUN (for narration-style output)\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Run the full agent loop with streaming narration.\n *\n * Instead of returning a single blob at the end, this method calls\n * `writer()` for every text token and tool-activity event so the\n * consumer (graph node) can push them out via `config.writer`.\n *\n * @param initialMessages - Starting conversation messages\n * @param writer - Callback to emit streaming events (from `config.writer`)\n * @param signal - Optional AbortSignal to cancel the streaming LLM call and tool execution\n * @returns Final response metadata (same shape as `run()`)\n */\n @Timed()\n async streamRun(\n initialMessages: BaseMessage[],\n writer?: StreamWriter,\n signal?: AbortSignal,\n ): Promise<{\n responseText: string;\n messages: BaseMessage[];\n iterationCount: number;\n debugMeta: { graph: string; iterations: number; tools: DebugMetaToolCall[]; llm: DebugMetaLlm; orchestratorNegotiations?: DebugMetaOrchestratorNegotiations; discoveryQuestions?: DebugMetaDiscoveryQuestions };\n }> {\n const llm: DebugMetaLlm = { calls: 0, totalDurationMs: 0, resets: [], hallucinations: [] };\n const orchestratorNegotiationIds = new Set<string>();\n let lastLlmStart = 0;\n let latestDiscoveryQuestionsDebug: DebugMetaDiscoveryQuestions | undefined;\n\n const emit = (event: AgentStreamEvent) => {\n if (event.type === \"llm_start\") {\n llm.calls += 1;\n lastLlmStart = Date.now();\n } else if (event.type === \"llm_end\") {\n if (lastLlmStart > 0) {\n llm.totalDurationMs += Date.now() - lastLlmStart;\n lastLlmStart = 0;\n }\n } else if (event.type === \"response_reset\") {\n llm.resets.push({ reason: event.reason, at: Date.now() });\n } else if (event.type === \"hallucination_detected\") {\n llm.hallucinations.push({ blockType: event.blockType, tool: event.tool, at: Date.now() });\n } else if (event.type === \"negotiation_session_start\") {\n orchestratorNegotiationIds.add(event.opportunityId);\n }\n try {\n writer?.(event);\n } catch {\n /* swallow if writer is gone */\n }\n };\n\n let messages = initialMessages;\n let iterationCount = 0;\n const toolsDebug: DebugMetaToolCall[] = [];\n const surfacedQuestionIds = new Set<string>();\n const hallucinationAutoInvokeCounts = new Map<string, number>();\n\n while (iterationCount < HARD_ITERATION_LIMIT) {\n if (signal?.aborted) {\n logger.verbose(\"Stream aborted by client\", { iterationCount });\n break;\n }\n emit({ type: \"iteration_start\", iteration: iterationCount });\n\n const iterCtx: IterationContext = {\n recentTools: extractRecentToolCalls(messages),\n currentMessage: ChatAgent.getCurrentUserMessage(messages),\n ctx: this.resolvedContext,\n };\n const systemContent = buildSystemContent(this.resolvedContext, iterCtx);\n const fullMessages: BaseMessage[] = [\n new SystemMessage(systemContent),\n ...messages,\n ];\n if (iterationCount >= SOFT_ITERATION_LIMIT) {\n fullMessages.push(new SystemMessage(ITERATION_NUDGE));\n }\n\n logger.verbose(\"Streaming iteration\", {\n iteration: iterationCount,\n messageCount: messages.length,\n pastSoftLimit: iterationCount >= SOFT_ITERATION_LIMIT,\n });\n\n // ── Stream the model response token-by-token ──────────────────────\n emit({ type: \"llm_start\", iteration: iterationCount });\n\n let accumulated: AIMessageChunk | undefined;\n let iterationText = \"\";\n\n try {\n const stream = await this.model.stream(fullMessages, { signal });\n for await (const chunk of stream) {\n // Accumulate using AIMessageChunk.concat() so tool_call_chunks merge and tool_calls is populated\n accumulated = accumulated ? accumulated.concat(chunk) : chunk;\n\n // Emit text content tokens to the user immediately\n const textPart = extractTextFromChunk(chunk);\n if (textPart) {\n emit({ type: \"text_chunk\", content: textPart });\n iterationText += textPart;\n }\n }\n } catch (err) {\n if (err instanceof Error && err.name === \"AbortError\") {\n logger.verbose(\"LLM stream aborted by client\", { iterationCount });\n break; // breaks the outer while loop\n }\n throw err; // re-throw non-abort errors\n }\n\n if (!accumulated) {\n logger.warn(\"Empty model response in streaming iteration\", {\n iterationCount,\n });\n iterationCount++;\n continue;\n }\n\n // ── Check for tool calls ──────────────────────────────────────────\n const toolCalls = accumulated.tool_calls || [];\n\n emit({\n type: \"llm_end\",\n iteration: iterationCount,\n hasToolCalls: toolCalls.length > 0,\n toolNames: toolCalls.length > 0 ? toolCalls.map((tc) => tc.name) : undefined,\n });\n\n if (toolCalls.length > 0) {\n logger.verbose(\"Streaming: agent made tool calls\", {\n iteration: iterationCount,\n tools: toolCalls.map((tc) => tc.name),\n });\n\n // Clear any narration text streamed before tool calls — this text is\n // intermediate reasoning and should not appear in the final response.\n // The next iteration (after tool execution) will produce the real response.\n if (iterationText) {\n emit({ type: \"response_reset\", reason: \"Tool calls detected\" });\n }\n\n // Execute tools one-by-one.\n const toolResults: Array<{\n toolCallId: string;\n name: string;\n result: string;\n }> = [];\n for (const tc of toolCalls) {\n if (signal?.aborted) {\n logger.verbose(\"Stream aborted by client during tool execution\");\n break;\n }\n emit({ type: \"tool_activity\", phase: \"start\", name: tc.name });\n\n const tool = this.toolsByName.get(tc.name);\n if (!tool) {\n const errResult = JSON.stringify({\n success: false,\n error: `Unknown tool: ${tc.name}`,\n });\n toolsDebug.push({\n name: tc.name,\n args: sanitizeForDebugMeta(tc.args) as Record<string, unknown>,\n resultSummary: \"Unknown tool\",\n success: false,\n durationMs: 0,\n });\n emit({\n type: \"tool_activity\",\n phase: \"end\",\n name: tc.name,\n success: false,\n summary: \"Unknown tool\",\n });\n toolResults.push({\n toolCallId: tc.id || `unknown-${Date.now()}`,\n name: tc.name,\n result: errResult,\n });\n continue;\n }\n\n const toolStart = Date.now();\n try {\n logger.verbose(\"Streaming: executing tool\", { name: tc.name });\n const currentCtx = requestContext.getStore() ?? {};\n let result = await requestContext.run(\n {\n ...currentCtx,\n traceEmitter: (e) => emit(e as AgentStreamEvent),\n // Propagate the caller's AbortSignal into requestContext so\n // long-running graph nodes (orchestrator negotiation fan-out)\n // can suppress event emits after the chat session closes.\n ...(signal && { abortSignal: signal }),\n },\n () => tool.invoke(tc.args),\n );\n const toolDurationMs = Date.now() - toolStart;\n let resultStr =\n typeof result === \"string\" ? result : JSON.stringify(result);\n\n const normalized = await this.normalizeToolResult(tc.name, resultStr, tc.args);\n if (normalized.discoveryQuestionsDebug) latestDiscoveryQuestionsDebug = normalized.discoveryQuestionsDebug;\n resultStr = normalized.resultStr;\n result = resultStr;\n\n if (normalized.decisionQuestions && normalized.decisionQuestions.length > 0) {\n const { fresh, newIds } = deduplicateQuestions(normalized.decisionQuestions, surfacedQuestionIds);\n if (fresh.length > 0) {\n emit({ type: \"decision_questions\", questions: fresh });\n for (const id of newIds) surfacedQuestionIds.add(id);\n }\n }\n\n logger.verbose(\"Streaming: tool completed\", {\n name: tc.name,\n resultLength: resultStr.length,\n });\n\n toolsDebug.push({\n name: tc.name,\n args: sanitizeForDebugMeta(tc.args) as Record<string, unknown>,\n resultSummary: normalized.summary,\n success: true,\n durationMs: toolDurationMs,\n ...(normalized.debugSteps?.length ? { steps: normalized.debugSteps } : {}),\n ...(normalized.graphTimings?.length ? { graphs: normalized.graphTimings } : {}),\n });\n emit({\n type: \"tool_activity\",\n phase: \"end\",\n name: tc.name,\n success: true,\n summary: normalized.summary,\n steps: normalized.debugSteps,\n });\n\n toolResults.push({\n toolCallId: tc.id || `${tc.name}-${Date.now()}`,\n name: tc.name,\n result: resultStr,\n });\n } catch (error) {\n const errMsg =\n error instanceof Error ? error.message : \"Unknown error\";\n logger.error(\"Streaming: tool failed\", {\n name: tc.name,\n error: errMsg,\n });\n toolsDebug.push({\n name: tc.name,\n args: sanitizeForDebugMeta(tc.args) as Record<string, unknown>,\n resultSummary: errMsg,\n success: false,\n durationMs: Date.now() - toolStart,\n });\n emit({\n type: \"tool_activity\",\n phase: \"end\",\n name: tc.name,\n success: false,\n summary: errMsg,\n });\n toolResults.push({\n toolCallId: tc.id || `${tc.name}-${Date.now()}`,\n name: tc.name,\n result: JSON.stringify({\n success: false,\n error: `Tool execution failed: ${errMsg}`,\n }),\n });\n }\n }\n\n // If aborted during tool execution, discard partial results\n if (signal?.aborted) {\n logger.verbose(\"Stream aborted after partial tool execution, discarding results\");\n break; // break outer while loop — don't append partial toolResults to messages\n }\n\n // Build updated messages and loop\n messages = [\n ...messages,\n accumulated, // AIMessage with tool_calls\n ...toolResults.map(\n (tr) =>\n new ToolMessage({\n tool_call_id: tr.toolCallId,\n content: tr.result,\n name: tr.name,\n }),\n ),\n ];\n iterationCount++;\n continue;\n }\n\n // ── No tool calls → check for hallucinated code blocks ──────────\n // LLMs sometimes write ```intent_proposal or ```opportunity blocks\n // directly instead of calling the corresponding tool. These blocks\n // lack valid proposalIds / data and won't work in the frontend.\n // Auto-invoke the correct tool directly instead of re-asking the LLM.\n const hallucinatedBlock = this.detectHallucinatedBlock(iterationText, toolsDebug, iterCtx.currentMessage);\n const priorAutoInvokes = hallucinatedBlock ? (hallucinationAutoInvokeCounts.get(hallucinatedBlock.type) ?? 0) : 0;\n if (hallucinatedBlock && priorAutoInvokes < 2 && iterationCount < HARD_ITERATION_LIMIT - 1) {\n hallucinationAutoInvokeCounts.set(hallucinatedBlock.type, priorAutoInvokes + 1);\n logger.warn(\"Streaming: detected hallucinated block, auto-invoking tool\", {\n iteration: iterationCount,\n blockType: hallucinatedBlock.type,\n tool: hallucinatedBlock.tool,\n extractedDescription: hallucinatedBlock.description,\n autoInvokeAttempt: priorAutoInvokes + 1,\n });\n // Tell the frontend to discard all streamed tokens from this iteration\n emit({ type: \"response_reset\", reason: `Hallucinated ${hallucinatedBlock.type} block detected` });\n emit({ type: \"hallucination_detected\", blockType: hallucinatedBlock.type, tool: hallucinatedBlock.tool });\n\n const tool = this.toolsByName.get(hallucinatedBlock.tool);\n if (tool) {\n const toolCallId = `auto-${hallucinatedBlock.tool}-${Date.now()}`;\n const toolArgs = hallucinatedBlock.type === \"opportunity\"\n ? { searchQuery: hallucinatedBlock.description }\n : { description: hallucinatedBlock.description };\n\n emit({ type: \"tool_activity\", phase: \"start\", name: hallucinatedBlock.tool });\n const toolStart = Date.now();\n try {\n const currentCtx = requestContext.getStore() ?? {};\n const result = await requestContext.run(\n {\n ...currentCtx,\n traceEmitter: (e) => emit(e as AgentStreamEvent),\n // Propagate the caller's AbortSignal into requestContext so\n // long-running graph nodes (orchestrator negotiation fan-out)\n // can suppress event emits after the chat session closes.\n ...(signal && { abortSignal: signal }),\n },\n () => tool.invoke(toolArgs),\n );\n const rawResultStr = typeof result === \"string\" ? result : JSON.stringify(result);\n const toolDurationMs = Date.now() - toolStart;\n\n // Same normalization as the main tool loop: callback + _graphTimings strip\n const normalized = await this.normalizeToolResult(hallucinatedBlock.tool, rawResultStr, toolArgs);\n\n toolsDebug.push({\n name: hallucinatedBlock.tool,\n args: sanitizeForDebugMeta(toolArgs) as Record<string, unknown>,\n resultSummary: normalized.summary,\n success: true,\n durationMs: toolDurationMs,\n ...(normalized.debugSteps?.length ? { steps: normalized.debugSteps } : {}),\n ...(normalized.graphTimings?.length ? { graphs: normalized.graphTimings } : {}),\n });\n // Mirror the main tool loop's handling: forward decision questions\n // and capture debug metadata even when the discovery tool was invoked\n // via the hallucination-recovery path.\n if (normalized.discoveryQuestionsDebug) {\n latestDiscoveryQuestionsDebug = normalized.discoveryQuestionsDebug;\n }\n if (normalized.decisionQuestions && normalized.decisionQuestions.length > 0) {\n const { fresh: freshHallucination, newIds: newIdsHallucination } = deduplicateQuestions(normalized.decisionQuestions, surfacedQuestionIds);\n if (freshHallucination.length > 0) {\n emit({ type: \"decision_questions\", questions: freshHallucination });\n for (const id of newIdsHallucination) surfacedQuestionIds.add(id);\n }\n }\n emit({\n type: \"tool_activity\",\n phase: \"end\",\n name: hallucinatedBlock.tool,\n success: true,\n summary: normalized.summary,\n steps: normalized.debugSteps,\n });\n\n // Build synthetic tool call message + tool result so the next LLM\n // iteration can narrate around real data instead of hallucinated blocks.\n const syntheticAIMessage = new AIMessage({\n content: \"\",\n tool_calls: [{ id: toolCallId, name: hallucinatedBlock.tool, args: toolArgs }],\n });\n messages = [\n ...messages,\n syntheticAIMessage,\n new ToolMessage({ tool_call_id: toolCallId, content: normalized.resultStr, name: hallucinatedBlock.tool }),\n ];\n } catch (error) {\n const errMsg = error instanceof Error ? error.message : \"Unknown error\";\n logger.error(\"Streaming: auto-invoked tool failed after hallucination\", {\n tool: hallucinatedBlock.tool,\n error: errMsg,\n });\n toolsDebug.push({\n name: hallucinatedBlock.tool,\n args: sanitizeForDebugMeta(toolArgs) as Record<string, unknown>,\n resultSummary: errMsg,\n success: false,\n durationMs: Date.now() - toolStart,\n });\n emit({ type: \"tool_activity\", phase: \"end\", name: hallucinatedBlock.tool, success: false, summary: errMsg });\n\n // Fall back to correction message if tool invocation fails\n messages = [\n ...messages,\n accumulated,\n new SystemMessage(\n `CORRECTION: You wrote a \\`\\`\\`${hallucinatedBlock.type} block without calling ${hallucinatedBlock.tool}. ` +\n `The auto-retry failed (${errMsg}). Please try calling the tool directly.`\n ),\n ];\n }\n } else {\n // Tool not found — fall back to correction message\n messages = [\n ...messages,\n accumulated,\n new SystemMessage(\n `CORRECTION: You wrote a \\`\\`\\`${hallucinatedBlock.type} block without calling ${hallucinatedBlock.tool}. ` +\n `That block is INVALID. Call the tool directly instead.`\n ),\n ];\n }\n iterationCount++;\n continue;\n }\n\n // ── Circuit breaker: hallucination detected but auto-invoke cap reached ──\n if (hallucinatedBlock && priorAutoInvokes >= 2) {\n logger.warn(\"Streaming: hallucination auto-invoke cap reached, stripping blocks\", {\n iteration: iterationCount,\n blockType: hallucinatedBlock.type,\n attempts: priorAutoInvokes,\n });\n emit({ type: \"response_reset\", reason: `Hallucination cap reached for ${hallucinatedBlock.type}` });\n const stripped = this.stripUnbackedBlocks(iterationText, toolsDebug);\n if (stripped.trim()) {\n emit({ type: \"text_chunk\", content: stripped });\n } else {\n messages = [\n ...messages,\n accumulated,\n new SystemMessage(\n \"Your previous response only contained invalid code blocks that were removed. \" +\n \"Write a plain text response now — summarize the results of the tools you used. \" +\n \"Do NOT include ```opportunity or ```intent_proposal blocks.\",\n ),\n ];\n iterationCount++;\n continue;\n }\n }\n\n // ── Phantom write: model claims a write action without calling any tools ──\n if (\n ChatAgent.detectPhantomWrite(iterationText, toolsDebug) &&\n iterationCount < HARD_ITERATION_LIMIT - 1\n ) {\n logger.warn(\"Streaming: detected phantom write claim without tool calls\", {\n iteration: iterationCount,\n });\n emit({ type: \"response_reset\", reason: \"Phantom write detected — no tools were called\" });\n emit({ type: \"hallucination_detected\", blockType: \"phantom_write\", tool: \"none\" });\n\n messages = [\n ...messages,\n accumulated,\n new SystemMessage(\n \"CORRECTION: You claimed to have performed an action (update, create, modify) but you did NOT call any tools. \" +\n \"The user's request has NOT been fulfilled. You MUST call the appropriate tool(s) to actually make the change, \" +\n \"then confirm based on the tool result. Do it now.\",\n ),\n ];\n iterationCount++;\n continue;\n }\n\n // ── Final response already streamed ─────────────────────────────\n // Defense-in-depth: strip any code blocks that require tool backing\n // but slipped through without a successful tool call.\n const sanitizedText = this.stripUnbackedBlocks(iterationText, toolsDebug);\n if (sanitizedText !== iterationText) {\n logger.warn(\"Streaming: stripped unbacked code blocks from final response\", {\n originalLength: iterationText.length,\n sanitizedLength: sanitizedText.length,\n });\n emit({ type: \"response_reset\", reason: \"Sanitized unbacked blocks from response\" });\n // Re-emit the sanitized text so the frontend displays clean content\n if (sanitizedText.trim()) {\n emit({ type: \"text_chunk\", content: sanitizedText });\n }\n\n // If stripping removed ALL content, force a recovery iteration so the\n // user sees an actual response instead of a blank message.\n if (!sanitizedText.trim() && iterationCount < HARD_ITERATION_LIMIT - 1) {\n logger.warn(\"Streaming: sanitized text is empty, forcing recovery iteration\", {\n iteration: iterationCount,\n });\n messages = [\n ...messages,\n accumulated,\n new SystemMessage(\n \"Your previous response only contained invalid code blocks that were removed. \" +\n \"Write a plain text response now — summarize the results of the tools you used. \" +\n \"Do NOT include ```opportunity or ```intent_proposal blocks.\",\n ),\n ];\n iterationCount++;\n continue;\n }\n }\n\n logger.verbose(\"Streaming: agent produced response\", {\n iteration: iterationCount,\n responseLength: sanitizedText.length,\n });\n messages = [...messages, accumulated];\n iterationCount++;\n\n return {\n responseText: sanitizedText,\n messages,\n iterationCount,\n debugMeta: {\n graph: \"agent_loop\",\n iterations: iterationCount,\n tools: toolsDebug,\n llm,\n ...(orchestratorNegotiationIds.size > 0 && {\n orchestratorNegotiations: { opportunityIds: [...orchestratorNegotiationIds] },\n }),\n ...(latestDiscoveryQuestionsDebug && { discoveryQuestions: latestDiscoveryQuestionsDebug }),\n },\n };\n }\n\n // If aborted, return immediately without making another LLM call\n if (signal?.aborted) {\n return {\n responseText: \"\",\n messages,\n iterationCount,\n debugMeta: {\n graph: \"agent_loop\",\n iterations: iterationCount,\n tools: toolsDebug,\n llm,\n ...(orchestratorNegotiationIds.size > 0 && {\n orchestratorNegotiations: { opportunityIds: [...orchestratorNegotiationIds] },\n }),\n ...(latestDiscoveryQuestionsDebug && { discoveryQuestions: latestDiscoveryQuestionsDebug }),\n },\n };\n }\n\n // ── Hard limit: force a response ──────────────────────────────────────\n logger.warn(\"Streaming: hit hard iteration limit\", { iterationCount });\n\n const forceMessages = [\n ...messages,\n new SystemMessage(\n \"You have reached the maximum number of tool calls. You MUST provide a final response now. Summarize what you've accomplished and what might still be needed.\",\n ),\n ];\n\n let forcedAccumulated: AIMessageChunk | undefined;\n let forcedResponseText = \"\";\n const forceStream = await this.model.stream(forceMessages);\n for await (const chunk of forceStream) {\n forcedAccumulated = forcedAccumulated\n ? forcedAccumulated.concat(chunk)\n : chunk;\n const textPart = extractTextFromChunk(chunk);\n if (textPart) {\n emit({ type: \"text_chunk\", content: textPart });\n forcedResponseText += textPart;\n }\n }\n\n return {\n responseText: forcedResponseText,\n messages: [\n ...messages,\n ...(forcedAccumulated ? [forcedAccumulated] : []),\n ],\n iterationCount,\n debugMeta: {\n graph: \"agent_loop\",\n iterations: iterationCount,\n tools: toolsDebug,\n llm,\n ...(orchestratorNegotiationIds.size > 0 && {\n orchestratorNegotiations: { opportunityIds: [...orchestratorNegotiationIds] },\n }),\n ...(latestDiscoveryQuestionsDebug && { discoveryQuestions: latestDiscoveryQuestionsDebug }),\n },\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"chat.agent.js","sourceRoot":"/","sources":["chat/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AE,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,CAAC;gBAChD,kBAAkB,IAAI,QAAQ,CAAC;YACjC,CAAC;QACH,CAAC;QAED,OAAO;YACL,YAAY,EAAE,kBAAkB;YAChC,QAAQ,EAAE;gBACR,GAAG,QAAQ;gBACX,GAAG,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;aAClD;YACD,cAAc;YACd,SAAS,EAAE;gBACT,KAAK,EAAE,YAAY;gBACnB,UAAU,EAAE,cAAc;gBAC1B,KAAK,EAAE,UAAU;gBACjB,GAAG;gBACH,GAAG,CAAC,0BAA0B,CAAC,IAAI,GAAG,CAAC,IAAI;oBACzC,wBAAwB,EAAE,EAAE,cAAc,EAAE,CAAC,GAAG,0BAA0B,CAAC,EAAE;iBAC9E,CAAC;gBACF,GAAG,CAAC,6BAA6B,IAAI,EAAE,kBAAkB,EAAE,6BAA6B,EAAE,CAAC;aAC5F;SACF,CAAC;IACJ,CAAC;;AAryBD,4EAA4E;AAEpD,gCAAsB,GAAG;IAC/C,6GAA6G;IAC7G,gGAAgG;IAChG,0GAA0G;IAC1G,oEAAoE;IACpE,iIAAiI;CAClI,CAAC;AAcF,6EAA6E;AACrD,yBAAe,GAAG,GAAG,CAAC;AAEtB,uBAAa,GAAG,GAAG,CAAC;AAxVtC;IADL,KAAK,EAAE;;;;6CAgGP;AA0XK;IADL,KAAK,EAAE;;;;oCAgDP;AAmBK;IADL,KAAK,EAAE;;sDAIG,WAAW;;0CAskBrB","sourcesContent":["import type { ChatOpenAI } from \"@langchain/openai\";\nimport { AIMessage, BaseMessage, SystemMessage, ToolMessage, AIMessageChunk } from \"@langchain/core/messages\";\nimport { createChatTools, type ToolContext, type ResolvedToolContext } from \"../shared/agent/tool.factory.js\";\nimport { resolveChatContext } from \"../shared/agent/tool.helpers.js\";\nimport { ITERATION_NUDGE, buildSystemContent } from \"./chat.prompt.js\";\nimport { extractRecentToolCalls, type IterationContext } from \"./chat.prompt.modules.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport { createModel, type ModelConfig } from \"../shared/agent/model.config.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\nimport { sanitizeForDebugMeta } from \"../shared/observability/debug-meta.sanitizer.js\";\nimport type { DebugMetaToolCall, DebugMetaLlm, DebugMetaOrchestratorNegotiations, DebugMetaDiscoveryQuestions } from \"./chat-streaming.types.js\";\nimport type { Question, QuestionStrategy } from \"../shared/schemas/question.schema.js\";\nimport type { Opportunity } from \"../shared/interfaces/database.interface.js\";\nimport { Timed } from \"../shared/observability/performance.js\";\nimport { requestContext } from \"../shared/observability/request-context.js\";\nimport { deduplicateQuestions } from \"./chat.question-dedup.js\";\n\nconst logger = protocolLogger(\"ChatAgent\");\n\n// Re-export for external consumers\nexport { ITERATION_NUDGE } from \"./chat.prompt.js\";\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TYPES\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Writer callback for streaming custom data out of the graph node.\n * Matches the `config.writer` signature from LangGraphRunnableConfig.\n */\nexport type StreamWriter = (data: unknown) => void;\n\n/**\n * Events emitted by `streamRun()` via the writer callback.\n *\n * - `iteration_start` — new agent loop iteration begins\n * - `llm_start` — LLM begins generating response\n * - `text_chunk` — a token (or group of tokens) of model text\n * - `llm_end` — LLM finished generating (may have tool calls)\n * - `tool_activity` — tool starts or finishes execution\n * - `graph_start` — a LangGraph sub-graph begins inside a tool\n * - `graph_end` — a LangGraph sub-graph completes\n * - `agent_start` — an LLM agent begins inside a graph node\n * - `agent_end` — an LLM agent completes\n * - `opportunity_draft_ready` — an orchestrator-triggered negotiation finalized\n * to `draft` and the card is ready to render inline\n */\nexport type AgentStreamEvent =\n | { type: \"iteration_start\"; iteration: number }\n | { type: \"llm_start\"; iteration: number }\n | { type: \"text_chunk\"; content: string }\n | { type: \"llm_end\"; iteration: number; hasToolCalls: boolean; toolNames?: string[] }\n | { type: \"tool_activity\"; phase: \"start\"; name: string }\n | {\n type: \"tool_activity\";\n phase: \"end\";\n name: string;\n success: boolean;\n summary?: string;\n steps?: Array<{ step: string; detail?: string; data?: Record<string, unknown> }>;\n }\n | { type: \"response_reset\"; reason: string }\n | { type: \"hallucination_detected\"; blockType: string; tool: string }\n | { type: \"graph_start\"; name: string }\n | { type: \"graph_end\"; name: string; durationMs: number }\n | { type: \"phase_start\"; name: string }\n | { type: \"phase_end\"; name: string; durationMs: number }\n | { type: \"agent_start\"; name: string }\n | { type: \"agent_end\"; name: string; durationMs: number; summary: string }\n | {\n // Emitted from the orchestrator branch of OpportunityGraph.negotiateNode\n // each time a per-candidate negotiation resolves to an accepted draft.\n // Carries the opportunity row plus the counterparty's display basics so\n // the frontend can append an inline card to the chat timeline without a\n // second round-trip user lookup.\n type: \"opportunity_draft_ready\";\n opportunityId: string;\n opportunity: Opportunity;\n /** Viewer-centric summary derived from interpretation.reasoning via viewerCentricCardSummary. */\n personalizedSummary?: string;\n counterparty: {\n userId: string;\n name?: string;\n };\n }\n | {\n type: \"negotiation_session_start\";\n opportunityId: string;\n negotiationConversationId: string;\n sourceUserId: string;\n candidateUserId: string;\n candidateName?: string;\n trigger: \"orchestrator\" | \"ambient\";\n startedAt: number;\n }\n | {\n type: \"negotiation_session_end\";\n opportunityId: string;\n negotiationConversationId: string;\n durationMs: number;\n }\n | {\n type: \"negotiation_turn\";\n opportunityId: string;\n negotiationConversationId: string;\n turnIndex: number;\n actor: \"source\" | \"candidate\";\n action: \"propose\" | \"accept\" | \"reject\" | \"counter\" | \"question\";\n reasoning?: string;\n message?: string;\n suggestedRoles?: { ownUser?: string; otherUser?: string };\n durationMs: number;\n }\n | {\n type: \"negotiation_outcome\";\n opportunityId: string;\n outcome:\n | \"accepted\"\n | \"rejected_stalled\"\n | \"waiting_for_agent\"\n | \"timed_out\"\n | \"turn_cap\";\n turnCount: number;\n reasoning?: string;\n agreedRoles?: { ownUser?: string; otherUser?: string };\n }\n | { type: \"decision_questions\"; questions: Question[] }\n | { type: \"chat_summarizer_start\"; payload: { sessionId: string } }\n | { type: \"chat_summarizer_end\"; payload: { durationMs: number } }\n | { type: \"question_generator_start\"; payload: { inputMode: \"transcripts\" | \"insights\"; negotiationCount: number; hasChatContext: boolean; truncated?: { originalCount: number; keptCount: number } } }\n | { type: \"question_generator_end\"; payload: { finalCount: number; strategies: QuestionStrategy[]; durationMs: number; inputMode: \"transcripts\" | \"insights\" } };\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// CONFIGURATION\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Soft limit: After this many iterations, inject a nudge message.\n */\nexport const SOFT_ITERATION_LIMIT = 8;\n\n/**\n * Hard limit: Force exit after this many iterations to prevent infinite loops.\n */\nexport const HARD_ITERATION_LIMIT = 12;\n\n/**\n * Extract plain text from message content (string or structured block array).\n * Filters to only `type: \"text\"` blocks, discarding tool metadata.\n */\nfunction extractTextContent(content: string | Array<Record<string, unknown>>): string {\n if (typeof content === \"string\") return content;\n if (Array.isArray(content)) {\n return content\n .filter((b): b is { type: \"text\"; text?: string } => (b as { type?: string }).type === \"text\")\n .map((b) => b.text ?? \"\")\n .join(\"\");\n }\n return \"\";\n}\n\n/**\n * Extract plain text from an AIMessageChunk (string content or text blocks).\n */\nfunction extractTextFromChunk(chunk: AIMessageChunk): string {\n return extractTextContent(chunk.content as string | Array<Record<string, unknown>>);\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// CHAT AGENT CLASS\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Result of a single agent iteration.\n */\nexport interface AgentIterationResult {\n /** Whether the agent wants to continue (made tool calls) or stop (produced final response) */\n shouldContinue: boolean;\n /** Tool calls made in this iteration (if any) */\n toolCalls?: Array<{\n id: string;\n name: string;\n args: Record<string, unknown>;\n }>;\n /** Tool results from executing the tool calls */\n toolResults?: Array<{\n toolCallId: string;\n name: string;\n result: string;\n }>;\n /** Final response text (if agent is done) */\n responseText?: string;\n /** Updated messages array */\n messages: BaseMessage[];\n}\n\n/**\n * ChatAgent: ReAct-style agent that uses tools to help users.\n *\n * The agent operates in a loop:\n * 1. Receive messages (conversation history + tool results)\n * 2. Decide: call tools OR respond to user\n * 3. If tools called: execute them, add results, loop back\n * 4. If response: return final text\n *\n * Use `ChatAgent.create(context)` to construct (async factory).\n */\nexport class ChatAgent {\n private model: ChatOpenAI;\n private tools: Awaited<ReturnType<typeof createChatTools>>;\n private toolsByName: Map<string, any>;\n\n /**\n * Private constructor — use `ChatAgent.create()` instead.\n */\n private constructor(\n private resolvedContext: ResolvedToolContext,\n tools: Awaited<ReturnType<typeof createChatTools>>,\n modelConfig?: ModelConfig,\n ) {\n this.model = createModel(\"chat\", modelConfig);\n\n // Store tools and index by name\n this.tools = tools;\n this.toolsByName = new Map();\n for (const tool of this.tools) {\n this.toolsByName.set(tool.name, tool);\n }\n\n // Bind tools to model\n this.model = this.model.bindTools(this.tools) as ChatOpenAI;\n }\n\n /**\n * Extracts the text content of the most recent HumanMessage.\n */\n private static getCurrentUserMessage(messages: BaseMessage[]): string | undefined {\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]._getType() === \"human\") {\n const content = messages[i].content;\n return typeof content === \"string\" ? content : undefined;\n }\n }\n return undefined;\n }\n\n /**\n * Async factory: creates a ChatAgent with resolved user/index context.\n * Resolves user/index identity from DB during tool initialization.\n */\n static async create(context: ToolContext): Promise<ChatAgent> {\n const resolved: ResolvedToolContext = await resolveChatContext({\n database: context.database,\n userId: context.userId,\n networkId: context.networkId,\n sessionId: context.sessionId,\n });\n const tools = await createChatTools(context, resolved);\n return new ChatAgent(resolved, tools, context.modelConfig);\n }\n\n /**\n * Run a single iteration of the agent loop.\n *\n * @param messages - Current conversation including any tool results\n * @param iterationCount - Current iteration number (for soft limit)\n * @returns Result indicating whether to continue and any tool calls/response\n */\n @Timed()\n async runIteration(\n messages: BaseMessage[],\n iterationCount: number,\n ): Promise<AgentIterationResult> {\n const iterCtx: IterationContext = {\n recentTools: extractRecentToolCalls(messages),\n currentMessage: ChatAgent.getCurrentUserMessage(messages),\n ctx: this.resolvedContext,\n };\n const systemContent = buildSystemContent(this.resolvedContext, iterCtx);\n\n const fullMessages: BaseMessage[] = [\n new SystemMessage(systemContent),\n ...messages,\n ];\n\n // Add nudge if past soft limit\n if (iterationCount >= SOFT_ITERATION_LIMIT) {\n fullMessages.push(new SystemMessage(ITERATION_NUDGE));\n }\n\n logger.verbose(\"Agent iteration\", {\n iteration: iterationCount,\n messageCount: messages.length,\n pastSoftLimit: iterationCount >= SOFT_ITERATION_LIMIT,\n });\n\n // Invoke model\n const response = await invokeWithAbortSignal(this.model, fullMessages);\n logger.debug(\"Chat model response\", {\n content:\n typeof response.content === \"string\"\n ? response.content\n : JSON.stringify(response.content),\n toolCalls: response.tool_calls?.length ?? 0,\n toolCallNames: response.tool_calls?.map((tc) => tc.name) ?? [],\n });\n\n // Check if model made tool calls\n const toolCalls = response.tool_calls || [];\n\n if (toolCalls.length > 0) {\n logger.verbose(\"Agent made tool calls\", {\n iteration: iterationCount,\n toolCount: toolCalls.length,\n tools: toolCalls.map((tc) => tc.name),\n });\n\n // Execute tools (can be parallelized if independent)\n const toolResults = await this.executeToolCalls(toolCalls);\n\n // Build updated messages\n const updatedMessages = [\n ...messages,\n response, // AIMessage with tool_calls\n ...toolResults.map(\n (tr) =>\n new ToolMessage({\n tool_call_id: tr.toolCallId,\n content: tr.result,\n name: tr.name,\n }),\n ),\n ];\n\n return {\n shouldContinue: true,\n toolCalls: toolCalls.map((tc) => ({\n id: tc.id!,\n name: tc.name,\n args: tc.args as Record<string, unknown>,\n })),\n toolResults,\n messages: updatedMessages,\n };\n }\n\n // No tool calls - agent is responding\n const responseText = extractTextContent(\n response.content as string | Array<Record<string, unknown>>,\n );\n logger.debug(\"Agent produced response (raw)\", {\n iteration: iterationCount,\n responseText,\n });\n logger.verbose(\"Agent produced response\", {\n iteration: iterationCount,\n responseLength: responseText.length,\n });\n\n return {\n shouldContinue: false,\n responseText,\n messages: [...messages, response],\n };\n }\n\n /**\n * Execute tool calls, potentially in parallel.\n */\n private async executeToolCalls(\n toolCalls: Array<{\n id?: string;\n name: string;\n args: Record<string, unknown>;\n }>,\n ): Promise<Array<{ toolCallId: string; name: string; result: string }>> {\n // Execute all tool calls in parallel\n const results = await Promise.all(\n toolCalls.map(async (tc) => {\n const tool = this.toolsByName.get(tc.name);\n\n if (!tool) {\n logger.error(\"Unknown tool\", { name: tc.name });\n return {\n toolCallId: tc.id || `unknown-${Date.now()}`,\n name: tc.name,\n result: JSON.stringify({\n success: false,\n error: `Unknown tool: ${tc.name}`,\n }),\n };\n }\n\n try {\n logger.verbose(\"Executing tool\", { name: tc.name, args: tc.args });\n let result = await tool.invoke(tc.args);\n let resultStr =\n typeof result === \"string\" ? result : JSON.stringify(result);\n\n if (tc.name === \"discover_opportunities\") {\n const newResult = await this.handleCreateIntentCallback(resultStr, tc.args);\n if (newResult !== null) {\n resultStr = newResult;\n result = newResult;\n }\n }\n\n logger.debug(\"Tool response\", { name: tc.name, result: resultStr });\n logger.verbose(\"Tool completed\", {\n name: tc.name,\n resultLength: resultStr.length,\n });\n\n return {\n toolCallId: tc.id || `${tc.name}-${Date.now()}`,\n name: tc.name,\n result: resultStr,\n };\n } catch (error) {\n logger.error(\"Tool execution failed\", {\n name: tc.name,\n error: error instanceof Error ? error.message : String(error),\n });\n\n return {\n toolCallId: tc.id || `${tc.name}-${Date.now()}`,\n name: tc.name,\n result: JSON.stringify({\n success: false,\n error: `Tool execution failed: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n }),\n };\n }\n }),\n );\n\n return results;\n }\n\n /**\n * When discover_opportunities returned createIntentSuggested, call create_intent then discover_opportunities.\n * Returns the new discover_opportunities result string or null if no callback / create_intent failed.\n */\n private async handleCreateIntentCallback(\n resultStr: string,\n originalArgs: Record<string, unknown>\n ): Promise<string | null> {\n let parsed: { success?: boolean; error?: string; data?: { createIntentSuggested?: boolean; suggestedIntentDescription?: string } };\n try {\n parsed = JSON.parse(resultStr) as typeof parsed;\n } catch {\n return null;\n }\n if (\n !parsed?.data?.createIntentSuggested ||\n typeof parsed.data.suggestedIntentDescription !== \"string\"\n ) {\n return null;\n }\n // Never auto-create intents during introducer flows — signals are personal\n if ((originalArgs as { introTargetUserId?: string }).introTargetUserId) {\n return null;\n }\n const createIntentTool = this.toolsByName.get(\"create_intent\");\n const discoverOpportunitiesTool = this.toolsByName.get(\"discover_opportunities\");\n if (!createIntentTool || !discoverOpportunitiesTool) return null;\n\n logger.verbose(\"Create-intent signal: auto-calling create_intent then discover_opportunities\");\n const createIntentResult = await createIntentTool.invoke({\n description: parsed.data.suggestedIntentDescription,\n networkId: (originalArgs as { networkId?: string }).networkId,\n });\n const createIntentStr =\n typeof createIntentResult === \"string\" ? createIntentResult : JSON.stringify(createIntentResult);\n let createIntentParsed: { success?: boolean; error?: string };\n try {\n createIntentParsed = JSON.parse(createIntentStr) as { success?: boolean; error?: string };\n } catch {\n createIntentParsed = {};\n }\n if (createIntentParsed.success === false) {\n logger.warn(\"Create-intent failed; not re-running discover_opportunities\", {\n error: createIntentParsed.error,\n });\n return null;\n }\n\n const newResult = await discoverOpportunitiesTool.invoke(originalArgs);\n return typeof newResult === \"string\" ? newResult : JSON.stringify(newResult);\n }\n\n /**\n * Check whether any tool call produced valid opportunity blocks.\n * Both `discover_opportunities` and `list_opportunities` can return\n * ```opportunity code blocks — either one counts as a valid source.\n */\n private static hasOpportunitySource(\n toolsUsed: Array<{ name: string; success: boolean; resultSummary?: string }>,\n ): boolean {\n return toolsUsed.some(\n (t) =>\n (t.name === \"discover_opportunities\" || t.name === \"list_opportunities\") &&\n t.success &&\n !t.resultSummary?.startsWith(\"Found 0\") &&\n !t.resultSummary?.startsWith(\"No matches\") &&\n !t.resultSummary?.startsWith(\"No opportunities\"),\n );\n }\n\n /**\n * Detect hallucinated ```intent_proposal or ```opportunity blocks in model text\n * that were NOT generated by the corresponding tool call.\n *\n * A tool call that returned 0 cards (e.g. \"Found 0 match(es)\") counts as\n * NOT having produced valid blocks — the LLM must not fabricate them.\n *\n * @returns Block info if hallucination detected, null otherwise\n */\n private detectHallucinatedBlock(\n text: string,\n toolsUsed: Array<{ name: string; success: boolean; resultSummary?: string }>,\n userMessage?: string,\n ): { type: string; tool: string; description: string } | null {\n const hasSuccessfulCreateIntent = toolsUsed.some(\n (t) => t.name === \"create_intent\" && t.success,\n );\n\n // Check for hallucinated intent_proposal\n if (text.includes(\"```intent_proposal\") && !hasSuccessfulCreateIntent) {\n const match = text.match(/```intent_proposal\\s*\\n\\s*\\{[^}]*\"description\"\\s*:\\s*\"([^\"]+)\"/);\n if (match) {\n return { type: \"intent_proposal\", tool: \"create_intent\", description: match[1] };\n }\n }\n\n // Check for hallucinated opportunity blocks\n if (text.includes(\"```opportunity\") && !ChatAgent.hasOpportunitySource(toolsUsed)) {\n // Use the user's original message as the search query — NOT fields from the\n // hallucinated JSON. The model fabricates person names and reasoning that have\n // nothing to do with the user's actual request, leading to wrong results and\n // the model re-calling the tool with the correct query (doubling negotiation cost).\n const description = userMessage?.trim() || \"find connections\";\n return { type: \"opportunity\", tool: \"discover_opportunities\", description };\n }\n\n return null;\n }\n\n /**\n * Strip ```opportunity and ```intent_proposal code blocks from text\n * when no corresponding successful tool call was made.\n * Defense-in-depth: catches hallucinated blocks that slip past detectHallucinatedBlock\n * (e.g. after a correction iteration that still hallucinates).\n *\n * @param text - The response text to sanitize\n * @param toolsUsed - Tool call records from the agent loop\n * @returns Sanitized text with unbacked blocks removed\n */\n private stripUnbackedBlocks(\n text: string,\n toolsUsed: Array<{ name: string; success: boolean; resultSummary?: string }>,\n ): string {\n let result = text;\n let removedBlock = false;\n\n const hasSuccessfulCreateIntent = toolsUsed.some(\n (t) => t.name === \"create_intent\" && t.success,\n );\n\n if (!ChatAgent.hasOpportunitySource(toolsUsed) && result.includes(\"```opportunity\")) {\n const next = result.replace(/```opportunity\\s*\\n[\\s\\S]*?```/g, \"\");\n removedBlock ||= next !== result;\n result = next;\n }\n if (!hasSuccessfulCreateIntent && result.includes(\"```intent_proposal\")) {\n const next = result.replace(/```intent_proposal\\s*\\n[\\s\\S]*?```/g, \"\");\n removedBlock ||= next !== result;\n result = next;\n }\n\n // Clean up leftover double blank lines only when a block was actually removed\n if (removedBlock) {\n result = result.replace(/\\n{3,}/g, \"\\n\\n\").trim();\n }\n\n return result;\n }\n\n // ─── Phantom write detection ─────────────────────────────────────────────\n\n private static readonly PHANTOM_WRITE_PATTERNS = [\n /\\bI(?:'ve| have) (?:updated|adjusted|changed|modified|edited|created|added|removed|deleted|saved|set up)\\b/i,\n /\\bI (?:updated|adjusted|changed|modified|edited|created|added|removed|deleted|saved|set up)\\b/i,\n /\\b(?:Updated|Adjusted|Changed|Modified|Edited|Created|Added|Removed|Deleted|Saved) (?:your|the|their)\\b/i,\n /\\bEverything is (?:now )?(?:updated|changed|adjusted|saved|set)\\b/i,\n /\\b(?:profile|bio|premise|signal|intent|membership|narrative) (?:has been|is now) (?:updated|changed|modified|adjusted|saved)\\b/i,\n ];\n\n /**\n * Detect when the model claims to have performed a write action\n * without having called any tools in the turn.\n */\n private static detectPhantomWrite(\n responseText: string,\n toolsUsed: Array<{ name: string }>,\n ): boolean {\n if (toolsUsed.length > 0) return false;\n return ChatAgent.PHANTOM_WRITE_PATTERNS.some(pattern => pattern.test(responseText));\n }\n\n // ─── Shared tool-result post-processing types ─────────────────────────────\n private static readonly STEP_DETAIL_MAX = 300;\n\n private static readonly STEP_NAME_MAX = 100;\n\n /**\n * Post-process a tool result: strip _graphTimings, extract summary/debugSteps,\n * and optionally run discover_opportunities → create_intent callback.\n *\n * Returns the normalized result string and extracted debug metadata so both\n * the normal streaming tool loop and the hallucination-recovery branch\n * produce identical LLM-facing payloads.\n */\n private async normalizeToolResult(\n toolName: string,\n resultStr: string,\n toolArgs: Record<string, unknown>,\n ): Promise<{\n resultStr: string;\n summary: string;\n debugSteps?: Array<{ step: string; detail?: string; data?: Record<string, unknown> }>;\n graphTimings?: Array<{ name: string; durationMs: number; agents: Array<{ name: string; durationMs: number }> }>;\n decisionQuestions?: Question[];\n discoveryQuestionsDebug?: DebugMetaDiscoveryQuestions;\n }> {\n let normalized = resultStr;\n\n // Run create_intent callback for discover_opportunities results\n if (toolName === \"discover_opportunities\") {\n const callbackResult = await this.handleCreateIntentCallback(normalized, toolArgs);\n if (callbackResult !== null) {\n normalized = callbackResult;\n }\n }\n\n type StepData = Record<string, unknown>;\n type DebugStep = { step: string; detail?: string; data?: StepData };\n type GraphTiming = { name: string; durationMs: number; agents: Array<{ name: string; durationMs: number }> };\n\n let summary = \"Done\";\n let debugSteps: DebugStep[] | undefined;\n let graphTimings: GraphTiming[] | undefined;\n let decisionQuestions: Question[] | undefined;\n let discoveryQuestionsDebug: DebugMetaDiscoveryQuestions | undefined;\n\n try {\n const parsed = JSON.parse(normalized) as {\n success?: boolean;\n data?: {\n summary?: string;\n debugSteps?: DebugStep[];\n _graphTimings?: GraphTiming[];\n };\n summary?: string;\n debugSteps?: DebugStep[];\n _graphTimings?: GraphTiming[];\n };\n const payload = parsed.success && parsed.data != null ? parsed.data : parsed;\n summary = payload.summary ?? parsed.summary ?? \"Done\";\n\n const rawSteps = payload.debugSteps ?? parsed.debugSteps;\n if (Array.isArray(rawSteps) && rawSteps.length > 0) {\n debugSteps = rawSteps.map((s) => ({\n step: String(s.step ?? \"\").slice(0, ChatAgent.STEP_NAME_MAX),\n detail:\n s.detail != null\n ? String(s.detail).slice(0, ChatAgent.STEP_DETAIL_MAX)\n : undefined,\n ...(s.data && typeof s.data === \"object\" ? { data: s.data } : {}),\n }));\n }\n\n const rawGraphTimings = payload._graphTimings ?? parsed._graphTimings;\n if (Array.isArray(rawGraphTimings) && rawGraphTimings.length > 0) {\n graphTimings = rawGraphTimings as GraphTiming[];\n // Strip _graphTimings from the result string sent back to the LLM\n try {\n const cleanedResult = JSON.parse(normalized) as Record<string, unknown>;\n delete cleanedResult._graphTimings;\n if (cleanedResult.data && typeof cleanedResult.data === \"object\") {\n delete (cleanedResult.data as Record<string, unknown>)._graphTimings;\n }\n normalized = JSON.stringify(cleanedResult);\n } catch { /* keep original if can't clean */ }\n }\n\n const rawQuestions = (payload as { questions?: unknown }).questions ?? (parsed as { questions?: unknown }).questions;\n const rawQuestionDebug = (payload as { _discoveryQuestionsDebug?: unknown })._discoveryQuestionsDebug\n ?? (parsed as { _discoveryQuestionsDebug?: unknown })._discoveryQuestionsDebug;\n if (Array.isArray(rawQuestions)) {\n decisionQuestions = rawQuestions as Question[];\n }\n if (rawQuestionDebug && typeof rawQuestionDebug === \"object\") {\n discoveryQuestionsDebug = rawQuestionDebug as DebugMetaDiscoveryQuestions;\n }\n // `_discoveryQuestionsDebug` is internal trace data — strip from the LLM-facing\n // tool result. `questions` is intentionally kept visible so the agent can\n // follow the prompt addendum and reference the decision prompts in its reply.\n if (discoveryQuestionsDebug !== undefined) {\n try {\n const cleaned = JSON.parse(normalized) as Record<string, unknown>;\n const stripFrom = (obj: Record<string, unknown>) => {\n delete obj._discoveryQuestionsDebug;\n };\n stripFrom(cleaned);\n if (cleaned.data && typeof cleaned.data === \"object\") {\n stripFrom(cleaned.data as Record<string, unknown>);\n }\n normalized = JSON.stringify(cleaned);\n } catch { /* keep original */ }\n }\n } catch {\n /* not JSON, keep default */\n }\n\n return {\n resultStr: normalized,\n summary,\n debugSteps,\n graphTimings,\n ...(decisionQuestions !== undefined ? { decisionQuestions } : {}),\n ...(discoveryQuestionsDebug !== undefined ? { discoveryQuestionsDebug } : {}),\n };\n }\n\n /**\n * Run the full agent loop until completion or hard limit.\n *\n * @param initialMessages - Starting conversation messages\n * @returns Final response text and full message history\n */\n @Timed()\n async run(initialMessages: BaseMessage[]): Promise<{\n responseText: string;\n messages: BaseMessage[];\n iterationCount: number;\n }> {\n let messages = initialMessages;\n let iterationCount = 0;\n\n while (iterationCount < HARD_ITERATION_LIMIT) {\n const result = await this.runIteration(messages, iterationCount);\n iterationCount++;\n messages = result.messages;\n\n if (!result.shouldContinue) {\n const responseText =\n result.responseText ||\n \"I apologize, but I couldn't generate a response.\";\n logger.debug(\"Agent final response\", { responseText });\n return {\n responseText,\n messages,\n iterationCount,\n };\n }\n }\n\n // Hit hard limit - force a response\n logger.warn(\"Hit hard iteration limit\", { iterationCount });\n\n const forceResponseMessages = [\n ...messages,\n new SystemMessage(\n \"You have reached the maximum number of tool calls. You MUST provide a final response now. Summarize what you've accomplished and what might still be needed.\",\n ),\n ];\n\n const forcedResponse = await invokeWithAbortSignal(this.model, forceResponseMessages);\n const responseText = extractTextContent(\n forcedResponse.content as string | Array<Record<string, unknown>>,\n );\n logger.debug(\"Agent forced response\", { responseText });\n\n return {\n responseText,\n messages: [...messages, forcedResponse],\n iterationCount,\n };\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // STREAMING RUN (for narration-style output)\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Run the full agent loop with streaming narration.\n *\n * Instead of returning a single blob at the end, this method calls\n * `writer()` for every text token and tool-activity event so the\n * consumer (graph node) can push them out via `config.writer`.\n *\n * @param initialMessages - Starting conversation messages\n * @param writer - Callback to emit streaming events (from `config.writer`)\n * @param signal - Optional AbortSignal to cancel the streaming LLM call and tool execution\n * @returns Final response metadata (same shape as `run()`)\n */\n @Timed()\n async streamRun(\n initialMessages: BaseMessage[],\n writer?: StreamWriter,\n signal?: AbortSignal,\n ): Promise<{\n responseText: string;\n messages: BaseMessage[];\n iterationCount: number;\n debugMeta: { graph: string; iterations: number; tools: DebugMetaToolCall[]; llm: DebugMetaLlm; orchestratorNegotiations?: DebugMetaOrchestratorNegotiations; discoveryQuestions?: DebugMetaDiscoveryQuestions };\n }> {\n const llm: DebugMetaLlm = { calls: 0, totalDurationMs: 0, resets: [], hallucinations: [] };\n const orchestratorNegotiationIds = new Set<string>();\n let lastLlmStart = 0;\n let latestDiscoveryQuestionsDebug: DebugMetaDiscoveryQuestions | undefined;\n\n const emit = (event: AgentStreamEvent) => {\n if (event.type === \"llm_start\") {\n llm.calls += 1;\n lastLlmStart = Date.now();\n } else if (event.type === \"llm_end\") {\n if (lastLlmStart > 0) {\n llm.totalDurationMs += Date.now() - lastLlmStart;\n lastLlmStart = 0;\n }\n } else if (event.type === \"response_reset\") {\n llm.resets.push({ reason: event.reason, at: Date.now() });\n } else if (event.type === \"hallucination_detected\") {\n llm.hallucinations.push({ blockType: event.blockType, tool: event.tool, at: Date.now() });\n } else if (event.type === \"negotiation_session_start\") {\n orchestratorNegotiationIds.add(event.opportunityId);\n }\n try {\n writer?.(event);\n } catch {\n /* swallow if writer is gone */\n }\n };\n\n let messages = initialMessages;\n let iterationCount = 0;\n const toolsDebug: DebugMetaToolCall[] = [];\n const surfacedQuestionIds = new Set<string>();\n const hallucinationAutoInvokeCounts = new Map<string, number>();\n\n while (iterationCount < HARD_ITERATION_LIMIT) {\n if (signal?.aborted) {\n logger.verbose(\"Stream aborted by client\", { iterationCount });\n break;\n }\n emit({ type: \"iteration_start\", iteration: iterationCount });\n\n const iterCtx: IterationContext = {\n recentTools: extractRecentToolCalls(messages),\n currentMessage: ChatAgent.getCurrentUserMessage(messages),\n ctx: this.resolvedContext,\n };\n const systemContent = buildSystemContent(this.resolvedContext, iterCtx);\n const fullMessages: BaseMessage[] = [\n new SystemMessage(systemContent),\n ...messages,\n ];\n if (iterationCount >= SOFT_ITERATION_LIMIT) {\n fullMessages.push(new SystemMessage(ITERATION_NUDGE));\n }\n\n logger.verbose(\"Streaming iteration\", {\n iteration: iterationCount,\n messageCount: messages.length,\n pastSoftLimit: iterationCount >= SOFT_ITERATION_LIMIT,\n });\n\n // ── Stream the model response token-by-token ──────────────────────\n emit({ type: \"llm_start\", iteration: iterationCount });\n\n let accumulated: AIMessageChunk | undefined;\n let iterationText = \"\";\n\n try {\n const stream = await this.model.stream(fullMessages, { signal });\n for await (const chunk of stream) {\n // Accumulate using AIMessageChunk.concat() so tool_call_chunks merge and tool_calls is populated\n accumulated = accumulated ? accumulated.concat(chunk) : chunk;\n\n // Emit text content tokens to the user immediately\n const textPart = extractTextFromChunk(chunk);\n if (textPart) {\n emit({ type: \"text_chunk\", content: textPart });\n iterationText += textPart;\n }\n }\n } catch (err) {\n if (err instanceof Error && err.name === \"AbortError\") {\n logger.verbose(\"LLM stream aborted by client\", { iterationCount });\n break; // breaks the outer while loop\n }\n throw err; // re-throw non-abort errors\n }\n\n if (!accumulated) {\n logger.warn(\"Empty model response in streaming iteration\", {\n iterationCount,\n });\n iterationCount++;\n continue;\n }\n\n // ── Check for tool calls ──────────────────────────────────────────\n const toolCalls = accumulated.tool_calls || [];\n\n emit({\n type: \"llm_end\",\n iteration: iterationCount,\n hasToolCalls: toolCalls.length > 0,\n toolNames: toolCalls.length > 0 ? toolCalls.map((tc) => tc.name) : undefined,\n });\n\n if (toolCalls.length > 0) {\n logger.verbose(\"Streaming: agent made tool calls\", {\n iteration: iterationCount,\n tools: toolCalls.map((tc) => tc.name),\n });\n\n // Clear any narration text streamed before tool calls — this text is\n // intermediate reasoning and should not appear in the final response.\n // The next iteration (after tool execution) will produce the real response.\n if (iterationText) {\n emit({ type: \"response_reset\", reason: \"Tool calls detected\" });\n }\n\n // Execute tools one-by-one.\n const toolResults: Array<{\n toolCallId: string;\n name: string;\n result: string;\n }> = [];\n for (const tc of toolCalls) {\n if (signal?.aborted) {\n logger.verbose(\"Stream aborted by client during tool execution\");\n break;\n }\n emit({ type: \"tool_activity\", phase: \"start\", name: tc.name });\n\n const tool = this.toolsByName.get(tc.name);\n if (!tool) {\n const errResult = JSON.stringify({\n success: false,\n error: `Unknown tool: ${tc.name}`,\n });\n toolsDebug.push({\n name: tc.name,\n args: sanitizeForDebugMeta(tc.args) as Record<string, unknown>,\n resultSummary: \"Unknown tool\",\n success: false,\n durationMs: 0,\n });\n emit({\n type: \"tool_activity\",\n phase: \"end\",\n name: tc.name,\n success: false,\n summary: \"Unknown tool\",\n });\n toolResults.push({\n toolCallId: tc.id || `unknown-${Date.now()}`,\n name: tc.name,\n result: errResult,\n });\n continue;\n }\n\n const toolStart = Date.now();\n try {\n logger.verbose(\"Streaming: executing tool\", { name: tc.name });\n const currentCtx = requestContext.getStore() ?? {};\n let result = await requestContext.run(\n {\n ...currentCtx,\n traceEmitter: (e) => emit(e as AgentStreamEvent),\n // Propagate the caller's AbortSignal into requestContext so\n // long-running graph nodes (orchestrator negotiation fan-out)\n // can suppress event emits after the chat session closes.\n ...(signal && { abortSignal: signal }),\n },\n () => tool.invoke(tc.args),\n );\n const toolDurationMs = Date.now() - toolStart;\n let resultStr =\n typeof result === \"string\" ? result : JSON.stringify(result);\n\n const normalized = await this.normalizeToolResult(tc.name, resultStr, tc.args);\n if (normalized.discoveryQuestionsDebug) latestDiscoveryQuestionsDebug = normalized.discoveryQuestionsDebug;\n resultStr = normalized.resultStr;\n result = resultStr;\n\n if (normalized.decisionQuestions && normalized.decisionQuestions.length > 0) {\n const { fresh, newIds } = deduplicateQuestions(normalized.decisionQuestions, surfacedQuestionIds);\n if (fresh.length > 0) {\n emit({ type: \"decision_questions\", questions: fresh });\n for (const id of newIds) surfacedQuestionIds.add(id);\n }\n }\n\n logger.verbose(\"Streaming: tool completed\", {\n name: tc.name,\n resultLength: resultStr.length,\n });\n\n toolsDebug.push({\n name: tc.name,\n args: sanitizeForDebugMeta(tc.args) as Record<string, unknown>,\n resultSummary: normalized.summary,\n success: true,\n durationMs: toolDurationMs,\n ...(normalized.debugSteps?.length ? { steps: normalized.debugSteps } : {}),\n ...(normalized.graphTimings?.length ? { graphs: normalized.graphTimings } : {}),\n });\n emit({\n type: \"tool_activity\",\n phase: \"end\",\n name: tc.name,\n success: true,\n summary: normalized.summary,\n steps: normalized.debugSteps,\n });\n\n toolResults.push({\n toolCallId: tc.id || `${tc.name}-${Date.now()}`,\n name: tc.name,\n result: resultStr,\n });\n } catch (error) {\n const errMsg =\n error instanceof Error ? error.message : \"Unknown error\";\n logger.error(\"Streaming: tool failed\", {\n name: tc.name,\n error: errMsg,\n });\n toolsDebug.push({\n name: tc.name,\n args: sanitizeForDebugMeta(tc.args) as Record<string, unknown>,\n resultSummary: errMsg,\n success: false,\n durationMs: Date.now() - toolStart,\n });\n emit({\n type: \"tool_activity\",\n phase: \"end\",\n name: tc.name,\n success: false,\n summary: errMsg,\n });\n toolResults.push({\n toolCallId: tc.id || `${tc.name}-${Date.now()}`,\n name: tc.name,\n result: JSON.stringify({\n success: false,\n error: `Tool execution failed: ${errMsg}`,\n }),\n });\n }\n }\n\n // If aborted during tool execution, discard partial results\n if (signal?.aborted) {\n logger.verbose(\"Stream aborted after partial tool execution, discarding results\");\n break; // break outer while loop — don't append partial toolResults to messages\n }\n\n // Build updated messages and loop\n messages = [\n ...messages,\n accumulated, // AIMessage with tool_calls\n ...toolResults.map(\n (tr) =>\n new ToolMessage({\n tool_call_id: tr.toolCallId,\n content: tr.result,\n name: tr.name,\n }),\n ),\n ];\n iterationCount++;\n continue;\n }\n\n // ── No tool calls → check for hallucinated code blocks ──────────\n // LLMs sometimes write ```intent_proposal or ```opportunity blocks\n // directly instead of calling the corresponding tool. These blocks\n // lack valid proposalIds / data and won't work in the frontend.\n // Auto-invoke the correct tool directly instead of re-asking the LLM.\n const hallucinatedBlock = this.detectHallucinatedBlock(iterationText, toolsDebug, iterCtx.currentMessage);\n const priorAutoInvokes = hallucinatedBlock ? (hallucinationAutoInvokeCounts.get(hallucinatedBlock.type) ?? 0) : 0;\n if (hallucinatedBlock && priorAutoInvokes < 2 && iterationCount < HARD_ITERATION_LIMIT - 1) {\n hallucinationAutoInvokeCounts.set(hallucinatedBlock.type, priorAutoInvokes + 1);\n logger.warn(\"Streaming: detected hallucinated block, auto-invoking tool\", {\n iteration: iterationCount,\n blockType: hallucinatedBlock.type,\n tool: hallucinatedBlock.tool,\n extractedDescription: hallucinatedBlock.description,\n autoInvokeAttempt: priorAutoInvokes + 1,\n });\n // Tell the frontend to discard all streamed tokens from this iteration\n emit({ type: \"response_reset\", reason: `Hallucinated ${hallucinatedBlock.type} block detected` });\n emit({ type: \"hallucination_detected\", blockType: hallucinatedBlock.type, tool: hallucinatedBlock.tool });\n\n const tool = this.toolsByName.get(hallucinatedBlock.tool);\n if (tool) {\n const toolCallId = `auto-${hallucinatedBlock.tool}-${Date.now()}`;\n const toolArgs = hallucinatedBlock.type === \"opportunity\"\n ? { searchQuery: hallucinatedBlock.description }\n : { description: hallucinatedBlock.description };\n\n emit({ type: \"tool_activity\", phase: \"start\", name: hallucinatedBlock.tool });\n const toolStart = Date.now();\n try {\n const currentCtx = requestContext.getStore() ?? {};\n const result = await requestContext.run(\n {\n ...currentCtx,\n traceEmitter: (e) => emit(e as AgentStreamEvent),\n // Propagate the caller's AbortSignal into requestContext so\n // long-running graph nodes (orchestrator negotiation fan-out)\n // can suppress event emits after the chat session closes.\n ...(signal && { abortSignal: signal }),\n },\n () => tool.invoke(toolArgs),\n );\n const rawResultStr = typeof result === \"string\" ? result : JSON.stringify(result);\n const toolDurationMs = Date.now() - toolStart;\n\n // Same normalization as the main tool loop: callback + _graphTimings strip\n const normalized = await this.normalizeToolResult(hallucinatedBlock.tool, rawResultStr, toolArgs);\n\n toolsDebug.push({\n name: hallucinatedBlock.tool,\n args: sanitizeForDebugMeta(toolArgs) as Record<string, unknown>,\n resultSummary: normalized.summary,\n success: true,\n durationMs: toolDurationMs,\n ...(normalized.debugSteps?.length ? { steps: normalized.debugSteps } : {}),\n ...(normalized.graphTimings?.length ? { graphs: normalized.graphTimings } : {}),\n });\n // Mirror the main tool loop's handling: forward decision questions\n // and capture debug metadata even when the discovery tool was invoked\n // via the hallucination-recovery path.\n if (normalized.discoveryQuestionsDebug) {\n latestDiscoveryQuestionsDebug = normalized.discoveryQuestionsDebug;\n }\n if (normalized.decisionQuestions && normalized.decisionQuestions.length > 0) {\n const { fresh: freshHallucination, newIds: newIdsHallucination } = deduplicateQuestions(normalized.decisionQuestions, surfacedQuestionIds);\n if (freshHallucination.length > 0) {\n emit({ type: \"decision_questions\", questions: freshHallucination });\n for (const id of newIdsHallucination) surfacedQuestionIds.add(id);\n }\n }\n emit({\n type: \"tool_activity\",\n phase: \"end\",\n name: hallucinatedBlock.tool,\n success: true,\n summary: normalized.summary,\n steps: normalized.debugSteps,\n });\n\n // Build synthetic tool call message + tool result so the next LLM\n // iteration can narrate around real data instead of hallucinated blocks.\n const syntheticAIMessage = new AIMessage({\n content: \"\",\n tool_calls: [{ id: toolCallId, name: hallucinatedBlock.tool, args: toolArgs }],\n });\n messages = [\n ...messages,\n syntheticAIMessage,\n new ToolMessage({ tool_call_id: toolCallId, content: normalized.resultStr, name: hallucinatedBlock.tool }),\n ];\n } catch (error) {\n const errMsg = error instanceof Error ? error.message : \"Unknown error\";\n logger.error(\"Streaming: auto-invoked tool failed after hallucination\", {\n tool: hallucinatedBlock.tool,\n error: errMsg,\n });\n toolsDebug.push({\n name: hallucinatedBlock.tool,\n args: sanitizeForDebugMeta(toolArgs) as Record<string, unknown>,\n resultSummary: errMsg,\n success: false,\n durationMs: Date.now() - toolStart,\n });\n emit({ type: \"tool_activity\", phase: \"end\", name: hallucinatedBlock.tool, success: false, summary: errMsg });\n\n // Fall back to correction message if tool invocation fails\n messages = [\n ...messages,\n accumulated,\n new SystemMessage(\n `CORRECTION: You wrote a \\`\\`\\`${hallucinatedBlock.type} block without calling ${hallucinatedBlock.tool}. ` +\n `The auto-retry failed (${errMsg}). Please try calling the tool directly.`\n ),\n ];\n }\n } else {\n // Tool not found — fall back to correction message\n messages = [\n ...messages,\n accumulated,\n new SystemMessage(\n `CORRECTION: You wrote a \\`\\`\\`${hallucinatedBlock.type} block without calling ${hallucinatedBlock.tool}. ` +\n `That block is INVALID. Call the tool directly instead.`\n ),\n ];\n }\n iterationCount++;\n continue;\n }\n\n // ── Circuit breaker: hallucination detected but auto-invoke cap reached ──\n if (hallucinatedBlock && priorAutoInvokes >= 2) {\n logger.warn(\"Streaming: hallucination auto-invoke cap reached, stripping blocks\", {\n iteration: iterationCount,\n blockType: hallucinatedBlock.type,\n attempts: priorAutoInvokes,\n });\n emit({ type: \"response_reset\", reason: `Hallucination cap reached for ${hallucinatedBlock.type}` });\n const stripped = this.stripUnbackedBlocks(iterationText, toolsDebug);\n if (stripped.trim()) {\n emit({ type: \"text_chunk\", content: stripped });\n } else {\n messages = [\n ...messages,\n accumulated,\n new SystemMessage(\n \"Your previous response only contained invalid code blocks that were removed. \" +\n \"Write a plain text response now — summarize the results of the tools you used. \" +\n \"Do NOT include ```opportunity or ```intent_proposal blocks.\",\n ),\n ];\n iterationCount++;\n continue;\n }\n }\n\n // ── Phantom write: model claims a write action without calling any tools ──\n if (\n ChatAgent.detectPhantomWrite(iterationText, toolsDebug) &&\n iterationCount < HARD_ITERATION_LIMIT - 1\n ) {\n logger.warn(\"Streaming: detected phantom write claim without tool calls\", {\n iteration: iterationCount,\n });\n emit({ type: \"response_reset\", reason: \"Phantom write detected — no tools were called\" });\n emit({ type: \"hallucination_detected\", blockType: \"phantom_write\", tool: \"none\" });\n\n messages = [\n ...messages,\n accumulated,\n new SystemMessage(\n \"CORRECTION: You claimed to have performed an action (update, create, modify) but you did NOT call any tools. \" +\n \"The user's request has NOT been fulfilled. You MUST call the appropriate tool(s) to actually make the change, \" +\n \"then confirm based on the tool result. Do it now.\",\n ),\n ];\n iterationCount++;\n continue;\n }\n\n // ── Final response already streamed ─────────────────────────────\n // Defense-in-depth: strip any code blocks that require tool backing\n // but slipped through without a successful tool call.\n const sanitizedText = this.stripUnbackedBlocks(iterationText, toolsDebug);\n if (sanitizedText !== iterationText) {\n logger.warn(\"Streaming: stripped unbacked code blocks from final response\", {\n originalLength: iterationText.length,\n sanitizedLength: sanitizedText.length,\n });\n emit({ type: \"response_reset\", reason: \"Sanitized unbacked blocks from response\" });\n // Re-emit the sanitized text so the frontend displays clean content\n if (sanitizedText.trim()) {\n emit({ type: \"text_chunk\", content: sanitizedText });\n }\n\n // If stripping removed ALL content, force a recovery iteration so the\n // user sees an actual response instead of a blank message.\n if (!sanitizedText.trim() && iterationCount < HARD_ITERATION_LIMIT - 1) {\n logger.warn(\"Streaming: sanitized text is empty, forcing recovery iteration\", {\n iteration: iterationCount,\n });\n messages = [\n ...messages,\n accumulated,\n new SystemMessage(\n \"Your previous response only contained invalid code blocks that were removed. \" +\n \"Write a plain text response now — summarize the results of the tools you used. \" +\n \"Do NOT include ```opportunity or ```intent_proposal blocks.\",\n ),\n ];\n iterationCount++;\n continue;\n }\n }\n\n logger.verbose(\"Streaming: agent produced response\", {\n iteration: iterationCount,\n responseLength: sanitizedText.length,\n });\n messages = [...messages, accumulated];\n iterationCount++;\n\n return {\n responseText: sanitizedText,\n messages,\n iterationCount,\n debugMeta: {\n graph: \"agent_loop\",\n iterations: iterationCount,\n tools: toolsDebug,\n llm,\n ...(orchestratorNegotiationIds.size > 0 && {\n orchestratorNegotiations: { opportunityIds: [...orchestratorNegotiationIds] },\n }),\n ...(latestDiscoveryQuestionsDebug && { discoveryQuestions: latestDiscoveryQuestionsDebug }),\n },\n };\n }\n\n // If aborted, return immediately without making another LLM call\n if (signal?.aborted) {\n return {\n responseText: \"\",\n messages,\n iterationCount,\n debugMeta: {\n graph: \"agent_loop\",\n iterations: iterationCount,\n tools: toolsDebug,\n llm,\n ...(orchestratorNegotiationIds.size > 0 && {\n orchestratorNegotiations: { opportunityIds: [...orchestratorNegotiationIds] },\n }),\n ...(latestDiscoveryQuestionsDebug && { discoveryQuestions: latestDiscoveryQuestionsDebug }),\n },\n };\n }\n\n // ── Hard limit: force a response ──────────────────────────────────────\n logger.warn(\"Streaming: hit hard iteration limit\", { iterationCount });\n\n const forceMessages = [\n ...messages,\n new SystemMessage(\n \"You have reached the maximum number of tool calls. You MUST provide a final response now. Summarize what you've accomplished and what might still be needed.\",\n ),\n ];\n\n let forcedAccumulated: AIMessageChunk | undefined;\n let forcedResponseText = \"\";\n const forceStream = await this.model.stream(forceMessages);\n for await (const chunk of forceStream) {\n forcedAccumulated = forcedAccumulated\n ? forcedAccumulated.concat(chunk)\n : chunk;\n const textPart = extractTextFromChunk(chunk);\n if (textPart) {\n emit({ type: \"text_chunk\", content: textPart });\n forcedResponseText += textPart;\n }\n }\n\n return {\n responseText: forcedResponseText,\n messages: [\n ...messages,\n ...(forcedAccumulated ? [forcedAccumulated] : []),\n ],\n iterationCount,\n debugMeta: {\n graph: \"agent_loop\",\n iterations: iterationCount,\n tools: toolsDebug,\n llm,\n ...(orchestratorNegotiationIds.size > 0 && {\n orchestratorNegotiations: { opportunityIds: [...orchestratorNegotiationIds] },\n }),\n ...(latestDiscoveryQuestionsDebug && { discoveryQuestions: latestDiscoveryQuestionsDebug }),\n },\n };\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat.graph.d.ts","sourceRoot":"/","sources":["chat/chat.graph.ts"],"names":[],"mappings":"AAAA,OAAO,EAA0B,mBAAmB,EAAgC,MAAM,sBAAsB,CAAC;AACjH,OAAO,EAAE,WAAW,EAAgB,MAAM,0BAA0B,CAAC;AAGrE,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,4CAA4C,CAAC;AAC7F,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,4CAA4C,CAAC;AAC3E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,2CAA2C,CAAC;AAEzE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,gDAAgD,CAAC;AACxF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AA2BpE;;;;;;;;;;;;;;GAcG;AACH,qBAAa,gBAAgB;IAIzB,OAAO,CAAC,QAAQ;IAChB,OAAO,CAAC,QAAQ;IAChB,OAAO,CAAC,OAAO;IACf,OAAO,CAAC,WAAW;IACnB,OAAO,CAAC,YAAY;IAPtB,OAAO,CAAC,gBAAgB,CAAe;gBAG7B,QAAQ,EAAE,0BAA0B,EACpC,QAAQ,EAAE,QAAQ,EAClB,OAAO,EAAE,OAAO,EAChB,WAAW,EAAE,iBA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C;QAAC,QAAQ,EAAE,WAAW,EAAE,CAAA;KAAE,EAClD,SAAS,EAAE,MAAM,EACjB,YAAY,CAAC,EAAE,mBAAmB,EAClC,MAAM,CAAC,EAAE,WAAW;IAKtB;;;OAGG;IACH,OAAO,CAAC,UAAU;CA4InB"}
|
package/dist/chat/chat.graph.js
CHANGED
|
@@ -84,18 +84,9 @@ export class ChatGraphFactory {
|
|
|
84
84
|
logger.verbose("No previous messages found", { sessionId });
|
|
85
85
|
return [];
|
|
86
86
|
}
|
|
87
|
-
// Convert database messages to LangChain format
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
return new HumanMessage(msg.content);
|
|
91
|
-
}
|
|
92
|
-
else if (msg.role === "assistant") {
|
|
93
|
-
return new HumanMessage(msg.content); // Using HumanMessage to avoid circular dependency
|
|
94
|
-
}
|
|
95
|
-
else {
|
|
96
|
-
return new HumanMessage(msg.content);
|
|
97
|
-
}
|
|
98
|
-
});
|
|
87
|
+
// Convert database messages to LangChain format.
|
|
88
|
+
// All roles map to HumanMessage to avoid circular dependency.
|
|
89
|
+
const langchainMessages = messages.map((msg) => new HumanMessage(msg.content));
|
|
99
90
|
// Truncate to fit within token limits
|
|
100
91
|
const truncatedMessages = truncateToTokenLimit(langchainMessages, MAX_CONTEXT_TOKENS);
|
|
101
92
|
logger.verbose("Context loaded", {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat.graph.js","sourceRoot":"/","sources":["chat/chat.graph.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,GAAG,EAAqD,MAAM,sBAAsB,CAAC;AACjH,OAAO,EAAe,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACrE,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAI5C,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAG5E,OAAO,EAAE,oBA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AC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;qBAC9D,CAAC,CAAC;oBAEH,OAAO;wBACL,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,mBAAmB;wBACnE,YAAY,EAAE,oFAAoF;wBAClG,cAAc,EAAE,KAAK;qBACtB,CAAC;gBACJ,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC,CAAC;QAEF,4EAA4E;QAC5E,iBAAiB;QACjB,4EAA4E;QAE5E,MAAM,QAAQ,GAAG,IAAI,UAAU,CAAC,cAAc,CAAC;aAC5C,OAAO,CAAC,YAAY,EAAE,aAAa,CAAC;aACpC,OAAO,CAAC,KAAK,EAAE,YAAY,CAAC;aAC5B,OAAO,CAAC,YAAY,EAAE,GAAG,CAAC,CAAC;QAE9B,MAAM,CAAC,OAAO,CAAC,oDAAoD,CAAC,CAAC;QACrE,OAAO,QAAQ,CAAC;IAClB,CAAC;CACF","sourcesContent":["import { StateGraph, START, END, BaseCheckpointSaver, type LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { BaseMessage, HumanMessage } from \"@langchain/core/messages\";\nimport { ChatGraphState } from \"./chat.state.js\";\nimport { ChatAgent } from \"./chat.agent.js\";\nimport type { ChatGraphCompositeDatabase } from \"../shared/interfaces/database.interface.js\";\nimport type { Embedder } from \"../shared/interfaces/embedder.interface.js\";\nimport type { Scraper } from \"../shared/interfaces/scraper.interface.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport type { ChatSessionReader } from \"../shared/interfaces/chat-session.interface.js\";\nimport type { ProtocolDeps } from \"../shared/agent/tool.helpers.js\";\nimport { truncateToTokenLimit, MAX_CONTEXT_TOKENS } from \"./chat.utils.js\";\nimport { ChatStreamer } from \"./chat.streamer.js\";\nimport { timed } from \"../shared/observability/performance.js\";\n\nconst logger = protocolLogger(\"ChatGraphFactory\");\n\nfunction isRetriableError(err: unknown): boolean {\n const status =\n (err as { status?: number }).status ?? (err as { statusCode?: number }).statusCode;\n if (typeof status === \"number\" && status >= 500 && status <= 599) return true;\n const msg = err instanceof Error ? err.message : String(err);\n const lower = msg.toLowerCase();\n return (\n lower.includes(\"internal server error\") ||\n /\\b500\\b|status[: ]*500/i.test(msg) ||\n lower.includes(\"econnreset\") ||\n lower.includes(\"etimedout\")\n );\n}\n\nconst RETRY_DELAY_MS = 800;\n\n// ══════════════════════════════════════════════════════════════════════════════\n// CHAT GRAPH FACTORY (Agent Loop Architecture)\n// ══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Factory class to build and compile the Chat Graph.\n * \n * Architecture: ReAct-Style Agent Loop\n * \n * The graph contains a single node that runs an agent loop:\n * 1. Agent receives messages (conversation + tool results)\n * 2. Agent decides: call tools OR respond to user\n * 3. If tools called → execute → add results → loop back\n * 4. If response → exit loop → stream to user\n * \n * This replaces the previous 17-node conditional routing architecture\n * with a flexible, LLM-driven approach that can handle multi-step\n * reasoning and self-correction.\n */\nexport class ChatGraphFactory {\n private streamingService: ChatStreamer;\n\n constructor(\n private database: ChatGraphCompositeDatabase,\n private embedder: Embedder,\n private scraper: Scraper,\n private chatSession: ChatSessionReader,\n private protocolDeps: ProtocolDeps,\n ) {\n this.streamingService = new ChatStreamer(\n (sessionId, maxMessages) => this.loadSessionContext(sessionId, maxMessages),\n (checkpointer) => this.createStreamingGraph(checkpointer)\n );\n }\n\n /**\n * Creates and compiles the Chat Graph without persistence.\n * @returns Compiled StateGraph ready for invocation\n */\n public createGraph() {\n return this.buildGraph().compile();\n }\n\n /**\n * Creates a streaming-enabled graph with optional checkpointer for persistence.\n * @param checkpointer - Optional checkpointer (e.g., MemorySaver or PostgresSaver)\n * @returns Compiled StateGraph ready for streaming\n */\n public createStreamingGraph(checkpointer?: BaseCheckpointSaver) {\n const graph = this.buildGraph();\n if (checkpointer) {\n return graph.compile({ checkpointer });\n }\n return graph.compile();\n }\n\n /**\n * Load previous messages from a session and convert to LangChain messages.\n * Handles token truncation to fit within context window limits.\n *\n * @param sessionId - The session ID to load context from\n * @param maxMessages - Maximum number of messages to load (default: 20)\n * @returns Array of LangChain BaseMessage objects\n */\n public async loadSessionContext(\n sessionId: string,\n maxMessages: number = 20\n ): Promise<BaseMessage[]> {\n logger.verbose(\"Loading session context\", {\n sessionId,\n maxMessages,\n });\n\n try {\n const messages = await this.chatSession.getSessionMessages(sessionId, maxMessages);\n\n if (messages.length === 0) {\n logger.verbose(\"No previous messages found\", { sessionId });\n return [];\n }\n\n // Convert database messages to LangChain format\n const langchainMessages = messages.map((msg) => {\n if (msg.role === \"user\") {\n return new HumanMessage(msg.content);\n } else if (msg.role === \"assistant\") {\n return new HumanMessage(msg.content); // Using HumanMessage to avoid circular dependency\n } else {\n return new HumanMessage(msg.content);\n }\n });\n\n // Truncate to fit within token limits\n const truncatedMessages = truncateToTokenLimit(langchainMessages, MAX_CONTEXT_TOKENS);\n\n logger.verbose(\"Context loaded\", {\n sessionId,\n originalCount: messages.length,\n truncatedCount: truncatedMessages.length,\n });\n return truncatedMessages;\n } catch (error) {\n logger.error(\"Failed to load context\", {\n sessionId,\n error: error instanceof Error ? error.message : String(error),\n });\n // Return empty array on error - don't fail the entire request\n return [];\n }\n }\n\n /**\n * Streams chat events with full session context.\n * Delegates to ChatGraphStreamingService.\n */\n public async *streamChatEventsWithContext(\n input: {\n userId: string;\n message: string;\n sessionId: string;\n maxContextMessages?: number;\n networkId?: string;\n prefillMessages?: Array<{ role: \"assistant\" | \"user\"; content: string }>;\n /** Per-run identifier used to form a composite LangGraph thread_id (sessionId:runId). */\n runId?: string;\n },\n checkpointer?: BaseCheckpointSaver,\n signal?: AbortSignal,\n ) {\n yield* this.streamingService.streamChatEventsWithContext(input, checkpointer, signal);\n }\n\n /**\n * Streams chat events from the graph execution.\n * Delegates to ChatGraphStreamingService.\n */\n public async *streamChatEvents(\n input: { userId: string; messages: BaseMessage[] },\n sessionId: string,\n checkpointer?: BaseCheckpointSaver,\n signal?: AbortSignal,\n ) {\n yield* this.streamingService.streamChatEvents(input, sessionId, checkpointer, signal);\n }\n\n /**\n * Internal method to build the graph structure.\n * @returns Uncompiled StateGraph\n */\n private buildGraph() {\n const database = this.database;\n const embedder = this.embedder;\n const scraper = this.scraper;\n const protocolDeps = this.protocolDeps;\n\n // ─────────────────────────────────────────────────────────────────────────\n // AGENT LOOP NODE\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * The main agent loop node.\n * Runs a ReAct-style agent that calls tools until it decides to respond.\n *\n * Uses `agent.streamRun()` + `config.writer` so that text tokens and\n * tool-activity events are pushed into the graph's custom stream in\n * real-time rather than batched at the end.\n */\n const agentLoopNode = async (\n state: typeof ChatGraphState.State,\n config: LangGraphRunnableConfig\n ) => {\n return timed(\"ChatGraph.agentLoop\", async () => {\n logger.verbose(\"Agent loop starting\", {\n userId: state.userId,\n messageCount: state.messages.length,\n currentIteration: state.iterationCount\n });\n\n const runLoop = async () => {\n const networkId = state.networkId;\n const agent = await ChatAgent.create({\n ...protocolDeps,\n userId: state.userId,\n database,\n embedder,\n scraper,\n networkId,\n sessionId: state.sessionId,\n } as import(\"../shared/agent/tool.helpers.js\").ToolContext);\n // Direct streaming writer - emit events immediately instead of buffering\n const directWriter = (data: unknown) => {\n try {\n config.writer?.(data);\n } catch {\n /* swallow if writer is gone */\n }\n };\n // Get signal from configurable (passed by streamer via graph.stream() config)\n const signal = config.configurable?.signal as AbortSignal | undefined;\n const result = await agent.streamRun(state.messages, directWriter, signal);\n return result;\n };\n\n try {\n const result = await runLoop();\n logger.debug(\"Agent streamRun result\", {\n responseText: result.responseText,\n iterationCount: result.iterationCount,\n messageCount: result.messages.length,\n });\n logger.verbose(\"Agent loop complete\", {\n userId: state.userId,\n iterations: result.iterationCount,\n responseLength: result.responseText.length\n });\n return {\n messages: result.messages,\n responseText: result.responseText,\n iterationCount: result.iterationCount,\n shouldContinue: false,\n debugMeta: result.debugMeta,\n };\n } catch (error) {\n if (isRetriableError(error)) {\n const signal = config.configurable?.signal as AbortSignal | undefined;\n if (signal?.aborted) {\n return {\n error: \"Request aborted\",\n responseText: \"\",\n shouldContinue: false,\n };\n }\n logger.warn(\"Agent loop failed with retriable error, retrying once\", {\n userId: state.userId,\n error: error instanceof Error ? error.message : String(error)\n });\n await new Promise((r) => setTimeout(r, RETRY_DELAY_MS));\n try {\n const result = await runLoop();\n logger.verbose(\"Agent loop complete after retry\", {\n userId: state.userId,\n iterations: result.iterationCount,\n });\n return {\n messages: result.messages,\n responseText: result.responseText,\n iterationCount: result.iterationCount,\n shouldContinue: false,\n debugMeta: result.debugMeta,\n };\n } catch (retryError) {\n logger.error(\"Agent loop failed on retry\", {\n userId: state.userId,\n error: retryError instanceof Error ? retryError.message : String(retryError)\n });\n return {\n error: retryError instanceof Error ? retryError.message : \"Agent loop failed\",\n responseText: \"I apologize, but I encountered an issue processing your request. Please try again.\",\n shouldContinue: false\n };\n }\n }\n\n logger.error(\"Agent loop failed\", {\n userId: state.userId,\n error: error instanceof Error ? error.message : String(error)\n });\n\n return {\n error: error instanceof Error ? error.message : \"Agent loop failed\",\n responseText: \"I apologize, but I encountered an issue processing your request. Please try again.\",\n shouldContinue: false\n };\n }\n });\n };\n\n // ─────────────────────────────────────────────────────────────────────────\n // GRAPH ASSEMBLY\n // ─────────────────────────────────────────────────────────────────────────\n\n const workflow = new StateGraph(ChatGraphState)\n .addNode(\"agent_loop\", agentLoopNode)\n .addEdge(START, \"agent_loop\")\n .addEdge(\"agent_loop\", END);\n\n logger.verbose(\"Graph built successfully (agent loop architecture)\");\n return workflow;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"chat.graph.js","sourceRoot":"/","sources":["chat/chat.graph.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,GAAG,EAAqD,MAAM,sBAAsB,CAAC;AACjH,OAAO,EAAe,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACrE,OAAO,EAAE,cA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AK,CAAC,OAAO,CAAC,CAAC,CAAC,mBAAmB;wBACnE,YAAY,EAAE,oFAAoF;wBAClG,cAAc,EAAE,KAAK;qBACtB,CAAC;gBACJ,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC,CAAC;QAEF,4EAA4E;QAC5E,iBAAiB;QACjB,4EAA4E;QAE5E,MAAM,QAAQ,GAAG,IAAI,UAAU,CAAC,cAAc,CAAC;aAC5C,OAAO,CAAC,YAAY,EAAE,aAAa,CAAC;aACpC,OAAO,CAAC,KAAK,EAAE,YAAY,CAAC;aAC5B,OAAO,CAAC,YAAY,EAAE,GAAG,CAAC,CAAC;QAE9B,MAAM,CAAC,OAAO,CAAC,oDAAoD,CAAC,CAAC;QACrE,OAAO,QAAQ,CAAC;IAClB,CAAC;CACF","sourcesContent":["import { StateGraph, START, END, BaseCheckpointSaver, type LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { BaseMessage, HumanMessage } from \"@langchain/core/messages\";\nimport { ChatGraphState } from \"./chat.state.js\";\nimport { ChatAgent } from \"./chat.agent.js\";\nimport type { ChatGraphCompositeDatabase } from \"../shared/interfaces/database.interface.js\";\nimport type { Embedder } from \"../shared/interfaces/embedder.interface.js\";\nimport type { Scraper } from \"../shared/interfaces/scraper.interface.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport type { ChatSessionReader } from \"../shared/interfaces/chat-session.interface.js\";\nimport type { ProtocolDeps } from \"../shared/agent/tool.helpers.js\";\nimport { truncateToTokenLimit, MAX_CONTEXT_TOKENS } from \"./chat.utils.js\";\nimport { ChatStreamer } from \"./chat.streamer.js\";\nimport { timed } from \"../shared/observability/performance.js\";\n\nconst logger = protocolLogger(\"ChatGraphFactory\");\n\nfunction isRetriableError(err: unknown): boolean {\n const status =\n (err as { status?: number }).status ?? (err as { statusCode?: number }).statusCode;\n if (typeof status === \"number\" && status >= 500 && status <= 599) return true;\n const msg = err instanceof Error ? err.message : String(err);\n const lower = msg.toLowerCase();\n return (\n lower.includes(\"internal server error\") ||\n /\\b500\\b|status[: ]*500/i.test(msg) ||\n lower.includes(\"econnreset\") ||\n lower.includes(\"etimedout\")\n );\n}\n\nconst RETRY_DELAY_MS = 800;\n\n// ══════════════════════════════════════════════════════════════════════════════\n// CHAT GRAPH FACTORY (Agent Loop Architecture)\n// ══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Factory class to build and compile the Chat Graph.\n * \n * Architecture: ReAct-Style Agent Loop\n * \n * The graph contains a single node that runs an agent loop:\n * 1. Agent receives messages (conversation + tool results)\n * 2. Agent decides: call tools OR respond to user\n * 3. If tools called → execute → add results → loop back\n * 4. If response → exit loop → stream to user\n * \n * This replaces the previous 17-node conditional routing architecture\n * with a flexible, LLM-driven approach that can handle multi-step\n * reasoning and self-correction.\n */\nexport class ChatGraphFactory {\n private streamingService: ChatStreamer;\n\n constructor(\n private database: ChatGraphCompositeDatabase,\n private embedder: Embedder,\n private scraper: Scraper,\n private chatSession: ChatSessionReader,\n private protocolDeps: ProtocolDeps,\n ) {\n this.streamingService = new ChatStreamer(\n (sessionId, maxMessages) => this.loadSessionContext(sessionId, maxMessages),\n (checkpointer) => this.createStreamingGraph(checkpointer)\n );\n }\n\n /**\n * Creates and compiles the Chat Graph without persistence.\n * @returns Compiled StateGraph ready for invocation\n */\n public createGraph() {\n return this.buildGraph().compile();\n }\n\n /**\n * Creates a streaming-enabled graph with optional checkpointer for persistence.\n * @param checkpointer - Optional checkpointer (e.g., MemorySaver or PostgresSaver)\n * @returns Compiled StateGraph ready for streaming\n */\n public createStreamingGraph(checkpointer?: BaseCheckpointSaver) {\n const graph = this.buildGraph();\n if (checkpointer) {\n return graph.compile({ checkpointer });\n }\n return graph.compile();\n }\n\n /**\n * Load previous messages from a session and convert to LangChain messages.\n * Handles token truncation to fit within context window limits.\n *\n * @param sessionId - The session ID to load context from\n * @param maxMessages - Maximum number of messages to load (default: 20)\n * @returns Array of LangChain BaseMessage objects\n */\n public async loadSessionContext(\n sessionId: string,\n maxMessages: number = 20\n ): Promise<BaseMessage[]> {\n logger.verbose(\"Loading session context\", {\n sessionId,\n maxMessages,\n });\n\n try {\n const messages = await this.chatSession.getSessionMessages(sessionId, maxMessages);\n\n if (messages.length === 0) {\n logger.verbose(\"No previous messages found\", { sessionId });\n return [];\n }\n\n // Convert database messages to LangChain format.\n // All roles map to HumanMessage to avoid circular dependency.\n const langchainMessages = messages.map((msg) => new HumanMessage(msg.content));\n\n // Truncate to fit within token limits\n const truncatedMessages = truncateToTokenLimit(langchainMessages, MAX_CONTEXT_TOKENS);\n\n logger.verbose(\"Context loaded\", {\n sessionId,\n originalCount: messages.length,\n truncatedCount: truncatedMessages.length,\n });\n return truncatedMessages;\n } catch (error) {\n logger.error(\"Failed to load context\", {\n sessionId,\n error: error instanceof Error ? error.message : String(error),\n });\n // Return empty array on error - don't fail the entire request\n return [];\n }\n }\n\n /**\n * Streams chat events with full session context.\n * Delegates to ChatGraphStreamingService.\n */\n public async *streamChatEventsWithContext(\n input: {\n userId: string;\n message: string;\n sessionId: string;\n maxContextMessages?: number;\n networkId?: string;\n prefillMessages?: Array<{ role: \"assistant\" | \"user\"; content: string }>;\n /** Per-run identifier used to form a composite LangGraph thread_id (sessionId:runId). */\n runId?: string;\n },\n checkpointer?: BaseCheckpointSaver,\n signal?: AbortSignal,\n ) {\n yield* this.streamingService.streamChatEventsWithContext(input, checkpointer, signal);\n }\n\n /**\n * Streams chat events from the graph execution.\n * Delegates to ChatGraphStreamingService.\n */\n public async *streamChatEvents(\n input: { userId: string; messages: BaseMessage[] },\n sessionId: string,\n checkpointer?: BaseCheckpointSaver,\n signal?: AbortSignal,\n ) {\n yield* this.streamingService.streamChatEvents(input, sessionId, checkpointer, signal);\n }\n\n /**\n * Internal method to build the graph structure.\n * @returns Uncompiled StateGraph\n */\n private buildGraph() {\n const database = this.database;\n const embedder = this.embedder;\n const scraper = this.scraper;\n const protocolDeps = this.protocolDeps;\n\n // ─────────────────────────────────────────────────────────────────────────\n // AGENT LOOP NODE\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * The main agent loop node.\n * Runs a ReAct-style agent that calls tools until it decides to respond.\n *\n * Uses `agent.streamRun()` + `config.writer` so that text tokens and\n * tool-activity events are pushed into the graph's custom stream in\n * real-time rather than batched at the end.\n */\n const agentLoopNode = async (\n state: typeof ChatGraphState.State,\n config: LangGraphRunnableConfig\n ) => {\n return timed(\"ChatGraph.agentLoop\", async () => {\n logger.verbose(\"Agent loop starting\", {\n userId: state.userId,\n messageCount: state.messages.length,\n currentIteration: state.iterationCount\n });\n\n const runLoop = async () => {\n const networkId = state.networkId;\n const agent = await ChatAgent.create({\n ...protocolDeps,\n userId: state.userId,\n database,\n embedder,\n scraper,\n networkId,\n sessionId: state.sessionId,\n } as import(\"../shared/agent/tool.helpers.js\").ToolContext);\n // Direct streaming writer - emit events immediately instead of buffering\n const directWriter = (data: unknown) => {\n try {\n config.writer?.(data);\n } catch {\n /* swallow if writer is gone */\n }\n };\n // Get signal from configurable (passed by streamer via graph.stream() config)\n const signal = config.configurable?.signal as AbortSignal | undefined;\n const result = await agent.streamRun(state.messages, directWriter, signal);\n return result;\n };\n\n try {\n const result = await runLoop();\n logger.debug(\"Agent streamRun result\", {\n responseText: result.responseText,\n iterationCount: result.iterationCount,\n messageCount: result.messages.length,\n });\n logger.verbose(\"Agent loop complete\", {\n userId: state.userId,\n iterations: result.iterationCount,\n responseLength: result.responseText.length\n });\n return {\n messages: result.messages,\n responseText: result.responseText,\n iterationCount: result.iterationCount,\n shouldContinue: false,\n debugMeta: result.debugMeta,\n };\n } catch (error) {\n if (isRetriableError(error)) {\n const signal = config.configurable?.signal as AbortSignal | undefined;\n if (signal?.aborted) {\n return {\n error: \"Request aborted\",\n responseText: \"\",\n shouldContinue: false,\n };\n }\n logger.warn(\"Agent loop failed with retriable error, retrying once\", {\n userId: state.userId,\n error: error instanceof Error ? error.message : String(error)\n });\n await new Promise((r) => setTimeout(r, RETRY_DELAY_MS));\n try {\n const result = await runLoop();\n logger.verbose(\"Agent loop complete after retry\", {\n userId: state.userId,\n iterations: result.iterationCount,\n });\n return {\n messages: result.messages,\n responseText: result.responseText,\n iterationCount: result.iterationCount,\n shouldContinue: false,\n debugMeta: result.debugMeta,\n };\n } catch (retryError) {\n logger.error(\"Agent loop failed on retry\", {\n userId: state.userId,\n error: retryError instanceof Error ? retryError.message : String(retryError)\n });\n return {\n error: retryError instanceof Error ? retryError.message : \"Agent loop failed\",\n responseText: \"I apologize, but I encountered an issue processing your request. Please try again.\",\n shouldContinue: false\n };\n }\n }\n\n logger.error(\"Agent loop failed\", {\n userId: state.userId,\n error: error instanceof Error ? error.message : String(error)\n });\n\n return {\n error: error instanceof Error ? error.message : \"Agent loop failed\",\n responseText: \"I apologize, but I encountered an issue processing your request. Please try again.\",\n shouldContinue: false\n };\n }\n });\n };\n\n // ─────────────────────────────────────────────────────────────────────────\n // GRAPH ASSEMBLY\n // ─────────────────────────────────────────────────────────────────────────\n\n const workflow = new StateGraph(ChatGraphState)\n .addNode(\"agent_loop\", agentLoopNode)\n .addEdge(START, \"agent_loop\")\n .addEdge(\"agent_loop\", END);\n\n logger.verbose(\"Graph built successfully (agent loop architecture)\");\n return workflow;\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat.interrupt.classifier.d.ts","sourceRoot":"/","sources":["chat/chat.interrupt.classifier.ts"],"names":[],"mappings":"AAkBA,MAAM,WAAW,sBAAsB;IACrC,4DAA4D;IAC5D,OAAO,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,UAAU,EAAE,MAAM,CAAC;CACpB;AAED;;;;GAIG;AACH,qBAAa,uBAAuB;IAClC,OAAO,CAAC,KAAK,CAAa;;IAM1B;;;;;OAKG;IAEG,QAAQ,CAAC,KAAK,EAAE,sBAAsB,GAAG,OAAO,CAAC,OAAO,GAAG,OAAO,CAAC;
|
|
1
|
+
{"version":3,"file":"chat.interrupt.classifier.d.ts","sourceRoot":"/","sources":["chat/chat.interrupt.classifier.ts"],"names":[],"mappings":"AAkBA,MAAM,WAAW,sBAAsB;IACrC,4DAA4D;IAC5D,OAAO,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,UAAU,EAAE,MAAM,CAAC;CACpB;AAED;;;;GAIG;AACH,qBAAa,uBAAuB;IAClC,OAAO,CAAC,KAAK,CAAa;;IAM1B;;;;;OAKG;IAEG,QAAQ,CAAC,KAAK,EAAE,sBAAsB,GAAG,OAAO,CAAC,OAAO,GAAG,OAAO,CAAC;CAuB1E"}
|
|
@@ -42,9 +42,7 @@ export class ChatInterruptClassifier {
|
|
|
42
42
|
new SystemMessage(SYSTEM_PROMPT),
|
|
43
43
|
new HumanMessage(`Current agent activity: ${agentState || "idle"}\n\nNew user message: "${message.slice(0, 500)}"\n\nDecision:`),
|
|
44
44
|
]);
|
|
45
|
-
const text =
|
|
46
|
-
? response.content.trim().toLowerCase()
|
|
47
|
-
: String(response.content ?? "").trim().toLowerCase();
|
|
45
|
+
const text = String(response.content ?? "").trim().toLowerCase();
|
|
48
46
|
if (text.startsWith("queue"))
|
|
49
47
|
return "queue";
|
|
50
48
|
// Default to steer on any ambiguity or unexpected output
|