@indexnetwork/protocol 4.5.0-rc.326.1 → 4.5.0-rc.328.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.
@@ -1 +1 @@
1
- {"version":3,"file":"chat.graph.js","sourceRoot":"/","sources":["chat/chat.graph.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,GAAG,EAAqD,MAAM,sBAAsB,CAAC;AACjH,OAAO,EAAe,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACrE,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAI5C,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAG5E,OAAO,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAC3E,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAE/D,MAAM,MAAM,GAAG,cAAc,CAAC,kBAAkB,CAAC,CAAC;AAElD,SAAS,gBAAgB,CAAC,GAAY;IACpC,MAAM,MAAM,GACT,GAA2B,CAAC,MAAM,IAAK,GAA+B,CAAC,UAAU,CAAC;IACrF,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,IAAI,GAAG,IAAI,MAAM,IAAI,GAAG;QAAE,OAAO,IAAI,CAAC;IAC9E,MAAM,GAAG,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IAC7D,MAAM,KAAK,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC;IAChC,OAAO,CACL,KAAK,CAAC,QAAQ,CAAC,uBAAuB,CAAC;QACvC,yBAAyB,CAAC,IAAI,CAAC,GAAG,CAAC;QACnC,KA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ClB,CAAC;CACF","sourcesContent":["import { StateGraph, START, END, BaseCheckpointSaver, type LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { BaseMessage, HumanMessage } from \"@langchain/core/messages\";\nimport { ChatGraphState } from \"./chat.state.js\";\nimport { ChatAgent } from \"./chat.agent.js\";\nimport type { ChatGraphCompositeDatabase } from \"../shared/interfaces/database.interface.js\";\nimport type { Embedder } from \"../shared/interfaces/embedder.interface.js\";\nimport type { Scraper } from \"../shared/interfaces/scraper.interface.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport type { ChatSessionReader } from \"../shared/interfaces/chat-session.interface.js\";\nimport type { ProtocolDeps } from \"../shared/agent/tool.helpers.js\";\nimport { truncateToTokenLimit, MAX_CONTEXT_TOKENS } from \"./chat.utils.js\";\nimport { ChatStreamer } from \"./chat.streamer.js\";\nimport { timed } from \"../shared/observability/performance.js\";\n\nconst logger = protocolLogger(\"ChatGraphFactory\");\n\nfunction isRetriableError(err: unknown): boolean {\n const status =\n (err as { status?: number }).status ?? (err as { statusCode?: number }).statusCode;\n if (typeof status === \"number\" && status >= 500 && status <= 599) return true;\n const msg = err instanceof Error ? err.message : String(err);\n const lower = msg.toLowerCase();\n return (\n lower.includes(\"internal server error\") ||\n /\\b500\\b|status[: ]*500/i.test(msg) ||\n lower.includes(\"econnreset\") ||\n lower.includes(\"etimedout\")\n );\n}\n\nconst RETRY_DELAY_MS = 800;\n\n// ══════════════════════════════════════════════════════════════════════════════\n// CHAT GRAPH FACTORY (Agent Loop Architecture)\n// ══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Factory class to build and compile the Chat Graph.\n * \n * Architecture: ReAct-Style Agent Loop\n * \n * The graph contains a single node that runs an agent loop:\n * 1. Agent receives messages (conversation + tool results)\n * 2. Agent decides: call tools OR respond to user\n * 3. If tools called → execute → add results → loop back\n * 4. If response → exit loop → stream to user\n * \n * This replaces the previous 17-node conditional routing architecture\n * with a flexible, LLM-driven approach that can handle multi-step\n * reasoning and self-correction.\n */\nexport class ChatGraphFactory {\n private streamingService: ChatStreamer;\n\n constructor(\n private database: ChatGraphCompositeDatabase,\n private embedder: Embedder,\n private scraper: Scraper,\n private chatSession: ChatSessionReader,\n private protocolDeps: ProtocolDeps,\n ) {\n this.streamingService = new ChatStreamer(\n (sessionId, maxMessages) => this.loadSessionContext(sessionId, maxMessages),\n (checkpointer) => this.createStreamingGraph(checkpointer)\n );\n }\n\n /**\n * Creates and compiles the Chat Graph without persistence.\n * @returns Compiled StateGraph ready for invocation\n */\n public createGraph() {\n return this.buildGraph().compile();\n }\n\n /**\n * Creates a streaming-enabled graph with optional checkpointer for persistence.\n * @param checkpointer - Optional checkpointer (e.g., MemorySaver or PostgresSaver)\n * @returns Compiled StateGraph ready for streaming\n */\n public createStreamingGraph(checkpointer?: BaseCheckpointSaver) {\n const graph = this.buildGraph();\n if (checkpointer) {\n return graph.compile({ checkpointer });\n }\n return graph.compile();\n }\n\n /**\n * Load previous messages from a session and convert to LangChain messages.\n * Handles token truncation to fit within context window limits.\n *\n * @param sessionId - The session ID to load context from\n * @param maxMessages - Maximum number of messages to load (default: 20)\n * @returns Array of LangChain BaseMessage objects\n */\n public async loadSessionContext(\n sessionId: string,\n maxMessages: number = 20\n ): Promise<BaseMessage[]> {\n logger.verbose(\"Loading session context\", {\n sessionId,\n maxMessages,\n });\n\n try {\n const messages = await this.chatSession.getSessionMessages(sessionId, maxMessages);\n\n if (messages.length === 0) {\n logger.verbose(\"No previous messages found\", { sessionId });\n return [];\n }\n\n // Convert database messages to LangChain format.\n // All roles map to HumanMessage to avoid circular dependency.\n const langchainMessages = messages.map((msg) => new HumanMessage(msg.content));\n\n // Truncate to fit within token limits\n const truncatedMessages = truncateToTokenLimit(langchainMessages, MAX_CONTEXT_TOKENS);\n\n logger.verbose(\"Context loaded\", {\n sessionId,\n originalCount: messages.length,\n truncatedCount: truncatedMessages.length,\n });\n return truncatedMessages;\n } catch (error) {\n logger.error(\"Failed to load context\", {\n sessionId,\n error: error instanceof Error ? error.message : String(error),\n });\n // Return empty array on error - don't fail the entire request\n return [];\n }\n }\n\n /**\n * Streams chat events with full session context.\n * Delegates to ChatGraphStreamingService.\n */\n public async *streamChatEventsWithContext(\n input: {\n userId: string;\n message: string;\n sessionId: string;\n maxContextMessages?: number;\n networkId?: string;\n prefillMessages?: Array<{ role: \"assistant\" | \"user\"; content: string }>;\n /** Per-run identifier used to form a composite LangGraph thread_id (sessionId:runId). */\n runId?: string;\n },\n checkpointer?: BaseCheckpointSaver,\n signal?: AbortSignal,\n ) {\n yield* this.streamingService.streamChatEventsWithContext(input, checkpointer, signal);\n }\n\n /**\n * Streams chat events from the graph execution.\n * Delegates to ChatGraphStreamingService.\n */\n public async *streamChatEvents(\n input: { userId: string; messages: BaseMessage[] },\n sessionId: string,\n checkpointer?: BaseCheckpointSaver,\n signal?: AbortSignal,\n ) {\n yield* this.streamingService.streamChatEvents(input, sessionId, checkpointer, signal);\n }\n\n /**\n * Internal method to build the graph structure.\n * @returns Uncompiled StateGraph\n */\n private buildGraph() {\n const database = this.database;\n const embedder = this.embedder;\n const scraper = this.scraper;\n const protocolDeps = this.protocolDeps;\n\n // ─────────────────────────────────────────────────────────────────────────\n // AGENT LOOP NODE\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * The main agent loop node.\n * Runs a ReAct-style agent that calls tools until it decides to respond.\n *\n * Uses `agent.streamRun()` + `config.writer` so that text tokens and\n * tool-activity events are pushed into the graph's custom stream in\n * real-time rather than batched at the end.\n */\n const agentLoopNode = async (\n state: typeof ChatGraphState.State,\n config: LangGraphRunnableConfig\n ) => {\n return timed(\"ChatGraph.agentLoop\", async () => {\n logger.verbose(\"Agent loop starting\", {\n userId: state.userId,\n messageCount: state.messages.length,\n currentIteration: state.iterationCount\n });\n\n const runLoop = async () => {\n const legacyNetworkId = state.networkId;\n const scopeType = state.scopeType ?? (legacyNetworkId ? 'network' as const : undefined);\n const scopeId = state.scopeId ?? legacyNetworkId;\n const agent = await ChatAgent.create({\n ...protocolDeps,\n userId: state.userId,\n database,\n embedder,\n scraper,\n ...(legacyNetworkId ? { networkId: legacyNetworkId } : {}),\n ...(scopeType && scopeId ? { scopeType, scopeId } : {}),\n sessionId: state.sessionId,\n } as import(\"../shared/agent/tool.helpers.js\").ToolContext);\n // Direct streaming writer - emit events immediately instead of buffering\n const directWriter = (data: unknown) => {\n try {\n config.writer?.(data);\n } catch {\n /* swallow if writer is gone */\n }\n };\n // Get signal from configurable (passed by streamer via graph.stream() config)\n const signal = config.configurable?.signal as AbortSignal | undefined;\n const result = await agent.streamRun(state.messages, directWriter, signal);\n return result;\n };\n\n try {\n const result = await runLoop();\n logger.debug(\"Agent streamRun result\", {\n responseText: result.responseText,\n iterationCount: result.iterationCount,\n messageCount: result.messages.length,\n });\n logger.verbose(\"Agent loop complete\", {\n userId: state.userId,\n iterations: result.iterationCount,\n responseLength: result.responseText.length\n });\n return {\n messages: result.messages,\n responseText: result.responseText,\n iterationCount: result.iterationCount,\n shouldContinue: false,\n debugMeta: result.debugMeta,\n };\n } catch (error) {\n if (isRetriableError(error)) {\n const signal = config.configurable?.signal as AbortSignal | undefined;\n if (signal?.aborted) {\n return {\n error: \"Request aborted\",\n responseText: \"\",\n shouldContinue: false,\n };\n }\n logger.warn(\"Agent loop failed with retriable error, retrying once\", {\n userId: state.userId,\n error: error instanceof Error ? error.message : String(error)\n });\n await new Promise((r) => setTimeout(r, RETRY_DELAY_MS));\n try {\n const result = await runLoop();\n logger.verbose(\"Agent loop complete after retry\", {\n userId: state.userId,\n iterations: result.iterationCount,\n });\n return {\n messages: result.messages,\n responseText: result.responseText,\n iterationCount: result.iterationCount,\n shouldContinue: false,\n debugMeta: result.debugMeta,\n };\n } catch (retryError) {\n logger.error(\"Agent loop failed on retry\", {\n userId: state.userId,\n error: retryError instanceof Error ? retryError.message : String(retryError)\n });\n return {\n error: retryError instanceof Error ? retryError.message : \"Agent loop failed\",\n responseText: \"I apologize, but I encountered an issue processing your request. Please try again.\",\n shouldContinue: false\n };\n }\n }\n\n logger.error(\"Agent loop failed\", {\n userId: state.userId,\n error: error instanceof Error ? error.message : String(error)\n });\n\n return {\n error: error instanceof Error ? error.message : \"Agent loop failed\",\n responseText: \"I apologize, but I encountered an issue processing your request. Please try again.\",\n shouldContinue: false\n };\n }\n });\n };\n\n // ─────────────────────────────────────────────────────────────────────────\n // GRAPH ASSEMBLY\n // ─────────────────────────────────────────────────────────────────────────\n\n const workflow = new StateGraph(ChatGraphState)\n .addNode(\"agent_loop\", agentLoopNode)\n .addEdge(START, \"agent_loop\")\n .addEdge(\"agent_loop\", END);\n\n logger.verbose(\"Graph built successfully (agent loop architecture)\");\n return workflow;\n }\n}\n"]}
1
+ {"version":3,"file":"chat.graph.js","sourceRoot":"/","sources":["chat/chat.graph.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,GAAG,EAAqD,MAAM,sBAAsB,CAAC;AACjH,OAAO,EAAe,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACrE,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,oBAAoB,EAA0B,MAAM,mBAAmB,CAAC;AAIjF,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAG5E,OAAO,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAC3E,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAE/D,MAAM,MAAM,GAAG,cAAc,CAAC,kBAAkB,CAAC,CAAC;AAElD,SAAS,gBAAgB,CAAC,GAAY;IACpC,MAAM,MAAM,GACT,GAA2B,CAAC,MAAM,IAAK,GAA+B,CAAC,UAAU,CAAC;IACrF,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,I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AE,KAAK,CAAC,MAAM;wBACpB,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;qBAC9D,CAAC,CAAC;oBAEH,OAAO;wBACL,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,mBAAmB;wBACnE,YAAY,EAAE,oFAAoF;wBAClG,cAAc,EAAE,KAAK;qBACtB,CAAC;gBACJ,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC,CAAC;QAEF,4EAA4E;QAC5E,iBAAiB;QACjB,4EAA4E;QAE5E,MAAM,QAAQ,GAAG,IAAI,UAAU,CAAC,cAAc,CAAC;aAC5C,OAAO,CAAC,YAAY,EAAE,aAAa,CAAC;aACpC,OAAO,CAAC,KAAK,EAAE,YAAY,CAAC;aAC5B,OAAO,CAAC,YAAY,EAAE,GAAG,CAAC,CAAC;QAE9B,MAAM,CAAC,OAAO,CAAC,oDAAoD,CAAC,CAAC;QACrE,OAAO,QAAQ,CAAC;IAClB,CAAC;CACF","sourcesContent":["import { StateGraph, START, END, BaseCheckpointSaver, type LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { BaseMessage, HumanMessage } from \"@langchain/core/messages\";\nimport { ChatGraphState } from \"./chat.state.js\";\nimport { ChatAgent } from \"./chat.agent.js\";\nimport { ORCHESTRATOR_PERSONA, type ChatPersonaConfig } from \"./chat.persona.js\";\nimport type { ChatGraphCompositeDatabase } from \"../shared/interfaces/database.interface.js\";\nimport type { Embedder } from \"../shared/interfaces/embedder.interface.js\";\nimport type { Scraper } from \"../shared/interfaces/scraper.interface.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport type { ChatSessionReader } from \"../shared/interfaces/chat-session.interface.js\";\nimport type { ProtocolDeps } from \"../shared/agent/tool.helpers.js\";\nimport { truncateToTokenLimit, MAX_CONTEXT_TOKENS } from \"./chat.utils.js\";\nimport { ChatStreamer } from \"./chat.streamer.js\";\nimport { timed } from \"../shared/observability/performance.js\";\n\nconst logger = protocolLogger(\"ChatGraphFactory\");\n\nfunction isRetriableError(err: unknown): boolean {\n const status =\n (err as { status?: number }).status ?? (err as { statusCode?: number }).statusCode;\n if (typeof status === \"number\" && status >= 500 && status <= 599) return true;\n const msg = err instanceof Error ? err.message : String(err);\n const lower = msg.toLowerCase();\n return (\n lower.includes(\"internal server error\") ||\n /\\b500\\b|status[: ]*500/i.test(msg) ||\n lower.includes(\"econnreset\") ||\n lower.includes(\"etimedout\")\n );\n}\n\nconst RETRY_DELAY_MS = 800;\n\n// ══════════════════════════════════════════════════════════════════════════════\n// CHAT GRAPH FACTORY (Agent Loop Architecture)\n// ══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Factory class to build and compile the Chat Graph.\n * \n * Architecture: ReAct-Style Agent Loop\n * \n * The graph contains a single node that runs an agent loop:\n * 1. Agent receives messages (conversation + tool results)\n * 2. Agent decides: call tools OR respond to user\n * 3. If tools called → execute → add results → loop back\n * 4. If response → exit loop → stream to user\n * \n * This replaces the previous 17-node conditional routing architecture\n * with a flexible, LLM-driven approach that can handle multi-step\n * reasoning and self-correction.\n */\nexport class ChatGraphFactory {\n private streamingService: ChatStreamer;\n\n constructor(\n private database: ChatGraphCompositeDatabase,\n private embedder: Embedder,\n private scraper: Scraper,\n private chatSession: ChatSessionReader,\n private protocolDeps: ProtocolDeps,\n /** Persona driving this graph's agent loop. Defaults to the orchestrator. */\n private persona: ChatPersonaConfig = ORCHESTRATOR_PERSONA,\n ) {\n this.streamingService = new ChatStreamer(\n (sessionId, maxMessages) => this.loadSessionContext(sessionId, maxMessages),\n (checkpointer) => this.createStreamingGraph(checkpointer)\n );\n }\n\n /**\n * Returns a sibling factory sharing all dependencies but driven by a\n * different persona. Used to derive per-session persona factories (e.g. the\n * negotiator, whose identity comes from the user's personal agent row) from\n * the composition-root orchestrator factory without re-wiring deps.\n *\n * @param persona - The persona config for the derived factory\n * @returns A new ChatGraphFactory with identical deps and the given persona\n */\n public withPersona(persona: ChatPersonaConfig): ChatGraphFactory {\n return new ChatGraphFactory(\n this.database,\n this.embedder,\n this.scraper,\n this.chatSession,\n this.protocolDeps,\n persona,\n );\n }\n\n /**\n * Creates and compiles the Chat Graph without persistence.\n * @returns Compiled StateGraph ready for invocation\n */\n public createGraph() {\n return this.buildGraph().compile();\n }\n\n /**\n * Creates a streaming-enabled graph with optional checkpointer for persistence.\n * @param checkpointer - Optional checkpointer (e.g., MemorySaver or PostgresSaver)\n * @returns Compiled StateGraph ready for streaming\n */\n public createStreamingGraph(checkpointer?: BaseCheckpointSaver) {\n const graph = this.buildGraph();\n if (checkpointer) {\n return graph.compile({ checkpointer });\n }\n return graph.compile();\n }\n\n /**\n * Load previous messages from a session and convert to LangChain messages.\n * Handles token truncation to fit within context window limits.\n *\n * @param sessionId - The session ID to load context from\n * @param maxMessages - Maximum number of messages to load (default: 20)\n * @returns Array of LangChain BaseMessage objects\n */\n public async loadSessionContext(\n sessionId: string,\n maxMessages: number = 20\n ): Promise<BaseMessage[]> {\n logger.verbose(\"Loading session context\", {\n sessionId,\n maxMessages,\n });\n\n try {\n const messages = await this.chatSession.getSessionMessages(sessionId, maxMessages);\n\n if (messages.length === 0) {\n logger.verbose(\"No previous messages found\", { sessionId });\n return [];\n }\n\n // Convert database messages to LangChain format.\n // All roles map to HumanMessage to avoid circular dependency.\n const langchainMessages = messages.map((msg) => new HumanMessage(msg.content));\n\n // Truncate to fit within token limits\n const truncatedMessages = truncateToTokenLimit(langchainMessages, MAX_CONTEXT_TOKENS);\n\n logger.verbose(\"Context loaded\", {\n sessionId,\n originalCount: messages.length,\n truncatedCount: truncatedMessages.length,\n });\n return truncatedMessages;\n } catch (error) {\n logger.error(\"Failed to load context\", {\n sessionId,\n error: error instanceof Error ? error.message : String(error),\n });\n // Return empty array on error - don't fail the entire request\n return [];\n }\n }\n\n /**\n * Streams chat events with full session context.\n * Delegates to ChatGraphStreamingService.\n */\n public async *streamChatEventsWithContext(\n input: {\n userId: string;\n message: string;\n sessionId: string;\n maxContextMessages?: number;\n networkId?: string;\n prefillMessages?: Array<{ role: \"assistant\" | \"user\"; content: string }>;\n /** Per-run identifier used to form a composite LangGraph thread_id (sessionId:runId). */\n runId?: string;\n },\n checkpointer?: BaseCheckpointSaver,\n signal?: AbortSignal,\n ) {\n yield* this.streamingService.streamChatEventsWithContext(input, checkpointer, signal);\n }\n\n /**\n * Streams chat events from the graph execution.\n * Delegates to ChatGraphStreamingService.\n */\n public async *streamChatEvents(\n input: { userId: string; messages: BaseMessage[] },\n sessionId: string,\n checkpointer?: BaseCheckpointSaver,\n signal?: AbortSignal,\n ) {\n yield* this.streamingService.streamChatEvents(input, sessionId, checkpointer, signal);\n }\n\n /**\n * Internal method to build the graph structure.\n * @returns Uncompiled StateGraph\n */\n private buildGraph() {\n const database = this.database;\n const embedder = this.embedder;\n const scraper = this.scraper;\n const protocolDeps = this.protocolDeps;\n const persona = this.persona;\n\n // ─────────────────────────────────────────────────────────────────────────\n // AGENT LOOP NODE\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * The main agent loop node.\n * Runs a ReAct-style agent that calls tools until it decides to respond.\n *\n * Uses `agent.streamRun()` + `config.writer` so that text tokens and\n * tool-activity events are pushed into the graph's custom stream in\n * real-time rather than batched at the end.\n */\n const agentLoopNode = async (\n state: typeof ChatGraphState.State,\n config: LangGraphRunnableConfig\n ) => {\n return timed(\"ChatGraph.agentLoop\", async () => {\n logger.verbose(\"Agent loop starting\", {\n userId: state.userId,\n messageCount: state.messages.length,\n currentIteration: state.iterationCount\n });\n\n const runLoop = async () => {\n const legacyNetworkId = state.networkId;\n const scopeType = state.scopeType ?? (legacyNetworkId ? 'network' as const : undefined);\n const scopeId = state.scopeId ?? legacyNetworkId;\n const agent = await ChatAgent.create({\n ...protocolDeps,\n userId: state.userId,\n database,\n embedder,\n scraper,\n ...(legacyNetworkId ? { networkId: legacyNetworkId } : {}),\n ...(scopeType && scopeId ? { scopeType, scopeId } : {}),\n sessionId: state.sessionId,\n } as import(\"../shared/agent/tool.helpers.js\").ToolContext, persona);\n // Direct streaming writer - emit events immediately instead of buffering\n const directWriter = (data: unknown) => {\n try {\n config.writer?.(data);\n } catch {\n /* swallow if writer is gone */\n }\n };\n // Get signal from configurable (passed by streamer via graph.stream() config)\n const signal = config.configurable?.signal as AbortSignal | undefined;\n const result = await agent.streamRun(state.messages, directWriter, signal);\n return result;\n };\n\n try {\n const result = await runLoop();\n logger.debug(\"Agent streamRun result\", {\n responseText: result.responseText,\n iterationCount: result.iterationCount,\n messageCount: result.messages.length,\n });\n logger.verbose(\"Agent loop complete\", {\n userId: state.userId,\n iterations: result.iterationCount,\n responseLength: result.responseText.length\n });\n return {\n messages: result.messages,\n responseText: result.responseText,\n iterationCount: result.iterationCount,\n shouldContinue: false,\n debugMeta: result.debugMeta,\n };\n } catch (error) {\n if (isRetriableError(error)) {\n const signal = config.configurable?.signal as AbortSignal | undefined;\n if (signal?.aborted) {\n return {\n error: \"Request aborted\",\n responseText: \"\",\n shouldContinue: false,\n };\n }\n logger.warn(\"Agent loop failed with retriable error, retrying once\", {\n userId: state.userId,\n error: error instanceof Error ? error.message : String(error)\n });\n await new Promise((r) => setTimeout(r, RETRY_DELAY_MS));\n try {\n const result = await runLoop();\n logger.verbose(\"Agent loop complete after retry\", {\n userId: state.userId,\n iterations: result.iterationCount,\n });\n return {\n messages: result.messages,\n responseText: result.responseText,\n iterationCount: result.iterationCount,\n shouldContinue: false,\n debugMeta: result.debugMeta,\n };\n } catch (retryError) {\n logger.error(\"Agent loop failed on retry\", {\n userId: state.userId,\n error: retryError instanceof Error ? retryError.message : String(retryError)\n });\n return {\n error: retryError instanceof Error ? retryError.message : \"Agent loop failed\",\n responseText: \"I apologize, but I encountered an issue processing your request. Please try again.\",\n shouldContinue: false\n };\n }\n }\n\n logger.error(\"Agent loop failed\", {\n userId: state.userId,\n error: error instanceof Error ? error.message : String(error)\n });\n\n return {\n error: error instanceof Error ? error.message : \"Agent loop failed\",\n responseText: \"I apologize, but I encountered an issue processing your request. Please try again.\",\n shouldContinue: false\n };\n }\n });\n };\n\n // ─────────────────────────────────────────────────────────────────────────\n // GRAPH ASSEMBLY\n // ─────────────────────────────────────────────────────────────────────────\n\n const workflow = new StateGraph(ChatGraphState)\n .addNode(\"agent_loop\", agentLoopNode)\n .addEdge(START, \"agent_loop\")\n .addEdge(\"agent_loop\", END);\n\n logger.verbose(\"Graph built successfully (agent loop architecture)\");\n return workflow;\n }\n}\n"]}
@@ -0,0 +1,56 @@
1
+ import { type ChatTools, type ToolContext, type ResolvedToolContext } from "../shared/agent/tool.factory.js";
2
+ import type { IterationContext } from "./chat.prompt.modules.js";
3
+ /**
4
+ * Orchestrator-specific behaviors that live in the agent loop itself
5
+ * (not in the prompt or toolset). Each persona opts in explicitly.
6
+ */
7
+ export interface ChatPersonaLoopBehaviors {
8
+ /**
9
+ * When `discover_opportunities` returns `createIntentSuggested`, auto-invoke
10
+ * `create_intent` and then re-run `discover_opportunities` with the original
11
+ * arguments.
12
+ */
13
+ createIntentCallback: boolean;
14
+ /**
15
+ * Detect hallucinated ```opportunity / ```intent_proposal code blocks in model
16
+ * text, auto-invoke the corresponding tool, and strip unbacked blocks from the
17
+ * final response. Only meaningful for personas whose toolset can legitimately
18
+ * produce those blocks.
19
+ */
20
+ hallucinationRecovery: boolean;
21
+ }
22
+ /**
23
+ * Persona configuration injected into `ChatAgent.create()`.
24
+ *
25
+ * A persona bundles the three orchestrator-coupled seams of the chat runtime:
26
+ * system-prompt construction, toolset creation, and loop behaviors.
27
+ */
28
+ export interface ChatPersonaConfig {
29
+ /**
30
+ * Stable persona identifier. Matches the `conversations.persona` column value
31
+ * for sessions driven by this persona.
32
+ */
33
+ id: string;
34
+ /** Builds the system prompt for each agent-loop iteration. */
35
+ buildSystemContent: (ctx: ResolvedToolContext, iterCtx: IterationContext) => string;
36
+ /** Creates the persona's toolset bound to the resolved user context. */
37
+ createTools: (deps: ToolContext, preResolvedContext?: ResolvedToolContext) => Promise<ChatTools>;
38
+ /** Orchestrator-specific loop behaviors this persona opts into. */
39
+ loopBehaviors: ChatPersonaLoopBehaviors;
40
+ }
41
+ /** Persona id for the default orchestrator ("You are Index…"). */
42
+ export declare const ORCHESTRATOR_PERSONA_ID = "orchestrator";
43
+ /**
44
+ * The orchestrator persona — exactly the pre-personafication wiring:
45
+ * `buildSystemContent` from chat.prompt, `createChatTools` from tool.factory,
46
+ * and all loop behaviors enabled.
47
+ *
48
+ * Both functions delegate lazily (arrow wrappers) instead of capturing the
49
+ * imported symbols at module-load time. This preserves ESM live-binding
50
+ * semantics: the pre-refactor code read `createChatTools` through its import
51
+ * binding at call time, which is what lets test suites swap the module via
52
+ * `mock.module` — a snapshot in this object literal would pin whichever
53
+ * version was loaded first.
54
+ */
55
+ export declare const ORCHESTRATOR_PERSONA: ChatPersonaConfig;
56
+ //# sourceMappingURL=chat.persona.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chat.persona.d.ts","sourceRoot":"/","sources":["chat/chat.persona.ts"],"names":[],"mappings":"AAAA,OAAO,EAAmB,KAAK,SAAS,EAAE,KAAK,WAAW,EAAE,KAAK,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AAE9H,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAejE;;;GAGG;AACH,MAAM,WAAW,wBAAwB;IACvC;;;;OAIG;IACH,oBAAoB,EAAE,OAAO,CAAC;IAC9B;;;;;OAKG;IACH,qBAAqB,EAAE,OAAO,CAAC;CAChC;AAED;;;;;GAKG;AACH,MAAM,WAAW,iBAAiB;IAChC;;;OAGG;IACH,EAAE,EAAE,MAAM,CAAC;IACX,8DAA8D;IAC9D,kBAAkB,EAAE,CAAC,GAAG,EAAE,mBAAmB,EAAE,OAAO,EAAE,gBAAgB,KAAK,MAAM,CAAC;IACpF,wEAAwE;IACxE,WAAW,EAAE,CAAC,IAAI,EAAE,WAAW,EAAE,kBAAkB,CAAC,EAAE,mBAAmB,KAAK,OAAO,CAAC,SAAS,CAAC,CAAC;IACjG,mEAAmE;IACnE,aAAa,EAAE,wBAAwB,CAAC;CACzC;AAED,kEAAkE;AAClE,eAAO,MAAM,uBAAuB,iBAAiB,CAAC;AAEtD;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,oBAAoB,EAAE,iBAQlC,CAAC"}
@@ -0,0 +1,26 @@
1
+ import { createChatTools } from "../shared/agent/tool.factory.js";
2
+ import { buildSystemContent } from "./chat.prompt.js";
3
+ /** Persona id for the default orchestrator ("You are Index…"). */
4
+ export const ORCHESTRATOR_PERSONA_ID = "orchestrator";
5
+ /**
6
+ * The orchestrator persona — exactly the pre-personafication wiring:
7
+ * `buildSystemContent` from chat.prompt, `createChatTools` from tool.factory,
8
+ * and all loop behaviors enabled.
9
+ *
10
+ * Both functions delegate lazily (arrow wrappers) instead of capturing the
11
+ * imported symbols at module-load time. This preserves ESM live-binding
12
+ * semantics: the pre-refactor code read `createChatTools` through its import
13
+ * binding at call time, which is what lets test suites swap the module via
14
+ * `mock.module` — a snapshot in this object literal would pin whichever
15
+ * version was loaded first.
16
+ */
17
+ export const ORCHESTRATOR_PERSONA = {
18
+ id: ORCHESTRATOR_PERSONA_ID,
19
+ buildSystemContent: (ctx, iterCtx) => buildSystemContent(ctx, iterCtx),
20
+ createTools: (deps, preResolvedContext) => createChatTools(deps, preResolvedContext),
21
+ loopBehaviors: {
22
+ createIntentCallback: true,
23
+ hallucinationRecovery: true,
24
+ },
25
+ };
26
+ //# sourceMappingURL=chat.persona.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chat.persona.js","sourceRoot":"/","sources":["chat/chat.persona.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAA8D,MAAM,iCAAiC,CAAC;AAC9H,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAwDtD,kEAAkE;AAClE,MAAM,CAAC,MAAM,uBAAuB,GAAG,cAAc,CAAC;AAEtD;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAsB;IACrD,EAAE,EAAE,uBAAuB;IAC3B,kBAAkB,EAAE,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,CAAC,kBAAkB,CAAC,GAAG,EAAE,OAAO,CAAC;IACtE,WAAW,EAAE,CAAC,IAAI,EAAE,kBAAkB,EAAE,EAAE,CAAC,eAAe,CAAC,IAAI,EAAE,kBAAkB,CAAC;IACpF,aAAa,EAAE;QACb,oBAAoB,EAAE,IAAI;QAC1B,qBAAqB,EAAE,IAAI;KAC5B;CACF,CAAC","sourcesContent":["import { createChatTools, type ChatTools, type ToolContext, type ResolvedToolContext } from \"../shared/agent/tool.factory.js\";\nimport { buildSystemContent } from \"./chat.prompt.js\";\nimport type { IterationContext } from \"./chat.prompt.modules.js\";\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// CHAT PERSONA CONFIG\n// ═══════════════════════════════════════════════════════════════════════════════\n//\n// The chat runtime (ChatAgent + ChatGraphFactory) is persona-neutral infrastructure:\n// prompt, toolset, and orchestrator-specific loop behaviors are injected via a\n// ChatPersonaConfig rather than hardcoded. The orchestrator is the default (and\n// currently only) registered persona — its config is exactly the pre-refactor\n// wiring, so behavior is byte-identical for existing chat sessions.\n//\n// Future personas (e.g. the per-user negotiator, P4.1) provide their own prompt\n// builder and toolset, and default all orchestrator loop behaviors OFF.\n\n/**\n * Orchestrator-specific behaviors that live in the agent loop itself\n * (not in the prompt or toolset). Each persona opts in explicitly.\n */\nexport interface ChatPersonaLoopBehaviors {\n /**\n * When `discover_opportunities` returns `createIntentSuggested`, auto-invoke\n * `create_intent` and then re-run `discover_opportunities` with the original\n * arguments.\n */\n createIntentCallback: boolean;\n /**\n * Detect hallucinated ```opportunity / ```intent_proposal code blocks in model\n * text, auto-invoke the corresponding tool, and strip unbacked blocks from the\n * final response. Only meaningful for personas whose toolset can legitimately\n * produce those blocks.\n */\n hallucinationRecovery: boolean;\n}\n\n/**\n * Persona configuration injected into `ChatAgent.create()`.\n *\n * A persona bundles the three orchestrator-coupled seams of the chat runtime:\n * system-prompt construction, toolset creation, and loop behaviors.\n */\nexport interface ChatPersonaConfig {\n /**\n * Stable persona identifier. Matches the `conversations.persona` column value\n * for sessions driven by this persona.\n */\n id: string;\n /** Builds the system prompt for each agent-loop iteration. */\n buildSystemContent: (ctx: ResolvedToolContext, iterCtx: IterationContext) => string;\n /** Creates the persona's toolset bound to the resolved user context. */\n createTools: (deps: ToolContext, preResolvedContext?: ResolvedToolContext) => Promise<ChatTools>;\n /** Orchestrator-specific loop behaviors this persona opts into. */\n loopBehaviors: ChatPersonaLoopBehaviors;\n}\n\n/** Persona id for the default orchestrator (\"You are Index…\"). */\nexport const ORCHESTRATOR_PERSONA_ID = \"orchestrator\";\n\n/**\n * The orchestrator persona — exactly the pre-personafication wiring:\n * `buildSystemContent` from chat.prompt, `createChatTools` from tool.factory,\n * and all loop behaviors enabled.\n *\n * Both functions delegate lazily (arrow wrappers) instead of capturing the\n * imported symbols at module-load time. This preserves ESM live-binding\n * semantics: the pre-refactor code read `createChatTools` through its import\n * binding at call time, which is what lets test suites swap the module via\n * `mock.module` — a snapshot in this object literal would pin whichever\n * version was loaded first.\n */\nexport const ORCHESTRATOR_PERSONA: ChatPersonaConfig = {\n id: ORCHESTRATOR_PERSONA_ID,\n buildSystemContent: (ctx, iterCtx) => buildSystemContent(ctx, iterCtx),\n createTools: (deps, preResolvedContext) => createChatTools(deps, preResolvedContext),\n loopBehaviors: {\n createIntentCallback: true,\n hallucinationRecovery: true,\n },\n};\n"]}
@@ -0,0 +1,49 @@
1
+ import { type ChatTools, type ToolContext, type ResolvedToolContext } from "../shared/agent/tool.factory.js";
2
+ import type { ChatPersonaConfig } from "./chat.persona.js";
3
+ import { type NegotiatorPromptOptions } from "./negotiator.prompt.js";
4
+ /**
5
+ * Persona id for the user's personal negotiator. Matches the
6
+ * `conversations.persona` column value for negotiator DM sessions.
7
+ */
8
+ export declare const NEGOTIATOR_PERSONA_ID = "negotiator";
9
+ /**
10
+ * Client-scoped tool allowlist for the negotiator persona.
11
+ *
12
+ * Deliberately excludes every network-facing capability: no discovery
13
+ * (`discover_opportunities`), no network/membership management, no profile or
14
+ * intent writes, no contact import. This agent works for one client; as the
15
+ * orchestrator sunsets, network-facing capabilities migrate here deliberately
16
+ * (out of scope for P4.1).
17
+ */
18
+ export declare const NEGOTIATOR_TOOL_NAMES: readonly ["list_negotiations", "get_negotiation", "respond_to_negotiation", "list_opportunities", "read_intents", "read_premises"];
19
+ /**
20
+ * Filters a full chat-tool registry down to the negotiator allowlist.
21
+ * Exported separately so the scoping rule is unit-testable without
22
+ * constructing the full tool factory dependency graph.
23
+ */
24
+ export declare function filterNegotiatorTools<T extends {
25
+ name: string;
26
+ }>(tools: T[]): T[];
27
+ /**
28
+ * Creates the negotiator persona's client-scoped toolset.
29
+ *
30
+ * Reuses the standard chat tool factory (so context resolution, scope
31
+ * derivation, logging, and error handling stay identical) and filters the
32
+ * registry to the allowlist. The negotiation tools are already context-bound
33
+ * to `context.userId`, so every tool in this set can only read or act on the
34
+ * calling client's own data.
35
+ */
36
+ export declare function createNegotiatorTools(deps: ToolContext, preResolvedContext?: ResolvedToolContext): Promise<ChatTools>;
37
+ /**
38
+ * Creates a negotiator `ChatPersonaConfig` bound to the client's personal
39
+ * negotiator agent row identity.
40
+ *
41
+ * Loop behaviors are all OFF: no create-intent callback and no
42
+ * hallucinated-block auto-invoke/strip — the negotiator's toolset cannot
43
+ * legitimately produce opportunity/intent-proposal blocks, and it must never
44
+ * inherit the orchestrator's discovery auto-invocation.
45
+ *
46
+ * @param opts - Identity from the user's `type='personal'` agent row
47
+ */
48
+ export declare function createNegotiatorPersona(opts: NegotiatorPromptOptions): ChatPersonaConfig;
49
+ //# sourceMappingURL=negotiator.persona.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"negotiator.persona.d.ts","sourceRoot":"/","sources":["chat/negotiator.persona.ts"],"names":[],"mappings":"AAAA,OAAO,EAAmB,KAAK,SAAS,EAAE,KAAK,WAAW,EAAE,KAAK,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AAC9H,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAC3D,OAAO,EAAgC,KAAK,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAYpG;;;GAGG;AACH,eAAO,MAAM,qBAAqB,eAAe,CAAC;AAElD;;;;;;;;GAQG;AACH,eAAO,MAAM,qBAAqB,oIAOxB,CAAC;AAIX;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,CAAC,SAAS;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,EAAE,KAAK,EAAE,CAAC,EAAE,GAAG,CAAC,EAAE,CAEjF;AAED;;;;;;;;GAQG;AACH,wBAAsB,qBAAqB,CACzC,IAAI,EAAE,WAAW,EACjB,kBAAkB,CAAC,EAAE,mBAAmB,GACvC,OAAO,CAAC,SAAS,CAAC,CAGpB;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,uBAAuB,GAAG,iBAAiB,CAUxF"}
@@ -0,0 +1,78 @@
1
+ import { createChatTools } from "../shared/agent/tool.factory.js";
2
+ import { buildNegotiatorSystemContent } from "./negotiator.prompt.js";
3
+ // ═══════════════════════════════════════════════════════════════════════════════
4
+ // NEGOTIATOR PERSONA (P4.1)
5
+ // ═══════════════════════════════════════════════════════════════════════════════
6
+ //
7
+ // A pure persona addition on the P4.0 persona-neutral chat runtime: advocate
8
+ // prompt, client-scoped toolset, and all orchestrator loop behaviors OFF.
9
+ // Unlike the orchestrator (a static singleton), the negotiator persona is
10
+ // created per session because its identity comes from the user's
11
+ // `type='personal'` agent row (name/description).
12
+ /**
13
+ * Persona id for the user's personal negotiator. Matches the
14
+ * `conversations.persona` column value for negotiator DM sessions.
15
+ */
16
+ export const NEGOTIATOR_PERSONA_ID = "negotiator";
17
+ /**
18
+ * Client-scoped tool allowlist for the negotiator persona.
19
+ *
20
+ * Deliberately excludes every network-facing capability: no discovery
21
+ * (`discover_opportunities`), no network/membership management, no profile or
22
+ * intent writes, no contact import. This agent works for one client; as the
23
+ * orchestrator sunsets, network-facing capabilities migrate here deliberately
24
+ * (out of scope for P4.1).
25
+ */
26
+ export const NEGOTIATOR_TOOL_NAMES = [
27
+ "list_negotiations",
28
+ "get_negotiation",
29
+ "respond_to_negotiation",
30
+ "list_opportunities",
31
+ "read_intents",
32
+ "read_premises",
33
+ ];
34
+ const NEGOTIATOR_TOOL_ALLOWLIST = new Set(NEGOTIATOR_TOOL_NAMES);
35
+ /**
36
+ * Filters a full chat-tool registry down to the negotiator allowlist.
37
+ * Exported separately so the scoping rule is unit-testable without
38
+ * constructing the full tool factory dependency graph.
39
+ */
40
+ export function filterNegotiatorTools(tools) {
41
+ return tools.filter((t) => NEGOTIATOR_TOOL_ALLOWLIST.has(t.name));
42
+ }
43
+ /**
44
+ * Creates the negotiator persona's client-scoped toolset.
45
+ *
46
+ * Reuses the standard chat tool factory (so context resolution, scope
47
+ * derivation, logging, and error handling stay identical) and filters the
48
+ * registry to the allowlist. The negotiation tools are already context-bound
49
+ * to `context.userId`, so every tool in this set can only read or act on the
50
+ * calling client's own data.
51
+ */
52
+ export async function createNegotiatorTools(deps, preResolvedContext) {
53
+ const tools = await createChatTools(deps, preResolvedContext);
54
+ return filterNegotiatorTools(tools);
55
+ }
56
+ /**
57
+ * Creates a negotiator `ChatPersonaConfig` bound to the client's personal
58
+ * negotiator agent row identity.
59
+ *
60
+ * Loop behaviors are all OFF: no create-intent callback and no
61
+ * hallucinated-block auto-invoke/strip — the negotiator's toolset cannot
62
+ * legitimately produce opportunity/intent-proposal blocks, and it must never
63
+ * inherit the orchestrator's discovery auto-invocation.
64
+ *
65
+ * @param opts - Identity from the user's `type='personal'` agent row
66
+ */
67
+ export function createNegotiatorPersona(opts) {
68
+ return {
69
+ id: NEGOTIATOR_PERSONA_ID,
70
+ buildSystemContent: (ctx, iterCtx) => buildNegotiatorSystemContent(ctx, opts, iterCtx),
71
+ createTools: (deps, preResolvedContext) => createNegotiatorTools(deps, preResolvedContext),
72
+ loopBehaviors: {
73
+ createIntentCallback: false,
74
+ hallucinationRecovery: false,
75
+ },
76
+ };
77
+ }
78
+ //# sourceMappingURL=negotiator.persona.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"negotiator.persona.js","sourceRoot":"/","sources":["chat/negotiator.persona.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAA8D,MAAM,iCAAiC,CAAC;AAE9H,OAAO,EAAE,4BAA4B,EAAgC,MAAM,wBAAwB,CAAC;AAEpG,kFAAkF;AAClF,4BAA4B;AAC5B,kFAAkF;AAClF,EAAE;AACF,6EAA6E;AAC7E,0EAA0E;AAC1E,0EAA0E;AAC1E,iEAAiE;AACjE,kDAAkD;AAElD;;;GAGG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,YAAY,CAAC;AAElD;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG;IACnC,mBAAmB;IACnB,iBAAiB;IACjB,wBAAwB;IACxB,oBAAoB;IACpB,cAAc;IACd,eAAe;CACP,CAAC;AAEX,MAAM,yBAAyB,GAAwB,IAAI,GAAG,CAAC,qBAAqB,CAAC,CAAC;AAEtF;;;;GAIG;AACH,MAAM,UAAU,qBAAqB,CAA6B,KAAU;IAC1E,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,yBAAyB,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;AACpE,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,qBAAqB,CACzC,IAAiB,EACjB,kBAAwC;IAExC,MAAM,KAAK,GAAG,MAAM,eAAe,CAAC,IAAI,EAAE,kBAAkB,CAAC,CAAC;IAC9D,OAAO,qBAAqB,CAAC,KAAK,CAAC,CAAC;AACtC,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,uBAAuB,CAAC,IAA6B;IACnE,OAAO;QACL,EAAE,EAAE,qBAAqB;QACzB,kBAAkB,EAAE,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,CAAC,4BAA4B,CAAC,GAAG,EAAE,IAAI,EAAE,OAAO,CAAC;QACtF,WAAW,EAAE,CAAC,IAAI,EAAE,kBAAkB,EAAE,EAAE,CAAC,qBAAqB,CAAC,IAAI,EAAE,kBAAkB,CAAC;QAC1F,aAAa,EAAE;YACb,oBAAoB,EAAE,KAAK;YAC3B,qBAAqB,EAAE,KAAK;SAC7B;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { createChatTools, type ChatTools, type ToolContext, type ResolvedToolContext } from \"../shared/agent/tool.factory.js\";\nimport type { ChatPersonaConfig } from \"./chat.persona.js\";\nimport { buildNegotiatorSystemContent, type NegotiatorPromptOptions } from \"./negotiator.prompt.js\";\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// NEGOTIATOR PERSONA (P4.1)\n// ═══════════════════════════════════════════════════════════════════════════════\n//\n// A pure persona addition on the P4.0 persona-neutral chat runtime: advocate\n// prompt, client-scoped toolset, and all orchestrator loop behaviors OFF.\n// Unlike the orchestrator (a static singleton), the negotiator persona is\n// created per session because its identity comes from the user's\n// `type='personal'` agent row (name/description).\n\n/**\n * Persona id for the user's personal negotiator. Matches the\n * `conversations.persona` column value for negotiator DM sessions.\n */\nexport const NEGOTIATOR_PERSONA_ID = \"negotiator\";\n\n/**\n * Client-scoped tool allowlist for the negotiator persona.\n *\n * Deliberately excludes every network-facing capability: no discovery\n * (`discover_opportunities`), no network/membership management, no profile or\n * intent writes, no contact import. This agent works for one client; as the\n * orchestrator sunsets, network-facing capabilities migrate here deliberately\n * (out of scope for P4.1).\n */\nexport const NEGOTIATOR_TOOL_NAMES = [\n \"list_negotiations\",\n \"get_negotiation\",\n \"respond_to_negotiation\",\n \"list_opportunities\",\n \"read_intents\",\n \"read_premises\",\n] as const;\n\nconst NEGOTIATOR_TOOL_ALLOWLIST: ReadonlySet<string> = new Set(NEGOTIATOR_TOOL_NAMES);\n\n/**\n * Filters a full chat-tool registry down to the negotiator allowlist.\n * Exported separately so the scoping rule is unit-testable without\n * constructing the full tool factory dependency graph.\n */\nexport function filterNegotiatorTools<T extends { name: string }>(tools: T[]): T[] {\n return tools.filter((t) => NEGOTIATOR_TOOL_ALLOWLIST.has(t.name));\n}\n\n/**\n * Creates the negotiator persona's client-scoped toolset.\n *\n * Reuses the standard chat tool factory (so context resolution, scope\n * derivation, logging, and error handling stay identical) and filters the\n * registry to the allowlist. The negotiation tools are already context-bound\n * to `context.userId`, so every tool in this set can only read or act on the\n * calling client's own data.\n */\nexport async function createNegotiatorTools(\n deps: ToolContext,\n preResolvedContext?: ResolvedToolContext,\n): Promise<ChatTools> {\n const tools = await createChatTools(deps, preResolvedContext);\n return filterNegotiatorTools(tools);\n}\n\n/**\n * Creates a negotiator `ChatPersonaConfig` bound to the client's personal\n * negotiator agent row identity.\n *\n * Loop behaviors are all OFF: no create-intent callback and no\n * hallucinated-block auto-invoke/strip — the negotiator's toolset cannot\n * legitimately produce opportunity/intent-proposal blocks, and it must never\n * inherit the orchestrator's discovery auto-invocation.\n *\n * @param opts - Identity from the user's `type='personal'` agent row\n */\nexport function createNegotiatorPersona(opts: NegotiatorPromptOptions): ChatPersonaConfig {\n return {\n id: NEGOTIATOR_PERSONA_ID,\n buildSystemContent: (ctx, iterCtx) => buildNegotiatorSystemContent(ctx, opts, iterCtx),\n createTools: (deps, preResolvedContext) => createNegotiatorTools(deps, preResolvedContext),\n loopBehaviors: {\n createIntentCallback: false,\n hallucinationRecovery: false,\n },\n };\n}\n"]}
@@ -0,0 +1,24 @@
1
+ import type { ResolvedToolContext } from "../shared/agent/tool.factory.js";
2
+ import type { IterationContext } from "./chat.prompt.modules.js";
3
+ /** Identity options resolved from the user's personal negotiator agent row. */
4
+ export interface NegotiatorPromptOptions {
5
+ /** The negotiator agent's display name (e.g. "Ada's Negotiator"). */
6
+ agentName: string;
7
+ /** The negotiator agent's description, when set on the agent row. */
8
+ agentDescription?: string;
9
+ }
10
+ /**
11
+ * Builds the system prompt for the negotiator chat persona.
12
+ *
13
+ * Grounded in the client's preloaded user/profile context; everything else
14
+ * (negotiations, opportunities, signals, premises) must be fetched through
15
+ * the client-scoped toolset each turn.
16
+ *
17
+ * @param ctx - Resolved tool context for the current session
18
+ * @param opts - Identity from the client's personal negotiator agent row
19
+ * @param _iterCtx - Iteration context (unused — the negotiator prompt has no
20
+ * dynamic modules; the nudge is injected by the agent loop)
21
+ * @returns The complete system prompt string
22
+ */
23
+ export declare function buildNegotiatorSystemContent(ctx: ResolvedToolContext, opts: NegotiatorPromptOptions, _iterCtx?: IterationContext): string;
24
+ //# sourceMappingURL=negotiator.prompt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"negotiator.prompt.d.ts","sourceRoot":"/","sources":["chat/negotiator.prompt.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AAC3E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAajE,+EAA+E;AAC/E,MAAM,WAAW,uBAAuB;IACtC,qEAAqE;IACrE,SAAS,EAAE,MAAM,CAAC;IAClB,qEAAqE;IACrE,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,4BAA4B,CAC1C,GAAG,EAAE,mBAAmB,EACxB,IAAI,EAAE,uBAAuB,EAC7B,QAAQ,CAAC,EAAE,gBAAgB,GAC1B,MAAM,CAyDR"}
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Builds the system prompt for the negotiator chat persona.
3
+ *
4
+ * Grounded in the client's preloaded user/profile context; everything else
5
+ * (negotiations, opportunities, signals, premises) must be fetched through
6
+ * the client-scoped toolset each turn.
7
+ *
8
+ * @param ctx - Resolved tool context for the current session
9
+ * @param opts - Identity from the client's personal negotiator agent row
10
+ * @param _iterCtx - Iteration context (unused — the negotiator prompt has no
11
+ * dynamic modules; the nudge is injected by the agent loop)
12
+ * @returns The complete system prompt string
13
+ */
14
+ export function buildNegotiatorSystemContent(ctx, opts, _iterCtx) {
15
+ const userContext = JSON.stringify(ctx.user, null, 2);
16
+ const profileContext = ctx.userProfile
17
+ ? JSON.stringify(ctx.userProfile, null, 2)
18
+ : "null";
19
+ const descriptionLine = opts.agentDescription?.trim()
20
+ ? `\n${opts.agentDescription.trim()}\n`
21
+ : "";
22
+ return `You are ${opts.agentName}, the personal negotiator agent working for ${ctx.userName}.
23
+ ${descriptionLine}
24
+ You work for exactly one client: ${ctx.userName}. You represent them in negotiations with other members' agents across the network, and this chat is your direct line to them. Your job here is to keep your client informed about what you have been doing on their behalf, explain your reasoning honestly, and act only on their explicit instructions.
25
+
26
+ ## What you do in this chat
27
+ - **Report on negotiations**: when the client asks what is happening, look up their negotiations and summarize status, counterparties, and where things stand.
28
+ - **Explain decisions**: when the client asks why something was pursued, declined, or stalled ("why did you pass on X?"), find the relevant negotiation and answer from the actual record — the messages, outcomes, and reasoning stored there. Never reconstruct a rationale from memory.
29
+ - **Review opportunities**: show the client the opportunities currently waiting on them and what accepting or passing would mean.
30
+ - **Stay grounded in their signals**: their active intents and premises define what you negotiate for. Read them before making claims about what the client is looking for.
31
+ - **Act on instruction**: respond to a negotiation (accept, decline, or reply) only when the client explicitly tells you to in this conversation. Never take a negotiation action the client did not just ask for.
32
+
33
+ ## What you cannot do here
34
+ - **No network-wide discovery.** You cannot look for new people, run matching, or create new connections from this chat. New matches are discovered by the system in the background and appear on the client's home page.
35
+ - **No profile, community, or membership management.** If the client asks for those, tell them plainly that it is outside your remit as their negotiator and they can do it from the main chat or the app.
36
+ - You cannot push updates after this conversation ends. You only report when asked.
37
+
38
+ ## Session
39
+ - Client: ${ctx.userName} (${ctx.userEmail}), id: ${ctx.userId}
40
+
41
+ ### Client (preloaded context)
42
+ \`\`\`json
43
+ ${userContext}
44
+ \`\`\`
45
+
46
+ ### Client Context (preloaded context)
47
+ \`\`\`json
48
+ ${profileContext}
49
+ \`\`\`
50
+
51
+ ## Tools Reference
52
+
53
+ | Tool | Params | What it does |
54
+ |------|--------|-------------|
55
+ | **list_negotiations** | status?, limit? | List the client's negotiations |
56
+ | **get_negotiation** | negotiationId | Full negotiation record: messages, outcome, reasoning |
57
+ | **respond_to_negotiation** | negotiationId, ... | Act on a negotiation — ONLY on explicit client instruction |
58
+ | **list_opportunities** | — | List the client's actionable opportunities |
59
+ | **read_intents** | — | The client's active signals (what they're looking for) |
60
+ | **read_premises** | — | The client's premises (facts they've established) |
61
+
62
+ ## Grounding rules
63
+ - **Never fabricate.** Every claim about a negotiation, opportunity, signal, or premise must come from a tool result in this conversation. If you have not looked it up this turn, look it up before answering. Only the client's identity and profile above are preloaded.
64
+ - **Check tool results before confirming.** Never claim an action succeeded without a successful tool result for it.
65
+ - **Be honest about your own actions.** If the record shows you made a judgment call the client disagrees with, explain the reasoning from the record — do not get defensive, and do not invent justifications the record does not support.
66
+ - **Never expose IDs, UUIDs, tool names, or raw JSON** to the client. Translate everything into natural language; refer to people and opportunities by name.
67
+ - **Respond in the language of the client's latest message.**
68
+ - **Voice**: first person, loyal but candid, calm and concise. No hype, no networking clichés, no exaggeration. You are their agent, not a salesperson.
69
+ - When calling tools, first write a short natural sentence plus a \`>\` blockquote describing what you are checking (e.g. "> Checking the record with Alice"), then leave an empty line after the blockquote.`;
70
+ }
71
+ //# sourceMappingURL=negotiator.prompt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"negotiator.prompt.js","sourceRoot":"/","sources":["chat/negotiator.prompt.ts"],"names":[],"mappings":"AAsBA;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,4BAA4B,CAC1C,GAAwB,EACxB,IAA6B,EAC7B,QAA2B;IAE3B,MAAM,WAAW,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IACtD,MAAM,cAAc,GAAG,GAAG,CAAC,WAAW;QACpC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,WAAW,EAAE,IAAI,EAAE,CAAC,CAAC;QAC1C,CAAC,CAAC,MAAM,CAAC;IACX,MAAM,eAAe,GAAG,IAAI,CAAC,gBAAgB,EAAE,IAAI,EAAE;QACnD,CAAC,CAAC,KAAK,IAAI,CAAC,gBAAgB,CAAC,IAAI,EAAE,IAAI;QACvC,CAAC,CAAC,EAAE,CAAC;IAEP,OAAO,WAAW,IAAI,CAAC,SAAS,+CAA+C,GAAG,CAAC,QAAQ;EAC3F,eAAe;mCACkB,GAAG,CAAC,QAAQ;;;;;;;;;;;;;;;YAenC,GAAG,CAAC,QAAQ,KAAK,GAAG,CAAC,SAAS,UAAU,GAAG,CAAC,MAAM;;;;EAI5D,WAAW;;;;;EAKX,cAAc;;;;;;;;;;;;;;;;;;;;;8MAqB8L,CAAC;AAC/M,CAAC","sourcesContent":["import type { ResolvedToolContext } from \"../shared/agent/tool.factory.js\";\nimport type { IterationContext } from \"./chat.prompt.modules.js\";\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// NEGOTIATOR PERSONA SYSTEM PROMPT (P4.1)\n// ═══════════════════════════════════════════════════════════════════════════════\n//\n// The direct chat line between a user and their personal negotiator agent\n// (the `type='personal'` agent row). Unlike the orchestrator prompt, this\n// persona works for exactly one client: it reports on the client's\n// negotiations and opportunities, explains decisions from the negotiation\n// record, and acts only on explicit client instruction. It has no\n// network-wide discovery capabilities.\n\n/** Identity options resolved from the user's personal negotiator agent row. */\nexport interface NegotiatorPromptOptions {\n /** The negotiator agent's display name (e.g. \"Ada's Negotiator\"). */\n agentName: string;\n /** The negotiator agent's description, when set on the agent row. */\n agentDescription?: string;\n}\n\n/**\n * Builds the system prompt for the negotiator chat persona.\n *\n * Grounded in the client's preloaded user/profile context; everything else\n * (negotiations, opportunities, signals, premises) must be fetched through\n * the client-scoped toolset each turn.\n *\n * @param ctx - Resolved tool context for the current session\n * @param opts - Identity from the client's personal negotiator agent row\n * @param _iterCtx - Iteration context (unused — the negotiator prompt has no\n * dynamic modules; the nudge is injected by the agent loop)\n * @returns The complete system prompt string\n */\nexport function buildNegotiatorSystemContent(\n ctx: ResolvedToolContext,\n opts: NegotiatorPromptOptions,\n _iterCtx?: IterationContext,\n): string {\n const userContext = JSON.stringify(ctx.user, null, 2);\n const profileContext = ctx.userProfile\n ? JSON.stringify(ctx.userProfile, null, 2)\n : \"null\";\n const descriptionLine = opts.agentDescription?.trim()\n ? `\\n${opts.agentDescription.trim()}\\n`\n : \"\";\n\n return `You are ${opts.agentName}, the personal negotiator agent working for ${ctx.userName}.\n${descriptionLine}\nYou work for exactly one client: ${ctx.userName}. You represent them in negotiations with other members' agents across the network, and this chat is your direct line to them. Your job here is to keep your client informed about what you have been doing on their behalf, explain your reasoning honestly, and act only on their explicit instructions.\n\n## What you do in this chat\n- **Report on negotiations**: when the client asks what is happening, look up their negotiations and summarize status, counterparties, and where things stand.\n- **Explain decisions**: when the client asks why something was pursued, declined, or stalled (\"why did you pass on X?\"), find the relevant negotiation and answer from the actual record — the messages, outcomes, and reasoning stored there. Never reconstruct a rationale from memory.\n- **Review opportunities**: show the client the opportunities currently waiting on them and what accepting or passing would mean.\n- **Stay grounded in their signals**: their active intents and premises define what you negotiate for. Read them before making claims about what the client is looking for.\n- **Act on instruction**: respond to a negotiation (accept, decline, or reply) only when the client explicitly tells you to in this conversation. Never take a negotiation action the client did not just ask for.\n\n## What you cannot do here\n- **No network-wide discovery.** You cannot look for new people, run matching, or create new connections from this chat. New matches are discovered by the system in the background and appear on the client's home page.\n- **No profile, community, or membership management.** If the client asks for those, tell them plainly that it is outside your remit as their negotiator and they can do it from the main chat or the app.\n- You cannot push updates after this conversation ends. You only report when asked.\n\n## Session\n- Client: ${ctx.userName} (${ctx.userEmail}), id: ${ctx.userId}\n\n### Client (preloaded context)\n\\`\\`\\`json\n${userContext}\n\\`\\`\\`\n\n### Client Context (preloaded context)\n\\`\\`\\`json\n${profileContext}\n\\`\\`\\`\n\n## Tools Reference\n\n| Tool | Params | What it does |\n|------|--------|-------------|\n| **list_negotiations** | status?, limit? | List the client's negotiations |\n| **get_negotiation** | negotiationId | Full negotiation record: messages, outcome, reasoning |\n| **respond_to_negotiation** | negotiationId, ... | Act on a negotiation — ONLY on explicit client instruction |\n| **list_opportunities** | — | List the client's actionable opportunities |\n| **read_intents** | — | The client's active signals (what they're looking for) |\n| **read_premises** | — | The client's premises (facts they've established) |\n\n## Grounding rules\n- **Never fabricate.** Every claim about a negotiation, opportunity, signal, or premise must come from a tool result in this conversation. If you have not looked it up this turn, look it up before answering. Only the client's identity and profile above are preloaded.\n- **Check tool results before confirming.** Never claim an action succeeded without a successful tool result for it.\n- **Be honest about your own actions.** If the record shows you made a judgment call the client disagrees with, explain the reasoning from the record — do not get defensive, and do not invent justifications the record does not support.\n- **Never expose IDs, UUIDs, tool names, or raw JSON** to the client. Translate everything into natural language; refer to people and opportunities by name.\n- **Respond in the language of the client's latest message.**\n- **Voice**: first person, loyal but candid, calm and concise. No hype, no networking clichés, no exaggeration. You are their agent, not a salesperson.\n- When calling tools, first write a short natural sentence plus a \\`>\\` blockquote describing what you are checking (e.g. \"> Checking the record with Alice\"), then leave an empty line after the blockquote.`;\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -51,6 +51,9 @@ export type { PromptPresenceInput, ResolveAssignmentNetworkScopeArgs, Assignment
51
51
  export { buildCandidateEvidence, withCandidateEvidence, mergeOpportunityEvidence, withMatchedStrategies, renderOpportunityEvidenceForPrompt } from "./opportunity/opportunity.evidence.js";
52
52
  export type { EvidenceCandidateInput } from "./opportunity/opportunity.evidence.js";
53
53
  export { ChatGraphFactory } from "./chat/chat.graph.js";
54
+ export { ORCHESTRATOR_PERSONA, ORCHESTRATOR_PERSONA_ID, type ChatPersonaConfig, type ChatPersonaLoopBehaviors, } from "./chat/chat.persona.js";
55
+ export { NEGOTIATOR_PERSONA_ID, NEGOTIATOR_TOOL_NAMES, createNegotiatorPersona, createNegotiatorTools, filterNegotiatorTools, } from "./chat/negotiator.persona.js";
56
+ export { buildNegotiatorSystemContent, type NegotiatorPromptOptions } from "./chat/negotiator.prompt.js";
54
57
  export { HomeGraphFactory } from "./opportunity/feed/feed.graph.js";
55
58
  export { HydeGraphFactory } from "./shared/hyde/hyde.graph.js";
56
59
  export { NetworkGraphFactory } from "./network/network.graph.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"/","sources":["index.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAC9D,YAAY,EAAE,SAAS,EAAE,MAAM,gCAAgC,CAAC;AAChE,YAAY,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AACjF,YAAY,EAAE,WAAW,EAAE,mBAAmB,EAAE,QAAQ,EAAE,YAAY,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AACjJ,OAAO,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AAC5F,OAAO,EACL,uBAAuB,EACvB,yBAAyB,EACzB,gBAAgB,EAChB,mBAAmB,EACnB,eAAe,EACf,kBAAkB,GACnB,MAAM,8BAA8B,CAAC;AACtC,YAAY,EAAE,iBAAiB,EAAE,aAAa,EAAE,eAAe,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AAC/H,OAAO,EAAE,cAAc,EAAE,MAAM,2CAA2C,CAAC;AAC3E,OAAO,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AACjE,YAAY,EAAE,gBAAgB,IAAI,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AACl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AAkB,EAAE,MAAM,iCAAiC,CAAC;AACrE,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,sBAAsB,EAAE,MAAM,oCAAoC,CAAC;AAC5E,OAAO,EAAE,uBAAuB,EAAE,MAAM,mCAAmC,CAAC;AAI5E,OAAO,EAAE,eAAe,EAAE,6BAA6B,EAAE,yBAAyB,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACpI,YAAY,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,EAAE,sBAAsB,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AACrF,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AACvE,YAAY,EAAE,gBAAgB,EAAE,aAAa,EAAE,0BAA0B,EAAE,MAAM,iCAAiC,CAAC;AAKnH,YAAY,EAAE,sBAAsB,EAAE,eAAe,EAAE,kBAAkB,EAAE,cAAc,EAAE,MAAM,8CAA8C,CAAC;AAChJ,YAAY,EAAE,oBAAoB,EAAE,MAAM,oCAAoC,CAAC;AAI/E,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC"}
package/dist/index.js CHANGED
@@ -32,6 +32,9 @@ export { DEFAULT_NETWORK_ASSIGNMENT_THRESHOLD, classifyPromptPresence, resolveAs
32
32
  export { buildCandidateEvidence, withCandidateEvidence, mergeOpportunityEvidence, withMatchedStrategies, renderOpportunityEvidenceForPrompt } from "./opportunity/opportunity.evidence.js";
33
33
  // ─── Graph factories ──────────────────────────────────────────────────────────
34
34
  export { ChatGraphFactory } from "./chat/chat.graph.js";
35
+ export { ORCHESTRATOR_PERSONA, ORCHESTRATOR_PERSONA_ID, } from "./chat/chat.persona.js";
36
+ export { NEGOTIATOR_PERSONA_ID, NEGOTIATOR_TOOL_NAMES, createNegotiatorPersona, createNegotiatorTools, filterNegotiatorTools, } from "./chat/negotiator.persona.js";
37
+ export { buildNegotiatorSystemContent } from "./chat/negotiator.prompt.js";
35
38
  export { HomeGraphFactory } from "./opportunity/feed/feed.graph.js";
36
39
  export { HydeGraphFactory } from "./shared/hyde/hyde.graph.js";
37
40
  export { NetworkGraphFactory } from "./network/network.graph.js";