@indexnetwork/protocol 2.0.1-rc.240.1 → 2.0.1-rc.244.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/README.md +2 -2
- package/dist/chat/chat.agent.d.ts +2 -0
- package/dist/chat/chat.agent.d.ts.map +1 -1
- package/dist/chat/chat.agent.js.map +1 -1
- package/dist/mcp/mcp.server.d.ts.map +1 -1
- package/dist/mcp/mcp.server.js +4 -3
- package/dist/mcp/mcp.server.js.map +1 -1
- package/dist/opportunity/opportunity.graph.d.ts.map +1 -1
- package/dist/opportunity/opportunity.graph.js +6 -0
- package/dist/opportunity/opportunity.graph.js.map +1 -1
- package/dist/shared/observability/request-context.d.ts +2 -0
- package/dist/shared/observability/request-context.d.ts.map +1 -1
- package/dist/shared/observability/request-context.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ npm install @indexnetwork/protocol
|
|
|
14
14
|
|
|
15
15
|
The package reads `OPENROUTER_API_KEY` (required), `CHAT_MODEL`, and `CHAT_REASONING_EFFORT` from environment variables. No startup call is needed.
|
|
16
16
|
|
|
17
|
-
To override the chat model or reasoning effort
|
|
17
|
+
To override the chat model or reasoning effort when using the built-in chat runtime (`ChatGraphFactory` / `ChatAgent`), pass `modelConfig` on `ToolContext`. `ChatAgent` reads these fields when the chat graph runs; the tools themselves do not consume `modelConfig`:
|
|
18
18
|
|
|
19
19
|
```typescript
|
|
20
20
|
import { createChatTools } from "@indexnetwork/protocol";
|
|
@@ -28,7 +28,7 @@ const tools = await createChatTools({
|
|
|
28
28
|
});
|
|
29
29
|
```
|
|
30
30
|
|
|
31
|
-
`apiKey` and `baseURL` can also be overridden
|
|
31
|
+
`apiKey` and `baseURL` can also be overridden this way. All other protocol agents (evaluators, generators, etc.) rely on `OPENROUTER_API_KEY` set in the environment regardless of `modelConfig`.
|
|
32
32
|
|
|
33
33
|
### 2. Implement the adapters
|
|
34
34
|
|
|
@@ -86,6 +86,8 @@ export type AgentStreamEvent = {
|
|
|
86
86
|
type: "opportunity_draft_ready";
|
|
87
87
|
opportunityId: string;
|
|
88
88
|
opportunity: Opportunity;
|
|
89
|
+
/** Viewer-centric summary derived from interpretation.reasoning via viewerCentricCardSummary. */
|
|
90
|
+
personalizedSummary?: string;
|
|
89
91
|
counterparty: {
|
|
90
92
|
userId: string;
|
|
91
93
|
name?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat.agent.d.ts","sourceRoot":"/","sources":["chat/chat.agent.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,WAAW,EAIZ,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAEL,KAAK,WAAW,EAEjB,MAAM,iCAAiC,CAAC;AAWzC,OAAO,KAAK,EAAE,iBAAiB,EAAE,YAAY,EAAE,iCAAiC,EAAE,2BAA2B,EAAE,MAAM,2BAA2B,CAAC;AACjJ,OAAO,KAAK,EAAE,QAAQ,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AACvF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,4CAA4C,CAAC;AAQ9E,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAMnD;;;GAGG;AACH,MAAM,MAAM,YAAY,GAAG,CAAC,IAAI,EAAE,OAAO,KAAK,IAAI,CAAC;AAEnD;;;;;;;;;;;;;;GAcG;AACH,MAAM,MAAM,gBAAgB,GACxB;IAAE,IAAI,EAAE,iBAAiB,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,GAC9C;IAAE,IAAI,EAAE,WAAW,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,GACxC;IAAE,IAAI,EAAE,YAAY,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GACvC;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,OAAO,CAAC;IAAC,SAAS,CAAC,E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QAAQ,EAAE,CAAC;gBACb,IAAI,CAAC,EAAE,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 {\n AIMessage,\n BaseMessage,\n SystemMessage,\n ToolMessage,\n AIMessageChunk,\n} from \"@langchain/core/messages\";\nimport {\n createChatTools,\n type ToolContext,\n type ResolvedToolContext,\n} from \"../shared/agent/tool.factory.js\";\nimport { resolveChatContext } from \"../shared/agent/tool.helpers.js\";\nimport { ITERATION_NUDGE, buildSystemContent } from \"./chat.prompt.js\";\nimport {\n extractRecentToolCalls,\n type IterationContext,\n} 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 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/chat.agent.ts"],"names":[],"mappings":";;;;;;;;;AACA,OAAO,EACL,SAAS,EAET,aAAa,EACb,WAAW,GAEZ,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,eAAe,GAGhB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AACrE,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AACvE,OAAO,EACL,sBAAsB,GAEvB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,WAAW,EAAoB,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AACxE,OAAO,EAAE,oBAAoB,EAAE,MAAM,iDAAiD,CAAC;AAIvF,OAAO,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAC/D,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAEhE,MAAM,MAAM,GAAG,cAAc,CAAC,WAAW,CAAC,CAAC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AAoE;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 {\n AIMessage,\n BaseMessage,\n SystemMessage,\n ToolMessage,\n AIMessageChunk,\n} from \"@langchain/core/messages\";\nimport {\n createChatTools,\n type ToolContext,\n type ResolvedToolContext,\n} from \"../shared/agent/tool.factory.js\";\nimport { resolveChatContext } from \"../shared/agent/tool.helpers.js\";\nimport { ITERATION_NUDGE, buildSystemContent } from \"./chat.prompt.js\";\nimport {\n extractRecentToolCalls,\n type IterationContext,\n} 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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp.server.d.ts","sourceRoot":"/","sources":["mcp/mcp.server.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAE,SAAS,EAAkB,MAAM,8BAA8B,CAAC;AAGzE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wCAAwC,CAAC;AAC9E,OAAO,KAAK,EAAE,QAAQ,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAA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,GAAG,SAAS,KACxC,MAAM,EAOR,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,0BAA0B,GACrC,SAAS,mBAAmB,EAC5B,gBAAgB,MAAM,GAAG,IAAI,GAAG,SAAS,KACxC,IAyBF,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,kBAAkB,EAAE,WAAW,CAAC,MAAM,CAiBjD,CAAC;AAEH;;;;GAIG;AACH,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,mBAAmB,GAAG,MAAM,CAyB1E;AAwCD,eAAO,MAAM,gBAAgB,QAsDrB,CAAC;AAET,wBAAgB,eAAe,CAC7B,IAAI,EAAE,QAAQ,EACd,YAAY,EAAE,eAAe,EAC7B,iBAAiB,EAAE,iBAAiB,GACnC,SAAS,CAqQX"}
|
package/dist/mcp/mcp.server.js
CHANGED
|
@@ -436,9 +436,10 @@ export function createMcpServer(deps, authResolver, scopedDepsFactory) {
|
|
|
436
436
|
type: 'text',
|
|
437
437
|
text: JSON.stringify({
|
|
438
438
|
error: 'Rate limit exceeded',
|
|
439
|
-
message: `Too many ${toolName} calls in a short period. Wait ${retryAfterSec}s before retrying
|
|
440
|
-
|
|
441
|
-
|
|
439
|
+
message: `Too many ${toolName} calls in a short period. Wait ${retryAfterSec}s before retrying.` +
|
|
440
|
+
(toolName === 'discover_opportunities'
|
|
441
|
+
? ` If a discovery run is in progress, poll get_discovery_run instead of calling discover_opportunities again.`
|
|
442
|
+
: ''),
|
|
442
443
|
retryAfterSec,
|
|
443
444
|
}),
|
|
444
445
|
}],
|