@indexnetwork/protocol 1.26.9-rc.237.1 → 2.0.0-rc.238.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 CHANGED
@@ -12,18 +12,24 @@ npm install @indexnetwork/protocol
12
12
 
13
13
  ### 1. Configure the LLM
14
14
 
15
- Call `configureProtocol` once at startup before creating any tools or graphs:
15
+ The package reads `OPENROUTER_API_KEY` (required), `CHAT_MODEL`, and `CHAT_REASONING_EFFORT` from environment variables. No startup call is needed.
16
+
17
+ To override the chat model or reasoning effort per request, set `modelConfig` on `ToolContext`:
16
18
 
17
19
  ```typescript
18
- import { configureProtocol } from "@indexnetwork/protocol";
20
+ import { createChatTools } from "@indexnetwork/protocol";
19
21
 
20
- configureProtocol({
21
- apiKey: process.env.OPENROUTER_API_KEY,
22
- chatModel: "google/gemini-2.5-flash", // optional — has a default
23
- chatReasoningEffort: "low", // optional: minimal | low | medium | high | xhigh
22
+ const tools = await createChatTools({
23
+ // ... other deps ...
24
+ modelConfig: {
25
+ chatModel: "google/gemini-2.5-flash", // optional has a default
26
+ chatReasoningEffort: "low", // optional: minimal | low | medium | high | xhigh
27
+ },
24
28
  });
25
29
  ```
26
30
 
31
+ `apiKey` and `baseURL` can also be overridden. Note: `modelConfig` is only honored by `ChatAgent` — it reads all `ModelConfig` fields (`apiKey`, `baseURL`, `chatModel`, `chatReasoningEffort`) from `ToolContext` when the chat graph runs. All other protocol agents (evaluators, generators, etc.) rely on `OPENROUTER_API_KEY` set in the environment.
32
+
27
33
  ### 2. Implement the adapters
28
34
 
29
35
  The package defines interfaces — your application provides the concrete implementations:
@@ -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,OA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AAC,eAAe,EAAE,WAAW,EAAE,GAAG,OAAO,CAAC;QACjD,YAAY,EAAE,MAAM,CAAC;QACrB,QAAQ,EAAE,WAAW,EAAE,CAAC;QACxB,cAAc,EAAE,MAAM,CAAC;KACxB,CAAC;IAiDF;;;;;;;;;;;OAWG;IAEG,SAAS,CACb,eAAe,EAAE,WAAW,EAAE,EAC9B,MAAM,CAAC,EAAE,YAAY,EACrB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC;QACT,YAAY,EAAE,MAAM,CAAC;QACrB,QAAQ,EAAE,WAAW,EAAE,CAAC;QACxB,cAAc,EAAE,MAAM,CAAC;QACvB,SAAS,EAAE;YAAE,KAAK,EAAE,MAAM,CAAC;YAAC,UAAU,EAAE,MAAM,CAAC;YAAC,KAAK,EAAE,iBAAiB,EAAE,CAAC;YAAC,GAAG,EAAE,YAAY,CAAC;YAAC,wBAAwB,CAAC,EAAE,iCAAiC,CAAC;YAAC,kBAAkB,CAAC,EAAE,2BAA2B,CAAA;SAAE,CAAC;KACjN,CAAC;CAikBH"}
@@ -69,9 +69,9 @@ export class ChatAgent {
69
69
  /**
70
70
  * Private constructor — use `ChatAgent.create()` instead.
71
71
  */
72
- constructor(resolvedContext, tools) {
72
+ constructor(resolvedContext, tools, modelConfig) {
73
73
  this.resolvedContext = resolvedContext;
74
- this.model = createModel("chat");
74
+ this.model = createModel("chat", modelConfig);
75
75
  // Store tools and index by name
76
76
  this.tools = tools;
77
77
  this.toolsByName = new Map();
@@ -105,7 +105,7 @@ export class ChatAgent {
105
105
  sessionId: context.sessionId,
106
106
  });
107
107
  const tools = await createChatTools(context, resolved);
108
- return new ChatAgent(resolved, tools);
108
+ return new ChatAgent(resolved, tools, context.modelConfig);
109
109
  }
110
110
  /**
111
111
  * Run a single iteration of the agent loop.
@@ -1 +1 @@
1
- {"version":3,"file":"chat.agent.js","sourceRoot":"/","sources":["chat/chat.agent.ts"],"names":[],"mappings":";;;;;;;;;AACA,OAAO,EACL,SAAS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ACH,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 } 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 ) {\n this.model = createModel(\"chat\");\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);\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;AAE3C,mCAAmC;AACnC,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AA8GnD,kFAAkF;AAClF,gBAAgB;AAChB,kFAAkF;AAElF;;GAEG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAEtC;;GAEG;AACH,MAAM,CAAC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E;;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"]}
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { createChatTools } from "./shared/agent/tool.factory.js";
2
- export { configureProtocol, getModelName } from "./shared/agent/model.config.js";
2
+ export { getModelName } from "./shared/agent/model.config.js";
3
3
  export type { ChatTools } from "./shared/agent/tool.factory.js";
4
4
  export type { ModelConfig, ModelSettings } from "./shared/agent/model.config.js";
5
5
  export type { ToolContext, ToolErrorReport, ResolvedToolContext, ToolDeps, ProtocolDeps, DefineTool, RawToolDefinition, CompiledGraph, ToolRegistry, } from "./shared/agent/tool.helpers.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"/","sources":["index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AACjF,YAAY,EAAE,SAAS,EA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YAAY,EACV,sBAAsB,EACtB,eAAe,EACf,kBAAkB,EAClB,cAAc,EACd,oBAAoB,GACrB,MAAM,oCAAoC,CAAC;AAI5C,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC"}
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // ─── Public API (recommended for external consumers) ──────────────────────────
2
2
  export { createChatTools } from "./shared/agent/tool.factory.js";
3
- export { configureProtocol, getModelName } from "./shared/agent/model.config.js";
3
+ export { getModelName } from "./shared/agent/model.config.js";
4
4
  export { ChatContextAccessError, resolveChatContext } from "./shared/agent/tool.helpers.js";
5
5
  export { requestContext } from "./shared/observability/request-context.js";
6
6
  export { setTimingWrapper } from "./shared/observability/performance.js";
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"/","sources":["index.ts"],"names":[],"mappings":"AAAA,iFAAiF;AAEjF,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAcjF,OAAO,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AAC5F,OAAO,EAAE,cAAc,EAAE,MAAM,2CAA2C,CAAC;AAC3E,OAAO,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AACzE,OAAO,EACL,gBAAgB,EAChB,oBAAoB,EACpB,iBAAiB,EACjB,wBAAwB,GACzB,MAAM,gCAAgC,CAAC;AAmBxC,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,yCAAyC,CAAC;AAyBrG,OAAO,EAAE,gBAAgB,EAAE,MAAM,wCAAwC,CAAC;AAE1E,iFAAiF;AAEjF,OAAO,EACL,uBAAuB,GAExB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EACL,oBAAoB,EACpB,cAAc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AAU,EAAE,uBAAuB,EAAE,MAAM,2CAA2C,CAAC;AAChG,OAAO,EACL,4BAA4B,EAC5B,uBAAuB,GAGxB,MAAM,sCAAsC,CAAC;AAE9C,iFAAiF;AAEjF,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AACrE,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,sBAAsB,EAAE,MAAM,oCAAoC,CAAC;AAC5E,OAAO,EAAE,uBAAuB,EAAE,MAAM,mCAAmC,CAAC;AAE5E,iFAAiF;AAEjF,OAAO,EAAE,eAAe,EAAE,sBAAsB,EAAE,yBAAyB,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAE7H,OAAO,EAAE,sBAAsB,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AACrF,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AAavE,iFAAiF;AAEjF,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC","sourcesContent":["// ─── Public API (recommended for external consumers) ──────────────────────────\n\nexport { createChatTools } from \"./shared/agent/tool.factory.js\";\nexport { configureProtocol, getModelName } from \"./shared/agent/model.config.js\";\nexport type { ChatTools } from \"./shared/agent/tool.factory.js\";\nexport type { ModelConfig, ModelSettings } from \"./shared/agent/model.config.js\";\nexport type {\n ToolContext,\n ToolErrorReport,\n ResolvedToolContext,\n ToolDeps,\n ProtocolDeps,\n DefineTool,\n RawToolDefinition,\n CompiledGraph,\n ToolRegistry,\n} from \"./shared/agent/tool.helpers.js\";\nexport { ChatContextAccessError, resolveChatContext } from \"./shared/agent/tool.helpers.js\";\nexport { requestContext } from \"./shared/observability/request-context.js\";\nexport { setTimingWrapper } from \"./shared/observability/performance.js\";\nexport {\n ToolRuntimeError,\n getToolTimeoutPolicy,\n invokeToolRuntime,\n toolRuntimeErrorToResult,\n} from \"./shared/agent/tool.runtime.js\";\nexport type { ToolRuntimeErrorCode, ToolTimeoutClass, ToolTimeoutPolicy } from \"./shared/agent/tool.runtime.js\";\n\n// ─── Interfaces (implement these to wire up your infrastructure) ───────────────\n\nexport type * from \"./shared/interfaces/auth.interface.js\";\nexport type * from \"./shared/interfaces/cache.interface.js\";\nexport type * from \"./shared/interfaces/chat-session.interface.js\";\nexport type { ChatSummaryReader } from \"./shared/interfaces/chat-summary.interface.js\";\nexport type { ChatMessageWriter } from \"./shared/interfaces/chat-message-writer.interface.js\";\nexport type { QuestionGeneratorReader } from \"./shared/interfaces/question-generator.interface.js\";\nexport type {\n QuestionerDatabase,\n PersistableQuestion,\n PersistedQuestion,\n QuestionFilters,\n} from \"./shared/interfaces/questioner.interface.js\";\nexport type { NegotiationSummaryReader } from \"./shared/interfaces/negotiation-summary.interface.js\";\nexport type { DiscoveryNegotiationDigest } from \"./shared/schemas/negotiation-digest.schema.js\";\nexport { NegotiationSummarizer, buildFallbackDigest } from \"./negotiation/negotiation.summarizer.js\";\nexport type * from \"./shared/interfaces/contact.interface.js\";\nexport type * from \"./shared/interfaces/database.interface.js\";\nexport type * from \"./shared/interfaces/embedder.interface.js\";\nexport type * from \"./shared/interfaces/enrichment.interface.js\";\nexport type * from \"./shared/interfaces/integration.interface.js\";\nexport type * from \"./shared/interfaces/queue.interface.js\";\nexport type * from \"./shared/interfaces/scraper.interface.js\";\nexport type * from \"./shared/interfaces/storage.interface.js\";\nexport type * from \"./shared/interfaces/delivery-ledger.interface.js\";\nexport type * from \"./shared/interfaces/connect-link.interface.js\";\nexport type * from \"./shared/interfaces/discovery-run.interface.js\";\nexport type * from \"./shared/interfaces/profile-run.interface.js\";\nexport type * from \"./shared/interfaces/negotiation-events.interface.js\";\nexport type { AgentDispatcher, AgentDispatchResult, NegotiationTurnPayload } from \"./shared/interfaces/agent-dispatcher.interface.js\";\nexport type {\n AgentRecord,\n AgentTransportRecord,\n AgentPermissionRecord,\n AgentWithRelations,\n CreateAgentInput,\n CreateTransportInput,\n GrantPermissionInput,\n AgentDatabase,\n} from './shared/interfaces/agent.interface.js';\nexport { SYSTEM_AGENT_IDS } from './shared/interfaces/agent.interface.js';\n\n// ─── Shared schemas ───────────────────────────────────────────────────────────\n\nexport {\n ChatContextDigestSchema,\n type ChatContextDigest,\n} from \"./shared/schemas/chat-context.schema.js\";\nexport {\n QuestionOptionSchema,\n QuestionSchema,\n QuestionStrategySchema,\n QuestionWithStrategySchema,\n QuestionGeneratorResponseSchema,\n QuestionModeSchema,\n QuestionDetectionSchema,\n QuestionActorSchema,\n QuestionAnswerSchema,\n type Question,\n type QuestionOption,\n type QuestionStrategy,\n type QuestionWithStrategy,\n type QuestionGeneratorResponse,\n type QuestionGenerationResult,\n type QuestionMode,\n type QuestionDetection,\n type QuestionActor,\n type QuestionAnswer,\n} from \"./shared/schemas/question.schema.js\";\nexport type { PendingQuestionSummary } from \"./shared/schemas/pending-question.schema.js\";\n\n// ─── Graph factories ──────────────────────────────────────────────────────────\n\nexport { ChatGraphFactory } from \"./chat/chat.graph.js\";\nexport { HomeGraphFactory } from \"./opportunity/feed/feed.graph.js\";\nexport { HydeGraphFactory } from \"./shared/hyde/hyde.graph.js\";\nexport { NetworkGraphFactory } from \"./network/network.graph.js\";\nexport { NetworkMembershipGraphFactory } from \"./network/membership/membership.graph.js\";\nexport { IntentGraphFactory } from \"./intent/intent.graph.js\";\nexport { IntentNetworkGraphFactory } from \"./network/indexer/indexer.graph.js\";\nexport { MaintenanceGraphFactory } from \"./maintenance/maintenance.graph.js\";\nexport type {\n MaintenanceGraphDatabase,\n MaintenanceGraphCache,\n MaintenanceGraphQueue,\n} from \"./maintenance/maintenance.graph.js\";\nexport { NegotiationGraphFactory, createDefaultNegotiationGraph, negotiateCandidates } from \"./negotiation/negotiation.graph.js\";\nexport { OpportunityGraphFactory } from \"./opportunity/opportunity.graph.js\";\nexport { ProfileGraphFactory } from \"./profile/profile.graph.js\";\nexport { PremiseGraphFactory } from \"./premise/premise.graph.js\";\n\n// ─── Agents ───────────────────────────────────────────────────────────────────\n\nexport { UserContextGenerator } from \"./context/context.generator.js\";\nexport type { UserContextInput, IncrementalContextInput, UserContextResult } from \"./context/context.generator.js\";\nexport { ChatTitleGenerator } from \"./chat/chat.title.generator.js\";\nexport { ChatSummarizer } from \"./chat/chat.summarizer.js\";\nexport type { ChatSummarizerInput, ChatSummarizerMessage } from \"./chat/chat.summarizer.js\";\nexport { HydeGenerator } from \"./shared/hyde/hyde.generator.js\";\nexport { SuggestionGenerator } from \"./chat/chat.suggester.js\";\nexport type { SuggestionGeneratorInput } from \"./chat/chat.suggester.js\";\nexport { generateInviteMessage } from \"./contact/contact.inviter.js\";\nexport type { InviteInput, InviteOutput } from \"./contact/contact.inviter.js\";\nexport { IntentIndexer } from \"./intent/intent.indexer.js\";\nexport { PremiseAnalyzer } from \"./premise/premise.analyzer.js\";\nexport type { PremiseAnalyzerOutput } from \"./premise/premise.analyzer.js\";\nexport { PremiseDecomposer } from \"./premise/premise.decomposer.js\";\nexport type { PremiseDecomposerOutput, DecomposedPremise } from \"./premise/premise.decomposer.js\";\nexport { PremiseIndexer } from \"./premise/premise.indexer.js\";\nexport type { PremiseIndexerOutput } from \"./premise/premise.indexer.js\";\nexport { LensInferrer } from \"./shared/hyde/lens.inferrer.js\";\nexport { NegotiationInsightsGenerator } from \"./negotiation/insight.generator.js\";\nexport type { NegotiationDigest } from \"./negotiation/insight.generator.js\";\nexport { IndexNegotiator } from \"./negotiation/negotiation.agent.js\";\nexport type { NegotiationAgentInput } from \"./negotiation/negotiation.agent.js\";\nexport { QuestionerAgent } from \"./questioner/questioner.agent.js\";\nexport type { QuestionerAgentConfig } from \"./questioner/questioner.agent.js\";\nexport type {\n QuestionerInput,\n QuestionerContext,\n QuestionerEnqueuePayload,\n QuestionerEnqueueFn,\n DiscoveryContext,\n IntentContext,\n ProfileContext,\n NegotiationContext,\n} from \"./questioner/questioner.types.js\";\nexport { getPreset } from \"./questioner/questioner.presets.js\";\nexport type { QuestionerPreset } from \"./questioner/questioner.presets.js\";\nexport { OpportunityEvaluator } from \"./opportunity/opportunity.evaluator.js\";\nexport type {\n EvaluatorInput,\n OpportunityEvaluatorOptionsConstructor,\n} from \"./opportunity/opportunity.evaluator.js\";\nexport { OpportunityPresenter, gatherPresenterContext } from \"./opportunity/opportunity.presenter.js\";\nexport { createOpportunityTools } from \"./opportunity/opportunity.tools.js\";\nexport { createProfileTools } from \"./profile/profile.tools.js\";\nexport type { PresenterDatabase } from \"./opportunity/opportunity.presenter.js\";\nexport { QuestionGenerator } from \"./opportunity/question.generator.js\";\nexport type {\n DiscoveryQuestionInput,\n DiscoveryNegotiation,\n DiscoveryOutcome,\n DiscoveryTurn,\n DiscoverySummary,\n DiscoverySourceProfile,\n NegotiationRole,\n} from \"./opportunity/question.prompt.js\";\n\n// ─── Support utilities ────────────────────────────────────────────────────────\n\nexport { renderNetworkContext } from './shared/network/metadata.renderer.js';\nexport {\n canUserSeeOpportunity,\n isActionableForViewer,\n validateOpportunityActors,\n classifyOpportunity,\n selectByComposition,\n FEED_SOFT_TARGETS,\n} from \"./opportunity/opportunity.utils.js\";\nexport { getPrimaryActionLabel } from \"./opportunity/opportunity.labels.js\";\nexport { computeFeedHealth } from \"./opportunity/feed/feed.health.js\";\nexport type { FeedHealthInput, FeedHealthResult } from \"./opportunity/feed/feed.health.js\";\nexport {\n selectContactsForDiscovery,\n shouldRunIntroducerDiscovery,\n runIntroducerDiscovery,\n MAX_CONTACTS_PER_CYCLE,\n MAX_CANDIDATES_PER_CONTACT,\n INTRODUCER_DISCOVERY_SOURCE,\n} from \"./opportunity/opportunity.introducer.js\";\nexport type {\n IntroducerDiscoveryDatabase,\n IntroducerDiscoveryQueue,\n ContactWithIntents,\n} from \"./opportunity/opportunity.introducer.js\";\nexport { persistOpportunities } from \"./opportunity/opportunity.persist.js\";\nexport { presentOpportunity } from \"./opportunity/opportunity.presentation.js\";\nexport type { UserInfo } from \"./opportunity/opportunity.presentation.js\";\nexport { stripUuids, stripIntroducerMentions } from \"./opportunity/opportunity.presentation.js\";\nexport {\n getOrCreateDeliveryCardBatch,\n DELIVERY_CARD_CACHE_TTL,\n type CachedDeliveryCard,\n type OpportunityWithContext,\n} from \"./opportunity/delivery-card.cache.js\";\n\n// ─── Tools ────────────────────────────────────────────────────────────────────\n\nexport { createToolRegistry } from \"./shared/agent/tool.registry.js\";\nexport { createAgentTools } from './agent/agent.tools.js';\nexport { AMBIENT_PARK_WINDOW_MS } from './negotiation/negotiation.tools.js';\nexport { normalizeTelegramHandle } from './shared/utils/telegram-handle.js';\n\n// ─── MCP ──────────────────────────────────────────────────────────────────────\n\nexport { createMcpServer, computeAgentIndexScope, buildMcpOnboardingMessage, ONBOARDING_ALLOWED } from \"./mcp/mcp.server.js\";\nexport type { ScopedDepsFactory } from \"./mcp/mcp.server.js\";\nexport { buildElicitationCreate, flattenChoice } from \"./mcp/elicitation.builder.js\";\nexport { dispatchElicitations } from \"./mcp/elicitation.dispatcher.js\";\nexport type { ElicitResultLike, ElicitInputFn, DispatchElicitationsParams } from \"./mcp/elicitation.dispatcher.js\";\n\n// ─── States (for advanced graph consumers) ────────────────────────────────────\n\nexport type {\n UserNegotiationContext,\n NegotiationTurn,\n NegotiationOutcome,\n SeedAssessment,\n NegotiationGraphLike,\n} from \"./negotiation/negotiation.state.js\";\n\n// ─── Streamers ────────────────────────────────────────────────────────────────\n\nexport { ChatStreamer } from \"./chat/chat.streamer.js\";\nexport { ResponseStreamer } from \"./shared/agent/response.streamer.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"/","sources":["index.ts"],"names":[],"mappings":"AAAA,iFAAiF;AAEjF,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAc9D,OAAO,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AAC5F,OAAO,EAAE,cAA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EACnB,iBAAiB,GAClB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,qBAAqB,EAAE,MAAM,qCAAqC,CAAC;AAC5E,OAAO,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAC;AAEtE,OAAO,EACL,0BAA0B,EAC1B,4BAA4B,EAC5B,sBAAsB,EACtB,sBAAsB,EACtB,0BAA0B,EAC1B,2BAA2B,GAC5B,MAAM,yCAAyC,CAAC;AAMjD,OAAO,EAAE,oBAAoB,EAAE,MAAM,sCAAsC,CAAC;AAC5E,OAAO,EAAE,kBAAkB,EAAE,MAAM,2CAA2C,CAAC;AAE/E,OAAO,EAAE,UAAU,EAAE,uBAAuB,EAAE,MAAM,2CAA2C,CAAC;AAChG,OAAO,EACL,4BAA4B,EAC5B,uBAAuB,GAGxB,MAAM,sCAAsC,CAAC;AAE9C,iFAAiF;AAEjF,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AACrE,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,sBAAsB,EAAE,MAAM,oCAAoC,CAAC;AAC5E,OAAO,EAAE,uBAAuB,EAAE,MAAM,mCAAmC,CAAC;AAE5E,iFAAiF;AAEjF,OAAO,EAAE,eAAe,EAAE,sBAAsB,EAAE,yBAAyB,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAE7H,OAAO,EAAE,sBAAsB,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AACrF,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AAavE,iFAAiF;AAEjF,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC","sourcesContent":["// ─── Public API (recommended for external consumers) ──────────────────────────\n\nexport { createChatTools } from \"./shared/agent/tool.factory.js\";\nexport { getModelName } from \"./shared/agent/model.config.js\";\nexport type { ChatTools } from \"./shared/agent/tool.factory.js\";\nexport type { ModelConfig, ModelSettings } from \"./shared/agent/model.config.js\";\nexport type {\n ToolContext,\n ToolErrorReport,\n ResolvedToolContext,\n ToolDeps,\n ProtocolDeps,\n DefineTool,\n RawToolDefinition,\n CompiledGraph,\n ToolRegistry,\n} from \"./shared/agent/tool.helpers.js\";\nexport { ChatContextAccessError, resolveChatContext } from \"./shared/agent/tool.helpers.js\";\nexport { requestContext } from \"./shared/observability/request-context.js\";\nexport { setTimingWrapper } from \"./shared/observability/performance.js\";\nexport {\n ToolRuntimeError,\n getToolTimeoutPolicy,\n invokeToolRuntime,\n toolRuntimeErrorToResult,\n} from \"./shared/agent/tool.runtime.js\";\nexport type { ToolRuntimeErrorCode, ToolTimeoutClass, ToolTimeoutPolicy } from \"./shared/agent/tool.runtime.js\";\n\n// ─── Interfaces (implement these to wire up your infrastructure) ───────────────\n\nexport type * from \"./shared/interfaces/auth.interface.js\";\nexport type * from \"./shared/interfaces/cache.interface.js\";\nexport type * from \"./shared/interfaces/chat-session.interface.js\";\nexport type { ChatSummaryReader } from \"./shared/interfaces/chat-summary.interface.js\";\nexport type { ChatMessageWriter } from \"./shared/interfaces/chat-message-writer.interface.js\";\nexport type { QuestionGeneratorReader } from \"./shared/interfaces/question-generator.interface.js\";\nexport type {\n QuestionerDatabase,\n PersistableQuestion,\n PersistedQuestion,\n QuestionFilters,\n} from \"./shared/interfaces/questioner.interface.js\";\nexport type { NegotiationSummaryReader } from \"./shared/interfaces/negotiation-summary.interface.js\";\nexport type { DiscoveryNegotiationDigest } from \"./shared/schemas/negotiation-digest.schema.js\";\nexport { NegotiationSummarizer, buildFallbackDigest } from \"./negotiation/negotiation.summarizer.js\";\nexport type * from \"./shared/interfaces/contact.interface.js\";\nexport type * from \"./shared/interfaces/database.interface.js\";\nexport type * from \"./shared/interfaces/embedder.interface.js\";\nexport type * from \"./shared/interfaces/enrichment.interface.js\";\nexport type * from \"./shared/interfaces/integration.interface.js\";\nexport type * from \"./shared/interfaces/queue.interface.js\";\nexport type * from \"./shared/interfaces/scraper.interface.js\";\nexport type * from \"./shared/interfaces/storage.interface.js\";\nexport type * from \"./shared/interfaces/delivery-ledger.interface.js\";\nexport type * from \"./shared/interfaces/connect-link.interface.js\";\nexport type * from \"./shared/interfaces/discovery-run.interface.js\";\nexport type * from \"./shared/interfaces/profile-run.interface.js\";\nexport type * from \"./shared/interfaces/negotiation-events.interface.js\";\nexport type { AgentDispatcher, AgentDispatchResult, NegotiationTurnPayload } from \"./shared/interfaces/agent-dispatcher.interface.js\";\nexport type {\n AgentRecord,\n AgentTransportRecord,\n AgentPermissionRecord,\n AgentWithRelations,\n CreateAgentInput,\n CreateTransportInput,\n GrantPermissionInput,\n AgentDatabase,\n} from './shared/interfaces/agent.interface.js';\nexport { SYSTEM_AGENT_IDS } from './shared/interfaces/agent.interface.js';\n\n// ─── Shared schemas ───────────────────────────────────────────────────────────\n\nexport {\n ChatContextDigestSchema,\n type ChatContextDigest,\n} from \"./shared/schemas/chat-context.schema.js\";\nexport {\n QuestionOptionSchema,\n QuestionSchema,\n QuestionStrategySchema,\n QuestionWithStrategySchema,\n QuestionGeneratorResponseSchema,\n QuestionModeSchema,\n QuestionDetectionSchema,\n QuestionActorSchema,\n QuestionAnswerSchema,\n type Question,\n type QuestionOption,\n type QuestionStrategy,\n type QuestionWithStrategy,\n type QuestionGeneratorResponse,\n type QuestionGenerationResult,\n type QuestionMode,\n type QuestionDetection,\n type QuestionActor,\n type QuestionAnswer,\n} from \"./shared/schemas/question.schema.js\";\nexport type { PendingQuestionSummary } from \"./shared/schemas/pending-question.schema.js\";\n\n// ─── Graph factories ──────────────────────────────────────────────────────────\n\nexport { ChatGraphFactory } from \"./chat/chat.graph.js\";\nexport { HomeGraphFactory } from \"./opportunity/feed/feed.graph.js\";\nexport { HydeGraphFactory } from \"./shared/hyde/hyde.graph.js\";\nexport { NetworkGraphFactory } from \"./network/network.graph.js\";\nexport { NetworkMembershipGraphFactory } from \"./network/membership/membership.graph.js\";\nexport { IntentGraphFactory } from \"./intent/intent.graph.js\";\nexport { IntentNetworkGraphFactory } from \"./network/indexer/indexer.graph.js\";\nexport { MaintenanceGraphFactory } from \"./maintenance/maintenance.graph.js\";\nexport type {\n MaintenanceGraphDatabase,\n MaintenanceGraphCache,\n MaintenanceGraphQueue,\n} from \"./maintenance/maintenance.graph.js\";\nexport { NegotiationGraphFactory, createDefaultNegotiationGraph, negotiateCandidates } from \"./negotiation/negotiation.graph.js\";\nexport { OpportunityGraphFactory } from \"./opportunity/opportunity.graph.js\";\nexport { ProfileGraphFactory } from \"./profile/profile.graph.js\";\nexport { PremiseGraphFactory } from \"./premise/premise.graph.js\";\n\n// ─── Agents ───────────────────────────────────────────────────────────────────\n\nexport { UserContextGenerator } from \"./context/context.generator.js\";\nexport type { UserContextInput, IncrementalContextInput, UserContextResult } from \"./context/context.generator.js\";\nexport { ChatTitleGenerator } from \"./chat/chat.title.generator.js\";\nexport { ChatSummarizer } from \"./chat/chat.summarizer.js\";\nexport type { ChatSummarizerInput, ChatSummarizerMessage } from \"./chat/chat.summarizer.js\";\nexport { HydeGenerator } from \"./shared/hyde/hyde.generator.js\";\nexport { SuggestionGenerator } from \"./chat/chat.suggester.js\";\nexport type { SuggestionGeneratorInput } from \"./chat/chat.suggester.js\";\nexport { generateInviteMessage } from \"./contact/contact.inviter.js\";\nexport type { InviteInput, InviteOutput } from \"./contact/contact.inviter.js\";\nexport { IntentIndexer } from \"./intent/intent.indexer.js\";\nexport { PremiseAnalyzer } from \"./premise/premise.analyzer.js\";\nexport type { PremiseAnalyzerOutput } from \"./premise/premise.analyzer.js\";\nexport { PremiseDecomposer } from \"./premise/premise.decomposer.js\";\nexport type { PremiseDecomposerOutput, DecomposedPremise } from \"./premise/premise.decomposer.js\";\nexport { PremiseIndexer } from \"./premise/premise.indexer.js\";\nexport type { PremiseIndexerOutput } from \"./premise/premise.indexer.js\";\nexport { LensInferrer } from \"./shared/hyde/lens.inferrer.js\";\nexport { NegotiationInsightsGenerator } from \"./negotiation/insight.generator.js\";\nexport type { NegotiationDigest } from \"./negotiation/insight.generator.js\";\nexport { IndexNegotiator } from \"./negotiation/negotiation.agent.js\";\nexport type { NegotiationAgentInput } from \"./negotiation/negotiation.agent.js\";\nexport { QuestionerAgent } from \"./questioner/questioner.agent.js\";\nexport type { QuestionerAgentConfig } from \"./questioner/questioner.agent.js\";\nexport type {\n QuestionerInput,\n QuestionerContext,\n QuestionerEnqueuePayload,\n QuestionerEnqueueFn,\n DiscoveryContext,\n IntentContext,\n ProfileContext,\n NegotiationContext,\n} from \"./questioner/questioner.types.js\";\nexport { getPreset } from \"./questioner/questioner.presets.js\";\nexport type { QuestionerPreset } from \"./questioner/questioner.presets.js\";\nexport { OpportunityEvaluator } from \"./opportunity/opportunity.evaluator.js\";\nexport type {\n EvaluatorInput,\n OpportunityEvaluatorOptionsConstructor,\n} from \"./opportunity/opportunity.evaluator.js\";\nexport { OpportunityPresenter, gatherPresenterContext } from \"./opportunity/opportunity.presenter.js\";\nexport { createOpportunityTools } from \"./opportunity/opportunity.tools.js\";\nexport { createProfileTools } from \"./profile/profile.tools.js\";\nexport type { PresenterDatabase } from \"./opportunity/opportunity.presenter.js\";\nexport { QuestionGenerator } from \"./opportunity/question.generator.js\";\nexport type {\n DiscoveryQuestionInput,\n DiscoveryNegotiation,\n DiscoveryOutcome,\n DiscoveryTurn,\n DiscoverySummary,\n DiscoverySourceProfile,\n NegotiationRole,\n} from \"./opportunity/question.prompt.js\";\n\n// ─── Support utilities ────────────────────────────────────────────────────────\n\nexport { renderNetworkContext } from './shared/network/metadata.renderer.js';\nexport {\n canUserSeeOpportunity,\n isActionableForViewer,\n validateOpportunityActors,\n classifyOpportunity,\n selectByComposition,\n FEED_SOFT_TARGETS,\n} from \"./opportunity/opportunity.utils.js\";\nexport { getPrimaryActionLabel } from \"./opportunity/opportunity.labels.js\";\nexport { computeFeedHealth } from \"./opportunity/feed/feed.health.js\";\nexport type { FeedHealthInput, FeedHealthResult } from \"./opportunity/feed/feed.health.js\";\nexport {\n selectContactsForDiscovery,\n shouldRunIntroducerDiscovery,\n runIntroducerDiscovery,\n MAX_CONTACTS_PER_CYCLE,\n MAX_CANDIDATES_PER_CONTACT,\n INTRODUCER_DISCOVERY_SOURCE,\n} from \"./opportunity/opportunity.introducer.js\";\nexport type {\n IntroducerDiscoveryDatabase,\n IntroducerDiscoveryQueue,\n ContactWithIntents,\n} from \"./opportunity/opportunity.introducer.js\";\nexport { persistOpportunities } from \"./opportunity/opportunity.persist.js\";\nexport { presentOpportunity } from \"./opportunity/opportunity.presentation.js\";\nexport type { UserInfo } from \"./opportunity/opportunity.presentation.js\";\nexport { stripUuids, stripIntroducerMentions } from \"./opportunity/opportunity.presentation.js\";\nexport {\n getOrCreateDeliveryCardBatch,\n DELIVERY_CARD_CACHE_TTL,\n type CachedDeliveryCard,\n type OpportunityWithContext,\n} from \"./opportunity/delivery-card.cache.js\";\n\n// ─── Tools ────────────────────────────────────────────────────────────────────\n\nexport { createToolRegistry } from \"./shared/agent/tool.registry.js\";\nexport { createAgentTools } from './agent/agent.tools.js';\nexport { AMBIENT_PARK_WINDOW_MS } from './negotiation/negotiation.tools.js';\nexport { normalizeTelegramHandle } from './shared/utils/telegram-handle.js';\n\n// ─── MCP ──────────────────────────────────────────────────────────────────────\n\nexport { createMcpServer, computeAgentIndexScope, buildMcpOnboardingMessage, ONBOARDING_ALLOWED } from \"./mcp/mcp.server.js\";\nexport type { ScopedDepsFactory } from \"./mcp/mcp.server.js\";\nexport { buildElicitationCreate, flattenChoice } from \"./mcp/elicitation.builder.js\";\nexport { dispatchElicitations } from \"./mcp/elicitation.dispatcher.js\";\nexport type { ElicitResultLike, ElicitInputFn, DispatchElicitationsParams } from \"./mcp/elicitation.dispatcher.js\";\n\n// ─── States (for advanced graph consumers) ────────────────────────────────────\n\nexport type {\n UserNegotiationContext,\n NegotiationTurn,\n NegotiationOutcome,\n SeedAssessment,\n NegotiationGraphLike,\n} from \"./negotiation/negotiation.state.js\";\n\n// ─── Streamers ────────────────────────────────────────────────────────────────\n\nexport { ChatStreamer } from \"./chat/chat.streamer.js\";\nexport { ResponseStreamer } from \"./shared/agent/response.streamer.js\";\n"]}
@@ -11,7 +11,10 @@ export interface ModelSettings {
11
11
  }
12
12
  /**
13
13
  * Runtime configuration for the protocol package.
14
- * Set once via configureProtocol() at application startup.
14
+ * When passed via `ToolContext.modelConfig`, all fields (`apiKey`, `baseURL`, `chatModel`,
15
+ * `chatReasoningEffort`) are honored by `ChatAgent` when the chat graph runs.
16
+ * Other protocol agents don't read from `ToolContext` but may accept an explicit `ModelConfig`
17
+ * as a direct parameter to `createModel()`.
15
18
  * All fields fall back to environment variables if not provided.
16
19
  */
17
20
  export interface ModelConfig {
@@ -24,14 +27,6 @@ export interface ModelConfig {
24
27
  /** Override the chat reasoning effort. Falls back to CHAT_REASONING_EFFORT env var. */
25
28
  chatReasoningEffort?: 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';
26
29
  }
27
- /**
28
- * Configure the protocol package with runtime credentials and settings.
29
- * Call once at application startup before any agents are used.
30
- * Falls back to environment variables for any field not provided.
31
- *
32
- * @param config - Runtime configuration overrides
33
- */
34
- export declare function configureProtocol(config: ModelConfig): void;
35
30
  declare function getModelConfig(config?: ModelConfig): {
36
31
  readonly intentInferrer: {
37
32
  readonly model: "google/gemini-2.5-flash";
@@ -135,13 +130,13 @@ declare function getModelConfig(config?: ModelConfig): {
135
130
  /**
136
131
  * Returns the model name string for the given agent key.
137
132
  * @param agent - Key from MODEL_CONFIG identifying which agent's settings to use.
138
- * @param config - Optional runtime config overrides (merged with module-level config).
133
+ * @param config - Optional runtime config overrides.
139
134
  */
140
135
  export declare function getModelName(agent: keyof ReturnType<typeof getModelConfig>, config?: ModelConfig): string;
141
136
  /**
142
137
  * Creates a ChatOpenAI instance configured for OpenRouter.
143
138
  * @param agent - Key identifying which agent's model settings to use.
144
- * @param config - Optional runtime config overrides (merged with module-level config).
139
+ * @param config - Optional runtime config overrides.
145
140
  */
146
141
  export declare function createModel(agent: keyof ReturnType<typeof getModelConfig>, config?: ModelConfig): ChatOpenAI;
147
142
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"model.config.d.ts","sourceRoot":"/","sources":["shared/agent/model.config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAE/C,iDAAiD;AACjD,MAAM,WAAW,aAAa;IAC5B,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,SAAS,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,CAAC;QAAC,OAAO,CAAC,EAAE,OAAO,CAAA;KAAE,CAAC;CAC7F;AAED;;;;GAIG;AACH,MAAM,WAAW,WAAW;IAC1B,oEAAoE;IACpE,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,sEAAsE;IACtE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,uEAAuE;IACvE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,uFAAuF;IACvF,mBAAmB,CAAC,EAAE,SAAS,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,CAAC;CACvE;AAKD;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,WAAW,GAAG,IAAI,CAE3D;AAED,iBAAS,cAAc,CAAC,MAAM,CAAC,EAAE,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;6BA+BkD,WAAW,CAAC,aAAa,CAAC,WAAW,CAAC,CAAC,CAAC,QAAQ,CAAC;;;;EAK9I;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,UAAU,C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AK,EAAE,MAAM,UAAU,CAAC,OAAO,cAAc,CAAC,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,MAAM,CAEzG;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,UAAU,CAAC,OAAO,cAAc,CAAC,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,UAAU,CA+B5G"}
@@ -1,18 +1,5 @@
1
1
  import { ChatOpenAI } from "@langchain/openai";
2
- /** Module-level config set by configureProtocol(). Merged with per-call overrides. */
3
- let _activeConfig = {};
4
- /**
5
- * Configure the protocol package with runtime credentials and settings.
6
- * Call once at application startup before any agents are used.
7
- * Falls back to environment variables for any field not provided.
8
- *
9
- * @param config - Runtime configuration overrides
10
- */
11
- export function configureProtocol(config) {
12
- _activeConfig = config;
13
- }
14
2
  function getModelConfig(config) {
15
- const merged = { ..._activeConfig, ...config };
16
3
  return {
17
4
  intentInferrer: { model: "google/gemini-2.5-flash" },
18
5
  intentIndexer: { model: "google/gemini-2.5-flash" },
@@ -39,10 +26,10 @@ function getModelConfig(config) {
39
26
  premiseIndexer: { model: "google/gemini-2.5-flash" },
40
27
  userContextGenerator: { model: "google/gemini-2.5-flash", temperature: 0.3, maxTokens: 512 },
41
28
  chat: {
42
- model: merged.chatModel ?? process.env.CHAT_MODEL ?? "google/gemini-3-pro-preview",
29
+ model: config?.chatModel ?? process.env.CHAT_MODEL ?? "google/gemini-3-pro-preview",
43
30
  maxTokens: 8192,
44
31
  reasoning: {
45
- effort: (merged.chatReasoningEffort ?? process.env.CHAT_REASONING_EFFORT ?? "low"),
32
+ effort: (config?.chatReasoningEffort ?? process.env.CHAT_REASONING_EFFORT ?? "low"),
46
33
  exclude: true,
47
34
  },
48
35
  },
@@ -51,7 +38,7 @@ function getModelConfig(config) {
51
38
  /**
52
39
  * Returns the model name string for the given agent key.
53
40
  * @param agent - Key from MODEL_CONFIG identifying which agent's settings to use.
54
- * @param config - Optional runtime config overrides (merged with module-level config).
41
+ * @param config - Optional runtime config overrides.
55
42
  */
56
43
  export function getModelName(agent, config) {
57
44
  return getModelConfig(config)[agent].model;
@@ -59,15 +46,14 @@ export function getModelName(agent, config) {
59
46
  /**
60
47
  * Creates a ChatOpenAI instance configured for OpenRouter.
61
48
  * @param agent - Key identifying which agent's model settings to use.
62
- * @param config - Optional runtime config overrides (merged with module-level config).
49
+ * @param config - Optional runtime config overrides.
63
50
  */
64
51
  export function createModel(agent, config) {
65
- const merged = { ..._activeConfig, ...config };
66
- const apiKey = merged.apiKey ?? process.env.OPENROUTER_API_KEY;
52
+ const apiKey = config?.apiKey ?? process.env.OPENROUTER_API_KEY;
67
53
  if (!apiKey?.trim()) {
68
- throw new Error(`createModel(${agent}): OPENROUTER_API_KEY is required. Pass via configureProtocol({ apiKey }) or set the OPENROUTER_API_KEY environment variable.`);
54
+ throw new Error(`createModel(${agent}): OPENROUTER_API_KEY is required. Pass via the config argument, ToolContext.modelConfig.apiKey, or set the OPENROUTER_API_KEY environment variable.`);
69
55
  }
70
- const cfg = getModelConfig(merged)[agent];
56
+ const cfg = getModelConfig(config)[agent];
71
57
  // Hard upper bound on a single LLM call. Without this, langchain's HTTP
72
58
  // client waits until the upstream cuts the socket (~3 minutes via
73
59
  // OpenRouter), blocking the entire chat response. 60 s is generous enough
@@ -84,7 +70,7 @@ export function createModel(agent, config) {
84
70
  return new ChatOpenAI({
85
71
  model: cfg.model,
86
72
  configuration: {
87
- baseURL: merged.baseURL ?? process.env.OPENROUTER_BASE_URL ?? "https://openrouter.ai/api/v1",
73
+ baseURL: config?.baseURL ?? process.env.OPENROUTER_BASE_URL ?? "https://openrouter.ai/api/v1",
88
74
  apiKey,
89
75
  },
90
76
  temperature: cfg.temperature,
@@ -1 +1 @@
1
- {"version":3,"file":"model.config.js","sourceRoot":"/","sources":["shared/agent/model.config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AA0B/C,sFAAsF;AACtF,IAAI,aAAa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W;QAC5B,SAAS,EAAE,GAAG,CAAC,SAAS;QACxB,OAAO;QACP,UAAU;QACV,GAAG,CAAC,GAAG,CAAC,SAAS,IAAI,EAAE,WAAW,EAAE,EAAE,SAAS,EAAE,GAAG,CAAC,SAAS,EAAE,EAAE,CAAC;KACpE,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { ChatOpenAI } from \"@langchain/openai\";\n\n/** Settings that can be configured per agent. */\nexport interface ModelSettings {\n model: string;\n temperature?: number;\n maxTokens?: number;\n reasoning?: { effort?: 'minimal' | 'low' | 'medium' | 'high' | 'xhigh'; exclude?: boolean };\n}\n\n/**\n * Runtime configuration for the protocol package.\n * Set once via configureProtocol() at application startup.\n * All fields fall back to environment variables if not provided.\n */\nexport interface ModelConfig {\n /** OpenRouter API key. Falls back to OPENROUTER_API_KEY env var. */\n apiKey?: string;\n /** OpenRouter base URL. Falls back to OPENROUTER_BASE_URL env var. */\n baseURL?: string;\n /** Override the chat agent model. Falls back to CHAT_MODEL env var. */\n chatModel?: string;\n /** Override the chat reasoning effort. Falls back to CHAT_REASONING_EFFORT env var. */\n chatReasoningEffort?: 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';\n}\n\n/** Module-level config set by configureProtocol(). Merged with per-call overrides. */\nlet _activeConfig: ModelConfig = {};\n\n/**\n * Configure the protocol package with runtime credentials and settings.\n * Call once at application startup before any agents are used.\n * Falls back to environment variables for any field not provided.\n *\n * @param config - Runtime configuration overrides\n */\nexport function configureProtocol(config: ModelConfig): void {\n _activeConfig = config;\n}\n\nfunction getModelConfig(config?: ModelConfig) {\n const merged: ModelConfig = { ..._activeConfig, ...config };\n return {\n intentInferrer: { model: \"google/gemini-2.5-flash\" },\n intentIndexer: { model: \"google/gemini-2.5-flash\" },\n intentVerifier: { model: \"google/gemini-2.5-flash\" },\n intentReconciler: { model: \"google/gemini-2.5-flash\" },\n intentClarifier: { model: \"google/gemini-2.5-flash\" },\n profileGenerator: { model: \"google/gemini-2.5-flash\" },\n hydeGenerator: { model: \"google/gemini-2.5-flash\" },\n lensInferrer: { model: \"google/gemini-2.5-flash\" },\n opportunityEvaluator: { model: \"google/gemini-2.5-flash\" },\n opportunityPresenter: { model: \"google/gemini-2.5-flash\" },\n negotiator: { model: \"google/gemini-2.5-flash\" },\n homeCategorizer: { model: \"google/gemini-2.5-flash\" },\n suggestionGenerator: { model: \"google/gemini-2.5-flash\", temperature: 0.4, maxTokens: 512 },\n chatTitleGenerator: { model: \"google/gemini-2.5-flash\", temperature: 0.3, maxTokens: 32 },\n negotiationInsights: { model: \"google/gemini-2.5-flash\", temperature: 0.4, maxTokens: 512 },\n chatContextSummarizer: { model: \"google/gemini-2.5-flash\", temperature: 0.2, maxTokens: 512 },\n discoveryQuestionGenerator: { model: \"google/gemini-2.5-flash\", temperature: 0.5, maxTokens: 1024 },\n questioner: { model: \"google/gemini-2.5-flash\", temperature: 0.5, maxTokens: 1024 },\n negotiationSummarizer: { model: \"google/gemini-2.5-flash\", temperature: 0.2, maxTokens: 256 },\n inviteGenerator: { model: \"google/gemini-2.5-flash\", temperature: 0.3, maxTokens: 512 },\n premiseAnalyzer: { model: \"google/gemini-2.5-flash\" },\n premiseDecomposer: { model: \"google/gemini-2.5-flash\" },\n premiseIndexer: { model: \"google/gemini-2.5-flash\" },\n userContextGenerator: { model: \"google/gemini-2.5-flash\", temperature: 0.3, maxTokens: 512 },\n chat: {\n model: merged.chatModel ?? process.env.CHAT_MODEL ?? \"google/gemini-3-pro-preview\",\n maxTokens: 8192,\n reasoning: {\n effort: (merged.chatReasoningEffort ?? process.env.CHAT_REASONING_EFFORT ?? \"low\") as NonNullable<ModelSettings[\"reasoning\"]>[\"effort\"],\n exclude: true,\n },\n },\n } as const;\n}\n\n/**\n * Returns the model name string for the given agent key.\n * @param agent - Key from MODEL_CONFIG identifying which agent's settings to use.\n * @param config - Optional runtime config overrides (merged with module-level config).\n */\nexport function getModelName(agent: keyof ReturnType<typeof getModelConfig>, config?: ModelConfig): string {\n return getModelConfig(config)[agent].model;\n}\n\n/**\n * Creates a ChatOpenAI instance configured for OpenRouter.\n * @param agent - Key identifying which agent's model settings to use.\n * @param config - Optional runtime config overrides (merged with module-level config).\n */\nexport function createModel(agent: keyof ReturnType<typeof getModelConfig>, config?: ModelConfig): ChatOpenAI {\n const merged: ModelConfig = { ..._activeConfig, ...config };\n const apiKey = merged.apiKey ?? process.env.OPENROUTER_API_KEY;\n if (!apiKey?.trim()) {\n throw new Error(`createModel(${agent}): OPENROUTER_API_KEY is required. Pass via configureProtocol({ apiKey }) or set the OPENROUTER_API_KEY environment variable.`);\n }\n const cfg = getModelConfig(merged)[agent] as ModelSettings;\n // Hard upper bound on a single LLM call. Without this, langchain's HTTP\n // client waits until the upstream cuts the socket (~3 minutes via\n // OpenRouter), blocking the entire chat response. 60 s is generous enough\n // for slow providers but bounds the worst case.\n const timeoutEnv = Number.parseInt(process.env.OPENROUTER_REQUEST_TIMEOUT_MS ?? \"\", 10);\n const timeout = Number.isFinite(timeoutEnv) && timeoutEnv > 0 ? timeoutEnv : 60_000;\n // ChatOpenAI defaults to maxRetries=2. That means a single hung upstream\n // provider gets retried up to 2 more times, each waiting `timeout` before\n // failing — so worst-case latency becomes timeout * 3. Cap retries at 1\n // so the worst case stays bounded at ~2 * timeout. Configurable via\n // OPENROUTER_MAX_RETRIES.\n const retriesEnv = Number.parseInt(process.env.OPENROUTER_MAX_RETRIES ?? \"\", 10);\n const maxRetries = Number.isFinite(retriesEnv) && retriesEnv >= 0 ? retriesEnv : 1;\n return new ChatOpenAI({\n model: cfg.model,\n configuration: {\n baseURL: merged.baseURL ?? process.env.OPENROUTER_BASE_URL ?? \"https://openrouter.ai/api/v1\",\n apiKey,\n },\n temperature: cfg.temperature,\n maxTokens: cfg.maxTokens,\n timeout,\n maxRetries,\n ...(cfg.reasoning && { modelKwargs: { reasoning: cfg.reasoning } }),\n });\n}\n"]}
1
+ {"version":3,"file":"model.config.js","sourceRoot":"/","sources":["shared/agent/model.config.ts"],"names":[],"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esContent":["import { ChatOpenAI } from \"@langchain/openai\";\n\n/** Settings that can be configured per agent. */\nexport interface ModelSettings {\n model: string;\n temperature?: number;\n maxTokens?: number;\n reasoning?: { effort?: 'minimal' | 'low' | 'medium' | 'high' | 'xhigh'; exclude?: boolean };\n}\n\n/**\n * Runtime configuration for the protocol package.\n * When passed via `ToolContext.modelConfig`, all fields (`apiKey`, `baseURL`, `chatModel`,\n * `chatReasoningEffort`) are honored by `ChatAgent` when the chat graph runs.\n * Other protocol agents don't read from `ToolContext` but may accept an explicit `ModelConfig`\n * as a direct parameter to `createModel()`.\n * All fields fall back to environment variables if not provided.\n */\nexport interface ModelConfig {\n /** OpenRouter API key. Falls back to OPENROUTER_API_KEY env var. */\n apiKey?: string;\n /** OpenRouter base URL. Falls back to OPENROUTER_BASE_URL env var. */\n baseURL?: string;\n /** Override the chat agent model. Falls back to CHAT_MODEL env var. */\n chatModel?: string;\n /** Override the chat reasoning effort. Falls back to CHAT_REASONING_EFFORT env var. */\n chatReasoningEffort?: 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';\n}\n\nfunction getModelConfig(config?: ModelConfig) {\n return {\n intentInferrer: { model: \"google/gemini-2.5-flash\" },\n intentIndexer: { model: \"google/gemini-2.5-flash\" },\n intentVerifier: { model: \"google/gemini-2.5-flash\" },\n intentReconciler: { model: \"google/gemini-2.5-flash\" },\n intentClarifier: { model: \"google/gemini-2.5-flash\" },\n profileGenerator: { model: \"google/gemini-2.5-flash\" },\n hydeGenerator: { model: \"google/gemini-2.5-flash\" },\n lensInferrer: { model: \"google/gemini-2.5-flash\" },\n opportunityEvaluator: { model: \"google/gemini-2.5-flash\" },\n opportunityPresenter: { model: \"google/gemini-2.5-flash\" },\n negotiator: { model: \"google/gemini-2.5-flash\" },\n homeCategorizer: { model: \"google/gemini-2.5-flash\" },\n suggestionGenerator: { model: \"google/gemini-2.5-flash\", temperature: 0.4, maxTokens: 512 },\n chatTitleGenerator: { model: \"google/gemini-2.5-flash\", temperature: 0.3, maxTokens: 32 },\n negotiationInsights: { model: \"google/gemini-2.5-flash\", temperature: 0.4, maxTokens: 512 },\n chatContextSummarizer: { model: \"google/gemini-2.5-flash\", temperature: 0.2, maxTokens: 512 },\n discoveryQuestionGenerator: { model: \"google/gemini-2.5-flash\", temperature: 0.5, maxTokens: 1024 },\n questioner: { model: \"google/gemini-2.5-flash\", temperature: 0.5, maxTokens: 1024 },\n negotiationSummarizer: { model: \"google/gemini-2.5-flash\", temperature: 0.2, maxTokens: 256 },\n inviteGenerator: { model: \"google/gemini-2.5-flash\", temperature: 0.3, maxTokens: 512 },\n premiseAnalyzer: { model: \"google/gemini-2.5-flash\" },\n premiseDecomposer: { model: \"google/gemini-2.5-flash\" },\n premiseIndexer: { model: \"google/gemini-2.5-flash\" },\n userContextGenerator: { model: \"google/gemini-2.5-flash\", temperature: 0.3, maxTokens: 512 },\n chat: {\n model: config?.chatModel ?? process.env.CHAT_MODEL ?? \"google/gemini-3-pro-preview\",\n maxTokens: 8192,\n reasoning: {\n effort: (config?.chatReasoningEffort ?? process.env.CHAT_REASONING_EFFORT ?? \"low\") as NonNullable<ModelSettings[\"reasoning\"]>[\"effort\"],\n exclude: true,\n },\n },\n } as const;\n}\n\n/**\n * Returns the model name string for the given agent key.\n * @param agent - Key from MODEL_CONFIG identifying which agent's settings to use.\n * @param config - Optional runtime config overrides.\n */\nexport function getModelName(agent: keyof ReturnType<typeof getModelConfig>, config?: ModelConfig): string {\n return getModelConfig(config)[agent].model;\n}\n\n/**\n * Creates a ChatOpenAI instance configured for OpenRouter.\n * @param agent - Key identifying which agent's model settings to use.\n * @param config - Optional runtime config overrides.\n */\nexport function createModel(agent: keyof ReturnType<typeof getModelConfig>, config?: ModelConfig): ChatOpenAI {\n const apiKey = config?.apiKey ?? process.env.OPENROUTER_API_KEY;\n if (!apiKey?.trim()) {\n throw new Error(`createModel(${agent}): OPENROUTER_API_KEY is required. Pass via the config argument, ToolContext.modelConfig.apiKey, or set the OPENROUTER_API_KEY environment variable.`);\n }\n const cfg = getModelConfig(config)[agent] as ModelSettings;\n // Hard upper bound on a single LLM call. Without this, langchain's HTTP\n // client waits until the upstream cuts the socket (~3 minutes via\n // OpenRouter), blocking the entire chat response. 60 s is generous enough\n // for slow providers but bounds the worst case.\n const timeoutEnv = Number.parseInt(process.env.OPENROUTER_REQUEST_TIMEOUT_MS ?? \"\", 10);\n const timeout = Number.isFinite(timeoutEnv) && timeoutEnv > 0 ? timeoutEnv : 60_000;\n // ChatOpenAI defaults to maxRetries=2. That means a single hung upstream\n // provider gets retried up to 2 more times, each waiting `timeout` before\n // failing — so worst-case latency becomes timeout * 3. Cap retries at 1\n // so the worst case stays bounded at ~2 * timeout. Configurable via\n // OPENROUTER_MAX_RETRIES.\n const retriesEnv = Number.parseInt(process.env.OPENROUTER_MAX_RETRIES ?? \"\", 10);\n const maxRetries = Number.isFinite(retriesEnv) && retriesEnv >= 0 ? retriesEnv : 1;\n return new ChatOpenAI({\n model: cfg.model,\n configuration: {\n baseURL: config?.baseURL ?? process.env.OPENROUTER_BASE_URL ?? \"https://openrouter.ai/api/v1\",\n apiKey,\n },\n temperature: cfg.temperature,\n maxTokens: cfg.maxTokens,\n timeout,\n maxRetries,\n ...(cfg.reasoning && { modelKwargs: { reasoning: cfg.reasoning } }),\n });\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"tool.factory.d.ts","sourceRoot":"/","sources":["shared/agent/tool.factory.ts"],"names":[],"mappings":"AAoBA,OAAO,EACL,KAAK,WAAW,EAChB,KAAK,mBAAmB,EAGzB,MAAM,mBAAmB,CAAC;AAe3B,YAAY,EAAE,WAAW,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACxF,YAAY,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAQlD;;;;;;;GAOG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,WAAW,EACjB,kBAAkB,CAAC,EAAE,mBAAmB,kBA2MzC;AAED;;GAEG;AACH,MAAM,MAAM,SAAS,GAAG,OAAO,CAAC,UAAU,CAAC,OAAO,eAAe,CAAC,CAAC,CAAC"}
1
+ {"version":3,"file":"tool.factory.d.ts","sourceRoot":"/","sources":["shared/agent/tool.factory.ts"],"names":[],"mappings":"AAmBA,OAAO,EACL,KAAK,WAAW,EAChB,KAAK,mBAAmB,EAGzB,MAAM,mBAAmB,CAAC;AAe3B,YAAY,EAAE,WAAW,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACxF,YAAY,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAQlD;;;;;;;GAOG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,WAAW,EACjB,kBAAkB,CAAC,EAAE,mBAAmB,kBAsMzC;AAED;;GAEG;AACH,MAAM,MAAM,SAAS,GAAG,OAAO,CAAC,UAAU,CAAC,OAAO,eAAe,CAAC,CAAC,CAAC"}
@@ -12,7 +12,6 @@ import { IntentIndexer } from "../../intent/intent.indexer.js";
12
12
  import { NegotiationGraphFactory } from "../../negotiation/negotiation.graph.js";
13
13
  import { PremiseGraphFactory } from "../../premise/premise.graph.js";
14
14
  import { protocolLogger } from "../observability/protocol.logger.js";
15
- import { configureProtocol } from "./model.config.js";
16
15
  import { resolveChatContext, } from "./tool.helpers.js";
17
16
  import { error, redactSensitiveFields } from "./tool.helpers.js";
18
17
  import { invokeToolRuntime, toolRuntimeErrorToResult } from "./tool.runtime.js";
@@ -39,10 +38,6 @@ const logger = protocolLogger("ChatTools");
39
38
  * via the `deps` parameter — the protocol lib never imports concrete adapters.
40
39
  */
41
40
  export async function createChatTools(deps, preResolvedContext) {
42
- // Apply model config so all agents created in this session use the right credentials.
43
- if (deps.modelConfig) {
44
- configureProtocol(deps.modelConfig);
45
- }
46
41
  const { database, embedder, scraper } = deps;
47
42
  // ─── Resolve context from DB ───────────────────────────────────────────────
48
43
  const resolvedContext = preResolvedContext ??
@@ -1 +1 @@
1
- {"version":3,"file":"t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GAAG,gBAAgB;QACnB,GAAG,YAAY;QACf,GAAG,UAAU;QACb,GAAG,gBAAgB;QACnB,GAAG,YAAY;KAChB,CAAC;AACJ,CAAC","sourcesContent":["import { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport type { HydeGraphDatabase, PremiseGraphDatabase } from \"../interfaces/database.interface.js\";\nimport { IntentGraphFactory } from \"../../intent/intent.graph.js\";\nimport { ProfileGraphFactory } from \"../../profile/profile.graph.js\";\nimport { OpportunityGraphFactory } from \"../../opportunity/opportunity.graph.js\";\nimport { HydeGraphFactory } from \"../hyde/hyde.graph.js\";\nimport { HydeGenerator } from \"../hyde/hyde.generator.js\";\nimport { LensInferrer } from \"../hyde/lens.inferrer.js\";\nimport { NetworkGraphFactory } from \"../../network/network.graph.js\";\nimport { NetworkMembershipGraphFactory } from \"../../network/membership/membership.graph.js\";\nimport { IntentNetworkGraphFactory } from \"../../network/indexer/indexer.graph.js\";\nimport { IntentIndexer } from \"../../intent/intent.indexer.js\";\nimport { NegotiationGraphFactory } from \"../../negotiation/negotiation.graph.js\";\nimport { PremiseGraphFactory } from \"../../premise/premise.graph.js\";\nimport { protocolLogger } from \"../observability/protocol.logger.js\";\nimport { configureProtocol } from \"./model.config.js\";\n\nimport type { QuestionerEnqueueFn } from \"../../questioner/questioner.types.js\";\n\nimport {\n type ToolContext,\n type ResolvedToolContext,\n type ToolDeps,\n resolveChatContext,\n} from \"./tool.helpers.js\";\nimport { error, redactSensitiveFields } from \"./tool.helpers.js\";\nimport { invokeToolRuntime, toolRuntimeErrorToResult } from \"./tool.runtime.js\";\nimport { createProfileTools } from \"../../profile/profile.tools.js\";\nimport { createIntentTools } from \"../../intent/intent.tools.js\";\nimport { createNetworkTools } from \"../../network/network.tools.js\";\nimport { createOpportunityTools } from \"../../opportunity/opportunity.tools.js\";\nimport { createUtilityTools } from \"./utility.tools.js\";\nimport { createIntegrationTools } from \"../../integration/integration.tools.js\";\nimport { createContactTools } from \"../../contact/contact.tools.js\";\nimport { createAgentTools } from \"../../agent/agent.tools.js\";\nimport { createNegotiationTools } from \"../../negotiation/negotiation.tools.js\";\nimport { createPremiseTools } from \"../../premise/premise.tools.js\";\n\n// Re-export types for consumers\nexport type { ToolContext, ResolvedToolContext, ProtocolDeps } from \"./tool.helpers.js\";\nexport type { ToolDeps } from \"./tool.helpers.js\";\n\nconst logger = protocolLogger(\"ChatTools\");\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TOOL FACTORY\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Creates all chat tools bound to a specific user context.\n * Resolves user/index identity from DB at init time.\n * Tools are created fresh for each user session to ensure proper isolation.\n *\n * All external dependencies (cache, integration, queue, etc.) are provided\n * via the `deps` parameter — the protocol lib never imports concrete adapters.\n */\nexport async function createChatTools(\n deps: ToolContext,\n preResolvedContext?: ResolvedToolContext\n) {\n // Apply model config so all agents created in this session use the right credentials.\n if (deps.modelConfig) {\n configureProtocol(deps.modelConfig);\n }\n\n const { database, embedder, scraper } = deps;\n\n // ─── Resolve context from DB ───────────────────────────────────────────────\n const resolvedContext =\n preResolvedContext ??\n (await resolveChatContext({\n database,\n userId: deps.userId,\n networkId: deps.networkId,\n sessionId: deps.sessionId,\n }));\n\n // Allow callers (e.g. MCP server, tests) to override the computed indexScope\n // without going through a full re-resolve. The MCP path sets this via\n // applyNetworkScopeToContext; ToolContext.indexScope provides the same override\n // when no preResolvedContext is given.\n if (!preResolvedContext && deps.indexScope !== undefined) {\n resolvedContext.indexScope = deps.indexScope;\n }\n\n // ─── Tool wrapper ──────────────────────────────────────────────────────────\n /**\n * Standardized tool factory. Auto-injects resolved context and\n * provides uniform logging / error handling for every tool.\n */\n function defineTool<T extends z.ZodType>(opts: {\n name: string;\n description: string;\n querySchema: T;\n handler: (input: { context: ResolvedToolContext; query: z.infer<T> }) => Promise<string>;\n }) {\n return tool(\n async (query: z.infer<T>) => {\n logger.info(`Tool: ${opts.name}`, {\n context: { userId: resolvedContext.userId, networkId: resolvedContext.networkId },\n query: redactSensitiveFields(query),\n });\n try {\n return await invokeToolRuntime({\n toolName: opts.name,\n tool: { handler: async ({ context, query }) => opts.handler({ context, query: query as z.infer<T> }) },\n context: resolvedContext,\n query,\n });\n } catch (err) {\n logger.error(`${opts.name} failed`, {\n error: err instanceof Error ? err.message : String(err),\n });\n const runtimeResult = toolRuntimeErrorToResult(err);\n if (runtimeResult) return runtimeResult;\n const reason = err instanceof Error ? err.message : String(err);\n return error(`Failed to execute ${opts.name}: ${reason}`);\n }\n },\n { name: opts.name, description: opts.description, schema: opts.querySchema }\n );\n }\n\n // ─── Compile subgraphs ─────────────────────────────────────────────────────\n\n // Wrap questionerEnqueue to include session context when available\n const sessionAwareEnqueue: QuestionerEnqueueFn | undefined = deps.questionerEnqueue\n ? (input) => deps.questionerEnqueue!({\n ...input,\n ...(resolvedContext.sessionId && !input.conversationId ? { conversationId: resolvedContext.sessionId } : {}),\n })\n : undefined;\n\n const intentGraph = new IntentGraphFactory(database, embedder, deps.intentQueue, sessionAwareEnqueue).createGraph();\n const premiseGraph = new PremiseGraphFactory(database as unknown as PremiseGraphDatabase, embedder).createGraph();\n const profileGraph = new ProfileGraphFactory(database, scraper, deps.enricher, sessionAwareEnqueue, premiseGraph).createGraph();\n const hydeCache = deps.hydeCache;\n const lensInferrer = new LensInferrer();\n const hydeGenerator = new HydeGenerator();\n const compiledHydeGraph = new HydeGraphFactory(\n database as unknown as HydeGraphDatabase,\n embedder,\n hydeCache,\n lensInferrer,\n hydeGenerator\n ).createGraph();\n const negotiationGraph = deps.agentDispatcher\n ? new NegotiationGraphFactory(\n deps.negotiationDatabase,\n deps.agentDispatcher,\n deps.negotiationTimeoutQueue,\n sessionAwareEnqueue,\n ).createGraph()\n : undefined;\n const opportunityGraph = new OpportunityGraphFactory(\n database,\n embedder,\n compiledHydeGraph,\n undefined, // evaluator (default)\n undefined, // queueNotification\n negotiationGraph,\n deps.agentDispatcher,\n deps.queueNegotiateExisting,\n ).createGraph();\n const networkGraph = new NetworkGraphFactory(database).createGraph();\n const networkMembershipGraph = new NetworkMembershipGraphFactory(database).createGraph();\n const intentNetworkGraph = new IntentNetworkGraphFactory(database, new IntentIndexer()).createGraph();\n\n // ─── Create context-bound databases ────────────────────────────────────────\n // Use injected instances when provided (e.g. tests). Otherwise create from the same\n // database used for graphs so that scope checks (e.g. ensureScopedMembership, opportunity\n // update) use the same adapter as the rest of the tool pipeline.\n //\n // The systemDb's DB-level clamp uses `resolvedContext.indexScope` — the same\n // set tools see — so the JSDoc claim that indexScope is \"the same set used\n // to clamp the DB-level systemDb\" holds for both the MCP path (where the\n // MCP server already populated indexScope via applyNetworkScopeToContext)\n // and the web-chat path (where resolveChatContext clamps to [bound, personal]\n // when networkId is set).\n const userDb = deps.userDb ?? deps.createUserDatabase(database, resolvedContext.userId);\n const systemDb = deps.systemDb ?? deps.createSystemDatabase(database, resolvedContext.userId, resolvedContext.indexScope, embedder);\n\n // ─── Assemble dependencies ─────────────────────────────────────────────────\n const cache = deps.cache;\n const integration = deps.integration;\n const toolDeps: ToolDeps = {\n database,\n userDb,\n systemDb,\n scraper,\n embedder,\n cache,\n integration,\n contactService: deps.contactService,\n integrationImporter: deps.integrationImporter,\n enricher: deps.enricher,\n negotiationDatabase: deps.negotiationDatabase,\n negotiationTimeoutQueue: deps.negotiationTimeoutQueue,\n agentDatabase: deps.agentDatabase,\n grantDefaultSystemPermissions: deps.grantDefaultSystemPermissions,\n agentDispatcher: deps.agentDispatcher,\n deliveryLedger: deps.deliveryLedger,\n discoveryRuns: deps.discoveryRuns,\n discoveryRunQueue: deps.discoveryRunQueue,\n profileRuns: deps.profileRuns,\n profileRunQueue: deps.profileRunQueue,\n mintConnectToken: deps.mintConnectToken,\n mintConnectLink: deps.mintConnectLink,\n frontendUrl: deps.frontendUrl,\n apiBaseUrl: deps.apiBaseUrl,\n ...(deps.premiseEvents && { premiseEvents: deps.premiseEvents }),\n ...(deps.chatSummary && { chatSummary: deps.chatSummary }),\n ...(deps.questionGenerator && { questionGenerator: deps.questionGenerator }),\n ...(sessionAwareEnqueue && { questionerEnqueue: sessionAwareEnqueue }),\n ...(deps.negotiationSummary && { negotiationSummary: deps.negotiationSummary }),\n graphs: {\n profile: profileGraph,\n intent: intentGraph,\n index: networkGraph,\n networkMembership: networkMembershipGraph,\n intentIndex: intentNetworkGraph,\n opportunity: opportunityGraph,\n premise: premiseGraph,\n },\n };\n\n // ─── Create domain tools ──────────────────────────────────────────────────\n const profileTools = createProfileTools(defineTool, toolDeps);\n const intentTools = createIntentTools(defineTool, toolDeps);\n const networkTools = createNetworkTools(defineTool, toolDeps);\n const opportunityTools = createOpportunityTools(defineTool, toolDeps);\n const utilityTools = createUtilityTools(defineTool, toolDeps);\n const contactTools = createContactTools(defineTool, toolDeps);\n const agentTools = createAgentTools(defineTool, toolDeps);\n const integrationTools = createIntegrationTools(defineTool, toolDeps);\n const negotiationTools = deps.agentDispatcher\n ? createNegotiationTools(defineTool, toolDeps)\n : [];\n const premiseTools = createPremiseTools(defineTool, toolDeps);\n\n // confirm_opportunity_delivery is an OpenClaw-delivery ledger write and must not be\n // callable from regular chat sessions.\n const chatOpportunityToolExclusions = new Set([\n \"confirm_opportunity_delivery\",\n ]);\n const opportunityToolsForChat = opportunityTools.filter(\n (t) => !chatOpportunityToolExclusions.has((t as { name: string }).name)\n );\n\n return [\n ...profileTools,\n ...intentTools,\n ...networkTools,\n ...opportunityToolsForChat,\n ...utilityTools,\n ...integrationTools,\n ...contactTools,\n ...agentTools,\n ...negotiationTools,\n ...premiseTools,\n ];\n}\n\n/**\n * Type for the tools array returned by createChatTools.\n */\nexport type ChatTools = Awaited<ReturnType<typeof createChatTools>>;\n"]}
1
+ {"version":3,"file":"tool.factory.js","sourceRoot":"/","sources":["shared/agent/tool.factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAG7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AACl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sB,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;IACtE,MAAM,YAAY,GAAG,kBAAkB,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;IAC9D,MAAM,YAAY,GAAG,kBAAkB,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;IAC9D,MAAM,UAAU,GAAG,gBAAgB,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;IAC1D,MAAM,gBAAgB,GAAG,sBAAsB,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;IACtE,MAAM,gBAAgB,GAAG,IAAI,CAAC,eAAe;QAC3C,CAAC,CAAC,sBAAsB,CAAC,UAAU,EAAE,QAAQ,CAAC;QAC9C,CAAC,CAAC,EAAE,CAAC;IACP,MAAM,YAAY,GAAG,kBAAkB,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;IAE9D,oFAAoF;IACpF,uCAAuC;IACvC,MAAM,6BAA6B,GAAG,IAAI,GAAG,CAAC;QAC5C,8BAA8B;KAC/B,CAAC,CAAC;IACH,MAAM,uBAAuB,GAAG,gBAAgB,CAAC,MAAM,CACrD,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,6BAA6B,CAAC,GAAG,CAAE,CAAsB,CAAC,IAAI,CAAC,CACxE,CAAC;IAEF,OAAO;QACL,GAAG,YAAY;QACf,GAAG,WAAW;QACd,GAAG,YAAY;QACf,GAAG,uBAAuB;QAC1B,GAAG,YAAY;QACf,GAAG,gBAAgB;QACnB,GAAG,YAAY;QACf,GAAG,UAAU;QACb,GAAG,gBAAgB;QACnB,GAAG,YAAY;KAChB,CAAC;AACJ,CAAC","sourcesContent":["import { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport type { HydeGraphDatabase, PremiseGraphDatabase } from \"../interfaces/database.interface.js\";\nimport { IntentGraphFactory } from \"../../intent/intent.graph.js\";\nimport { ProfileGraphFactory } from \"../../profile/profile.graph.js\";\nimport { OpportunityGraphFactory } from \"../../opportunity/opportunity.graph.js\";\nimport { HydeGraphFactory } from \"../hyde/hyde.graph.js\";\nimport { HydeGenerator } from \"../hyde/hyde.generator.js\";\nimport { LensInferrer } from \"../hyde/lens.inferrer.js\";\nimport { NetworkGraphFactory } from \"../../network/network.graph.js\";\nimport { NetworkMembershipGraphFactory } from \"../../network/membership/membership.graph.js\";\nimport { IntentNetworkGraphFactory } from \"../../network/indexer/indexer.graph.js\";\nimport { IntentIndexer } from \"../../intent/intent.indexer.js\";\nimport { NegotiationGraphFactory } from \"../../negotiation/negotiation.graph.js\";\nimport { PremiseGraphFactory } from \"../../premise/premise.graph.js\";\nimport { protocolLogger } from \"../observability/protocol.logger.js\";\n\nimport type { QuestionerEnqueueFn } from \"../../questioner/questioner.types.js\";\n\nimport {\n type ToolContext,\n type ResolvedToolContext,\n type ToolDeps,\n resolveChatContext,\n} from \"./tool.helpers.js\";\nimport { error, redactSensitiveFields } from \"./tool.helpers.js\";\nimport { invokeToolRuntime, toolRuntimeErrorToResult } from \"./tool.runtime.js\";\nimport { createProfileTools } from \"../../profile/profile.tools.js\";\nimport { createIntentTools } from \"../../intent/intent.tools.js\";\nimport { createNetworkTools } from \"../../network/network.tools.js\";\nimport { createOpportunityTools } from \"../../opportunity/opportunity.tools.js\";\nimport { createUtilityTools } from \"./utility.tools.js\";\nimport { createIntegrationTools } from \"../../integration/integration.tools.js\";\nimport { createContactTools } from \"../../contact/contact.tools.js\";\nimport { createAgentTools } from \"../../agent/agent.tools.js\";\nimport { createNegotiationTools } from \"../../negotiation/negotiation.tools.js\";\nimport { createPremiseTools } from \"../../premise/premise.tools.js\";\n\n// Re-export types for consumers\nexport type { ToolContext, ResolvedToolContext, ProtocolDeps } from \"./tool.helpers.js\";\nexport type { ToolDeps } from \"./tool.helpers.js\";\n\nconst logger = protocolLogger(\"ChatTools\");\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TOOL FACTORY\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Creates all chat tools bound to a specific user context.\n * Resolves user/index identity from DB at init time.\n * Tools are created fresh for each user session to ensure proper isolation.\n *\n * All external dependencies (cache, integration, queue, etc.) are provided\n * via the `deps` parameter — the protocol lib never imports concrete adapters.\n */\nexport async function createChatTools(\n deps: ToolContext,\n preResolvedContext?: ResolvedToolContext\n) {\n const { database, embedder, scraper } = deps;\n\n // ─── Resolve context from DB ───────────────────────────────────────────────\n const resolvedContext =\n preResolvedContext ??\n (await resolveChatContext({\n database,\n userId: deps.userId,\n networkId: deps.networkId,\n sessionId: deps.sessionId,\n }));\n\n // Allow callers (e.g. MCP server, tests) to override the computed indexScope\n // without going through a full re-resolve. The MCP path sets this via\n // applyNetworkScopeToContext; ToolContext.indexScope provides the same override\n // when no preResolvedContext is given.\n if (!preResolvedContext && deps.indexScope !== undefined) {\n resolvedContext.indexScope = deps.indexScope;\n }\n\n // ─── Tool wrapper ──────────────────────────────────────────────────────────\n /**\n * Standardized tool factory. Auto-injects resolved context and\n * provides uniform logging / error handling for every tool.\n */\n function defineTool<T extends z.ZodType>(opts: {\n name: string;\n description: string;\n querySchema: T;\n handler: (input: { context: ResolvedToolContext; query: z.infer<T> }) => Promise<string>;\n }) {\n return tool(\n async (query: z.infer<T>) => {\n logger.info(`Tool: ${opts.name}`, {\n context: { userId: resolvedContext.userId, networkId: resolvedContext.networkId },\n query: redactSensitiveFields(query),\n });\n try {\n return await invokeToolRuntime({\n toolName: opts.name,\n tool: { handler: async ({ context, query }) => opts.handler({ context, query: query as z.infer<T> }) },\n context: resolvedContext,\n query,\n });\n } catch (err) {\n logger.error(`${opts.name} failed`, {\n error: err instanceof Error ? err.message : String(err),\n });\n const runtimeResult = toolRuntimeErrorToResult(err);\n if (runtimeResult) return runtimeResult;\n const reason = err instanceof Error ? err.message : String(err);\n return error(`Failed to execute ${opts.name}: ${reason}`);\n }\n },\n { name: opts.name, description: opts.description, schema: opts.querySchema }\n );\n }\n\n // ─── Compile subgraphs ─────────────────────────────────────────────────────\n\n // Wrap questionerEnqueue to include session context when available\n const sessionAwareEnqueue: QuestionerEnqueueFn | undefined = deps.questionerEnqueue\n ? (input) => deps.questionerEnqueue!({\n ...input,\n ...(resolvedContext.sessionId && !input.conversationId ? { conversationId: resolvedContext.sessionId } : {}),\n })\n : undefined;\n\n const intentGraph = new IntentGraphFactory(database, embedder, deps.intentQueue, sessionAwareEnqueue).createGraph();\n const premiseGraph = new PremiseGraphFactory(database as unknown as PremiseGraphDatabase, embedder).createGraph();\n const profileGraph = new ProfileGraphFactory(database, scraper, deps.enricher, sessionAwareEnqueue, premiseGraph).createGraph();\n const hydeCache = deps.hydeCache;\n const lensInferrer = new LensInferrer();\n const hydeGenerator = new HydeGenerator();\n const compiledHydeGraph = new HydeGraphFactory(\n database as unknown as HydeGraphDatabase,\n embedder,\n hydeCache,\n lensInferrer,\n hydeGenerator\n ).createGraph();\n const negotiationGraph = deps.agentDispatcher\n ? new NegotiationGraphFactory(\n deps.negotiationDatabase,\n deps.agentDispatcher,\n deps.negotiationTimeoutQueue,\n sessionAwareEnqueue,\n ).createGraph()\n : undefined;\n const opportunityGraph = new OpportunityGraphFactory(\n database,\n embedder,\n compiledHydeGraph,\n undefined, // evaluator (default)\n undefined, // queueNotification\n negotiationGraph,\n deps.agentDispatcher,\n deps.queueNegotiateExisting,\n ).createGraph();\n const networkGraph = new NetworkGraphFactory(database).createGraph();\n const networkMembershipGraph = new NetworkMembershipGraphFactory(database).createGraph();\n const intentNetworkGraph = new IntentNetworkGraphFactory(database, new IntentIndexer()).createGraph();\n\n // ─── Create context-bound databases ────────────────────────────────────────\n // Use injected instances when provided (e.g. tests). Otherwise create from the same\n // database used for graphs so that scope checks (e.g. ensureScopedMembership, opportunity\n // update) use the same adapter as the rest of the tool pipeline.\n //\n // The systemDb's DB-level clamp uses `resolvedContext.indexScope` — the same\n // set tools see — so the JSDoc claim that indexScope is \"the same set used\n // to clamp the DB-level systemDb\" holds for both the MCP path (where the\n // MCP server already populated indexScope via applyNetworkScopeToContext)\n // and the web-chat path (where resolveChatContext clamps to [bound, personal]\n // when networkId is set).\n const userDb = deps.userDb ?? deps.createUserDatabase(database, resolvedContext.userId);\n const systemDb = deps.systemDb ?? deps.createSystemDatabase(database, resolvedContext.userId, resolvedContext.indexScope, embedder);\n\n // ─── Assemble dependencies ─────────────────────────────────────────────────\n const cache = deps.cache;\n const integration = deps.integration;\n const toolDeps: ToolDeps = {\n database,\n userDb,\n systemDb,\n scraper,\n embedder,\n cache,\n integration,\n contactService: deps.contactService,\n integrationImporter: deps.integrationImporter,\n enricher: deps.enricher,\n negotiationDatabase: deps.negotiationDatabase,\n negotiationTimeoutQueue: deps.negotiationTimeoutQueue,\n agentDatabase: deps.agentDatabase,\n grantDefaultSystemPermissions: deps.grantDefaultSystemPermissions,\n agentDispatcher: deps.agentDispatcher,\n deliveryLedger: deps.deliveryLedger,\n discoveryRuns: deps.discoveryRuns,\n discoveryRunQueue: deps.discoveryRunQueue,\n profileRuns: deps.profileRuns,\n profileRunQueue: deps.profileRunQueue,\n mintConnectToken: deps.mintConnectToken,\n mintConnectLink: deps.mintConnectLink,\n frontendUrl: deps.frontendUrl,\n apiBaseUrl: deps.apiBaseUrl,\n ...(deps.premiseEvents && { premiseEvents: deps.premiseEvents }),\n ...(deps.chatSummary && { chatSummary: deps.chatSummary }),\n ...(deps.questionGenerator && { questionGenerator: deps.questionGenerator }),\n ...(sessionAwareEnqueue && { questionerEnqueue: sessionAwareEnqueue }),\n ...(deps.negotiationSummary && { negotiationSummary: deps.negotiationSummary }),\n graphs: {\n profile: profileGraph,\n intent: intentGraph,\n index: networkGraph,\n networkMembership: networkMembershipGraph,\n intentIndex: intentNetworkGraph,\n opportunity: opportunityGraph,\n premise: premiseGraph,\n },\n };\n\n // ─── Create domain tools ──────────────────────────────────────────────────\n const profileTools = createProfileTools(defineTool, toolDeps);\n const intentTools = createIntentTools(defineTool, toolDeps);\n const networkTools = createNetworkTools(defineTool, toolDeps);\n const opportunityTools = createOpportunityTools(defineTool, toolDeps);\n const utilityTools = createUtilityTools(defineTool, toolDeps);\n const contactTools = createContactTools(defineTool, toolDeps);\n const agentTools = createAgentTools(defineTool, toolDeps);\n const integrationTools = createIntegrationTools(defineTool, toolDeps);\n const negotiationTools = deps.agentDispatcher\n ? createNegotiationTools(defineTool, toolDeps)\n : [];\n const premiseTools = createPremiseTools(defineTool, toolDeps);\n\n // confirm_opportunity_delivery is an OpenClaw-delivery ledger write and must not be\n // callable from regular chat sessions.\n const chatOpportunityToolExclusions = new Set([\n \"confirm_opportunity_delivery\",\n ]);\n const opportunityToolsForChat = opportunityTools.filter(\n (t) => !chatOpportunityToolExclusions.has((t as { name: string }).name)\n );\n\n return [\n ...profileTools,\n ...intentTools,\n ...networkTools,\n ...opportunityToolsForChat,\n ...utilityTools,\n ...integrationTools,\n ...contactTools,\n ...agentTools,\n ...negotiationTools,\n ...premiseTools,\n ];\n}\n\n/**\n * Type for the tools array returned by createChatTools.\n */\nexport type ChatTools = Awaited<ReturnType<typeof createChatTools>>;\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@indexnetwork/protocol",
3
- "version": "1.26.9-rc.237.1",
3
+ "version": "2.0.0-rc.238.1",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",