@indexnetwork/protocol 6.7.0-rc.392.1 → 6.7.1-rc.393.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chat/chat-streaming.types.d.ts +1 -7
- package/dist/chat/chat-streaming.types.d.ts.map +1 -1
- package/dist/chat/chat-streaming.types.js.map +1 -1
- package/dist/chat/chat.agent.d.ts +0 -7
- package/dist/chat/chat.agent.d.ts.map +1 -1
- package/dist/chat/chat.agent.js.map +1 -1
- package/dist/questioner/questioner.ask.tool.d.ts.map +1 -1
- package/dist/questioner/questioner.ask.tool.js +3 -7
- package/dist/questioner/questioner.ask.tool.js.map +1 -1
- package/dist/shared/observability/request-context.d.ts +0 -7
- package/dist/shared/observability/request-context.d.ts.map +1 -1
- package/dist/shared/observability/request-context.js.map +1 -1
- package/package.json +1 -1
|
@@ -481,14 +481,8 @@ export interface DecisionQuestionsEvent extends ChatStreamEventBase {
|
|
|
481
481
|
* questions REST endpoints while the turn is still blocked.
|
|
482
482
|
*/
|
|
483
483
|
export interface UserQuestionPayload {
|
|
484
|
+
/** Canonical question identity. The client must resolve all display fields from the server. */
|
|
484
485
|
id: string;
|
|
485
|
-
title: string;
|
|
486
|
-
prompt: string;
|
|
487
|
-
options: Array<{
|
|
488
|
-
label: string;
|
|
489
|
-
description: string;
|
|
490
|
-
}>;
|
|
491
|
-
multiSelect: boolean;
|
|
492
486
|
}
|
|
493
487
|
/**
|
|
494
488
|
* User question event — emitted when the orchestrator's ask_user_question
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat-streaming.types.d.ts","sourceRoot":"/","sources":["chat/chat-streaming.types.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AAGvF,MAAM,MAAM,mBAAmB,GAC3B,QAAQ,GACR,SAAS,GACT,UAAU,GACV,gBAAgB,GAChB,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,CAEnB;AAED;;GAEG;AACH,wBAAgB,uBAAuB,CACrC,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,OAAO,GAAG,OAAO,EAC3B,SAAS,EAAE,MAAM,GAChB,iBAAiB,CAKnB"}
|
|
1
|
+
{"version":3,"file":"chat-streaming.types.d.ts","sourceRoot":"/","sources":["chat/chat-streaming.types.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AAGvF,MAAM,MAAM,mBAAmB,GAC3B,QAAQ,GACR,SAAS,GACT,UAAU,GACV,gBAAgB,GAChB,iBAAiB,GACjB,OAAO,GACP,MAAM,GACN,OAAO,GAEP,YAAY,GACZ,UAAU,GACV,gBAAgB,GAEhB,eAAe,GAEf,iBAAiB,GACjB,WAAW,GACX,SAAS,GAET,mBAAmB,GACnB,gBAAgB,GAEhB,YAAY,GACZ,aAAa,GACb,WAAW,GACX,aAAa,GACb,WAAW,GACX,aAAa,GACb,WAAW,GACX,wBAAwB,GAExB,2BAA2B,GAC3B,yBAAyB,GACzB,kBAAkB,GAClB,qBAAqB,GAErB,uBAAuB,GACvB,qBAAqB,GACrB,0BAA0B,GAC1B,wBAAwB,GACxB,oBAAoB,GAEpB,eAAe,GAEf,gBAAgB,CAAC;AAErB;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC,+BAA+B;IAC/B,IAAI,EAAE,mBAAmB,CAAC;IAC1B,sCAAsC;IACtC,SAAS,EAAE,MAAM,CAAC;IAClB,yBAAyB;IACzB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;;GAEG;AACH,MAAM,WAAW,WAAY,SAAQ,mBAAmB;IACtD,IAAI,EAAE,QAAQ,CAAC;IACf,oCAAoC;IACpC,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;GAEG;AACH,MAAM,WAAW,YAAa,SAAQ,mBAAmB;IACvD,IAAI,EAAE,SAAS,CAAC;IAChB,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UAAU,+BAA+B,CAC7C,SAAiB,EACjB,OAA6C;IAE7C,OAAO,iBAAiB,CAA4B,wBAAwB,EAAE,SAAS,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;AACxG,CAAC;AAED,MAAM,UAAU,4BAA4B,CAC1C,SAAiB,EACjB,OAAkC;IAElC,OAAO,iBAAiB,CAAyB,oBAAoB,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;AAC7F,CAAC;AAED,MAAM,UAAU,uBAAuB,CACrC,SAAiB,EACjB,OAA6C;IAE7C,OAAO,iBAAiB,CAAoB,eAAe,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;AACnF,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,uBAAuB,CACrC,SAAiB,EACjB,QAA2B,EAC3B,SAAiB;IAEjB,OAAO,iBAAiB,CAAoB,gBAAgB,EAAE,SAAS,EAAE;QACvE,QAAQ;QACR,SAAS;KACV,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * SSE Event types for Chat Graph streaming.\n *\n * These types define the structure of events sent during streaming chat responses.\n * Events are sent as Server-Sent Events (SSE) with JSON payloads.\n */\n\nimport type { Question, QuestionStrategy } from \"../shared/schemas/question.schema.js\";\n\n// Event type discriminator\nexport type ChatStreamEventType =\n | \"status\"\n | \"routing\"\n | \"thinking\"\n | \"subgraph_start\"\n | \"subgraph_result\"\n | \"token\"\n | \"done\"\n | \"error\"\n // Agent Loop Architecture events\n | \"tool_start\"\n | \"tool_end\"\n | \"agent_thinking\"\n // Streaming narration events\n | \"tool_activity\"\n // Agent loop trace events\n | \"iteration_start\"\n | \"llm_start\"\n | \"llm_end\"\n // Internal response tracking events\n | \"response_complete\"\n | \"response_reset\"\n // Debug meta (per-turn graph/tool usage for copy debug)\n | \"debug_meta\"\n | \"graph_start\"\n | \"graph_end\"\n | \"phase_start\"\n | \"phase_end\"\n | \"agent_start\"\n | \"agent_end\"\n | \"hallucination_detected\"\n // Orchestrator-inline negotiation trace events\n | \"negotiation_session_start\"\n | \"negotiation_session_end\"\n | \"negotiation_turn\"\n | \"negotiation_outcome\"\n // Discovery decision-question events\n | \"chat_summarizer_start\"\n | \"chat_summarizer_end\"\n | \"question_generator_start\"\n | \"question_generator_end\"\n | \"decision_questions\"\n // Blocking mid-turn user question (ask_user_question tool)\n | \"user_question\"\n // Steer-or-queue interrupt event\n | \"steer_or_queue\";\n\n/**\n * Base interface for all chat stream events.\n */\nexport interface ChatStreamEventBase {\n /** Event type discriminator */\n type: ChatStreamEventType;\n /** Session ID for the chat session */\n sessionId: string;\n /** ISO 8601 timestamp */\n timestamp: string;\n}\n\n/**\n * Status event - sent to indicate processing state changes.\n */\nexport interface StatusEvent extends ChatStreamEventBase {\n type: \"status\";\n /** Human-readable status message */\n message: string;\n}\n\n/**\n * Routing event - sent when the router determines which subgraph to use.\n */\nexport interface RoutingEvent extends ChatStreamEventBase {\n type: \"routing\";\n /** Target subgraph name */\n target: string;\n /** Optional reasoning for the routing decision */\n reasoning?: string;\n}\n\n/**\n * Thinking event - sent to stream the model's reasoning and decision-making process.\n */\nexport interface ThinkingEvent extends ChatStreamEventBase {\n type: \"thinking\";\n /** The thinking/reasoning content */\n content: string;\n /** Optional step identifier (e.g., 'router', 'inference', 'verification') */\n step?: string;\n}\n\n/**\n * Subgraph start event - sent when a subgraph begins processing.\n */\nexport interface SubgraphStartEvent extends ChatStreamEventBase {\n type: \"subgraph_start\";\n /** Name of the subgraph being executed */\n subgraph: string;\n}\n\n/**\n * Subgraph result event - sent when a subgraph completes with results.\n */\nexport interface SubgraphResultEvent extends ChatStreamEventBase {\n type: \"subgraph_result\";\n /** Name of the subgraph that completed */\n subgraph: string;\n /** Result data from the subgraph */\n data: Record<string, unknown>;\n}\n\n/**\n * Token event - sent for each token during streaming response.\n */\nexport interface TokenEvent extends ChatStreamEventBase {\n type: \"token\";\n /** Token content (partial text) */\n content: string;\n}\n\n/**\n * Chat suggestion for follow-up actions.\n * Matches frontend Suggestion type (label, type, followupText/prefill).\n */\nexport interface ChatSuggestion {\n label: string;\n type: \"direct\" | \"prompt\";\n /** For 'direct' type: text to auto-submit as next message */\n followupText?: string;\n /** For 'prompt' type: text to prefill the input */\n prefill?: string;\n}\n\n/**\n * Rich opportunity card data for chat messages.\n * Matches the home page card format for consistent rendering.\n */\nexport interface OpportunityCardPayload {\n opportunityId: string;\n userId: string;\n name?: string;\n avatar?: string | null;\n /** Main body text (personalizedSummary from presenter). */\n mainText: string;\n /** Call-to-action line (suggestedAction from presenter). */\n cta?: string;\n /** Short headline hook. */\n headline?: string;\n /** Label for primary action button (e.g. \"Start Chat\"). */\n primaryActionLabel?: string;\n /** Label for secondary action button (e.g. \"Skip\"). */\n secondaryActionLabel?: string;\n /** Subtitle under the other party name (e.g. \"1 mutual intent\"). */\n mutualIntentsLabel?: string;\n /** Narrator chip for human-introduced opportunities. */\n narratorChip?: {\n name: string;\n text: string;\n avatar?: string | null;\n userId?: string;\n };\n /** Viewer's role in this opportunity. */\n viewerRole?: string;\n /** Match confidence score (0-1). */\n score?: number;\n /** Opportunity status. */\n status?: string;\n /** Second party in introducer arrow layout (name -> name). Present when viewerRole is 'introducer'. */\n secondParty?: {\n name: string;\n avatar?: string | null;\n userId?: string;\n };\n}\n\n/**\n * Done event - sent when the response is complete.\n */\nexport interface DoneEvent extends ChatStreamEventBase {\n type: \"done\";\n /** Complete response text */\n response: string;\n /** Server-generated assistant message ID (for trace event persistence) */\n messageId?: string;\n /** Optional routing decision metadata */\n routingDecision?: Record<string, unknown>;\n /** Optional subgraph results metadata */\n subgraphResults?: Record<string, unknown>;\n /** Optional session title (auto-generated or existing) */\n title?: string;\n /** Optional context-aware follow-up suggestions */\n suggestions?: ChatSuggestion[];\n /** Optional rich opportunity cards returned by tools */\n opportunityCards?: OpportunityCardPayload[];\n /** Decision questions to render (orchestrator flow only). */\n decisionQuestions?: Question[];\n}\n\n/**\n * Error event - sent when an error occurs.\n */\nexport interface ErrorEvent extends ChatStreamEventBase {\n type: \"error\";\n /** Human-readable error message */\n message: string;\n /** Optional error code for programmatic handling */\n code?: string;\n}\n\n// ════════════════════════════════════════════════════════════════════════════\n// AGENT LOOP ARCHITECTURE EVENTS\n// ════════════════════════════════════════════════════════════════════════════\n\n/**\n * Tool start event - sent when a tool begins executing.\n */\nexport interface ToolStartEvent extends ChatStreamEventBase {\n type: \"tool_start\";\n /** Name of the tool being executed */\n toolName: string;\n /** Arguments passed to the tool */\n toolArgs: Record<string, unknown>;\n}\n\n/**\n * Tool end event - sent when a tool finishes executing.\n */\nexport interface ToolEndEvent extends ChatStreamEventBase {\n type: \"tool_end\";\n /** Name of the tool that completed */\n toolName: string;\n /** Whether the tool execution succeeded */\n success: boolean;\n /** Brief summary of the result */\n resultSummary?: string;\n}\n\n/**\n * Agent thinking event - sent between agent iterations.\n */\nexport interface AgentThinkingEvent extends ChatStreamEventBase {\n type: \"agent_thinking\";\n /** Current iteration number */\n iteration: number;\n /** Tools used in this iteration */\n toolsUsed: string[];\n}\n\n// ════════════════════════════════════════════════════════════════════════════\n// AGENT LOOP TRACE EVENTS\n// ════════════════════════════════════════════════════════════════════════════\n\n/**\n * Iteration start event - emitted when a new agent loop iteration begins.\n */\nexport interface IterationStartEvent extends ChatStreamEventBase {\n type: \"iteration_start\";\n iteration: number;\n}\n\n/**\n * LLM start event - emitted when the LLM begins generating a response.\n */\nexport interface LlmStartEvent extends ChatStreamEventBase {\n type: \"llm_start\";\n iteration: number;\n}\n\n/**\n * LLM end event - emitted when the LLM finishes generating (may include tool calls).\n */\nexport interface LlmEndEvent extends ChatStreamEventBase {\n type: \"llm_end\";\n iteration: number;\n hasToolCalls: boolean;\n toolNames?: string[];\n}\n\n/**\n * Tool activity event - inline narration of tool execution.\n * Sent as the agent streams its response, replacing the old ThinkingDropdown.\n */\nexport interface ToolActivityEvent extends ChatStreamEventBase {\n type: \"tool_activity\";\n /** Internal tool name */\n toolName: string;\n /** User-friendly description (e.g. \"Looking up your profile...\") */\n description: string;\n /** Whether the tool is starting or has finished */\n phase: \"start\" | \"end\";\n /** Whether the tool succeeded (present when phase === 'end') */\n success?: boolean;\n /** Brief result summary (present when phase === 'end') */\n summary?: string;\n /** Internal steps executed by this tool (present when phase === 'end') */\n steps?: DebugMetaStep[];\n}\n\n/**\n * Internal event carrying the agent's authoritative final response text.\n * Emitted by the streamer after the graph completes. Not forwarded to the frontend SSE stream.\n */\nexport interface ResponseCompleteEvent extends ChatStreamEventBase {\n type: \"response_complete\";\n /** The agent's final response text (from the last iteration only) */\n response: string;\n}\n\n/**\n * Response reset event — tells the frontend to discard all previously streamed tokens.\n * Emitted when the agent detects hallucinated code blocks and forces a correction iteration.\n */\nexport interface ResponseResetEvent extends ChatStreamEventBase {\n type: \"response_reset\";\n /** Human-readable reason for the reset */\n reason: string;\n}\n\n/**\n * Hallucination detected event — tells the frontend that the agent caught a\n * hallucinated code block and is auto-invoking the correct tool.\n */\nexport interface HallucinationDetectedEvent extends ChatStreamEventBase {\n type: \"hallucination_detected\";\n /** The type of block that was hallucinated (e.g. \"intent_proposal\", \"opportunity\") */\n blockType: string;\n /** The tool being auto-invoked to recover */\n tool: string;\n}\n\n/**\n * One internal step reported by a tool for debug visibility (e.g. subgraph, subtask).\n */\nexport interface DebugMetaStep {\n step: string;\n detail?: string;\n /** Structured data for rich display (e.g., Felicity scores, classification, candidate info). */\n data?: Record<string, unknown>;\n}\n\n/**\n * One agent invocation recorded inside a graph run.\n */\nexport interface DebugMetaAgent {\n /** Name of the agent (e.g. \"opportunity.evaluator\"). */\n name: string;\n /** Wall-clock milliseconds for this agent invocation. */\n durationMs: number;\n}\n\n/**\n * One graph invocation recorded by a tool that calls a LangGraph graph.\n */\nexport interface DebugMetaGraph {\n /** Name of the graph (e.g. \"opportunity\"). */\n name: string;\n /** Wall-clock milliseconds for the full graph run. */\n durationMs: number;\n /** Agent invocations recorded inside this graph run. */\n agents: DebugMetaAgent[];\n}\n\n/**\n * One tool call entry in debug meta (sanitized args, result summary, optional steps).\n */\nexport interface DebugMetaToolCall {\n name: string;\n args: Record<string, unknown>;\n resultSummary: string;\n success: boolean;\n /** Wall-clock milliseconds for the full tool execution. */\n durationMs: number;\n /** Internal steps (subgraphs, subtasks) when the tool reports debugSteps in its result. */\n steps?: DebugMetaStep[];\n /** LangGraph graphs invoked by this tool, with their agent timings. */\n graphs?: DebugMetaGraph[];\n}\n\n/**\n * LLM call statistics accumulated during a single agent turn.\n */\nexport interface DebugMetaLlm {\n /** Total number of LLM calls made in this turn. */\n calls: number;\n /** Cumulative wall-clock time spent waiting for the LLM across all calls. */\n totalDurationMs: number;\n /** Entries recorded each time a response_reset event was emitted. */\n resets: Array<{ reason: string; at: number }>;\n /** Entries recorded each time a hallucination_detected event was emitted. */\n hallucinations: Array<{ blockType: string; tool: string; at: number }>;\n}\n\n/**\n * Negotiation sessions initiated by the orchestrator during this turn.\n */\nexport interface DebugMetaOrchestratorNegotiations {\n /** Opportunity IDs for which a negotiation_session_start was emitted. */\n opportunityIds: string[];\n}\n\n/**\n * Decision-question generation debug data (orchestrator path only).\n */\nexport interface DebugMetaDiscoveryQuestions {\n inputMode: \"transcripts\" | \"insights\";\n finalCount: number;\n strategies: QuestionStrategy[];\n durationMs: number;\n}\n\n/**\n * Debug meta event - per-turn graph and tool usage for copy debug.\n */\nexport interface DebugMetaEvent extends ChatStreamEventBase {\n type: \"debug_meta\";\n graph: string;\n iterations: number;\n tools: DebugMetaToolCall[];\n llm: DebugMetaLlm;\n orchestratorNegotiations?: DebugMetaOrchestratorNegotiations;\n /** Decision-question generation debug data (orchestrator path only). */\n discoveryQuestions?: DebugMetaDiscoveryQuestions;\n}\n\n/** Graph start event — emitted when a LangGraph sub-graph begins inside a tool. */\nexport interface GraphStartEvent extends ChatStreamEventBase {\n type: \"graph_start\";\n graphName: string;\n}\n\n/** Graph end event — emitted when a LangGraph sub-graph completes. */\nexport interface GraphEndEvent extends ChatStreamEventBase {\n type: \"graph_end\";\n graphName: string;\n durationMs: number;\n}\n\n/**\n * Phase start event — emitted when a logical groupings of inline work begins\n * inside a tool. Phases share container semantics with graphs (they can host\n * agents) but render differently in the trace UI so users can tell them\n * apart from LangGraph state machines.\n */\nexport interface PhaseStartEvent extends ChatStreamEventBase {\n type: \"phase_start\";\n phaseName: string;\n}\n\n/** Phase end event — emitted when a logical phase completes. */\nexport interface PhaseEndEvent extends ChatStreamEventBase {\n type: \"phase_end\";\n phaseName: string;\n durationMs: number;\n}\n\n/** Agent start event — emitted when an LLM agent begins inside a graph node. */\nexport interface AgentStartEvent extends ChatStreamEventBase {\n type: \"agent_start\";\n agentName: string;\n}\n\n/** Agent end event — emitted when an LLM agent completes. */\nexport interface AgentEndEvent extends ChatStreamEventBase {\n type: \"agent_end\";\n agentName: string;\n durationMs: number;\n /** Structured outcome summary, e.g. \"5 of 12 passed\" or \"3 intents extracted\". */\n summary: string;\n}\n\n/** Orchestrator per-candidate negotiation wrapper — emitted from `negotiateCandidates`. */\nexport interface NegotiationSessionStartEvent extends ChatStreamEventBase {\n type: \"negotiation_session_start\";\n opportunityId: string;\n negotiationConversationId: string;\n sourceUserId: string;\n candidateUserId: string;\n /** The user holding the initiating seat for this match (v2 stamp). */\n initiatorUserId?: string;\n candidateName?: string;\n trigger: \"orchestrator\" | \"ambient\";\n startedAt: number;\n}\n\nexport interface NegotiationSessionEndEvent extends ChatStreamEventBase {\n type: \"negotiation_session_end\";\n opportunityId: string;\n negotiationConversationId: string;\n durationMs: number;\n}\n\n/** One turn inside a bilateral negotiation. Emitted by the negotiation graph's turn node. */\nexport interface NegotiationTurnEvent extends ChatStreamEventBase {\n type: \"negotiation_turn\";\n opportunityId: string;\n negotiationConversationId: string;\n turnIndex: number;\n actor: \"source\" | \"candidate\";\n action: \"propose\" | \"accept\" | \"reject\" | \"counter\" | \"question\" | \"outreach\" | \"withdraw\" | \"decline\" | \"ask_user\";\n reasoning?: string;\n message?: string;\n suggestedRoles?: { ownUser?: string; otherUser?: string };\n durationMs: number;\n}\n\nexport interface NegotiationOutcomeEvent extends ChatStreamEventBase {\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 | \"screened_out\";\n turnCount: number;\n reasoning?: string;\n agreedRoles?: { ownUser?: string; otherUser?: string };\n}\n\nexport interface ChatSummarizerStartEvent extends ChatStreamEventBase {\n type: \"chat_summarizer_start\";\n payload: { sessionId: string };\n}\n\nexport interface ChatSummarizerEndEvent extends ChatStreamEventBase {\n type: \"chat_summarizer_end\";\n payload: {\n durationMs: number;\n };\n}\n\nexport interface QuestionGeneratorStartEvent extends ChatStreamEventBase {\n type: \"question_generator_start\";\n payload: {\n inputMode: \"transcripts\" | \"insights\";\n negotiationCount: number;\n hasChatContext: boolean;\n truncated?: { originalCount: number; keptCount: number };\n };\n}\n\nexport interface QuestionGeneratorEndEvent extends ChatStreamEventBase {\n type: \"question_generator_end\";\n payload: {\n finalCount: number;\n strategies: QuestionStrategy[];\n durationMs: number;\n inputMode: \"transcripts\" | \"insights\";\n };\n}\n\nexport interface DecisionQuestionsEvent extends ChatStreamEventBase {\n type: \"decision_questions\";\n questions: Question[];\n}\n\n/**\n * One persisted question streamed by the ask_user_question tool.\n * Carries the DB id so the frontend can answer/dismiss it through the\n * questions REST endpoints while the turn is still blocked.\n */\nexport interface UserQuestionPayload {\n id: string;\n title: string;\n prompt: string;\n options: Array<{ label: string; description: string }>;\n multiSelect: boolean;\n}\n\n/**\n * User question event — emitted when the orchestrator's ask_user_question\n * tool persisted chat-mode questions and is now blocking the turn awaiting\n * the user's inline answer.\n */\nexport interface UserQuestionEvent extends ChatStreamEventBase {\n type: \"user_question\";\n questions: UserQuestionPayload[];\n}\n\n/**\n * Steer-or-queue event — injected into the active SSE stream by the /chat/interrupt\n * endpoint after the classifier runs. The frontend holds the mid-stream message as\n * \"pending\" until this event arrives, then acts on the decision.\n */\nexport interface SteerOrQueueEvent extends ChatStreamEventBase {\n type: \"steer_or_queue\";\n /** Classifier decision: interrupt and restart, or buffer until current run completes. */\n decision: \"steer\" | \"queue\";\n /** Echoed from the interrupt request so the frontend can update the correct pending message. */\n messageId: string;\n}\n\n/**\n * Union type of all chat stream events.\n */\nexport type ChatStreamEvent =\n | StatusEvent\n | RoutingEvent\n | ThinkingEvent\n | SubgraphStartEvent\n | SubgraphResultEvent\n | TokenEvent\n | DoneEvent\n | ErrorEvent\n // Agent Loop Architecture events\n | ToolStartEvent\n | ToolEndEvent\n | AgentThinkingEvent\n // Streaming narration events\n | ToolActivityEvent\n // Agent loop trace events\n | IterationStartEvent\n | LlmStartEvent\n | LlmEndEvent\n // Internal response tracking events\n | ResponseCompleteEvent\n | ResponseResetEvent\n | HallucinationDetectedEvent\n // Debug meta\n | DebugMetaEvent\n // Trace hierarchy events\n | GraphStartEvent\n | GraphEndEvent\n | PhaseStartEvent\n | PhaseEndEvent\n | AgentStartEvent\n | AgentEndEvent\n | NegotiationSessionStartEvent\n | NegotiationSessionEndEvent\n | NegotiationTurnEvent\n | NegotiationOutcomeEvent\n | ChatSummarizerStartEvent\n | ChatSummarizerEndEvent\n | QuestionGeneratorStartEvent\n | QuestionGeneratorEndEvent\n | DecisionQuestionsEvent\n | UserQuestionEvent\n | SteerOrQueueEvent;\n\n/**\n * Formats a chat stream event as an SSE message. If JSON.stringify throws (e.g. circular ref,\n * non-serializable value), returns a minimal error event so the stream stays valid.\n *\n * @param event - The event to format\n * @returns SSE-formatted string with \"data: \" prefix and double newline\n */\nexport function formatSSEEvent(event: ChatStreamEvent): string {\n try {\n return `data: ${JSON.stringify(event)}\\n\\n`;\n } catch (serializeError) {\n const fallback: ErrorEvent = {\n type: \"error\",\n sessionId:\n typeof (event as ChatStreamEventBase).sessionId === \"string\"\n ? (event as ChatStreamEventBase).sessionId\n : \"unknown\",\n timestamp: new Date().toISOString(),\n message: \"Response could not be serialized. Please try again.\",\n code: \"SERIALIZATION_ERROR\",\n };\n return `data: ${JSON.stringify(fallback)}\\n\\n`;\n }\n}\n\n/**\n * Creates a chat stream event with common fields populated.\n *\n * @param type - Event type\n * @param sessionId - Session ID\n * @param data - Event-specific data (excluding type, sessionId, timestamp)\n * @returns Complete event object\n *\n * @example\n * ```ts\n * const statusEvent = createStreamEvent<StatusEvent>('status', 'session-123', {\n * message: 'Processing your request...'\n * });\n * ```\n */\nexport function createStreamEvent<T extends ChatStreamEvent>(\n type: T[\"type\"],\n sessionId: string,\n data: Omit<T, \"type\" | \"sessionId\" | \"timestamp\">,\n): T {\n return {\n ...data,\n type,\n sessionId,\n timestamp: new Date().toISOString(),\n } as T;\n}\n\n/**\n * Type guard to check if an event is a specific type.\n */\nexport function isEventType<T extends ChatStreamEvent>(\n event: ChatStreamEvent,\n type: T[\"type\"],\n): event is T {\n return event.type === type;\n}\n\n/**\n * Creates a formatted status event.\n */\nexport function createStatusEvent(\n sessionId: string,\n message: string,\n): StatusEvent {\n return createStreamEvent<StatusEvent>(\"status\", sessionId, { message });\n}\n\n/**\n * Creates a formatted routing event.\n */\nexport function createRoutingEvent(\n sessionId: string,\n target: string,\n reasoning?: string,\n): RoutingEvent {\n return createStreamEvent<RoutingEvent>(\"routing\", sessionId, {\n target,\n reasoning,\n });\n}\n\n/**\n * Creates a formatted subgraph start event.\n */\nexport function createSubgraphStartEvent(\n sessionId: string,\n subgraph: string,\n): SubgraphStartEvent {\n return createStreamEvent<SubgraphStartEvent>(\"subgraph_start\", sessionId, {\n subgraph,\n });\n}\n\n/**\n * Creates a formatted subgraph result event.\n */\nexport function createSubgraphResultEvent(\n sessionId: string,\n subgraph: string,\n data: Record<string, unknown>,\n): SubgraphResultEvent {\n return createStreamEvent<SubgraphResultEvent>(\"subgraph_result\", sessionId, {\n subgraph,\n data,\n });\n}\n\n/**\n * Creates a formatted token event.\n */\nexport function createTokenEvent(\n sessionId: string,\n content: string,\n): TokenEvent {\n return createStreamEvent<TokenEvent>(\"token\", sessionId, { content });\n}\n\n/**\n * Options for the done event (optional metadata).\n */\nexport interface CreateDoneEventOptions {\n messageId?: string;\n routingDecision?: Record<string, unknown>;\n subgraphResults?: Record<string, unknown>;\n title?: string;\n suggestions?: ChatSuggestion[];\n opportunityCards?: OpportunityCardPayload[];\n decisionQuestions?: Question[];\n}\n\n/**\n * Creates a formatted done event.\n */\nexport function createDoneEvent(\n sessionId: string,\n response: string,\n options?: CreateDoneEventOptions,\n): DoneEvent {\n return createStreamEvent<DoneEvent>(\"done\", sessionId, {\n ...options,\n response,\n });\n}\n\n/**\n * Creates a formatted error event.\n */\nexport function createErrorEvent(\n sessionId: string,\n message: string,\n code?: string,\n): ErrorEvent {\n return createStreamEvent<ErrorEvent>(\"error\", sessionId, { message, code });\n}\n\n/**\n * Creates a formatted thinking event.\n */\nexport function createThinkingEvent(\n sessionId: string,\n content: string,\n step?: string,\n): ThinkingEvent {\n return createStreamEvent<ThinkingEvent>(\"thinking\", sessionId, {\n content,\n step,\n });\n}\n\n// ════════════════════════════════════════════════════════════════════════════\n// AGENT LOOP EVENT CREATORS\n// ════════════════════════════════════════════════════════════════════════════\n\n/**\n * Creates a formatted tool start event.\n */\nexport function createToolStartEvent(\n sessionId: string,\n toolName: string,\n toolArgs: Record<string, unknown>,\n): ToolStartEvent {\n return createStreamEvent<ToolStartEvent>(\"tool_start\", sessionId, {\n toolName,\n toolArgs,\n });\n}\n\n/**\n * Creates a formatted tool end event.\n */\nexport function createToolEndEvent(\n sessionId: string,\n toolName: string,\n success: boolean,\n resultSummary?: string,\n): ToolEndEvent {\n return createStreamEvent<ToolEndEvent>(\"tool_end\", sessionId, {\n toolName,\n success,\n resultSummary,\n });\n}\n\n/**\n * Creates a formatted agent thinking event.\n */\nexport function createAgentThinkingEvent(\n sessionId: string,\n iteration: number,\n toolsUsed: string[],\n): AgentThinkingEvent {\n return createStreamEvent<AgentThinkingEvent>(\"agent_thinking\", sessionId, {\n iteration,\n toolsUsed,\n });\n}\n\n// ════════════════════════════════════════════════════════════════════════════\n// AGENT LOOP TRACE EVENT CREATORS\n// ════════════════════════════════════════════════════════════════════════════\n\n/**\n * Creates a formatted iteration start event.\n */\nexport function createIterationStartEvent(\n sessionId: string,\n iteration: number,\n): IterationStartEvent {\n return createStreamEvent<IterationStartEvent>(\"iteration_start\", sessionId, {\n iteration,\n });\n}\n\n/**\n * Creates a formatted LLM start event.\n */\nexport function createLlmStartEvent(\n sessionId: string,\n iteration: number,\n): LlmStartEvent {\n return createStreamEvent<LlmStartEvent>(\"llm_start\", sessionId, {\n iteration,\n });\n}\n\n/**\n * Creates a formatted LLM end event.\n */\nexport function createLlmEndEvent(\n sessionId: string,\n iteration: number,\n hasToolCalls: boolean,\n toolNames?: string[],\n): LlmEndEvent {\n return createStreamEvent<LlmEndEvent>(\"llm_end\", sessionId, {\n iteration,\n hasToolCalls,\n toolNames,\n });\n}\n\n// ════════════════════════════════════════════════════════════════════════════\n// STREAMING NARRATION EVENT CREATORS\n// ════════════════════════════════════════════════════════════════════════════\n\n/**\n * Creates a formatted tool activity event (inline narration).\n */\nexport function createToolActivityEvent(\n sessionId: string,\n toolName: string,\n description: string,\n phase: \"start\" | \"end\",\n success?: boolean,\n summary?: string,\n steps?: DebugMetaStep[],\n): ToolActivityEvent {\n return createStreamEvent<ToolActivityEvent>(\"tool_activity\", sessionId, {\n toolName,\n description,\n phase,\n success,\n summary,\n steps,\n });\n}\n\n// ════════════════════════════════════════════════════════════════════════════\n// INTERNAL RESPONSE TRACKING EVENT CREATORS\n// ════════════════════════════════════════════════════════════════════════════\n\n/**\n * Creates a formatted response complete event.\n */\nexport function createResponseCompleteEvent(\n sessionId: string,\n response: string,\n): ResponseCompleteEvent {\n return createStreamEvent<ResponseCompleteEvent>(\"response_complete\", sessionId, { response });\n}\n\n/**\n * Creates a formatted response reset event.\n * Tells the frontend to discard all previously streamed tokens.\n */\nexport function createResponseResetEvent(\n sessionId: string,\n reason: string,\n): ResponseResetEvent {\n return createStreamEvent<ResponseResetEvent>(\"response_reset\", sessionId, { reason });\n}\n\n/**\n * Creates a hallucination detected event for the trace panel.\n */\nexport function createHallucinationDetectedEvent(\n sessionId: string,\n blockType: string,\n tool: string,\n): HallucinationDetectedEvent {\n return createStreamEvent<HallucinationDetectedEvent>(\"hallucination_detected\", sessionId, { blockType, tool });\n}\n\n// ════════════════════════════════════════════════════════════════════════════\n// DEBUG META EVENT CREATORS\n// ════════════════════════════════════════════════════════════════════════════\n\n/**\n * Creates a formatted debug meta event (per-turn graph and tool usage).\n */\nexport function createDebugMetaEvent(\n sessionId: string,\n graph: string,\n iterations: number,\n tools: DebugMetaToolCall[],\n llm: DebugMetaLlm,\n orchestratorNegotiations?: DebugMetaOrchestratorNegotiations,\n discoveryQuestions?: DebugMetaDiscoveryQuestions,\n): DebugMetaEvent {\n return createStreamEvent<DebugMetaEvent>(\"debug_meta\", sessionId, {\n graph,\n iterations,\n tools,\n llm,\n ...(orchestratorNegotiations !== undefined && { orchestratorNegotiations }),\n ...(discoveryQuestions !== undefined && { discoveryQuestions }),\n });\n}\n\n// ════════════════════════════════════════════════════════════════════════════\n// TRACE HIERARCHY EVENT CREATORS\n// ════════════════════════════════════════════════════════════════════════════\n\n/**\n * Creates a graph start event emitted when a LangGraph sub-graph begins inside a tool.\n */\nexport function createGraphStartEvent(sessionId: string, graphName: string): GraphStartEvent {\n return createStreamEvent<GraphStartEvent>(\"graph_start\", sessionId, { graphName });\n}\n\n/**\n * Creates a graph end event emitted when a LangGraph sub-graph completes.\n */\nexport function createGraphEndEvent(sessionId: string, graphName: string, durationMs: number): GraphEndEvent {\n return createStreamEvent<GraphEndEvent>(\"graph_end\", sessionId, { graphName, durationMs });\n}\n\nexport function createPhaseStartEvent(sessionId: string, phaseName: string): PhaseStartEvent {\n return createStreamEvent<PhaseStartEvent>(\"phase_start\", sessionId, { phaseName });\n}\n\nexport function createPhaseEndEvent(sessionId: string, phaseName: string, durationMs: number): PhaseEndEvent {\n return createStreamEvent<PhaseEndEvent>(\"phase_end\", sessionId, { phaseName, durationMs });\n}\n\n/**\n * Creates an agent start event emitted when an LLM agent begins inside a graph node.\n */\nexport function createAgentStartEvent(sessionId: string, agentName: string): AgentStartEvent {\n return createStreamEvent<AgentStartEvent>(\"agent_start\", sessionId, { agentName });\n}\n\n/**\n * Creates an agent end event emitted when an LLM agent completes.\n */\nexport function createAgentEndEvent(\n sessionId: string,\n agentName: string,\n durationMs: number,\n summary: string,\n): AgentEndEvent {\n return createStreamEvent<AgentEndEvent>(\"agent_end\", sessionId, { agentName, durationMs, summary });\n}\n\nexport function createNegotiationSessionStartEvent(\n sessionId: string,\n payload: Omit<NegotiationSessionStartEvent, \"type\" | \"sessionId\" | \"timestamp\">,\n): NegotiationSessionStartEvent {\n return createStreamEvent<NegotiationSessionStartEvent>(\n \"negotiation_session_start\",\n sessionId,\n payload,\n );\n}\n\nexport function createNegotiationSessionEndEvent(\n sessionId: string,\n payload: Omit<NegotiationSessionEndEvent, \"type\" | \"sessionId\" | \"timestamp\">,\n): NegotiationSessionEndEvent {\n return createStreamEvent<NegotiationSessionEndEvent>(\n \"negotiation_session_end\",\n sessionId,\n payload,\n );\n}\n\nexport function createNegotiationTurnEvent(\n sessionId: string,\n payload: Omit<NegotiationTurnEvent, \"type\" | \"sessionId\" | \"timestamp\">,\n): NegotiationTurnEvent {\n return createStreamEvent<NegotiationTurnEvent>(\"negotiation_turn\", sessionId, payload);\n}\n\nexport function createNegotiationOutcomeEvent(\n sessionId: string,\n payload: Omit<NegotiationOutcomeEvent, \"type\" | \"sessionId\" | \"timestamp\">,\n): NegotiationOutcomeEvent {\n return createStreamEvent<NegotiationOutcomeEvent>(\n \"negotiation_outcome\",\n sessionId,\n payload,\n );\n}\n\nexport function createChatSummarizerStartEvent(\n sessionId: string,\n payload: ChatSummarizerStartEvent[\"payload\"],\n): ChatSummarizerStartEvent {\n return createStreamEvent<ChatSummarizerStartEvent>(\"chat_summarizer_start\", sessionId, { payload });\n}\n\nexport function createChatSummarizerEndEvent(\n sessionId: string,\n payload: ChatSummarizerEndEvent[\"payload\"],\n): ChatSummarizerEndEvent {\n return createStreamEvent<ChatSummarizerEndEvent>(\"chat_summarizer_end\", sessionId, { payload });\n}\n\nexport function createQuestionGeneratorStartEvent(\n sessionId: string,\n payload: QuestionGeneratorStartEvent[\"payload\"],\n): QuestionGeneratorStartEvent {\n return createStreamEvent<QuestionGeneratorStartEvent>(\"question_generator_start\", sessionId, { payload });\n}\n\nexport function createQuestionGeneratorEndEvent(\n sessionId: string,\n payload: QuestionGeneratorEndEvent[\"payload\"],\n): QuestionGeneratorEndEvent {\n return createStreamEvent<QuestionGeneratorEndEvent>(\"question_generator_end\", sessionId, { payload });\n}\n\nexport function createDecisionQuestionsEvent(\n sessionId: string,\n payload: { questions: Question[] },\n): DecisionQuestionsEvent {\n return createStreamEvent<DecisionQuestionsEvent>(\"decision_questions\", sessionId, payload);\n}\n\nexport function createUserQuestionEvent(\n sessionId: string,\n payload: { questions: UserQuestionPayload[] },\n): UserQuestionEvent {\n return createStreamEvent<UserQuestionEvent>(\"user_question\", sessionId, payload);\n}\n\n/**\n * Creates a steer-or-queue event injected into the active stream by the interrupt endpoint.\n */\nexport function createSteerOrQueueEvent(\n sessionId: string,\n decision: \"steer\" | \"queue\",\n messageId: string,\n): SteerOrQueueEvent {\n return createStreamEvent<SteerOrQueueEvent>(\"steer_or_queue\", sessionId, {\n decision,\n messageId,\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"chat-streaming.types.js","sourceRoot":"/","sources":["chat/chat-streaming.types.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAioBH;;;;;;GAMG;AACH,MAAM,UAAU,cAAc,CAAC,KAAsB;IACnD,IAAI,CAAC;QACH,OAAO,SAAS,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC;IAC9C,CAAC;IAAC,OAAO,cAAc,EAAE,CAAC;QACxB,MAAM,QAAQ,GAAe;YAC3B,IAAI,EAAE,OAAO;YACb,SAAS,EACP,OAAQ,KAA6B,CAAC,SAAS,KAAK,QAAQ;gBAC1D,CAAC,CAAE,KA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E5C,OAAO,iBAAiB,CAA2B,uBAAuB,EAAE,SAAS,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;AACtG,CAAC;AAED,MAAM,UAAU,4BAA4B,CAC1C,SAAiB,EACjB,OAA0C;IAE1C,OAAO,iBAAiB,CAAyB,qBAAqB,EAAE,SAAS,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;AAClG,CAAC;AAED,MAAM,UAAU,iCAAiC,CAC/C,SAAiB,EACjB,OAA+C;IAE/C,OAAO,iBAAiB,CAA8B,0BAA0B,EAAE,SAAS,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;AAC5G,CAAC;AAED,MAAM,UAAU,+BAA+B,CAC7C,SAAiB,EACjB,OAA6C;IAE7C,OAAO,iBAAiB,CAA4B,wBAAwB,EAAE,SAAS,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;AACxG,CAAC;AAED,MAAM,UAAU,4BAA4B,CAC1C,SAAiB,EACjB,OAAkC;IAElC,OAAO,iBAAiB,CAAyB,oBAAoB,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;AAC7F,CAAC;AAED,MAAM,UAAU,uBAAuB,CACrC,SAAiB,EACjB,OAA6C;IAE7C,OAAO,iBAAiB,CAAoB,eAAe,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;AACnF,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,uBAAuB,CACrC,SAAiB,EACjB,QAA2B,EAC3B,SAAiB;IAEjB,OAAO,iBAAiB,CAAoB,gBAAgB,EAAE,SAAS,EAAE;QACvE,QAAQ;QACR,SAAS;KACV,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * SSE Event types for Chat Graph streaming.\n *\n * These types define the structure of events sent during streaming chat responses.\n * Events are sent as Server-Sent Events (SSE) with JSON payloads.\n */\n\nimport type { Question, QuestionStrategy } from \"../shared/schemas/question.schema.js\";\n\n// Event type discriminator\nexport type ChatStreamEventType =\n | \"status\"\n | \"routing\"\n | \"thinking\"\n | \"subgraph_start\"\n | \"subgraph_result\"\n | \"token\"\n | \"done\"\n | \"error\"\n // Agent Loop Architecture events\n | \"tool_start\"\n | \"tool_end\"\n | \"agent_thinking\"\n // Streaming narration events\n | \"tool_activity\"\n // Agent loop trace events\n | \"iteration_start\"\n | \"llm_start\"\n | \"llm_end\"\n // Internal response tracking events\n | \"response_complete\"\n | \"response_reset\"\n // Debug meta (per-turn graph/tool usage for copy debug)\n | \"debug_meta\"\n | \"graph_start\"\n | \"graph_end\"\n | \"phase_start\"\n | \"phase_end\"\n | \"agent_start\"\n | \"agent_end\"\n | \"hallucination_detected\"\n // Orchestrator-inline negotiation trace events\n | \"negotiation_session_start\"\n | \"negotiation_session_end\"\n | \"negotiation_turn\"\n | \"negotiation_outcome\"\n // Discovery decision-question events\n | \"chat_summarizer_start\"\n | \"chat_summarizer_end\"\n | \"question_generator_start\"\n | \"question_generator_end\"\n | \"decision_questions\"\n // Blocking mid-turn user question (ask_user_question tool)\n | \"user_question\"\n // Steer-or-queue interrupt event\n | \"steer_or_queue\";\n\n/**\n * Base interface for all chat stream events.\n */\nexport interface ChatStreamEventBase {\n /** Event type discriminator */\n type: ChatStreamEventType;\n /** Session ID for the chat session */\n sessionId: string;\n /** ISO 8601 timestamp */\n timestamp: string;\n}\n\n/**\n * Status event - sent to indicate processing state changes.\n */\nexport interface StatusEvent extends ChatStreamEventBase {\n type: \"status\";\n /** Human-readable status message */\n message: string;\n}\n\n/**\n * Routing event - sent when the router determines which subgraph to use.\n */\nexport interface RoutingEvent extends ChatStreamEventBase {\n type: \"routing\";\n /** Target subgraph name */\n target: string;\n /** Optional reasoning for the routing decision */\n reasoning?: string;\n}\n\n/**\n * Thinking event - sent to stream the model's reasoning and decision-making process.\n */\nexport interface ThinkingEvent extends ChatStreamEventBase {\n type: \"thinking\";\n /** The thinking/reasoning content */\n content: string;\n /** Optional step identifier (e.g., 'router', 'inference', 'verification') */\n step?: string;\n}\n\n/**\n * Subgraph start event - sent when a subgraph begins processing.\n */\nexport interface SubgraphStartEvent extends ChatStreamEventBase {\n type: \"subgraph_start\";\n /** Name of the subgraph being executed */\n subgraph: string;\n}\n\n/**\n * Subgraph result event - sent when a subgraph completes with results.\n */\nexport interface SubgraphResultEvent extends ChatStreamEventBase {\n type: \"subgraph_result\";\n /** Name of the subgraph that completed */\n subgraph: string;\n /** Result data from the subgraph */\n data: Record<string, unknown>;\n}\n\n/**\n * Token event - sent for each token during streaming response.\n */\nexport interface TokenEvent extends ChatStreamEventBase {\n type: \"token\";\n /** Token content (partial text) */\n content: string;\n}\n\n/**\n * Chat suggestion for follow-up actions.\n * Matches frontend Suggestion type (label, type, followupText/prefill).\n */\nexport interface ChatSuggestion {\n label: string;\n type: \"direct\" | \"prompt\";\n /** For 'direct' type: text to auto-submit as next message */\n followupText?: string;\n /** For 'prompt' type: text to prefill the input */\n prefill?: string;\n}\n\n/**\n * Rich opportunity card data for chat messages.\n * Matches the home page card format for consistent rendering.\n */\nexport interface OpportunityCardPayload {\n opportunityId: string;\n userId: string;\n name?: string;\n avatar?: string | null;\n /** Main body text (personalizedSummary from presenter). */\n mainText: string;\n /** Call-to-action line (suggestedAction from presenter). */\n cta?: string;\n /** Short headline hook. */\n headline?: string;\n /** Label for primary action button (e.g. \"Start Chat\"). */\n primaryActionLabel?: string;\n /** Label for secondary action button (e.g. \"Skip\"). */\n secondaryActionLabel?: string;\n /** Subtitle under the other party name (e.g. \"1 mutual intent\"). */\n mutualIntentsLabel?: string;\n /** Narrator chip for human-introduced opportunities. */\n narratorChip?: {\n name: string;\n text: string;\n avatar?: string | null;\n userId?: string;\n };\n /** Viewer's role in this opportunity. */\n viewerRole?: string;\n /** Match confidence score (0-1). */\n score?: number;\n /** Opportunity status. */\n status?: string;\n /** Second party in introducer arrow layout (name -> name). Present when viewerRole is 'introducer'. */\n secondParty?: {\n name: string;\n avatar?: string | null;\n userId?: string;\n };\n}\n\n/**\n * Done event - sent when the response is complete.\n */\nexport interface DoneEvent extends ChatStreamEventBase {\n type: \"done\";\n /** Complete response text */\n response: string;\n /** Server-generated assistant message ID (for trace event persistence) */\n messageId?: string;\n /** Optional routing decision metadata */\n routingDecision?: Record<string, unknown>;\n /** Optional subgraph results metadata */\n subgraphResults?: Record<string, unknown>;\n /** Optional session title (auto-generated or existing) */\n title?: string;\n /** Optional context-aware follow-up suggestions */\n suggestions?: ChatSuggestion[];\n /** Optional rich opportunity cards returned by tools */\n opportunityCards?: OpportunityCardPayload[];\n /** Decision questions to render (orchestrator flow only). */\n decisionQuestions?: Question[];\n}\n\n/**\n * Error event - sent when an error occurs.\n */\nexport interface ErrorEvent extends ChatStreamEventBase {\n type: \"error\";\n /** Human-readable error message */\n message: string;\n /** Optional error code for programmatic handling */\n code?: string;\n}\n\n// ════════════════════════════════════════════════════════════════════════════\n// AGENT LOOP ARCHITECTURE EVENTS\n// ════════════════════════════════════════════════════════════════════════════\n\n/**\n * Tool start event - sent when a tool begins executing.\n */\nexport interface ToolStartEvent extends ChatStreamEventBase {\n type: \"tool_start\";\n /** Name of the tool being executed */\n toolName: string;\n /** Arguments passed to the tool */\n toolArgs: Record<string, unknown>;\n}\n\n/**\n * Tool end event - sent when a tool finishes executing.\n */\nexport interface ToolEndEvent extends ChatStreamEventBase {\n type: \"tool_end\";\n /** Name of the tool that completed */\n toolName: string;\n /** Whether the tool execution succeeded */\n success: boolean;\n /** Brief summary of the result */\n resultSummary?: string;\n}\n\n/**\n * Agent thinking event - sent between agent iterations.\n */\nexport interface AgentThinkingEvent extends ChatStreamEventBase {\n type: \"agent_thinking\";\n /** Current iteration number */\n iteration: number;\n /** Tools used in this iteration */\n toolsUsed: string[];\n}\n\n// ════════════════════════════════════════════════════════════════════════════\n// AGENT LOOP TRACE EVENTS\n// ════════════════════════════════════════════════════════════════════════════\n\n/**\n * Iteration start event - emitted when a new agent loop iteration begins.\n */\nexport interface IterationStartEvent extends ChatStreamEventBase {\n type: \"iteration_start\";\n iteration: number;\n}\n\n/**\n * LLM start event - emitted when the LLM begins generating a response.\n */\nexport interface LlmStartEvent extends ChatStreamEventBase {\n type: \"llm_start\";\n iteration: number;\n}\n\n/**\n * LLM end event - emitted when the LLM finishes generating (may include tool calls).\n */\nexport interface LlmEndEvent extends ChatStreamEventBase {\n type: \"llm_end\";\n iteration: number;\n hasToolCalls: boolean;\n toolNames?: string[];\n}\n\n/**\n * Tool activity event - inline narration of tool execution.\n * Sent as the agent streams its response, replacing the old ThinkingDropdown.\n */\nexport interface ToolActivityEvent extends ChatStreamEventBase {\n type: \"tool_activity\";\n /** Internal tool name */\n toolName: string;\n /** User-friendly description (e.g. \"Looking up your profile...\") */\n description: string;\n /** Whether the tool is starting or has finished */\n phase: \"start\" | \"end\";\n /** Whether the tool succeeded (present when phase === 'end') */\n success?: boolean;\n /** Brief result summary (present when phase === 'end') */\n summary?: string;\n /** Internal steps executed by this tool (present when phase === 'end') */\n steps?: DebugMetaStep[];\n}\n\n/**\n * Internal event carrying the agent's authoritative final response text.\n * Emitted by the streamer after the graph completes. Not forwarded to the frontend SSE stream.\n */\nexport interface ResponseCompleteEvent extends ChatStreamEventBase {\n type: \"response_complete\";\n /** The agent's final response text (from the last iteration only) */\n response: string;\n}\n\n/**\n * Response reset event — tells the frontend to discard all previously streamed tokens.\n * Emitted when the agent detects hallucinated code blocks and forces a correction iteration.\n */\nexport interface ResponseResetEvent extends ChatStreamEventBase {\n type: \"response_reset\";\n /** Human-readable reason for the reset */\n reason: string;\n}\n\n/**\n * Hallucination detected event — tells the frontend that the agent caught a\n * hallucinated code block and is auto-invoking the correct tool.\n */\nexport interface HallucinationDetectedEvent extends ChatStreamEventBase {\n type: \"hallucination_detected\";\n /** The type of block that was hallucinated (e.g. \"intent_proposal\", \"opportunity\") */\n blockType: string;\n /** The tool being auto-invoked to recover */\n tool: string;\n}\n\n/**\n * One internal step reported by a tool for debug visibility (e.g. subgraph, subtask).\n */\nexport interface DebugMetaStep {\n step: string;\n detail?: string;\n /** Structured data for rich display (e.g., Felicity scores, classification, candidate info). */\n data?: Record<string, unknown>;\n}\n\n/**\n * One agent invocation recorded inside a graph run.\n */\nexport interface DebugMetaAgent {\n /** Name of the agent (e.g. \"opportunity.evaluator\"). */\n name: string;\n /** Wall-clock milliseconds for this agent invocation. */\n durationMs: number;\n}\n\n/**\n * One graph invocation recorded by a tool that calls a LangGraph graph.\n */\nexport interface DebugMetaGraph {\n /** Name of the graph (e.g. \"opportunity\"). */\n name: string;\n /** Wall-clock milliseconds for the full graph run. */\n durationMs: number;\n /** Agent invocations recorded inside this graph run. */\n agents: DebugMetaAgent[];\n}\n\n/**\n * One tool call entry in debug meta (sanitized args, result summary, optional steps).\n */\nexport interface DebugMetaToolCall {\n name: string;\n args: Record<string, unknown>;\n resultSummary: string;\n success: boolean;\n /** Wall-clock milliseconds for the full tool execution. */\n durationMs: number;\n /** Internal steps (subgraphs, subtasks) when the tool reports debugSteps in its result. */\n steps?: DebugMetaStep[];\n /** LangGraph graphs invoked by this tool, with their agent timings. */\n graphs?: DebugMetaGraph[];\n}\n\n/**\n * LLM call statistics accumulated during a single agent turn.\n */\nexport interface DebugMetaLlm {\n /** Total number of LLM calls made in this turn. */\n calls: number;\n /** Cumulative wall-clock time spent waiting for the LLM across all calls. */\n totalDurationMs: number;\n /** Entries recorded each time a response_reset event was emitted. */\n resets: Array<{ reason: string; at: number }>;\n /** Entries recorded each time a hallucination_detected event was emitted. */\n hallucinations: Array<{ blockType: string; tool: string; at: number }>;\n}\n\n/**\n * Negotiation sessions initiated by the orchestrator during this turn.\n */\nexport interface DebugMetaOrchestratorNegotiations {\n /** Opportunity IDs for which a negotiation_session_start was emitted. */\n opportunityIds: string[];\n}\n\n/**\n * Decision-question generation debug data (orchestrator path only).\n */\nexport interface DebugMetaDiscoveryQuestions {\n inputMode: \"transcripts\" | \"insights\";\n finalCount: number;\n strategies: QuestionStrategy[];\n durationMs: number;\n}\n\n/**\n * Debug meta event - per-turn graph and tool usage for copy debug.\n */\nexport interface DebugMetaEvent extends ChatStreamEventBase {\n type: \"debug_meta\";\n graph: string;\n iterations: number;\n tools: DebugMetaToolCall[];\n llm: DebugMetaLlm;\n orchestratorNegotiations?: DebugMetaOrchestratorNegotiations;\n /** Decision-question generation debug data (orchestrator path only). */\n discoveryQuestions?: DebugMetaDiscoveryQuestions;\n}\n\n/** Graph start event — emitted when a LangGraph sub-graph begins inside a tool. */\nexport interface GraphStartEvent extends ChatStreamEventBase {\n type: \"graph_start\";\n graphName: string;\n}\n\n/** Graph end event — emitted when a LangGraph sub-graph completes. */\nexport interface GraphEndEvent extends ChatStreamEventBase {\n type: \"graph_end\";\n graphName: string;\n durationMs: number;\n}\n\n/**\n * Phase start event — emitted when a logical groupings of inline work begins\n * inside a tool. Phases share container semantics with graphs (they can host\n * agents) but render differently in the trace UI so users can tell them\n * apart from LangGraph state machines.\n */\nexport interface PhaseStartEvent extends ChatStreamEventBase {\n type: \"phase_start\";\n phaseName: string;\n}\n\n/** Phase end event — emitted when a logical phase completes. */\nexport interface PhaseEndEvent extends ChatStreamEventBase {\n type: \"phase_end\";\n phaseName: string;\n durationMs: number;\n}\n\n/** Agent start event — emitted when an LLM agent begins inside a graph node. */\nexport interface AgentStartEvent extends ChatStreamEventBase {\n type: \"agent_start\";\n agentName: string;\n}\n\n/** Agent end event — emitted when an LLM agent completes. */\nexport interface AgentEndEvent extends ChatStreamEventBase {\n type: \"agent_end\";\n agentName: string;\n durationMs: number;\n /** Structured outcome summary, e.g. \"5 of 12 passed\" or \"3 intents extracted\". */\n summary: string;\n}\n\n/** Orchestrator per-candidate negotiation wrapper — emitted from `negotiateCandidates`. */\nexport interface NegotiationSessionStartEvent extends ChatStreamEventBase {\n type: \"negotiation_session_start\";\n opportunityId: string;\n negotiationConversationId: string;\n sourceUserId: string;\n candidateUserId: string;\n /** The user holding the initiating seat for this match (v2 stamp). */\n initiatorUserId?: string;\n candidateName?: string;\n trigger: \"orchestrator\" | \"ambient\";\n startedAt: number;\n}\n\nexport interface NegotiationSessionEndEvent extends ChatStreamEventBase {\n type: \"negotiation_session_end\";\n opportunityId: string;\n negotiationConversationId: string;\n durationMs: number;\n}\n\n/** One turn inside a bilateral negotiation. Emitted by the negotiation graph's turn node. */\nexport interface NegotiationTurnEvent extends ChatStreamEventBase {\n type: \"negotiation_turn\";\n opportunityId: string;\n negotiationConversationId: string;\n turnIndex: number;\n actor: \"source\" | \"candidate\";\n action: \"propose\" | \"accept\" | \"reject\" | \"counter\" | \"question\" | \"outreach\" | \"withdraw\" | \"decline\" | \"ask_user\";\n reasoning?: string;\n message?: string;\n suggestedRoles?: { ownUser?: string; otherUser?: string };\n durationMs: number;\n}\n\nexport interface NegotiationOutcomeEvent extends ChatStreamEventBase {\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 | \"screened_out\";\n turnCount: number;\n reasoning?: string;\n agreedRoles?: { ownUser?: string; otherUser?: string };\n}\n\nexport interface ChatSummarizerStartEvent extends ChatStreamEventBase {\n type: \"chat_summarizer_start\";\n payload: { sessionId: string };\n}\n\nexport interface ChatSummarizerEndEvent extends ChatStreamEventBase {\n type: \"chat_summarizer_end\";\n payload: {\n durationMs: number;\n };\n}\n\nexport interface QuestionGeneratorStartEvent extends ChatStreamEventBase {\n type: \"question_generator_start\";\n payload: {\n inputMode: \"transcripts\" | \"insights\";\n negotiationCount: number;\n hasChatContext: boolean;\n truncated?: { originalCount: number; keptCount: number };\n };\n}\n\nexport interface QuestionGeneratorEndEvent extends ChatStreamEventBase {\n type: \"question_generator_end\";\n payload: {\n finalCount: number;\n strategies: QuestionStrategy[];\n durationMs: number;\n inputMode: \"transcripts\" | \"insights\";\n };\n}\n\nexport interface DecisionQuestionsEvent extends ChatStreamEventBase {\n type: \"decision_questions\";\n questions: Question[];\n}\n\n/**\n * One persisted question streamed by the ask_user_question tool.\n * Carries the DB id so the frontend can answer/dismiss it through the\n * questions REST endpoints while the turn is still blocked.\n */\nexport interface UserQuestionPayload {\n /** Canonical question identity. The client must resolve all display fields from the server. */\n id: string;\n}\n\n/**\n * User question event — emitted when the orchestrator's ask_user_question\n * tool persisted chat-mode questions and is now blocking the turn awaiting\n * the user's inline answer.\n */\nexport interface UserQuestionEvent extends ChatStreamEventBase {\n type: \"user_question\";\n questions: UserQuestionPayload[];\n}\n\n/**\n * Steer-or-queue event — injected into the active SSE stream by the /chat/interrupt\n * endpoint after the classifier runs. The frontend holds the mid-stream message as\n * \"pending\" until this event arrives, then acts on the decision.\n */\nexport interface SteerOrQueueEvent extends ChatStreamEventBase {\n type: \"steer_or_queue\";\n /** Classifier decision: interrupt and restart, or buffer until current run completes. */\n decision: \"steer\" | \"queue\";\n /** Echoed from the interrupt request so the frontend can update the correct pending message. */\n messageId: string;\n}\n\n/**\n * Union type of all chat stream events.\n */\nexport type ChatStreamEvent =\n | StatusEvent\n | RoutingEvent\n | ThinkingEvent\n | SubgraphStartEvent\n | SubgraphResultEvent\n | TokenEvent\n | DoneEvent\n | ErrorEvent\n // Agent Loop Architecture events\n | ToolStartEvent\n | ToolEndEvent\n | AgentThinkingEvent\n // Streaming narration events\n | ToolActivityEvent\n // Agent loop trace events\n | IterationStartEvent\n | LlmStartEvent\n | LlmEndEvent\n // Internal response tracking events\n | ResponseCompleteEvent\n | ResponseResetEvent\n | HallucinationDetectedEvent\n // Debug meta\n | DebugMetaEvent\n // Trace hierarchy events\n | GraphStartEvent\n | GraphEndEvent\n | PhaseStartEvent\n | PhaseEndEvent\n | AgentStartEvent\n | AgentEndEvent\n | NegotiationSessionStartEvent\n | NegotiationSessionEndEvent\n | NegotiationTurnEvent\n | NegotiationOutcomeEvent\n | ChatSummarizerStartEvent\n | ChatSummarizerEndEvent\n | QuestionGeneratorStartEvent\n | QuestionGeneratorEndEvent\n | DecisionQuestionsEvent\n | UserQuestionEvent\n | SteerOrQueueEvent;\n\n/**\n * Formats a chat stream event as an SSE message. If JSON.stringify throws (e.g. circular ref,\n * non-serializable value), returns a minimal error event so the stream stays valid.\n *\n * @param event - The event to format\n * @returns SSE-formatted string with \"data: \" prefix and double newline\n */\nexport function formatSSEEvent(event: ChatStreamEvent): string {\n try {\n return `data: ${JSON.stringify(event)}\\n\\n`;\n } catch (serializeError) {\n const fallback: ErrorEvent = {\n type: \"error\",\n sessionId:\n typeof (event as ChatStreamEventBase).sessionId === \"string\"\n ? (event as ChatStreamEventBase).sessionId\n : \"unknown\",\n timestamp: new Date().toISOString(),\n message: \"Response could not be serialized. Please try again.\",\n code: \"SERIALIZATION_ERROR\",\n };\n return `data: ${JSON.stringify(fallback)}\\n\\n`;\n }\n}\n\n/**\n * Creates a chat stream event with common fields populated.\n *\n * @param type - Event type\n * @param sessionId - Session ID\n * @param data - Event-specific data (excluding type, sessionId, timestamp)\n * @returns Complete event object\n *\n * @example\n * ```ts\n * const statusEvent = createStreamEvent<StatusEvent>('status', 'session-123', {\n * message: 'Processing your request...'\n * });\n * ```\n */\nexport function createStreamEvent<T extends ChatStreamEvent>(\n type: T[\"type\"],\n sessionId: string,\n data: Omit<T, \"type\" | \"sessionId\" | \"timestamp\">,\n): T {\n return {\n ...data,\n type,\n sessionId,\n timestamp: new Date().toISOString(),\n } as T;\n}\n\n/**\n * Type guard to check if an event is a specific type.\n */\nexport function isEventType<T extends ChatStreamEvent>(\n event: ChatStreamEvent,\n type: T[\"type\"],\n): event is T {\n return event.type === type;\n}\n\n/**\n * Creates a formatted status event.\n */\nexport function createStatusEvent(\n sessionId: string,\n message: string,\n): StatusEvent {\n return createStreamEvent<StatusEvent>(\"status\", sessionId, { message });\n}\n\n/**\n * Creates a formatted routing event.\n */\nexport function createRoutingEvent(\n sessionId: string,\n target: string,\n reasoning?: string,\n): RoutingEvent {\n return createStreamEvent<RoutingEvent>(\"routing\", sessionId, {\n target,\n reasoning,\n });\n}\n\n/**\n * Creates a formatted subgraph start event.\n */\nexport function createSubgraphStartEvent(\n sessionId: string,\n subgraph: string,\n): SubgraphStartEvent {\n return createStreamEvent<SubgraphStartEvent>(\"subgraph_start\", sessionId, {\n subgraph,\n });\n}\n\n/**\n * Creates a formatted subgraph result event.\n */\nexport function createSubgraphResultEvent(\n sessionId: string,\n subgraph: string,\n data: Record<string, unknown>,\n): SubgraphResultEvent {\n return createStreamEvent<SubgraphResultEvent>(\"subgraph_result\", sessionId, {\n subgraph,\n data,\n });\n}\n\n/**\n * Creates a formatted token event.\n */\nexport function createTokenEvent(\n sessionId: string,\n content: string,\n): TokenEvent {\n return createStreamEvent<TokenEvent>(\"token\", sessionId, { content });\n}\n\n/**\n * Options for the done event (optional metadata).\n */\nexport interface CreateDoneEventOptions {\n messageId?: string;\n routingDecision?: Record<string, unknown>;\n subgraphResults?: Record<string, unknown>;\n title?: string;\n suggestions?: ChatSuggestion[];\n opportunityCards?: OpportunityCardPayload[];\n decisionQuestions?: Question[];\n}\n\n/**\n * Creates a formatted done event.\n */\nexport function createDoneEvent(\n sessionId: string,\n response: string,\n options?: CreateDoneEventOptions,\n): DoneEvent {\n return createStreamEvent<DoneEvent>(\"done\", sessionId, {\n ...options,\n response,\n });\n}\n\n/**\n * Creates a formatted error event.\n */\nexport function createErrorEvent(\n sessionId: string,\n message: string,\n code?: string,\n): ErrorEvent {\n return createStreamEvent<ErrorEvent>(\"error\", sessionId, { message, code });\n}\n\n/**\n * Creates a formatted thinking event.\n */\nexport function createThinkingEvent(\n sessionId: string,\n content: string,\n step?: string,\n): ThinkingEvent {\n return createStreamEvent<ThinkingEvent>(\"thinking\", sessionId, {\n content,\n step,\n });\n}\n\n// ════════════════════════════════════════════════════════════════════════════\n// AGENT LOOP EVENT CREATORS\n// ════════════════════════════════════════════════════════════════════════════\n\n/**\n * Creates a formatted tool start event.\n */\nexport function createToolStartEvent(\n sessionId: string,\n toolName: string,\n toolArgs: Record<string, unknown>,\n): ToolStartEvent {\n return createStreamEvent<ToolStartEvent>(\"tool_start\", sessionId, {\n toolName,\n toolArgs,\n });\n}\n\n/**\n * Creates a formatted tool end event.\n */\nexport function createToolEndEvent(\n sessionId: string,\n toolName: string,\n success: boolean,\n resultSummary?: string,\n): ToolEndEvent {\n return createStreamEvent<ToolEndEvent>(\"tool_end\", sessionId, {\n toolName,\n success,\n resultSummary,\n });\n}\n\n/**\n * Creates a formatted agent thinking event.\n */\nexport function createAgentThinkingEvent(\n sessionId: string,\n iteration: number,\n toolsUsed: string[],\n): AgentThinkingEvent {\n return createStreamEvent<AgentThinkingEvent>(\"agent_thinking\", sessionId, {\n iteration,\n toolsUsed,\n });\n}\n\n// ════════════════════════════════════════════════════════════════════════════\n// AGENT LOOP TRACE EVENT CREATORS\n// ════════════════════════════════════════════════════════════════════════════\n\n/**\n * Creates a formatted iteration start event.\n */\nexport function createIterationStartEvent(\n sessionId: string,\n iteration: number,\n): IterationStartEvent {\n return createStreamEvent<IterationStartEvent>(\"iteration_start\", sessionId, {\n iteration,\n });\n}\n\n/**\n * Creates a formatted LLM start event.\n */\nexport function createLlmStartEvent(\n sessionId: string,\n iteration: number,\n): LlmStartEvent {\n return createStreamEvent<LlmStartEvent>(\"llm_start\", sessionId, {\n iteration,\n });\n}\n\n/**\n * Creates a formatted LLM end event.\n */\nexport function createLlmEndEvent(\n sessionId: string,\n iteration: number,\n hasToolCalls: boolean,\n toolNames?: string[],\n): LlmEndEvent {\n return createStreamEvent<LlmEndEvent>(\"llm_end\", sessionId, {\n iteration,\n hasToolCalls,\n toolNames,\n });\n}\n\n// ════════════════════════════════════════════════════════════════════════════\n// STREAMING NARRATION EVENT CREATORS\n// ════════════════════════════════════════════════════════════════════════════\n\n/**\n * Creates a formatted tool activity event (inline narration).\n */\nexport function createToolActivityEvent(\n sessionId: string,\n toolName: string,\n description: string,\n phase: \"start\" | \"end\",\n success?: boolean,\n summary?: string,\n steps?: DebugMetaStep[],\n): ToolActivityEvent {\n return createStreamEvent<ToolActivityEvent>(\"tool_activity\", sessionId, {\n toolName,\n description,\n phase,\n success,\n summary,\n steps,\n });\n}\n\n// ════════════════════════════════════════════════════════════════════════════\n// INTERNAL RESPONSE TRACKING EVENT CREATORS\n// ════════════════════════════════════════════════════════════════════════════\n\n/**\n * Creates a formatted response complete event.\n */\nexport function createResponseCompleteEvent(\n sessionId: string,\n response: string,\n): ResponseCompleteEvent {\n return createStreamEvent<ResponseCompleteEvent>(\"response_complete\", sessionId, { response });\n}\n\n/**\n * Creates a formatted response reset event.\n * Tells the frontend to discard all previously streamed tokens.\n */\nexport function createResponseResetEvent(\n sessionId: string,\n reason: string,\n): ResponseResetEvent {\n return createStreamEvent<ResponseResetEvent>(\"response_reset\", sessionId, { reason });\n}\n\n/**\n * Creates a hallucination detected event for the trace panel.\n */\nexport function createHallucinationDetectedEvent(\n sessionId: string,\n blockType: string,\n tool: string,\n): HallucinationDetectedEvent {\n return createStreamEvent<HallucinationDetectedEvent>(\"hallucination_detected\", sessionId, { blockType, tool });\n}\n\n// ════════════════════════════════════════════════════════════════════════════\n// DEBUG META EVENT CREATORS\n// ════════════════════════════════════════════════════════════════════════════\n\n/**\n * Creates a formatted debug meta event (per-turn graph and tool usage).\n */\nexport function createDebugMetaEvent(\n sessionId: string,\n graph: string,\n iterations: number,\n tools: DebugMetaToolCall[],\n llm: DebugMetaLlm,\n orchestratorNegotiations?: DebugMetaOrchestratorNegotiations,\n discoveryQuestions?: DebugMetaDiscoveryQuestions,\n): DebugMetaEvent {\n return createStreamEvent<DebugMetaEvent>(\"debug_meta\", sessionId, {\n graph,\n iterations,\n tools,\n llm,\n ...(orchestratorNegotiations !== undefined && { orchestratorNegotiations }),\n ...(discoveryQuestions !== undefined && { discoveryQuestions }),\n });\n}\n\n// ════════════════════════════════════════════════════════════════════════════\n// TRACE HIERARCHY EVENT CREATORS\n// ════════════════════════════════════════════════════════════════════════════\n\n/**\n * Creates a graph start event emitted when a LangGraph sub-graph begins inside a tool.\n */\nexport function createGraphStartEvent(sessionId: string, graphName: string): GraphStartEvent {\n return createStreamEvent<GraphStartEvent>(\"graph_start\", sessionId, { graphName });\n}\n\n/**\n * Creates a graph end event emitted when a LangGraph sub-graph completes.\n */\nexport function createGraphEndEvent(sessionId: string, graphName: string, durationMs: number): GraphEndEvent {\n return createStreamEvent<GraphEndEvent>(\"graph_end\", sessionId, { graphName, durationMs });\n}\n\nexport function createPhaseStartEvent(sessionId: string, phaseName: string): PhaseStartEvent {\n return createStreamEvent<PhaseStartEvent>(\"phase_start\", sessionId, { phaseName });\n}\n\nexport function createPhaseEndEvent(sessionId: string, phaseName: string, durationMs: number): PhaseEndEvent {\n return createStreamEvent<PhaseEndEvent>(\"phase_end\", sessionId, { phaseName, durationMs });\n}\n\n/**\n * Creates an agent start event emitted when an LLM agent begins inside a graph node.\n */\nexport function createAgentStartEvent(sessionId: string, agentName: string): AgentStartEvent {\n return createStreamEvent<AgentStartEvent>(\"agent_start\", sessionId, { agentName });\n}\n\n/**\n * Creates an agent end event emitted when an LLM agent completes.\n */\nexport function createAgentEndEvent(\n sessionId: string,\n agentName: string,\n durationMs: number,\n summary: string,\n): AgentEndEvent {\n return createStreamEvent<AgentEndEvent>(\"agent_end\", sessionId, { agentName, durationMs, summary });\n}\n\nexport function createNegotiationSessionStartEvent(\n sessionId: string,\n payload: Omit<NegotiationSessionStartEvent, \"type\" | \"sessionId\" | \"timestamp\">,\n): NegotiationSessionStartEvent {\n return createStreamEvent<NegotiationSessionStartEvent>(\n \"negotiation_session_start\",\n sessionId,\n payload,\n );\n}\n\nexport function createNegotiationSessionEndEvent(\n sessionId: string,\n payload: Omit<NegotiationSessionEndEvent, \"type\" | \"sessionId\" | \"timestamp\">,\n): NegotiationSessionEndEvent {\n return createStreamEvent<NegotiationSessionEndEvent>(\n \"negotiation_session_end\",\n sessionId,\n payload,\n );\n}\n\nexport function createNegotiationTurnEvent(\n sessionId: string,\n payload: Omit<NegotiationTurnEvent, \"type\" | \"sessionId\" | \"timestamp\">,\n): NegotiationTurnEvent {\n return createStreamEvent<NegotiationTurnEvent>(\"negotiation_turn\", sessionId, payload);\n}\n\nexport function createNegotiationOutcomeEvent(\n sessionId: string,\n payload: Omit<NegotiationOutcomeEvent, \"type\" | \"sessionId\" | \"timestamp\">,\n): NegotiationOutcomeEvent {\n return createStreamEvent<NegotiationOutcomeEvent>(\n \"negotiation_outcome\",\n sessionId,\n payload,\n );\n}\n\nexport function createChatSummarizerStartEvent(\n sessionId: string,\n payload: ChatSummarizerStartEvent[\"payload\"],\n): ChatSummarizerStartEvent {\n return createStreamEvent<ChatSummarizerStartEvent>(\"chat_summarizer_start\", sessionId, { payload });\n}\n\nexport function createChatSummarizerEndEvent(\n sessionId: string,\n payload: ChatSummarizerEndEvent[\"payload\"],\n): ChatSummarizerEndEvent {\n return createStreamEvent<ChatSummarizerEndEvent>(\"chat_summarizer_end\", sessionId, { payload });\n}\n\nexport function createQuestionGeneratorStartEvent(\n sessionId: string,\n payload: QuestionGeneratorStartEvent[\"payload\"],\n): QuestionGeneratorStartEvent {\n return createStreamEvent<QuestionGeneratorStartEvent>(\"question_generator_start\", sessionId, { payload });\n}\n\nexport function createQuestionGeneratorEndEvent(\n sessionId: string,\n payload: QuestionGeneratorEndEvent[\"payload\"],\n): QuestionGeneratorEndEvent {\n return createStreamEvent<QuestionGeneratorEndEvent>(\"question_generator_end\", sessionId, { payload });\n}\n\nexport function createDecisionQuestionsEvent(\n sessionId: string,\n payload: { questions: Question[] },\n): DecisionQuestionsEvent {\n return createStreamEvent<DecisionQuestionsEvent>(\"decision_questions\", sessionId, payload);\n}\n\nexport function createUserQuestionEvent(\n sessionId: string,\n payload: { questions: UserQuestionPayload[] },\n): UserQuestionEvent {\n return createStreamEvent<UserQuestionEvent>(\"user_question\", sessionId, payload);\n}\n\n/**\n * Creates a steer-or-queue event injected into the active stream by the interrupt endpoint.\n */\nexport function createSteerOrQueueEvent(\n sessionId: string,\n decision: \"steer\" | \"queue\",\n messageId: string,\n): SteerOrQueueEvent {\n return createStreamEvent<SteerOrQueueEvent>(\"steer_or_queue\", sessionId, {\n decision,\n messageId,\n });\n}\n"]}
|
|
@@ -135,13 +135,6 @@ export type AgentStreamEvent = {
|
|
|
135
135
|
type: "user_question";
|
|
136
136
|
questions: Array<{
|
|
137
137
|
id: string;
|
|
138
|
-
title: string;
|
|
139
|
-
prompt: string;
|
|
140
|
-
options: Array<{
|
|
141
|
-
label: string;
|
|
142
|
-
description: string;
|
|
143
|
-
}>;
|
|
144
|
-
multiSelect: boolean;
|
|
145
138
|
}>;
|
|
146
139
|
} | {
|
|
147
140
|
type: "status";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat.agent.d.ts","sourceRoot":"/","sources":["chat/chat.agent.ts"],"names":[],"mappings":"AACA,OAAO,EAAa,WAAW,EAA8C,MAAM,0BAA0B,CAAC;AAC9G,OAAO,KAAK,EAAa,WAAW,EAAuB,MAAM,iCAAiC,CAAC;AAInG,OAAO,EAAwB,KAAK,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAMjF,OAAO,KAAK,EAAE,iBAAiB,EAAE,YAAY,EAAE,iCAAiC,EAAE,2BAA2B,EAAE,MAAM,2BAA2B,CAAC;AACjJ,OAAO,KAAK,EAAE,QAAQ,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AACvF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,4CAA4C,CAAC;AAsD9E,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAMnD;;;GAGG;AACH,MAAM,MAAM,YAAY,GAAG,CAAC,IAAI,EAAE,OAAO,KAAK,IAAI,CAAC;AAEnD;;;;;;;;;;;;;;GAcG;AACH,MAAM,MAAM,gBAAgB,GACxB;IAAE,IAAI,EAAE,iBAAiB,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,GAC9C;IAAE,IAAI,EAAE,WAAW,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,GACxC;IAAE,IAAI,EAAE,YAAY,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GACvC;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,SAA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IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,CAAC;gBAChD,kBAAkB,IAAI,QAAQ,CAAC;YACjC,CAAC;QACH,CAAC;QAED,OAAO;YACL,YAAY,EAAE,kBAAkB;YAChC,QAAQ,EAAE;gBACR,GAAG,QAAQ;gBACX,GAAG,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;aAClD;YACD,cAAc;YACd,SAAS,EAAE;gBACT,KAAK,EAAE,YAAY;gBACnB,UAAU,EAAE,cAAc;gBAC1B,KAAK,EAAE,UAAU;gBACjB,GAAG;gBACH,GAAG,CAAC,0BAA0B,CAAC,IAAI,GAAG,CAAC,IAAI;oBACzC,wBAAwB,EAAE,EAAE,cAAc,EAAE,CAAC,GAAG,0BAA0B,CAAC,EAAE;iBAC9E,CAAC;gBACF,GAAG,CAAC,6BAA6B,IAAI,EAAE,kBAAkB,EAAE,6BAA6B,EAAE,CAAC;aAC5F;SACF,CAAC;IACJ,CAAC;;AAj0BD,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;AArWtC;IADL,KAAK,EAAE;;;;6CA6GP;AA0XK;IADL,KAAK,EAAE;;;;oCAgDP;AAmBK;IADL,KAAK,EAAE;;sDAIG,WAAW;;0CAkmBrB","sourcesContent":["import type { ChatOpenAI } from \"@langchain/openai\";\nimport { AIMessage, BaseMessage, SystemMessage, ToolMessage, AIMessageChunk } from \"@langchain/core/messages\";\nimport type { ChatTools, ToolContext, ResolvedToolContext } from \"../shared/agent/tool.factory.js\";\nimport { resolveChatContext } from \"../shared/agent/tool.helpers.js\";\nimport { scopeFromNetworkId } from \"../shared/agent/tool.scope.js\";\nimport { ITERATION_NUDGE } from \"./chat.prompt.js\";\nimport { ORCHESTRATOR_PERSONA, type ChatPersonaConfig } from \"./chat.persona.js\";\nimport { extractRecentToolCalls, type IterationContext } from \"./chat.prompt.modules.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport { createModel, type ModelConfig } from \"../shared/agent/model.config.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\nimport { sanitizeForDebugMeta } from \"../shared/observability/debug-meta.sanitizer.js\";\nimport type { DebugMetaToolCall, DebugMetaLlm, DebugMetaOrchestratorNegotiations, DebugMetaDiscoveryQuestions } from \"./chat-streaming.types.js\";\nimport type { Question, QuestionStrategy } from \"../shared/schemas/question.schema.js\";\nimport type { Opportunity } from \"../shared/interfaces/database.interface.js\";\nimport { Timed } from \"../shared/observability/performance.js\";\nimport { requestContext } from \"../shared/observability/request-context.js\";\nimport { deduplicateQuestions } from \"./chat.question-dedup.js\";\n\nconst AGENT_ACTION_PROPOSAL_FENCE_PATTERN = /```agent_action_proposal\\s*\\n([\\s\\S]*?)\\n```/g;\nconst AGENT_ACTION_PROPOSAL_KEYS = new Set([\"proposalId\", \"actions\"]);\nconst AGENT_ACTION_KEYS = new Set([\n \"type\",\n \"entityId\",\n \"currentState\",\n \"proposedOperation\",\n \"skipped\",\n \"reason\",\n \"description\",\n \"evidence\",\n]);\nconst AGENT_ACTION_OPERATIONS = {\n retract_premise: \"RETRACT_PREMISE\",\n narrow_signal: \"NARROW_SIGNAL\",\n pause_signal: \"PAUSE_SIGNAL\",\n} as const;\n\nfunction isVisibleAgentActionProposal(payload: unknown): boolean {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) return false;\n const proposal = payload as Record<string, unknown>;\n if (Object.keys(proposal).some((key) => !AGENT_ACTION_PROPOSAL_KEYS.has(key))) return false;\n if (\n typeof proposal.proposalId !== \"string\"\n || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(proposal.proposalId)\n || !Array.isArray(proposal.actions)\n || proposal.actions.length < 1\n || proposal.actions.length > 5\n ) return false;\n\n return proposal.actions.every((rawAction) => {\n if (!rawAction || typeof rawAction !== \"object\" || Array.isArray(rawAction)) return false;\n const action = rawAction as Record<string, unknown>;\n if (Object.keys(action).some((key) => !AGENT_ACTION_KEYS.has(key))) return false;\n if (typeof action.type !== \"string\" || !(action.type in AGENT_ACTION_OPERATIONS)) return false;\n const type = action.type as keyof typeof AGENT_ACTION_OPERATIONS;\n if (action.proposedOperation !== AGENT_ACTION_OPERATIONS[type]) return false;\n if (typeof action.entityId !== \"string\" || !action.entityId.trim()) return false;\n if (typeof action.currentState !== \"string\" || !action.currentState.trim()) return false;\n if (action.skipped !== undefined && typeof action.skipped !== \"boolean\") return false;\n return [\"reason\", \"description\", \"evidence\"].every(\n (key) => action[key] === undefined || typeof action[key] === \"string\",\n );\n });\n}\n\nconst logger = protocolLogger(\"ChatAgent\");\n\n// Re-export for external consumers\nexport { ITERATION_NUDGE } from \"./chat.prompt.js\";\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TYPES\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Writer callback for streaming custom data out of the graph node.\n * Matches the `config.writer` signature from LangGraphRunnableConfig.\n */\nexport type StreamWriter = (data: unknown) => void;\n\n/**\n * Events emitted by `streamRun()` via the writer callback.\n *\n * - `iteration_start` — new agent loop iteration begins\n * - `llm_start` — LLM begins generating response\n * - `text_chunk` — a token (or group of tokens) of model text\n * - `llm_end` — LLM finished generating (may have tool calls)\n * - `tool_activity` — tool starts or finishes execution\n * - `graph_start` — a LangGraph sub-graph begins inside a tool\n * - `graph_end` — a LangGraph sub-graph completes\n * - `agent_start` — an LLM agent begins inside a graph node\n * - `agent_end` — an LLM agent completes\n * - `opportunity_draft_ready` — an orchestrator-triggered negotiation finalized\n * to `draft` and the card is ready to render inline\n */\nexport type AgentStreamEvent =\n | { type: \"iteration_start\"; iteration: number }\n | { type: \"llm_start\"; iteration: number }\n | { type: \"text_chunk\"; content: string }\n | { type: \"llm_end\"; iteration: number; hasToolCalls: boolean; toolNames?: string[] }\n | { type: \"tool_activity\"; phase: \"start\"; name: string }\n | {\n type: \"tool_activity\";\n phase: \"end\";\n name: string;\n success: boolean;\n summary?: string;\n steps?: Array<{ step: string; detail?: string; data?: Record<string, unknown> }>;\n }\n | { type: \"response_reset\"; reason: string }\n | { type: \"hallucination_detected\"; blockType: string; tool: string }\n | { type: \"graph_start\"; name: string }\n | { type: \"graph_end\"; name: string; durationMs: number }\n | { type: \"phase_start\"; name: string }\n | { type: \"phase_end\"; name: string; durationMs: number }\n | { type: \"agent_start\"; name: string }\n | { type: \"agent_end\"; name: string; durationMs: number; summary: string }\n | {\n // Emitted from the orchestrator branch of OpportunityGraph.negotiateNode\n // each time a per-candidate negotiation resolves to an accepted draft.\n // Carries the opportunity row plus the counterparty's display basics so\n // the frontend can append an inline card to the chat timeline without a\n // second round-trip user lookup.\n type: \"opportunity_draft_ready\";\n opportunityId: string;\n opportunity: Opportunity;\n /** Viewer-centric summary derived from interpretation.reasoning via viewerCentricCardSummary. */\n personalizedSummary?: string;\n counterparty: {\n userId: string;\n name?: string;\n };\n }\n | {\n type: \"negotiation_session_start\";\n opportunityId: string;\n negotiationConversationId: string;\n sourceUserId: string;\n candidateUserId: string;\n candidateName?: string;\n trigger: \"orchestrator\" | \"ambient\";\n startedAt: number;\n }\n | {\n type: \"negotiation_session_end\";\n opportunityId: string;\n negotiationConversationId: string;\n durationMs: number;\n }\n | {\n type: \"negotiation_turn\";\n opportunityId: string;\n negotiationConversationId: string;\n turnIndex: number;\n actor: \"source\" | \"candidate\";\n action: \"propose\" | \"accept\" | \"reject\" | \"counter\" | \"question\" | \"outreach\" | \"withdraw\" | \"decline\" | \"ask_user\";\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 | \"screened_out\";\n turnCount: number;\n reasoning?: string;\n agreedRoles?: { ownUser?: string; otherUser?: string };\n }\n | {\n // Emitted by the ask_user_question tool after persisting chat-mode\n // questions: the turn is blocked awaiting the user's inline answer.\n type: \"user_question\";\n questions: Array<{\n id: string;\n title: string;\n prompt: string;\n options: Array<{ label: string; description: string }>;\n multiSelect: boolean;\n }>;\n }\n | { type: \"status\"; message: string }\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: ChatTools;\n private toolsByName: Map<string, any>;\n\n /**\n * Private constructor — use `ChatAgent.create()` instead.\n */\n private constructor(\n private resolvedContext: ResolvedToolContext,\n private persona: ChatPersonaConfig,\n tools: ChatTools,\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 * Detects a prior visible action proposal without considering current-turn\n * tool calls. The reporter uses this only to make typed confirmation\n * language contextual rather than executable on its own.\n */\n static hasPriorAgentActionProposal(messages: BaseMessage[]): boolean {\n let currentHumanIndex = -1;\n let previousHumanIndex = -1;\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n if (messages[index]._getType() !== \"human\") continue;\n if (currentHumanIndex < 0) {\n currentHumanIndex = index;\n } else {\n previousHumanIndex = index;\n break;\n }\n }\n if (currentHumanIndex < 0 || previousHumanIndex < 0) return false;\n\n let latestAssistant: BaseMessage | undefined;\n for (let index = currentHumanIndex - 1; index > previousHumanIndex; index -= 1) {\n if (messages[index]._getType() === \"ai\") {\n latestAssistant = messages[index];\n break;\n }\n }\n if (!latestAssistant || typeof latestAssistant.content !== \"string\") return false;\n\n AGENT_ACTION_PROPOSAL_FENCE_PATTERN.lastIndex = 0;\n for (const match of latestAssistant.content.matchAll(AGENT_ACTION_PROPOSAL_FENCE_PATTERN)) {\n try {\n if (isVisibleAgentActionProposal(JSON.parse(match[1]))) return true;\n } catch {\n // An invalid prior fence is not visible proposal context.\n }\n }\n return false;\n }\n\n /**\n * Async factory: creates a ChatAgent with resolved user/index context.\n * Resolves user/network identity from DB during tool initialization.\n *\n * @param context - Tool context (database, userId, scope, deps)\n * @param persona - Persona config (prompt builder, toolset, loop behaviors).\n * Defaults to the orchestrator persona.\n */\n static async create(\n context: ToolContext,\n persona: ChatPersonaConfig = ORCHESTRATOR_PERSONA,\n ): Promise<ChatAgent> {\n const { networkId: legacyNetworkId } = context;\n const explicitScope = context.scopeType && context.scopeId\n ? { scopeType: context.scopeType, scopeId: context.scopeId }\n : scopeFromNetworkId(legacyNetworkId);\n const scopedNetworkId = explicitScope.scopeType === 'network' ? explicitScope.scopeId : undefined;\n const resolved: ResolvedToolContext = await resolveChatContext({\n database: context.database,\n userId: context.userId,\n networkId: scopedNetworkId,\n sessionId: context.sessionId,\n contactsEnabled: context.contactsEnabled,\n actionToolsEnabled: context.actionToolsEnabled,\n });\n if (explicitScope.scopeType && explicitScope.scopeId) {\n resolved.scopeType = explicitScope.scopeType;\n resolved.scopeId = explicitScope.scopeId;\n }\n const tools = await persona.createTools(context, resolved);\n return new ChatAgent(resolved, persona, 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 hasPriorAgentActionProposal: ChatAgent.hasPriorAgentActionProposal(messages),\n ctx: this.resolvedContext,\n };\n const deterministicResponse = this.persona.resolveDeterministicResponse?.(\n this.resolvedContext,\n iterCtx,\n );\n if (deterministicResponse !== undefined && deterministicResponse !== null) {\n const response = new AIMessage(deterministicResponse);\n return {\n shouldContinue: false,\n responseText: deterministicResponse,\n messages: [...messages, response],\n };\n }\n const systemContent = this.persona.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\" && this.persona.loopBehaviors.createIntentCallback) {\n const newResult = await this.handleCreateIntentCallback(resultStr, tc.args);\n if (newResult !== null) {\n resultStr = newResult;\n result = newResult;\n }\n }\n\n logger.debug(\"Tool response\", { name: tc.name, result: resultStr });\n logger.verbose(\"Tool completed\", {\n name: tc.name,\n resultLength: resultStr.length,\n });\n\n return {\n toolCallId: tc.id || `${tc.name}-${Date.now()}`,\n name: tc.name,\n result: resultStr,\n };\n } catch (error) {\n logger.error(\"Tool execution failed\", {\n name: tc.name,\n error: error instanceof Error ? error.message : String(error),\n });\n\n return {\n toolCallId: tc.id || `${tc.name}-${Date.now()}`,\n name: tc.name,\n result: JSON.stringify({\n success: false,\n error: `Tool execution failed: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n }),\n };\n }\n }),\n );\n\n return results;\n }\n\n /**\n * When discover_opportunities returned createIntentSuggested, call create_intent then discover_opportunities.\n * Returns the new discover_opportunities result string or null if no callback / create_intent failed.\n */\n private async handleCreateIntentCallback(\n resultStr: string,\n originalArgs: Record<string, unknown>\n ): Promise<string | null> {\n let parsed: { success?: boolean; error?: string; data?: { createIntentSuggested?: boolean; suggestedIntentDescription?: string } };\n try {\n parsed = JSON.parse(resultStr) as typeof parsed;\n } catch {\n return null;\n }\n if (\n !parsed?.data?.createIntentSuggested ||\n typeof parsed.data.suggestedIntentDescription !== \"string\"\n ) {\n return null;\n }\n // Never auto-create intents during introducer flows — signals are personal\n if ((originalArgs as { introTargetUserId?: string }).introTargetUserId) {\n return null;\n }\n const createIntentTool = this.toolsByName.get(\"create_intent\");\n const discoverOpportunitiesTool = this.toolsByName.get(\"discover_opportunities\");\n if (!createIntentTool || !discoverOpportunitiesTool) return null;\n\n logger.verbose(\"Create-intent signal: auto-calling create_intent then discover_opportunities\");\n const createIntentResult = await createIntentTool.invoke({\n description: parsed.data.suggestedIntentDescription,\n networkId: (originalArgs as { networkId?: string }).networkId,\n });\n const createIntentStr =\n typeof createIntentResult === \"string\" ? createIntentResult : JSON.stringify(createIntentResult);\n let createIntentParsed: { success?: boolean; error?: string };\n try {\n createIntentParsed = JSON.parse(createIntentStr) as { success?: boolean; error?: string };\n } catch {\n createIntentParsed = {};\n }\n if (createIntentParsed.success === false) {\n logger.warn(\"Create-intent failed; not re-running discover_opportunities\", {\n error: createIntentParsed.error,\n });\n return null;\n }\n\n const newResult = await discoverOpportunitiesTool.invoke(originalArgs);\n return typeof newResult === \"string\" ? newResult : JSON.stringify(newResult);\n }\n\n /**\n * Check whether any tool call produced valid opportunity blocks.\n * Both `discover_opportunities` and `list_opportunities` can return\n * ```opportunity code blocks — either one counts as a valid source.\n */\n private static hasOpportunitySource(\n toolsUsed: Array<{ name: string; success: boolean; resultSummary?: string }>,\n ): boolean {\n return toolsUsed.some(\n (t) =>\n (t.name === \"discover_opportunities\" || t.name === \"list_opportunities\") &&\n t.success &&\n !t.resultSummary?.startsWith(\"Found 0\") &&\n !t.resultSummary?.startsWith(\"No matches\") &&\n !t.resultSummary?.startsWith(\"No opportunities\"),\n );\n }\n\n /**\n * Detect hallucinated ```intent_proposal or ```opportunity blocks in model text\n * that were NOT generated by the corresponding tool call.\n *\n * A tool call that returned 0 cards (e.g. \"Found 0 match(es)\") counts as\n * NOT having produced valid blocks — the LLM must not fabricate them.\n *\n * @returns Block info if hallucination detected, null otherwise\n */\n private detectHallucinatedBlock(\n text: string,\n toolsUsed: Array<{ name: string; success: boolean; resultSummary?: string }>,\n userMessage?: string,\n ): { type: string; tool: string; description: string } | null {\n const hasSuccessfulCreateIntent = toolsUsed.some(\n (t) => t.name === \"create_intent\" && t.success,\n );\n\n // Check for hallucinated intent_proposal\n if (text.includes(\"```intent_proposal\") && !hasSuccessfulCreateIntent) {\n const match = text.match(/```intent_proposal\\s*\\n\\s*\\{[^}]*\"description\"\\s*:\\s*\"([^\"]+)\"/);\n if (match) {\n return { type: \"intent_proposal\", tool: \"create_intent\", description: match[1] };\n }\n }\n\n // Check for hallucinated opportunity blocks\n if (text.includes(\"```opportunity\") && !ChatAgent.hasOpportunitySource(toolsUsed)) {\n // Use the user's original message as the search query — NOT fields from the\n // hallucinated JSON. The model fabricates person names and reasoning that have\n // nothing to do with the user's actual request, leading to wrong results and\n // the model re-calling the tool with the correct query (doubling negotiation cost).\n const description = userMessage?.trim() || \"find connections\";\n return { type: \"opportunity\", tool: \"discover_opportunities\", description };\n }\n\n return null;\n }\n\n /**\n * Strip ```opportunity and ```intent_proposal code blocks from text\n * when no corresponding successful tool call was made.\n * Defense-in-depth: catches hallucinated blocks that slip past detectHallucinatedBlock\n * (e.g. after a correction iteration that still hallucinates).\n *\n * @param text - The response text to sanitize\n * @param toolsUsed - Tool call records from the agent loop\n * @returns Sanitized text with unbacked blocks removed\n */\n private stripUnbackedBlocks(\n text: string,\n toolsUsed: Array<{ name: string; success: boolean; resultSummary?: string }>,\n ): string {\n let result = text;\n let removedBlock = false;\n\n const hasSuccessfulCreateIntent = toolsUsed.some(\n (t) => t.name === \"create_intent\" && t.success,\n );\n\n if (!ChatAgent.hasOpportunitySource(toolsUsed) && result.includes(\"```opportunity\")) {\n const next = result.replace(/```opportunity\\s*\\n[\\s\\S]*?```/g, \"\");\n removedBlock ||= next !== result;\n result = next;\n }\n if (!hasSuccessfulCreateIntent && result.includes(\"```intent_proposal\")) {\n const next = result.replace(/```intent_proposal\\s*\\n[\\s\\S]*?```/g, \"\");\n removedBlock ||= next !== result;\n result = next;\n }\n\n // Clean up leftover double blank lines only when a block was actually removed\n if (removedBlock) {\n result = result.replace(/\\n{3,}/g, \"\\n\\n\").trim();\n }\n\n return result;\n }\n\n // ─── Phantom write detection ─────────────────────────────────────────────\n\n private static readonly PHANTOM_WRITE_PATTERNS = [\n /\\bI(?:'ve| have) (?:updated|adjusted|changed|modified|edited|created|added|removed|deleted|saved|set up)\\b/i,\n /\\bI (?:updated|adjusted|changed|modified|edited|created|added|removed|deleted|saved|set up)\\b/i,\n /\\b(?:Updated|Adjusted|Changed|Modified|Edited|Created|Added|Removed|Deleted|Saved) (?:your|the|their)\\b/i,\n /\\bEverything is (?:now )?(?:updated|changed|adjusted|saved|set)\\b/i,\n /\\b(?:profile|bio|premise|signal|intent|membership|narrative) (?:has been|is now) (?:updated|changed|modified|adjusted|saved)\\b/i,\n ];\n\n /**\n * Detect when the model claims to have performed a write action\n * without having called any tools in the turn.\n */\n private static detectPhantomWrite(\n responseText: string,\n toolsUsed: Array<{ name: string }>,\n ): boolean {\n if (toolsUsed.length > 0) return false;\n return ChatAgent.PHANTOM_WRITE_PATTERNS.some(pattern => pattern.test(responseText));\n }\n\n // ─── Shared tool-result post-processing types ─────────────────────────────\n private static readonly STEP_DETAIL_MAX = 300;\n\n private static readonly STEP_NAME_MAX = 100;\n\n /**\n * Post-process a tool result: strip _graphTimings, extract summary/debugSteps,\n * and optionally run discover_opportunities → create_intent callback.\n *\n * Returns the normalized result string and extracted debug metadata so both\n * the normal streaming tool loop and the hallucination-recovery branch\n * produce identical LLM-facing payloads.\n */\n private async normalizeToolResult(\n toolName: string,\n resultStr: string,\n toolArgs: Record<string, unknown>,\n ): Promise<{\n resultStr: string;\n summary: string;\n debugSteps?: Array<{ step: string; detail?: string; data?: Record<string, unknown> }>;\n graphTimings?: Array<{ name: string; durationMs: number; agents: Array<{ name: string; durationMs: number }> }>;\n decisionQuestions?: Question[];\n discoveryQuestionsDebug?: DebugMetaDiscoveryQuestions;\n }> {\n let normalized = resultStr;\n\n // Run create_intent callback for discover_opportunities results (orchestrator behavior)\n if (toolName === \"discover_opportunities\" && this.persona.loopBehaviors.createIntentCallback) {\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 hasPriorAgentActionProposal: ChatAgent.hasPriorAgentActionProposal(messages),\n ctx: this.resolvedContext,\n };\n const deterministicResponse = this.persona.resolveDeterministicResponse?.(\n this.resolvedContext,\n iterCtx,\n );\n if (deterministicResponse !== undefined && deterministicResponse !== null) {\n emit({ type: \"text_chunk\", content: deterministicResponse });\n messages = [...messages, new AIMessage(deterministicResponse)];\n iterationCount++;\n return {\n responseText: deterministicResponse,\n messages,\n iterationCount,\n debugMeta: {\n graph: \"agent_loop\",\n iterations: iterationCount,\n tools: toolsDebug,\n llm,\n },\n };\n }\n const systemContent = this.persona.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 // Persona-gated: only personas with hallucinationRecovery enabled (orchestrator)\n // run detection/auto-invoke — other personas never trigger this branch.\n const hallucinatedBlock = this.persona.loopBehaviors.hallucinationRecovery\n ? this.detectHallucinatedBlock(iterationText, toolsDebug, iterCtx.currentMessage)\n : null;\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 (persona-gated,\n // same flag as detection since both police tool-backed block types).\n const sanitizedText = this.persona.loopBehaviors.hallucinationRecovery\n ? this.stripUnbackedBlocks(iterationText, toolsDebug)\n : iterationText;\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,EAAE,SAAS,EAAe,aAAa,EAAE,WAAW,EAAkB,MAAM,0BAA0B,CAAC;AAE9G,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AACrE,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,oBAAoB,EAA0B,MAAM,mBAAmB,CAAC;AACjF,OAAO,EAAE,sBAAsB,EAAyB,MAAM,0BAA0B,CAAC;AACzF,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,WAAW,EAAoB,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAAE,qBAAqB,EAAE,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,mCAAmC,GAAG,+CAA+C,CAAC;AAC5F,MAAM,0BAA0B,GAAG,IAAI,GAAG,CAAC,CAAC,YAAY,EAAE,SAAS,CAAC,CAAC,CAAC;AACtE,MAAM,iBAAiB,GAAG,IAAI,GAAG,CAAC;IAChC,MAAM;IACN,UAAU;IACV,cAAc;IACd,mB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B,CAAC,KAAK,CAAC,CAAC;YAC7C,IAAI,QAAQ,EAAE,CAAC;gBACb,IAAI,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,CAAC;gBAChD,kBAAkB,IAAI,QAAQ,CAAC;YACjC,CAAC;QACH,CAAC;QAED,OAAO;YACL,YAAY,EAAE,kBAAkB;YAChC,QAAQ,EAAE;gBACR,GAAG,QAAQ;gBACX,GAAG,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;aAClD;YACD,cAAc;YACd,SAAS,EAAE;gBACT,KAAK,EAAE,YAAY;gBACnB,UAAU,EAAE,cAAc;gBAC1B,KAAK,EAAE,UAAU;gBACjB,GAAG;gBACH,GAAG,CAAC,0BAA0B,CAAC,IAAI,GAAG,CAAC,IAAI;oBACzC,wBAAwB,EAAE,EAAE,cAAc,EAAE,CAAC,GAAG,0BAA0B,CAAC,EAAE;iBAC9E,CAAC;gBACF,GAAG,CAAC,6BAA6B,IAAI,EAAE,kBAAkB,EAAE,6BAA6B,EAAE,CAAC;aAC5F;SACF,CAAC;IACJ,CAAC;;AAj0BD,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;AArWtC;IADL,KAAK,EAAE;;;;6CA6GP;AA0XK;IADL,KAAK,EAAE;;;;oCAgDP;AAmBK;IADL,KAAK,EAAE;;sDAIG,WAAW;;0CAkmBrB","sourcesContent":["import type { ChatOpenAI } from \"@langchain/openai\";\nimport { AIMessage, BaseMessage, SystemMessage, ToolMessage, AIMessageChunk } from \"@langchain/core/messages\";\nimport type { ChatTools, ToolContext, ResolvedToolContext } from \"../shared/agent/tool.factory.js\";\nimport { resolveChatContext } from \"../shared/agent/tool.helpers.js\";\nimport { scopeFromNetworkId } from \"../shared/agent/tool.scope.js\";\nimport { ITERATION_NUDGE } from \"./chat.prompt.js\";\nimport { ORCHESTRATOR_PERSONA, type ChatPersonaConfig } from \"./chat.persona.js\";\nimport { extractRecentToolCalls, type IterationContext } from \"./chat.prompt.modules.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport { createModel, type ModelConfig } from \"../shared/agent/model.config.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\nimport { sanitizeForDebugMeta } from \"../shared/observability/debug-meta.sanitizer.js\";\nimport type { DebugMetaToolCall, DebugMetaLlm, DebugMetaOrchestratorNegotiations, DebugMetaDiscoveryQuestions } from \"./chat-streaming.types.js\";\nimport type { Question, QuestionStrategy } from \"../shared/schemas/question.schema.js\";\nimport type { Opportunity } from \"../shared/interfaces/database.interface.js\";\nimport { Timed } from \"../shared/observability/performance.js\";\nimport { requestContext } from \"../shared/observability/request-context.js\";\nimport { deduplicateQuestions } from \"./chat.question-dedup.js\";\n\nconst AGENT_ACTION_PROPOSAL_FENCE_PATTERN = /```agent_action_proposal\\s*\\n([\\s\\S]*?)\\n```/g;\nconst AGENT_ACTION_PROPOSAL_KEYS = new Set([\"proposalId\", \"actions\"]);\nconst AGENT_ACTION_KEYS = new Set([\n \"type\",\n \"entityId\",\n \"currentState\",\n \"proposedOperation\",\n \"skipped\",\n \"reason\",\n \"description\",\n \"evidence\",\n]);\nconst AGENT_ACTION_OPERATIONS = {\n retract_premise: \"RETRACT_PREMISE\",\n narrow_signal: \"NARROW_SIGNAL\",\n pause_signal: \"PAUSE_SIGNAL\",\n} as const;\n\nfunction isVisibleAgentActionProposal(payload: unknown): boolean {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) return false;\n const proposal = payload as Record<string, unknown>;\n if (Object.keys(proposal).some((key) => !AGENT_ACTION_PROPOSAL_KEYS.has(key))) return false;\n if (\n typeof proposal.proposalId !== \"string\"\n || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(proposal.proposalId)\n || !Array.isArray(proposal.actions)\n || proposal.actions.length < 1\n || proposal.actions.length > 5\n ) return false;\n\n return proposal.actions.every((rawAction) => {\n if (!rawAction || typeof rawAction !== \"object\" || Array.isArray(rawAction)) return false;\n const action = rawAction as Record<string, unknown>;\n if (Object.keys(action).some((key) => !AGENT_ACTION_KEYS.has(key))) return false;\n if (typeof action.type !== \"string\" || !(action.type in AGENT_ACTION_OPERATIONS)) return false;\n const type = action.type as keyof typeof AGENT_ACTION_OPERATIONS;\n if (action.proposedOperation !== AGENT_ACTION_OPERATIONS[type]) return false;\n if (typeof action.entityId !== \"string\" || !action.entityId.trim()) return false;\n if (typeof action.currentState !== \"string\" || !action.currentState.trim()) return false;\n if (action.skipped !== undefined && typeof action.skipped !== \"boolean\") return false;\n return [\"reason\", \"description\", \"evidence\"].every(\n (key) => action[key] === undefined || typeof action[key] === \"string\",\n );\n });\n}\n\nconst logger = protocolLogger(\"ChatAgent\");\n\n// Re-export for external consumers\nexport { ITERATION_NUDGE } from \"./chat.prompt.js\";\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TYPES\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Writer callback for streaming custom data out of the graph node.\n * Matches the `config.writer` signature from LangGraphRunnableConfig.\n */\nexport type StreamWriter = (data: unknown) => void;\n\n/**\n * Events emitted by `streamRun()` via the writer callback.\n *\n * - `iteration_start` — new agent loop iteration begins\n * - `llm_start` — LLM begins generating response\n * - `text_chunk` — a token (or group of tokens) of model text\n * - `llm_end` — LLM finished generating (may have tool calls)\n * - `tool_activity` — tool starts or finishes execution\n * - `graph_start` — a LangGraph sub-graph begins inside a tool\n * - `graph_end` — a LangGraph sub-graph completes\n * - `agent_start` — an LLM agent begins inside a graph node\n * - `agent_end` — an LLM agent completes\n * - `opportunity_draft_ready` — an orchestrator-triggered negotiation finalized\n * to `draft` and the card is ready to render inline\n */\nexport type AgentStreamEvent =\n | { type: \"iteration_start\"; iteration: number }\n | { type: \"llm_start\"; iteration: number }\n | { type: \"text_chunk\"; content: string }\n | { type: \"llm_end\"; iteration: number; hasToolCalls: boolean; toolNames?: string[] }\n | { type: \"tool_activity\"; phase: \"start\"; name: string }\n | {\n type: \"tool_activity\";\n phase: \"end\";\n name: string;\n success: boolean;\n summary?: string;\n steps?: Array<{ step: string; detail?: string; data?: Record<string, unknown> }>;\n }\n | { type: \"response_reset\"; reason: string }\n | { type: \"hallucination_detected\"; blockType: string; tool: string }\n | { type: \"graph_start\"; name: string }\n | { type: \"graph_end\"; name: string; durationMs: number }\n | { type: \"phase_start\"; name: string }\n | { type: \"phase_end\"; name: string; durationMs: number }\n | { type: \"agent_start\"; name: string }\n | { type: \"agent_end\"; name: string; durationMs: number; summary: string }\n | {\n // Emitted from the orchestrator branch of OpportunityGraph.negotiateNode\n // each time a per-candidate negotiation resolves to an accepted draft.\n // Carries the opportunity row plus the counterparty's display basics so\n // the frontend can append an inline card to the chat timeline without a\n // second round-trip user lookup.\n type: \"opportunity_draft_ready\";\n opportunityId: string;\n opportunity: Opportunity;\n /** Viewer-centric summary derived from interpretation.reasoning via viewerCentricCardSummary. */\n personalizedSummary?: string;\n counterparty: {\n userId: string;\n name?: string;\n };\n }\n | {\n type: \"negotiation_session_start\";\n opportunityId: string;\n negotiationConversationId: string;\n sourceUserId: string;\n candidateUserId: string;\n candidateName?: string;\n trigger: \"orchestrator\" | \"ambient\";\n startedAt: number;\n }\n | {\n type: \"negotiation_session_end\";\n opportunityId: string;\n negotiationConversationId: string;\n durationMs: number;\n }\n | {\n type: \"negotiation_turn\";\n opportunityId: string;\n negotiationConversationId: string;\n turnIndex: number;\n actor: \"source\" | \"candidate\";\n action: \"propose\" | \"accept\" | \"reject\" | \"counter\" | \"question\" | \"outreach\" | \"withdraw\" | \"decline\" | \"ask_user\";\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 | \"screened_out\";\n turnCount: number;\n reasoning?: string;\n agreedRoles?: { ownUser?: string; otherUser?: string };\n }\n | {\n // Emitted by the ask_user_question tool after persisting chat-mode\n // questions: the turn is blocked awaiting the user's inline answer.\n type: \"user_question\";\n questions: Array<{ id: string }>;\n }\n | { type: \"status\"; message: string }\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: ChatTools;\n private toolsByName: Map<string, any>;\n\n /**\n * Private constructor — use `ChatAgent.create()` instead.\n */\n private constructor(\n private resolvedContext: ResolvedToolContext,\n private persona: ChatPersonaConfig,\n tools: ChatTools,\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 * Detects a prior visible action proposal without considering current-turn\n * tool calls. The reporter uses this only to make typed confirmation\n * language contextual rather than executable on its own.\n */\n static hasPriorAgentActionProposal(messages: BaseMessage[]): boolean {\n let currentHumanIndex = -1;\n let previousHumanIndex = -1;\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n if (messages[index]._getType() !== \"human\") continue;\n if (currentHumanIndex < 0) {\n currentHumanIndex = index;\n } else {\n previousHumanIndex = index;\n break;\n }\n }\n if (currentHumanIndex < 0 || previousHumanIndex < 0) return false;\n\n let latestAssistant: BaseMessage | undefined;\n for (let index = currentHumanIndex - 1; index > previousHumanIndex; index -= 1) {\n if (messages[index]._getType() === \"ai\") {\n latestAssistant = messages[index];\n break;\n }\n }\n if (!latestAssistant || typeof latestAssistant.content !== \"string\") return false;\n\n AGENT_ACTION_PROPOSAL_FENCE_PATTERN.lastIndex = 0;\n for (const match of latestAssistant.content.matchAll(AGENT_ACTION_PROPOSAL_FENCE_PATTERN)) {\n try {\n if (isVisibleAgentActionProposal(JSON.parse(match[1]))) return true;\n } catch {\n // An invalid prior fence is not visible proposal context.\n }\n }\n return false;\n }\n\n /**\n * Async factory: creates a ChatAgent with resolved user/index context.\n * Resolves user/network identity from DB during tool initialization.\n *\n * @param context - Tool context (database, userId, scope, deps)\n * @param persona - Persona config (prompt builder, toolset, loop behaviors).\n * Defaults to the orchestrator persona.\n */\n static async create(\n context: ToolContext,\n persona: ChatPersonaConfig = ORCHESTRATOR_PERSONA,\n ): Promise<ChatAgent> {\n const { networkId: legacyNetworkId } = context;\n const explicitScope = context.scopeType && context.scopeId\n ? { scopeType: context.scopeType, scopeId: context.scopeId }\n : scopeFromNetworkId(legacyNetworkId);\n const scopedNetworkId = explicitScope.scopeType === 'network' ? explicitScope.scopeId : undefined;\n const resolved: ResolvedToolContext = await resolveChatContext({\n database: context.database,\n userId: context.userId,\n networkId: scopedNetworkId,\n sessionId: context.sessionId,\n contactsEnabled: context.contactsEnabled,\n actionToolsEnabled: context.actionToolsEnabled,\n });\n if (explicitScope.scopeType && explicitScope.scopeId) {\n resolved.scopeType = explicitScope.scopeType;\n resolved.scopeId = explicitScope.scopeId;\n }\n const tools = await persona.createTools(context, resolved);\n return new ChatAgent(resolved, persona, 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 hasPriorAgentActionProposal: ChatAgent.hasPriorAgentActionProposal(messages),\n ctx: this.resolvedContext,\n };\n const deterministicResponse = this.persona.resolveDeterministicResponse?.(\n this.resolvedContext,\n iterCtx,\n );\n if (deterministicResponse !== undefined && deterministicResponse !== null) {\n const response = new AIMessage(deterministicResponse);\n return {\n shouldContinue: false,\n responseText: deterministicResponse,\n messages: [...messages, response],\n };\n }\n const systemContent = this.persona.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\" && this.persona.loopBehaviors.createIntentCallback) {\n const newResult = await this.handleCreateIntentCallback(resultStr, tc.args);\n if (newResult !== null) {\n resultStr = newResult;\n result = newResult;\n }\n }\n\n logger.debug(\"Tool response\", { name: tc.name, result: resultStr });\n logger.verbose(\"Tool completed\", {\n name: tc.name,\n resultLength: resultStr.length,\n });\n\n return {\n toolCallId: tc.id || `${tc.name}-${Date.now()}`,\n name: tc.name,\n result: resultStr,\n };\n } catch (error) {\n logger.error(\"Tool execution failed\", {\n name: tc.name,\n error: error instanceof Error ? error.message : String(error),\n });\n\n return {\n toolCallId: tc.id || `${tc.name}-${Date.now()}`,\n name: tc.name,\n result: JSON.stringify({\n success: false,\n error: `Tool execution failed: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n }),\n };\n }\n }),\n );\n\n return results;\n }\n\n /**\n * When discover_opportunities returned createIntentSuggested, call create_intent then discover_opportunities.\n * Returns the new discover_opportunities result string or null if no callback / create_intent failed.\n */\n private async handleCreateIntentCallback(\n resultStr: string,\n originalArgs: Record<string, unknown>\n ): Promise<string | null> {\n let parsed: { success?: boolean; error?: string; data?: { createIntentSuggested?: boolean; suggestedIntentDescription?: string } };\n try {\n parsed = JSON.parse(resultStr) as typeof parsed;\n } catch {\n return null;\n }\n if (\n !parsed?.data?.createIntentSuggested ||\n typeof parsed.data.suggestedIntentDescription !== \"string\"\n ) {\n return null;\n }\n // Never auto-create intents during introducer flows — signals are personal\n if ((originalArgs as { introTargetUserId?: string }).introTargetUserId) {\n return null;\n }\n const createIntentTool = this.toolsByName.get(\"create_intent\");\n const discoverOpportunitiesTool = this.toolsByName.get(\"discover_opportunities\");\n if (!createIntentTool || !discoverOpportunitiesTool) return null;\n\n logger.verbose(\"Create-intent signal: auto-calling create_intent then discover_opportunities\");\n const createIntentResult = await createIntentTool.invoke({\n description: parsed.data.suggestedIntentDescription,\n networkId: (originalArgs as { networkId?: string }).networkId,\n });\n const createIntentStr =\n typeof createIntentResult === \"string\" ? createIntentResult : JSON.stringify(createIntentResult);\n let createIntentParsed: { success?: boolean; error?: string };\n try {\n createIntentParsed = JSON.parse(createIntentStr) as { success?: boolean; error?: string };\n } catch {\n createIntentParsed = {};\n }\n if (createIntentParsed.success === false) {\n logger.warn(\"Create-intent failed; not re-running discover_opportunities\", {\n error: createIntentParsed.error,\n });\n return null;\n }\n\n const newResult = await discoverOpportunitiesTool.invoke(originalArgs);\n return typeof newResult === \"string\" ? newResult : JSON.stringify(newResult);\n }\n\n /**\n * Check whether any tool call produced valid opportunity blocks.\n * Both `discover_opportunities` and `list_opportunities` can return\n * ```opportunity code blocks — either one counts as a valid source.\n */\n private static hasOpportunitySource(\n toolsUsed: Array<{ name: string; success: boolean; resultSummary?: string }>,\n ): boolean {\n return toolsUsed.some(\n (t) =>\n (t.name === \"discover_opportunities\" || t.name === \"list_opportunities\") &&\n t.success &&\n !t.resultSummary?.startsWith(\"Found 0\") &&\n !t.resultSummary?.startsWith(\"No matches\") &&\n !t.resultSummary?.startsWith(\"No opportunities\"),\n );\n }\n\n /**\n * Detect hallucinated ```intent_proposal or ```opportunity blocks in model text\n * that were NOT generated by the corresponding tool call.\n *\n * A tool call that returned 0 cards (e.g. \"Found 0 match(es)\") counts as\n * NOT having produced valid blocks — the LLM must not fabricate them.\n *\n * @returns Block info if hallucination detected, null otherwise\n */\n private detectHallucinatedBlock(\n text: string,\n toolsUsed: Array<{ name: string; success: boolean; resultSummary?: string }>,\n userMessage?: string,\n ): { type: string; tool: string; description: string } | null {\n const hasSuccessfulCreateIntent = toolsUsed.some(\n (t) => t.name === \"create_intent\" && t.success,\n );\n\n // Check for hallucinated intent_proposal\n if (text.includes(\"```intent_proposal\") && !hasSuccessfulCreateIntent) {\n const match = text.match(/```intent_proposal\\s*\\n\\s*\\{[^}]*\"description\"\\s*:\\s*\"([^\"]+)\"/);\n if (match) {\n return { type: \"intent_proposal\", tool: \"create_intent\", description: match[1] };\n }\n }\n\n // Check for hallucinated opportunity blocks\n if (text.includes(\"```opportunity\") && !ChatAgent.hasOpportunitySource(toolsUsed)) {\n // Use the user's original message as the search query — NOT fields from the\n // hallucinated JSON. The model fabricates person names and reasoning that have\n // nothing to do with the user's actual request, leading to wrong results and\n // the model re-calling the tool with the correct query (doubling negotiation cost).\n const description = userMessage?.trim() || \"find connections\";\n return { type: \"opportunity\", tool: \"discover_opportunities\", description };\n }\n\n return null;\n }\n\n /**\n * Strip ```opportunity and ```intent_proposal code blocks from text\n * when no corresponding successful tool call was made.\n * Defense-in-depth: catches hallucinated blocks that slip past detectHallucinatedBlock\n * (e.g. after a correction iteration that still hallucinates).\n *\n * @param text - The response text to sanitize\n * @param toolsUsed - Tool call records from the agent loop\n * @returns Sanitized text with unbacked blocks removed\n */\n private stripUnbackedBlocks(\n text: string,\n toolsUsed: Array<{ name: string; success: boolean; resultSummary?: string }>,\n ): string {\n let result = text;\n let removedBlock = false;\n\n const hasSuccessfulCreateIntent = toolsUsed.some(\n (t) => t.name === \"create_intent\" && t.success,\n );\n\n if (!ChatAgent.hasOpportunitySource(toolsUsed) && result.includes(\"```opportunity\")) {\n const next = result.replace(/```opportunity\\s*\\n[\\s\\S]*?```/g, \"\");\n removedBlock ||= next !== result;\n result = next;\n }\n if (!hasSuccessfulCreateIntent && result.includes(\"```intent_proposal\")) {\n const next = result.replace(/```intent_proposal\\s*\\n[\\s\\S]*?```/g, \"\");\n removedBlock ||= next !== result;\n result = next;\n }\n\n // Clean up leftover double blank lines only when a block was actually removed\n if (removedBlock) {\n result = result.replace(/\\n{3,}/g, \"\\n\\n\").trim();\n }\n\n return result;\n }\n\n // ─── Phantom write detection ─────────────────────────────────────────────\n\n private static readonly PHANTOM_WRITE_PATTERNS = [\n /\\bI(?:'ve| have) (?:updated|adjusted|changed|modified|edited|created|added|removed|deleted|saved|set up)\\b/i,\n /\\bI (?:updated|adjusted|changed|modified|edited|created|added|removed|deleted|saved|set up)\\b/i,\n /\\b(?:Updated|Adjusted|Changed|Modified|Edited|Created|Added|Removed|Deleted|Saved) (?:your|the|their)\\b/i,\n /\\bEverything is (?:now )?(?:updated|changed|adjusted|saved|set)\\b/i,\n /\\b(?:profile|bio|premise|signal|intent|membership|narrative) (?:has been|is now) (?:updated|changed|modified|adjusted|saved)\\b/i,\n ];\n\n /**\n * Detect when the model claims to have performed a write action\n * without having called any tools in the turn.\n */\n private static detectPhantomWrite(\n responseText: string,\n toolsUsed: Array<{ name: string }>,\n ): boolean {\n if (toolsUsed.length > 0) return false;\n return ChatAgent.PHANTOM_WRITE_PATTERNS.some(pattern => pattern.test(responseText));\n }\n\n // ─── Shared tool-result post-processing types ─────────────────────────────\n private static readonly STEP_DETAIL_MAX = 300;\n\n private static readonly STEP_NAME_MAX = 100;\n\n /**\n * Post-process a tool result: strip _graphTimings, extract summary/debugSteps,\n * and optionally run discover_opportunities → create_intent callback.\n *\n * Returns the normalized result string and extracted debug metadata so both\n * the normal streaming tool loop and the hallucination-recovery branch\n * produce identical LLM-facing payloads.\n */\n private async normalizeToolResult(\n toolName: string,\n resultStr: string,\n toolArgs: Record<string, unknown>,\n ): Promise<{\n resultStr: string;\n summary: string;\n debugSteps?: Array<{ step: string; detail?: string; data?: Record<string, unknown> }>;\n graphTimings?: Array<{ name: string; durationMs: number; agents: Array<{ name: string; durationMs: number }> }>;\n decisionQuestions?: Question[];\n discoveryQuestionsDebug?: DebugMetaDiscoveryQuestions;\n }> {\n let normalized = resultStr;\n\n // Run create_intent callback for discover_opportunities results (orchestrator behavior)\n if (toolName === \"discover_opportunities\" && this.persona.loopBehaviors.createIntentCallback) {\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 hasPriorAgentActionProposal: ChatAgent.hasPriorAgentActionProposal(messages),\n ctx: this.resolvedContext,\n };\n const deterministicResponse = this.persona.resolveDeterministicResponse?.(\n this.resolvedContext,\n iterCtx,\n );\n if (deterministicResponse !== undefined && deterministicResponse !== null) {\n emit({ type: \"text_chunk\", content: deterministicResponse });\n messages = [...messages, new AIMessage(deterministicResponse)];\n iterationCount++;\n return {\n responseText: deterministicResponse,\n messages,\n iterationCount,\n debugMeta: {\n graph: \"agent_loop\",\n iterations: iterationCount,\n tools: toolsDebug,\n llm,\n },\n };\n }\n const systemContent = this.persona.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 // Persona-gated: only personas with hallucinationRecovery enabled (orchestrator)\n // run detection/auto-invoke — other personas never trigger this branch.\n const hallucinatedBlock = this.persona.loopBehaviors.hallucinationRecovery\n ? this.detectHallucinatedBlock(iterationText, toolsDebug, iterCtx.currentMessage)\n : null;\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 (persona-gated,\n // same flag as detection since both police tool-backed block types).\n const sanitizedText = this.persona.loopBehaviors.hallucinationRecovery\n ? this.stripUnbackedBlocks(iterationText, toolsDebug)\n : iterationText;\n if (sanitizedText !== iterationText) {\n logger.warn(\"Streaming: stripped unbacked code blocks from final response\", {\n originalLength: iterationText.length,\n sanitizedLength: sanitizedText.length,\n });\n emit({ type: \"response_reset\", reason: \"Sanitized unbacked blocks from response\" });\n // Re-emit the sanitized text so the frontend displays clean content\n if (sanitizedText.trim()) {\n emit({ type: \"text_chunk\", content: sanitizedText });\n }\n\n // If stripping removed ALL content, force a recovery iteration so the\n // user sees an actual response instead of a blank message.\n if (!sanitizedText.trim() && iterationCount < HARD_ITERATION_LIMIT - 1) {\n logger.warn(\"Streaming: sanitized text is empty, forcing recovery iteration\", {\n iteration: iterationCount,\n });\n messages = [\n ...messages,\n accumulated,\n new SystemMessage(\n \"Your previous response only contained invalid code blocks that were removed. \" +\n \"Write a plain text response now — summarize the results of the tools you used. \" +\n \"Do NOT include ```opportunity or ```intent_proposal blocks.\",\n ),\n ];\n iterationCount++;\n continue;\n }\n }\n\n logger.verbose(\"Streaming: agent produced response\", {\n iteration: iterationCount,\n responseLength: sanitizedText.length,\n });\n messages = [...messages, accumulated];\n iterationCount++;\n\n return {\n responseText: sanitizedText,\n messages,\n iterationCount,\n debugMeta: {\n graph: \"agent_loop\",\n iterations: iterationCount,\n tools: toolsDebug,\n llm,\n ...(orchestratorNegotiationIds.size > 0 && {\n orchestratorNegotiations: { opportunityIds: [...orchestratorNegotiationIds] },\n }),\n ...(latestDiscoveryQuestionsDebug && { discoveryQuestions: latestDiscoveryQuestionsDebug }),\n },\n };\n }\n\n // If aborted, return immediately without making another LLM call\n if (signal?.aborted) {\n return {\n responseText: \"\",\n messages,\n iterationCount,\n debugMeta: {\n graph: \"agent_loop\",\n iterations: iterationCount,\n tools: toolsDebug,\n llm,\n ...(orchestratorNegotiationIds.size > 0 && {\n orchestratorNegotiations: { opportunityIds: [...orchestratorNegotiationIds] },\n }),\n ...(latestDiscoveryQuestionsDebug && { discoveryQuestions: latestDiscoveryQuestionsDebug }),\n },\n };\n }\n\n // ── Hard limit: force a response ──────────────────────────────────────\n logger.warn(\"Streaming: hit hard iteration limit\", { iterationCount });\n\n const forceMessages = [\n ...messages,\n new SystemMessage(\n \"You have reached the maximum number of tool calls. You MUST provide a final response now. Summarize what you've accomplished and what might still be needed.\",\n ),\n ];\n\n let forcedAccumulated: AIMessageChunk | undefined;\n let forcedResponseText = \"\";\n const forceStream = await this.model.stream(forceMessages);\n for await (const chunk of forceStream) {\n forcedAccumulated = forcedAccumulated\n ? forcedAccumulated.concat(chunk)\n : chunk;\n const textPart = extractTextFromChunk(chunk);\n if (textPart) {\n emit({ type: \"text_chunk\", content: textPart });\n forcedResponseText += textPart;\n }\n }\n\n return {\n responseText: forcedResponseText,\n messages: [\n ...messages,\n ...(forcedAccumulated ? [forcedAccumulated] : []),\n ],\n iterationCount,\n debugMeta: {\n graph: \"agent_loop\",\n iterations: iterationCount,\n tools: toolsDebug,\n llm,\n ...(orchestratorNegotiationIds.size > 0 && {\n orchestratorNegotiations: { opportunityIds: [...orchestratorNegotiationIds] },\n }),\n ...(latestDiscoveryQuestionsDebug && { discoveryQuestions: latestDiscoveryQuestionsDebug }),\n },\n };\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"questioner.ask.tool.d.ts","sourceRoot":"/","sources":["questioner/questioner.ask.tool.ts"],"names":[],"mappings":"AA4BA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AAM5E,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AA8BxD,8EAA8E;AAC9E,wBAAgB,4BAA4B,CAAC,KAAK,EAAE,eAAe,GAAG,IAAI,GAAG,IAAI,CAEhF;AAqCD;;;;;;;GAOG;AACH,wBAAgB,0BAA0B,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,
|
|
1
|
+
{"version":3,"file":"questioner.ask.tool.d.ts","sourceRoot":"/","sources":["questioner/questioner.ask.tool.ts"],"names":[],"mappings":"AA4BA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AAM5E,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AA8BxD,8EAA8E;AAC9E,wBAAgB,4BAA4B,CAAC,KAAK,EAAE,eAAe,GAAG,IAAI,GAAG,IAAI,CAEhF;AAqCD;;;;;;;GAOG;AACH,wBAAgB,0BAA0B,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,kBAsMhF"}
|
|
@@ -219,13 +219,9 @@ export function createAskUserQuestionTools(defineTool, deps) {
|
|
|
219
219
|
// ── 4. Stream the cards to the frontend ────────────────────────────
|
|
220
220
|
emit({
|
|
221
221
|
type: "user_question",
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
prompt: q.payload.prompt,
|
|
226
|
-
options: q.payload.options,
|
|
227
|
-
multiSelect: q.payload.multiSelect,
|
|
228
|
-
})),
|
|
222
|
+
// The event is an opaque action reference. Question text is canonical
|
|
223
|
+
// only after the recipient resolves this ID through the server.
|
|
224
|
+
questions: persisted.map((q) => ({ id: q.id })),
|
|
229
225
|
});
|
|
230
226
|
// ── 5. Block until answered / dismissed / timeout / abort ──────────
|
|
231
227
|
const heartbeat = setInterval(() => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"questioner.ask.tool.js","sourceRoot":"/","sources":["questioner/questioner.ask.tool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAG5E,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,yBAAyB,EAAE,MAAM,qBAAqB,CAAC;AAGhE,MAAM,MAAM,GAAG,cAAc,CAAC,qBAAqB,CAAC,CAAC;AAGrD,2EAA2E;AAC3E,MAAM,iBAAiB,GAAG,KAAM,CAAC;AAEjC,gFAAgF;AAChF,MAAM,qBAAqB,GAAG,EAAE,CAAC;AAEjC;;;;GAIG;AACH,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAEhC,qDAAqD;AACrD,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAElC,+EAA+E;AAC/E,IAAI,eAAe,GAA2B,IAAI,CAAC;AACnD,SAAS,kBAAkB;IACzB,IAAI,CAAC,eAAe;QAAE,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC;IAC9D,OAAO,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AAC,CAAC;QAC3F,IAAI,CAAC,QAAQ,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,EAAE,CAAC;QAClD,OAAO,QAAQ;aACZ,KAAK,CAAC,CAAC,qBAAqB,CAAC;aAC7B,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE;YACT,MAAM,IAAI,GAAG,CAAC,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC;YAC3D,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;YAC3D,OAAO,GAAG,IAAI,KAAK,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,qBAAqB,CAAC,EAAE,CAAC;QAC5D,CAAC,CAAC;aACD,IAAI,CAAC,IAAI,CAAC,CAAC;IAChB,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,CAAC,IAAI,CAAC,qCAAqC,EAAE;YACjD,KAAK,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC;SACxD,CAAC,CAAC;QACH,OAAO,EAAE,CAAC;IACZ,CAAC;AACH,CAAC","sourcesContent":["/**\n * ask_user_question — blocking mid-conversation questions for the chat\n * orchestrator (AskUserQuestion-style human-in-the-loop).\n *\n * Flow (hybrid authoring):\n * 1. The orchestrator states what it needs to learn (`purpose`) plus optional\n * draft questions.\n * 2. The QuestionerAgent (mode `chat`) refines that into polished structured\n * questions, grounded in the recent conversation excerpt and the user's\n * global context.\n * 3. Questions are persisted (`questions` table, mode `chat`,\n * `conversationId = sessionId`) via the injected {@link ChatQuestionsHost}.\n * 4. A `user_question` trace event streams the persisted questions to the\n * frontend, which renders them inline while the turn stays open.\n * 5. The tool blocks on `awaitAnswers` until the user answers/dismisses\n * through the questions REST endpoints, the wait budget elapses, or the\n * run is aborted. Answers come back as the tool result so the model\n * continues the SAME turn.\n *\n * On timeout the questions remain `pending`: they survive reloads via the\n * conversation-linked question fetch, and a later answer re-enters the chat\n * as a new user turn (frontend responsibility).\n *\n * Chat-only: not registered in the MCP tool registry. The handler also fails\n * gracefully when the session/stream context or host bridge is missing.\n */\nimport { z } from \"zod\";\n\nimport type { DefineTool, ToolDeps } from \"../shared/agent/tool.helpers.js\";\nimport { error, success } from \"../shared/agent/tool.helpers.js\";\nimport { requestContext } from \"../shared/observability/request-context.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport type { PersistableQuestion, PersistedQuestion, ChatQuestionAnswerOutcome } from \"../shared/interfaces/questioner.interface.js\";\nimport type { Question, QuestionGenerationResult, QuestionStrategy, UnderspecificationType } from \"../shared/schemas/question.schema.js\";\nimport { QuestionerAgent } from \"./questioner.agent.js\";\nimport { chatQuestionWaitTimeoutMs } from \"./questioner.env.js\";\nimport type { ChatContext } from \"./questioner.types.js\";\n\nconst logger = protocolLogger(\"AskUserQuestionTool\");\n\n\n/** Heartbeat interval while blocked, so SSE transports do not idle out. */\nconst WAIT_HEARTBEAT_MS = 15_000;\n\n/** Messages included in the conversation excerpt fed to the QuestionerAgent. */\nconst EXCERPT_MESSAGE_COUNT = 10;\n\n/**\n * Fetch window for the excerpt. Host adapters return the FIRST N messages\n * (ascending) when a limit is passed, so we fetch a wide window and keep the\n * tail to get the most recent exchange.\n */\nconst EXCERPT_FETCH_LIMIT = 100;\n\n/** Max characters per message inside the excerpt. */\nconst EXCERPT_MESSAGE_CHARS = 400;\n\n// Lazy singleton — construction binds the LLM once; invocations are stateless.\nlet questionerAgent: QuestionerAgent | null = null;\nfunction getQuestionerAgent(): QuestionerAgent {\n if (!questionerAgent) questionerAgent = new QuestionerAgent();\n return questionerAgent;\n}\n\n/** Test seam: replace or reset the module-level QuestionerAgent singleton. */\nexport function setQuestionerAgentForTesting(agent: QuestionerAgent | null): void {\n questionerAgent = agent;\n}\n\nconst draftQuestionSchema = z.object({\n prompt: z\n .string()\n .min(5)\n .max(400)\n .describe(\"The question to ask, ending in a question mark. Self-contained plain language.\"),\n options: z\n .array(z.string().min(1).max(120))\n .min(2)\n .max(4)\n .optional()\n .describe(\"2-4 mutually distinct answer options. Omit to let the question generator derive them.\"),\n multiSelect: z\n .boolean()\n .optional()\n .describe(\"True when several options can be picked together (priorities, bundles).\"),\n});\n\n/**\n * Build a fallback Question directly from an orchestrator draft when the\n * QuestionerAgent produced nothing. Requires the draft to carry options.\n */\nfunction questionFromDraft(draft: z.infer<typeof draftQuestionSchema>, index: number): Question | null {\n if (!draft.options || draft.options.length < 2) return null;\n return {\n title: `Question ${index + 1}`,\n prompt: draft.prompt.slice(0, 400),\n options: draft.options.slice(0, 4).map((label) => ({\n label: label.slice(0, 120),\n description: label.slice(0, 280),\n })),\n multiSelect: draft.multiSelect ?? false,\n };\n}\n\n/**\n * Creates the chat-only `ask_user_question` tool. Registered by\n * `createChatTools` only when `deps.chatQuestions` is provided — never part\n * of the MCP tool registry (MCP clients have their own elicitation surface).\n *\n * @param defineTool - Tool factory provided by the composition root.\n * @param deps - Shared tool dependencies; requires `chatQuestions`.\n */\nexport function createAskUserQuestionTools(defineTool: DefineTool, deps: ToolDeps) {\n const askUserQuestion = defineTool({\n name: \"ask_user_question\",\n description:\n \"Ask the user 1-3 structured clarifying questions and WAIT for their answer before continuing. \" +\n \"The conversation pauses: the user sees interactive question cards inline and your turn resumes \" +\n \"with their selections as the tool result.\\n\\n\" +\n \"**Use when** a decision materially changes what you do next — before an expensive operation \" +\n \"(discovery, creating an intent from ambiguous input), when facing meaningfully different \" +\n \"directions, or when one concrete missing detail (timing, scope, budget, format) blocks progress.\\n\\n\" +\n \"**Do not use** for facts already visible in the conversation or profile, procedural \" +\n \"confirmations (\\\"Should I proceed?\\\"), or open-ended questions better asked in your response text.\\n\\n\" +\n \"**Input:** `purpose` states what you need to learn and why. Optionally propose `questions` \" +\n \"drafts (prompt + 2-4 options); a question generator refines wording and option quality.\\n\\n\" +\n \"**Returns:** One entry per question with `status` (`answered`/`dismissed`/`timeout`) and the \" +\n \"user's `selectedOptions`/`freeText`. On `timeout` the questions stay visible in the \" +\n \"conversation — acknowledge briefly and end your turn; do NOT repeat the questions in text.\",\n querySchema: z.object({\n purpose: z\n .string()\n .min(10)\n .max(600)\n .describe(\"What you need to learn from the user and why it changes what you do next.\"),\n questions: z\n .array(draftQuestionSchema)\n .min(1)\n .max(3)\n .optional()\n .describe(\"Draft questions to ask. The question generator polishes them before display.\"),\n }),\n handler: async ({ context, query }) => {\n const host = deps.chatQuestions;\n if (!host) {\n return error(\n \"Interactive questions are not available in this environment. Ask the user directly in your response text instead.\",\n );\n }\n if (context.isMcp || !context.sessionId) {\n return error(\n \"Interactive questions require a live chat session. Ask the user directly in your response text instead.\",\n );\n }\n const store = requestContext.getStore();\n const emit = store?.traceEmitter;\n const signal = store?.abortSignal;\n if (!emit) {\n return error(\n \"Interactive questions require a streaming chat turn. Ask the user directly in your response text instead.\",\n );\n }\n\n const sessionId = context.sessionId;\n\n // ── 1. Gather grounding context ────────────────────────────────────\n const [conversationExcerpt, userContext] = await Promise.all([\n loadConversationExcerpt(deps, sessionId),\n deps.getUserContextText?.(context.userId).catch(() => \"\") ?? Promise.resolve(\"\"),\n ]);\n\n // ── 2. Generate polished questions (hybrid: drafts + QuestionerAgent) ──\n const chatContext: ChatContext = {\n purpose: query.purpose,\n ...(query.questions?.length ? { draftQuestions: query.questions } : {}),\n ...(conversationExcerpt ? { conversationExcerpt } : {}),\n ...(userContext ? { userContext } : {}),\n };\n\n let generated: QuestionGenerationResult | null = null;\n try {\n generated = await getQuestionerAgent().invoke(\n {\n mode: \"chat\",\n userId: context.userId,\n sourceType: \"conversation\",\n sourceId: sessionId,\n context: chatContext,\n conversationId: sessionId,\n },\n signal ? { signal } : undefined,\n );\n } catch (err) {\n logger.warn(\"QuestionerAgent invocation failed\", {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n\n let finalQuestions: Question[];\n let strategies: QuestionStrategy[];\n let underspecificationTypes: Array<UnderspecificationType | null>;\n if (generated && generated.questions.length > 0) {\n finalQuestions = generated.questions;\n strategies = generated.strategies;\n underspecificationTypes = generated.underspecificationTypes;\n } else {\n // Fallback: use the orchestrator's own drafts verbatim (options required).\n const fromDrafts = (query.questions ?? [])\n .map((d, i) => questionFromDraft(d, i))\n .filter((q): q is Question => q !== null);\n if (fromDrafts.length === 0) {\n return error(\n \"Could not prepare structured questions. Ask the user directly in your response text instead.\",\n );\n }\n finalQuestions = fromDrafts;\n strategies = fromDrafts.map(() => \"surface_missing_detail\" as const);\n underspecificationTypes = fromDrafts.map(() => null);\n }\n\n if (signal?.aborted) {\n return error(\"The chat turn was cancelled before the questions could be shown.\");\n }\n\n // ── 3. Persist (mode `chat`, linked to this conversation) ──────────\n const timestamp = new Date().toISOString();\n const batch: PersistableQuestion[] = finalQuestions.map((payload, i) => ({\n detection: {\n mode: \"chat\",\n sourceType: \"conversation\",\n sourceId: sessionId,\n timestamp,\n },\n actors: [{ userId: context.userId, role: \"subject\" as const }],\n payload,\n strategy: strategies[i] ?? \"surface_missing_detail\",\n underspecificationType: underspecificationTypes[i] ?? null,\n conversationId: sessionId,\n }));\n\n let persisted: PersistedQuestion[];\n try {\n persisted = await host.persist(batch);\n } catch (err) {\n logger.error(\"Failed to persist chat questions\", {\n error: err instanceof Error ? err.message : String(err),\n });\n return error(\"Could not deliver the questions to the user. Ask directly in your response text instead.\");\n }\n\n // ── 4. Stream the cards to the frontend ────────────────────────────\n emit({\n type: \"user_question\",\n questions: persisted.map((q) => ({\n id: q.id,\n title: q.payload.title,\n prompt: q.payload.prompt,\n options: q.payload.options,\n multiSelect: q.payload.multiSelect,\n })),\n });\n\n // ── 5. Block until answered / dismissed / timeout / abort ──────────\n const heartbeat = setInterval(() => {\n try {\n emit({ type: \"status\", message: \"Waiting for your answer…\" });\n } catch {\n /* stream may be closing; the wait resolves via timeout/abort */\n }\n }, WAIT_HEARTBEAT_MS);\n\n let outcomes: ChatQuestionAnswerOutcome[];\n try {\n outcomes = await host.awaitAnswers(\n persisted.map((q) => q.id),\n { timeoutMs: chatQuestionWaitTimeoutMs(), ...(signal ? { signal } : {}) },\n );\n } finally {\n clearInterval(heartbeat);\n }\n\n const byId = new Map(persisted.map((q) => [q.id, q]));\n const results = outcomes.map((o) => {\n const q = byId.get(o.questionId);\n return {\n questionId: o.questionId,\n prompt: q?.payload.prompt ?? \"\",\n status: o.status,\n ...(o.answer\n ? {\n selectedOptions: o.answer.selectedOptions,\n ...(o.answer.freeText ? { freeText: o.answer.freeText } : {}),\n }\n : {}),\n };\n });\n\n const answeredCount = results.filter((r) => r.status === \"answered\").length;\n const timedOut = results.some((r) => r.status === \"timeout\");\n\n return success({\n answers: results,\n summary: `${answeredCount} of ${results.length} question(s) answered`,\n ...(timedOut\n ? {\n guidance:\n \"The user has not answered the remaining question(s) yet. They stay visible in the conversation — acknowledge briefly, do NOT repeat the questions in text, and end your turn.\",\n }\n : {}),\n });\n },\n });\n\n return [askUserQuestion] as const;\n}\n\n/**\n * Load a compact excerpt of the most recent conversation messages for the\n * QuestionerAgent's grounding. Best-effort: returns \"\" on any failure or when\n * no chat session reader is available. Note: the in-flight user message is\n * not yet persisted; the orchestrator's `purpose` carries that context.\n */\nasync function loadConversationExcerpt(deps: ToolDeps, sessionId: string): Promise<string> {\n if (!deps.chatSession) return \"\";\n try {\n const messages = await deps.chatSession.getSessionMessages(sessionId, EXCERPT_FETCH_LIMIT);\n if (!messages || messages.length === 0) return \"\";\n return messages\n .slice(-EXCERPT_MESSAGE_COUNT)\n .map((m) => {\n const role = m.role === \"assistant\" ? \"Assistant\" : \"User\";\n const text = (m.content ?? \"\").replace(/\\s+/g, \" \").trim();\n return `${role}: ${text.slice(0, EXCERPT_MESSAGE_CHARS)}`;\n })\n .join(\"\\n\");\n } catch (err) {\n logger.warn(\"Failed to load conversation excerpt\", {\n error: err instanceof Error ? err.message : String(err),\n });\n return \"\";\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"questioner.ask.tool.js","sourceRoot":"/","sources":["questioner/questioner.ask.tool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAG5E,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,yBAAyB,EAAE,MAAM,qBAAqB,CAAC;AAGhE,MAAM,MAAM,GAAG,cAAc,CAAC,qBAAqB,CAAC,CAAC;AAGrD,2EAA2E;AAC3E,MAAM,iBAAiB,GAAG,KAAM,CAAC;AAEjC,gFAAgF;AAChF,MAAM,qBAAqB,GAAG,EAAE,CAAC;AAEjC;;;;GAIG;AACH,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAEhC,qDAAqD;AACrD,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAElC,+EAA+E;AAC/E,IAAI,eAAe,GAA2B,IAAI,CAAC;AACnD,SAAS,kBAAkB;IACzB,IAAI,CAAC,eAAe;QAAE,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC;IAC9D,OAAO,eAAe,CAAC;AACzB,CAAC;AAED,8EAA8E;AAC9E,MAAM,UAAU,4BAA4B,CAAC,KAA6B;IACxE,eAAe,GAAG,KAAK,CAAC;AAC1B,CAAC;AAED,MAAM,mBAAmB,GAAG,CAAC,CAAC,MAAM,CAAC;IACnC,MAAM,EAAE,CAAC;SACN,MAAM,EAAE;SACR,GAAG,CAAC,CAAC,CAAC;SACN,GAAG,CAAC,GAAG,CAAC;SACR,QAAQ,CAAC,gFAAgF,CAAC;I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AAI,CAAC,KAAK,CAAC,CAAC,EAAE,qBAAqB,CAAC,EAAE,CAAC;QAC5D,CAAC,CAAC;aACD,IAAI,CAAC,IAAI,CAAC,CAAC;IAChB,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,CAAC,IAAI,CAAC,qCAAqC,EAAE;YACjD,KAAK,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC;SACxD,CAAC,CAAC;QACH,OAAO,EAAE,CAAC;IACZ,CAAC;AACH,CAAC","sourcesContent":["/**\n * ask_user_question — blocking mid-conversation questions for the chat\n * orchestrator (AskUserQuestion-style human-in-the-loop).\n *\n * Flow (hybrid authoring):\n * 1. The orchestrator states what it needs to learn (`purpose`) plus optional\n * draft questions.\n * 2. The QuestionerAgent (mode `chat`) refines that into polished structured\n * questions, grounded in the recent conversation excerpt and the user's\n * global context.\n * 3. Questions are persisted (`questions` table, mode `chat`,\n * `conversationId = sessionId`) via the injected {@link ChatQuestionsHost}.\n * 4. A `user_question` trace event streams the persisted questions to the\n * frontend, which renders them inline while the turn stays open.\n * 5. The tool blocks on `awaitAnswers` until the user answers/dismisses\n * through the questions REST endpoints, the wait budget elapses, or the\n * run is aborted. Answers come back as the tool result so the model\n * continues the SAME turn.\n *\n * On timeout the questions remain `pending`: they survive reloads via the\n * conversation-linked question fetch, and a later answer re-enters the chat\n * as a new user turn (frontend responsibility).\n *\n * Chat-only: not registered in the MCP tool registry. The handler also fails\n * gracefully when the session/stream context or host bridge is missing.\n */\nimport { z } from \"zod\";\n\nimport type { DefineTool, ToolDeps } from \"../shared/agent/tool.helpers.js\";\nimport { error, success } from \"../shared/agent/tool.helpers.js\";\nimport { requestContext } from \"../shared/observability/request-context.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport type { PersistableQuestion, PersistedQuestion, ChatQuestionAnswerOutcome } from \"../shared/interfaces/questioner.interface.js\";\nimport type { Question, QuestionGenerationResult, QuestionStrategy, UnderspecificationType } from \"../shared/schemas/question.schema.js\";\nimport { QuestionerAgent } from \"./questioner.agent.js\";\nimport { chatQuestionWaitTimeoutMs } from \"./questioner.env.js\";\nimport type { ChatContext } from \"./questioner.types.js\";\n\nconst logger = protocolLogger(\"AskUserQuestionTool\");\n\n\n/** Heartbeat interval while blocked, so SSE transports do not idle out. */\nconst WAIT_HEARTBEAT_MS = 15_000;\n\n/** Messages included in the conversation excerpt fed to the QuestionerAgent. */\nconst EXCERPT_MESSAGE_COUNT = 10;\n\n/**\n * Fetch window for the excerpt. Host adapters return the FIRST N messages\n * (ascending) when a limit is passed, so we fetch a wide window and keep the\n * tail to get the most recent exchange.\n */\nconst EXCERPT_FETCH_LIMIT = 100;\n\n/** Max characters per message inside the excerpt. */\nconst EXCERPT_MESSAGE_CHARS = 400;\n\n// Lazy singleton — construction binds the LLM once; invocations are stateless.\nlet questionerAgent: QuestionerAgent | null = null;\nfunction getQuestionerAgent(): QuestionerAgent {\n if (!questionerAgent) questionerAgent = new QuestionerAgent();\n return questionerAgent;\n}\n\n/** Test seam: replace or reset the module-level QuestionerAgent singleton. */\nexport function setQuestionerAgentForTesting(agent: QuestionerAgent | null): void {\n questionerAgent = agent;\n}\n\nconst draftQuestionSchema = z.object({\n prompt: z\n .string()\n .min(5)\n .max(400)\n .describe(\"The question to ask, ending in a question mark. Self-contained plain language.\"),\n options: z\n .array(z.string().min(1).max(120))\n .min(2)\n .max(4)\n .optional()\n .describe(\"2-4 mutually distinct answer options. Omit to let the question generator derive them.\"),\n multiSelect: z\n .boolean()\n .optional()\n .describe(\"True when several options can be picked together (priorities, bundles).\"),\n});\n\n/**\n * Build a fallback Question directly from an orchestrator draft when the\n * QuestionerAgent produced nothing. Requires the draft to carry options.\n */\nfunction questionFromDraft(draft: z.infer<typeof draftQuestionSchema>, index: number): Question | null {\n if (!draft.options || draft.options.length < 2) return null;\n return {\n title: `Question ${index + 1}`,\n prompt: draft.prompt.slice(0, 400),\n options: draft.options.slice(0, 4).map((label) => ({\n label: label.slice(0, 120),\n description: label.slice(0, 280),\n })),\n multiSelect: draft.multiSelect ?? false,\n };\n}\n\n/**\n * Creates the chat-only `ask_user_question` tool. Registered by\n * `createChatTools` only when `deps.chatQuestions` is provided — never part\n * of the MCP tool registry (MCP clients have their own elicitation surface).\n *\n * @param defineTool - Tool factory provided by the composition root.\n * @param deps - Shared tool dependencies; requires `chatQuestions`.\n */\nexport function createAskUserQuestionTools(defineTool: DefineTool, deps: ToolDeps) {\n const askUserQuestion = defineTool({\n name: \"ask_user_question\",\n description:\n \"Ask the user 1-3 structured clarifying questions and WAIT for their answer before continuing. \" +\n \"The conversation pauses: the user sees interactive question cards inline and your turn resumes \" +\n \"with their selections as the tool result.\\n\\n\" +\n \"**Use when** a decision materially changes what you do next — before an expensive operation \" +\n \"(discovery, creating an intent from ambiguous input), when facing meaningfully different \" +\n \"directions, or when one concrete missing detail (timing, scope, budget, format) blocks progress.\\n\\n\" +\n \"**Do not use** for facts already visible in the conversation or profile, procedural \" +\n \"confirmations (\\\"Should I proceed?\\\"), or open-ended questions better asked in your response text.\\n\\n\" +\n \"**Input:** `purpose` states what you need to learn and why. Optionally propose `questions` \" +\n \"drafts (prompt + 2-4 options); a question generator refines wording and option quality.\\n\\n\" +\n \"**Returns:** One entry per question with `status` (`answered`/`dismissed`/`timeout`) and the \" +\n \"user's `selectedOptions`/`freeText`. On `timeout` the questions stay visible in the \" +\n \"conversation — acknowledge briefly and end your turn; do NOT repeat the questions in text.\",\n querySchema: z.object({\n purpose: z\n .string()\n .min(10)\n .max(600)\n .describe(\"What you need to learn from the user and why it changes what you do next.\"),\n questions: z\n .array(draftQuestionSchema)\n .min(1)\n .max(3)\n .optional()\n .describe(\"Draft questions to ask. The question generator polishes them before display.\"),\n }),\n handler: async ({ context, query }) => {\n const host = deps.chatQuestions;\n if (!host) {\n return error(\n \"Interactive questions are not available in this environment. Ask the user directly in your response text instead.\",\n );\n }\n if (context.isMcp || !context.sessionId) {\n return error(\n \"Interactive questions require a live chat session. Ask the user directly in your response text instead.\",\n );\n }\n const store = requestContext.getStore();\n const emit = store?.traceEmitter;\n const signal = store?.abortSignal;\n if (!emit) {\n return error(\n \"Interactive questions require a streaming chat turn. Ask the user directly in your response text instead.\",\n );\n }\n\n const sessionId = context.sessionId;\n\n // ── 1. Gather grounding context ────────────────────────────────────\n const [conversationExcerpt, userContext] = await Promise.all([\n loadConversationExcerpt(deps, sessionId),\n deps.getUserContextText?.(context.userId).catch(() => \"\") ?? Promise.resolve(\"\"),\n ]);\n\n // ── 2. Generate polished questions (hybrid: drafts + QuestionerAgent) ──\n const chatContext: ChatContext = {\n purpose: query.purpose,\n ...(query.questions?.length ? { draftQuestions: query.questions } : {}),\n ...(conversationExcerpt ? { conversationExcerpt } : {}),\n ...(userContext ? { userContext } : {}),\n };\n\n let generated: QuestionGenerationResult | null = null;\n try {\n generated = await getQuestionerAgent().invoke(\n {\n mode: \"chat\",\n userId: context.userId,\n sourceType: \"conversation\",\n sourceId: sessionId,\n context: chatContext,\n conversationId: sessionId,\n },\n signal ? { signal } : undefined,\n );\n } catch (err) {\n logger.warn(\"QuestionerAgent invocation failed\", {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n\n let finalQuestions: Question[];\n let strategies: QuestionStrategy[];\n let underspecificationTypes: Array<UnderspecificationType | null>;\n if (generated && generated.questions.length > 0) {\n finalQuestions = generated.questions;\n strategies = generated.strategies;\n underspecificationTypes = generated.underspecificationTypes;\n } else {\n // Fallback: use the orchestrator's own drafts verbatim (options required).\n const fromDrafts = (query.questions ?? [])\n .map((d, i) => questionFromDraft(d, i))\n .filter((q): q is Question => q !== null);\n if (fromDrafts.length === 0) {\n return error(\n \"Could not prepare structured questions. Ask the user directly in your response text instead.\",\n );\n }\n finalQuestions = fromDrafts;\n strategies = fromDrafts.map(() => \"surface_missing_detail\" as const);\n underspecificationTypes = fromDrafts.map(() => null);\n }\n\n if (signal?.aborted) {\n return error(\"The chat turn was cancelled before the questions could be shown.\");\n }\n\n // ── 3. Persist (mode `chat`, linked to this conversation) ──────────\n const timestamp = new Date().toISOString();\n const batch: PersistableQuestion[] = finalQuestions.map((payload, i) => ({\n detection: {\n mode: \"chat\",\n sourceType: \"conversation\",\n sourceId: sessionId,\n timestamp,\n },\n actors: [{ userId: context.userId, role: \"subject\" as const }],\n payload,\n strategy: strategies[i] ?? \"surface_missing_detail\",\n underspecificationType: underspecificationTypes[i] ?? null,\n conversationId: sessionId,\n }));\n\n let persisted: PersistedQuestion[];\n try {\n persisted = await host.persist(batch);\n } catch (err) {\n logger.error(\"Failed to persist chat questions\", {\n error: err instanceof Error ? err.message : String(err),\n });\n return error(\"Could not deliver the questions to the user. Ask directly in your response text instead.\");\n }\n\n // ── 4. Stream the cards to the frontend ────────────────────────────\n emit({\n type: \"user_question\",\n // The event is an opaque action reference. Question text is canonical\n // only after the recipient resolves this ID through the server.\n questions: persisted.map((q) => ({ id: q.id })),\n });\n\n // ── 5. Block until answered / dismissed / timeout / abort ──────────\n const heartbeat = setInterval(() => {\n try {\n emit({ type: \"status\", message: \"Waiting for your answer…\" });\n } catch {\n /* stream may be closing; the wait resolves via timeout/abort */\n }\n }, WAIT_HEARTBEAT_MS);\n\n let outcomes: ChatQuestionAnswerOutcome[];\n try {\n outcomes = await host.awaitAnswers(\n persisted.map((q) => q.id),\n { timeoutMs: chatQuestionWaitTimeoutMs(), ...(signal ? { signal } : {}) },\n );\n } finally {\n clearInterval(heartbeat);\n }\n\n const byId = new Map(persisted.map((q) => [q.id, q]));\n const results = outcomes.map((o) => {\n const q = byId.get(o.questionId);\n return {\n questionId: o.questionId,\n prompt: q?.payload.prompt ?? \"\",\n status: o.status,\n ...(o.answer\n ? {\n selectedOptions: o.answer.selectedOptions,\n ...(o.answer.freeText ? { freeText: o.answer.freeText } : {}),\n }\n : {}),\n };\n });\n\n const answeredCount = results.filter((r) => r.status === \"answered\").length;\n const timedOut = results.some((r) => r.status === \"timeout\");\n\n return success({\n answers: results,\n summary: `${answeredCount} of ${results.length} question(s) answered`,\n ...(timedOut\n ? {\n guidance:\n \"The user has not answered the remaining question(s) yet. They stay visible in the conversation — acknowledge briefly, do NOT repeat the questions in text, and end your turn.\",\n }\n : {}),\n });\n },\n });\n\n return [askUserQuestion] as const;\n}\n\n/**\n * Load a compact excerpt of the most recent conversation messages for the\n * QuestionerAgent's grounding. Best-effort: returns \"\" on any failure or when\n * no chat session reader is available. Note: the in-flight user message is\n * not yet persisted; the orchestrator's `purpose` carries that context.\n */\nasync function loadConversationExcerpt(deps: ToolDeps, sessionId: string): Promise<string> {\n if (!deps.chatSession) return \"\";\n try {\n const messages = await deps.chatSession.getSessionMessages(sessionId, EXCERPT_FETCH_LIMIT);\n if (!messages || messages.length === 0) return \"\";\n return messages\n .slice(-EXCERPT_MESSAGE_COUNT)\n .map((m) => {\n const role = m.role === \"assistant\" ? \"Assistant\" : \"User\";\n const text = (m.content ?? \"\").replace(/\\s+/g, \" \").trim();\n return `${role}: ${text.slice(0, EXCERPT_MESSAGE_CHARS)}`;\n })\n .join(\"\\n\");\n } catch (err) {\n logger.warn(\"Failed to load conversation excerpt\", {\n error: err instanceof Error ? err.message : String(err),\n });\n return \"\";\n }\n}\n"]}
|
|
@@ -23,13 +23,6 @@ export type TraceEmitter = (event: {
|
|
|
23
23
|
type: "user_question";
|
|
24
24
|
questions: Array<{
|
|
25
25
|
id: string;
|
|
26
|
-
title: string;
|
|
27
|
-
prompt: string;
|
|
28
|
-
options: Array<{
|
|
29
|
-
label: string;
|
|
30
|
-
description: string;
|
|
31
|
-
}>;
|
|
32
|
-
multiSelect: boolean;
|
|
33
26
|
}>;
|
|
34
27
|
} | {
|
|
35
28
|
type: "status";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request-context.d.ts","sourceRoot":"/","sources":["shared/observability/request-context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qCAAqC,CAAC;AACvE,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAEhD;;;;;;;;;;;;;GAaG;AACH,MAAM,MAAM,YAAY,GAAG,CACzB,KAAK,EACD;IACE,IAAI,EAAE,aAAa,GAAG,WAAW,GAAG,aAAa,GAAG,WAAW,CAAC;IAChE,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB,GACD;IAKE,IAAI,EAAE,eAAe,CAAC;IACtB,SAAS,EAAE,KAAK,CAAC;
|
|
1
|
+
{"version":3,"file":"request-context.d.ts","sourceRoot":"/","sources":["shared/observability/request-context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qCAAqC,CAAC;AACvE,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAEhD;;;;;;;;;;;;;GAaG;AACH,MAAM,MAAM,YAAY,GAAG,CACzB,KAAK,EACD;IACE,IAAI,EAAE,aAAa,GAAG,WAAW,GAAG,aAAa,GAAG,WAAW,CAAC;IAChE,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB,GACD;IAKE,IAAI,EAAE,eAAe,CAAC;IACtB,SAAS,EAAE,KAAK,CAAC;QAAE,EAAE,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CAClC,GACD;IAGE,IAAI,EAAE,QAAQ,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;CACjB,GACD;IACE,IAAI,EAAE,yBAAyB,CAAC;IAChC,aAAa,EAAE,MAAM,CAAC;IACtB,WAAW,EAAE,WAAW,CAAC;IACzB,oEAAoE;IACpE,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B;;;;;;OAMG;IACH,YAAY,EAAE;QACZ,MAAM,EAAE,MAAM,CAAC;QACf,IAAI,CAAC,EAAE,MAAM,CAAC;KACf,CAAC;CACH,KACF,IAAI,CAAC;AAEV,UAAU,cAAc;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,YAAY,CAAC,EAAE,YAAY,CAAC;IAC5B;;;;;;;;;OASG;IACH,WAAW,CAAC,EAAE,WAAW,CAAC;CAC3B;AAED;;;GAGG;AACH,eAAO,MAAM,cAAc,mCAA0C,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request-context.js","sourceRoot":"/","sources":["shared/observability/request-context.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"request-context.js","sourceRoot":"/","sources":["shared/observability/request-context.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AA0EhD;;;GAGG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,IAAI,iBAAiB,EAAkB,CAAC","sourcesContent":["import type { Opportunity } from \"../interfaces/database.interface.js\";\nimport { AsyncLocalStorage } from \"async_hooks\";\n\n/**\n * Callback for streaming trace / domain events from deep inside graph nodes\n * back to the caller (typically chat.agent's stream pipeline).\n *\n * Carries two flavors of event:\n * - Trace events (`graph_start | graph_end | agent_start | agent_end`) — used\n * by the chat TRACE panel to visualize what the agent is doing.\n * - Domain events (`opportunity_draft_ready`) — emitted by the orchestrator\n * branch of OpportunityGraph.negotiateNode so the frontend can render each\n * accepted draft card progressively as its negotiation resolves.\n *\n * Kept as a single emitter rather than splitting into two to minimize plumbing\n * through AsyncLocalStorage; the chat.agent relay branches on event.type.\n */\nexport type TraceEmitter = (\n event:\n | {\n type: \"graph_start\" | \"graph_end\" | \"agent_start\" | \"agent_end\";\n name: string;\n durationMs?: number;\n summary?: string;\n }\n | {\n // Emitted by the ask_user_question tool: structured questions were\n // persisted and the turn is now blocked awaiting the user's answer.\n // Carries persisted question ids so the frontend can answer them\n // through the questions REST endpoints while the stream is live.\n type: \"user_question\";\n questions: Array<{ id: string }>;\n }\n | {\n // Lightweight keep-alive/status line. Used by long-blocking tools\n // (ask_user_question wait loop) so SSE transports do not idle out.\n type: \"status\";\n message: string;\n }\n | {\n type: \"opportunity_draft_ready\";\n opportunityId: string;\n opportunity: Opportunity;\n /** Viewer-centric summary derived from interpretation.reasoning. */\n personalizedSummary?: string;\n /**\n * Minimal counterparty data for rendering the inline card without a\n * second-round-trip user lookup. Populated from the negotiation\n * candidate's profile; avatar is intentionally omitted (the card\n * falls back to initials) since UserNegotiationContext doesn't\n * carry avatars.\n */\n counterparty: {\n userId: string;\n name?: string;\n };\n },\n) => void;\n\ninterface RequestContext {\n originUrl?: string;\n traceEmitter?: TraceEmitter;\n /**\n * Signal for cooperative cancellation — propagates the caller's AbortSignal\n * into long-running graph nodes (e.g. orchestrator negotiation fan-out) so\n * they can stop emitting events when the chat session closes.\n *\n * The orchestrator branch checks this before persisting status flips or\n * pushing `opportunity_draft_ready` events. In-flight negotiations are not\n * forcibly cancelled — they finish or time out naturally via their park\n * window — but their results are suppressed once the signal trips.\n */\n abortSignal?: AbortSignal;\n}\n\n/**\n * AsyncLocalStorage for propagating request-scoped context through the protocol layer.\n * The host application is responsible for calling `requestContext.run()` to set the context.\n */\nexport const requestContext = new AsyncLocalStorage<RequestContext>();\n"]}
|