@indexnetwork/protocol 3.9.0-rc.284.1 → 3.11.0-rc.286.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.
Files changed (43) hide show
  1. package/dist/intent/intent.graph.d.ts.map +1 -1
  2. package/dist/intent/intent.graph.js +16 -51
  3. package/dist/intent/intent.graph.js.map +1 -1
  4. package/dist/negotiation/negotiation.graph.d.ts.map +1 -1
  5. package/dist/negotiation/negotiation.graph.js +2 -1
  6. package/dist/negotiation/negotiation.graph.js.map +1 -1
  7. package/dist/network/network.recommender.d.ts +2 -7
  8. package/dist/network/network.recommender.d.ts.map +1 -1
  9. package/dist/network/network.recommender.js +3 -8
  10. package/dist/network/network.recommender.js.map +1 -1
  11. package/dist/network/network.tools.d.ts.map +1 -1
  12. package/dist/network/network.tools.js +7 -9
  13. package/dist/network/network.tools.js.map +1 -1
  14. package/dist/opportunity/discovery-question.helper.d.ts +2 -2
  15. package/dist/opportunity/discovery-question.helper.d.ts.map +1 -1
  16. package/dist/opportunity/discovery-question.helper.js +1 -17
  17. package/dist/opportunity/discovery-question.helper.js.map +1 -1
  18. package/dist/opportunity/opportunity.discover.d.ts.map +1 -1
  19. package/dist/opportunity/opportunity.discover.js +5 -2
  20. package/dist/opportunity/opportunity.discover.js.map +1 -1
  21. package/dist/opportunity/question.prompt.d.ts +7 -2
  22. package/dist/opportunity/question.prompt.d.ts.map +1 -1
  23. package/dist/opportunity/question.prompt.js +1 -15
  24. package/dist/opportunity/question.prompt.js.map +1 -1
  25. package/dist/profile/profile.graph.d.ts.map +1 -1
  26. package/dist/profile/profile.graph.js +22 -19
  27. package/dist/profile/profile.graph.js.map +1 -1
  28. package/dist/questioner/questioner.presets.d.ts.map +1 -1
  29. package/dist/questioner/questioner.presets.js +10 -21
  30. package/dist/questioner/questioner.presets.js.map +1 -1
  31. package/dist/questioner/questioner.types.d.ts +6 -19
  32. package/dist/questioner/questioner.types.d.ts.map +1 -1
  33. package/dist/questioner/questioner.types.js.map +1 -1
  34. package/dist/shared/agent/tool.helpers.d.ts +7 -6
  35. package/dist/shared/agent/tool.helpers.d.ts.map +1 -1
  36. package/dist/shared/agent/tool.helpers.js.map +1 -1
  37. package/dist/shared/interfaces/database.interface.d.ts +3 -3
  38. package/dist/shared/interfaces/database.interface.d.ts.map +1 -1
  39. package/dist/shared/interfaces/database.interface.js.map +1 -1
  40. package/dist/shared/schemas/discovery-question.schema.d.ts +2 -1
  41. package/dist/shared/schemas/discovery-question.schema.d.ts.map +1 -1
  42. package/dist/shared/schemas/discovery-question.schema.js.map +1 -1
  43. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"negotiation.graph.js","sourceRoot":"/","sources":["negotiation/negotiation.graph.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAElD,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AACxE,OAAO,EAAE,cAAc,EAAqB,MAAM,4CAA4C,CAAC;AAI/F,OAAO,EAAE,qBAAqB,EAA8H,MAAM,wBAAwB,CAAC;AAC3L,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAG5E,MAAM,MAAM,GAAG,cAAc,CAAC,kBAAkB,CAAC,CAAC;AAElD,6EAA6E;AAC7E,SAAS,iBAAiB,CAAC,QAAqC;IAC9D,OAAO,QAAQ;SACZ,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE;QACT,MAAM,QAAQ,GAAI,CAAC,CAAC,KAAkD,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC;QACtG,OAAO,QAAQ,EAAE,IAAuB,CAAC;IAC3C,CAAC,CAAC;SACD,MAAM,CAAC,OAAO,CAAC,CAAC;AACrB,CAAC;AAED;;;GAGG;AACH,MAAM,OA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CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC;4BAC3D,SAAS,EAAE,CAAC;yBACb;qBACF,CAAC,CAAC;gBACL,CAAC;gBAAC,MAAM,CAAC;oBACP,oCAAoC;gBACtC,CAAC;YACH,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC,CAAC,CACH,CAAC;IAEF,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAA0B,EAAE,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC;AACnE,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,6BAA6B,CAAC,IAI7C;IACC,MAAM,OAAO,GAAG,IAAI,uBAAuB,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;IAC/F,OAAO,OAAO,CAAC,WAAW,EAAE,CAAC;AAC/B,CAAC","sourcesContent":["import { StateGraph } from \"@langchain/langgraph\";\n\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\nimport { requestContext, type TraceEmitter } from \"../shared/observability/request-context.js\";\nimport type { NegotiationGraphDatabase } from \"../shared/interfaces/database.interface.js\";\nimport type { NegotiationTimeoutQueue } from \"../shared/interfaces/negotiation-events.interface.js\";\nimport type { AgentDispatcher, NegotiationTurnPayload } from \"../shared/interfaces/agent-dispatcher.interface.js\";\nimport { NegotiationGraphState, type NegotiationTurn, type NegotiationOutcome, type UserNegotiationContext, type SeedAssessment, type NegotiationGraphLike } from \"./negotiation.state.js\";\nimport { IndexNegotiator } from \"./negotiation.agent.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport type { QuestionerEnqueueFn } from \"../questioner/questioner.types.js\";\n\nconst logger = protocolLogger(\"NegotiationGraph\");\n\n/** Extracts the ordered NegotiationTurn list from A2A message data parts. */\nfunction turnsFromMessages(messages: Array<{ parts: unknown[] }>): NegotiationTurn[] {\n return messages\n .map((m) => {\n const dataPart = (m.parts as Array<{ kind?: string; data?: unknown }>).find((p) => p.kind === \"data\");\n return dataPart?.data as NegotiationTurn;\n })\n .filter(Boolean);\n}\n\n/**\n * Factory for the bilateral negotiation LangGraph state machine.\n * @remarks Accepts an AgentDispatcher for per-turn agent resolution.\n */\nexport class NegotiationGraphFactory {\n constructor(\n private database: NegotiationGraphDatabase,\n private dispatcher: AgentDispatcher,\n private timeoutQueue?: NegotiationTimeoutQueue,\n private questionerEnqueue?: QuestionerEnqueueFn,\n ) {}\n\n createGraph() {\n const { database, dispatcher, timeoutQueue, questionerEnqueue } = this;\n const systemAgent = new IndexNegotiator();\n\n const initNode = async (state: typeof NegotiationGraphState.State) => {\n try {\n // Find-or-create the DM conversation for this agent pair (same as user DMs)\n const agentIdA = `agent:${state.sourceUser.id}`;\n const agentIdB = `agent:${state.candidateUser.id}`;\n const conversation = await database.getOrCreateDM(agentIdA, agentIdB, 'agent');\n\n // --- Lock gate: check for an active task on this conversation ---\n const priorMessages = await database.getMessagesForConversation(conversation.id);\n\n let isLocked = false;\n if (state.opportunityId) {\n const priorTask = await database.getNegotiationTaskForOpportunity(state.opportunityId);\n if (priorTask) {\n const activeStates = ['submitted', 'working', 'input_required', 'waiting_for_agent', 'claimed'];\n const isFresh = (Date.now() - new Date(priorTask.updatedAt).getTime()) < 5 * 60 * 1000;\n if (activeStates.includes(priorTask.state) && isFresh) {\n isLocked = true;\n }\n }\n }\n\n if (isLocked) {\n logger.info('[Graph:Init] Conversation locked by active task, returning busy', {\n conversationId: conversation.id,\n opportunityId: state.opportunityId,\n });\n return { error: 'busy' };\n }\n\n // --- Load prior messages and determine continuation ---\n const priorTurns: NegotiationTurn[] = turnsFromMessages(priorMessages);\n\n const isContinuation = priorTurns.length > 0;\n\n // Determine currentSpeaker from last prior message\n let currentSpeaker: 'source' | 'candidate' = 'source';\n if (isContinuation && priorMessages.length > 0) {\n const lastSender = priorMessages[priorMessages.length - 1].senderId;\n currentSpeaker = lastSender === agentIdA ? 'candidate' : 'source';\n }\n\n // Determine scenario-based maxTurns\n const scope = { action: 'manage:negotiations', scopeType: 'network', scopeId: state.indexContext.networkId };\n const [sourceHasAgent, candidateHasAgent] = await Promise.all([\n dispatcher.hasPersonalAgent(state.sourceUser.id, scope),\n dispatcher.hasPersonalAgent(state.candidateUser.id, scope),\n ]);\n\n const ambientMax = Number(process.env.NEGOTIATION_MAX_TURNS_AMBIENT) || 6;\n let maxTurns = state.maxTurns;\n if (maxTurns == null) {\n maxTurns = (sourceHasAgent && candidateHasAgent) ? 0 : ambientMax;\n }\n\n const task = await database.createTask(conversation.id, {\n type: 'negotiation',\n sourceUserId: state.sourceUser.id,\n candidateUserId: state.candidateUser.id,\n networkId: state.indexContext.networkId,\n ...(state.opportunityId && { opportunityId: state.opportunityId }),\n maxTurns,\n isContinuation,\n priorTurnCount: priorTurns.length,\n });\n\n if (state.opportunityId) {\n await database.updateOpportunityStatus(state.opportunityId, 'negotiating').catch((err) => {\n logger.error('[Graph:Init] Failed to set opportunity status to negotiating', { opportunityId: state.opportunityId, error: err });\n });\n }\n\n // Load user answers collected by the questioner between sessions\n const userAnswers = (isContinuation && state.opportunityId)\n ? await database.getOpportunityUserAnswers(state.opportunityId).catch((err) => {\n logger.error('[Graph:Init] Failed to load user answers', { opportunityId: state.opportunityId, error: err });\n return [];\n })\n : [];\n\n // Seed messages with prior turns (additive reducer appends new turns on top)\n const seedMessages = isContinuation ? priorMessages.map((m) => ({\n id: m.id,\n senderId: m.senderId,\n role: 'agent' as const,\n parts: m.parts,\n createdAt: m.createdAt,\n })) : [];\n\n return {\n conversationId: conversation.id,\n taskId: task.id,\n currentSpeaker,\n turnCount: 0,\n maxTurns,\n isContinuation,\n priorTurnCount: priorTurns.length,\n ...(userAnswers.length > 0 && { userAnswers }),\n ...(seedMessages.length > 0 && { messages: seedMessages }),\n };\n } catch (err) {\n return { error: `Init failed: ${err instanceof Error ? err.message : String(err)}` };\n }\n };\n\n const turnNode = async (state: typeof NegotiationGraphState.State) => {\n const traceEmitter = requestContext.getStore()?.traceEmitter;\n // Local helper to emit events whose shape is wider than the declared\n // `TraceEmitter` union. The chat agent already casts at its relay sink;\n // here we localize the cast at the callsite so the rest of the body stays typed.\n const emitWide = (event: Record<string, unknown>) =>\n (traceEmitter as ((e: Record<string, unknown>) => void) | undefined)?.(event);\n const agentName = \"Index negotiator\";\n const agentStart = Date.now();\n traceEmitter?.({ type: \"agent_start\", name: agentName });\n\n try {\n const history: NegotiationTurn[] = turnsFromMessages(state.messages);\n\n const isSource = state.currentSpeaker === \"source\";\n const ownUser = isSource ? state.sourceUser : state.candidateUser;\n const otherUser = isSource ? state.candidateUser : state.sourceUser;\n\n // Determine if this is the system agent's final allowed turn\n const maxTurns = state.maxTurns ?? 0;\n const isFinalTurn = maxTurns > 0 && (state.turnCount + 1) >= maxTurns;\n\n const payload: NegotiationTurnPayload = {\n negotiationId: state.taskId,\n ownUser,\n otherUser,\n indexContext: state.indexContext,\n seedAssessment: state.seedAssessment,\n history,\n isFinalTurn,\n isDiscoverer: isSource,\n ...(state.discoveryQuery && isSource && { discoveryQuery: state.discoveryQuery }),\n };\n\n const scope = { action: 'manage:negotiations', scopeType: 'network', scopeId: state.indexContext.networkId };\n\n const dispatchResult = await dispatcher.dispatch(ownUser.id, scope, payload, { timeoutMs: state.timeoutMs });\n\n let turn: NegotiationTurn;\n\n if (dispatchResult.handled) {\n // Personal agent responded\n turn = dispatchResult.turn;\n } else if (dispatchResult.reason === 'waiting') {\n // Long timeout — graph suspends. Persist the full turn context so the\n // polling agent (and MCP consumers via get_negotiation) reconstruct\n // the same view the in-process system agent would see. The view is\n // stored in absolute source/candidate terms; perspective is projected\n // at pickup time using the claiming user's id.\n traceEmitter?.({ type: \"agent_end\", name: agentName, durationMs: Date.now() - agentStart, summary: \"waiting_for_agent\" });\n await database.setTaskTurnContext(state.taskId, {\n sourceUser: state.sourceUser,\n candidateUser: state.candidateUser,\n indexContext: state.indexContext,\n seedAssessment: state.seedAssessment,\n // Keep discoveryQuery speaker-scoped: include it only when the\n // parked turn belongs to the discoverer (source). Persisting it on\n // candidate-side turns would make the pickup prompt frame the\n // search as \"your user searched for X\" for the wrong user.\n ...(isSource && state.discoveryQuery && { discoveryQuery: state.discoveryQuery }),\n });\n await database.updateTaskState(state.taskId, \"waiting_for_agent\");\n return { status: 'waiting_for_agent' as const };\n } else {\n // No personal agent or timeout — run system agent\n turn = await systemAgent.invoke({\n ownUser,\n otherUser,\n indexContext: state.indexContext,\n seedAssessment: state.seedAssessment,\n history,\n isFinalTurn,\n isDiscoverer: isSource,\n ...(state.discoveryQuery && isSource && { discoveryQuery: state.discoveryQuery }),\n isContinuation: state.isContinuation,\n ...(state.userAnswers.length > 0 && { userAnswers: state.userAnswers }),\n });\n }\n\n traceEmitter?.({ type: \"agent_end\", name: agentName, durationMs: Date.now() - agentStart, summary: `${turn.action}` });\n\n // First turn must be \"propose\" (unless continuing a prior conversation)\n if (state.turnCount === 0 && !state.isContinuation && turn.action !== \"propose\") {\n logger.warn(\"[Graph:Turn] Agent returned unexpected action on turn 0, forcing to propose\", { action: turn.action });\n turn.action = \"propose\";\n }\n\n const parts = [{ kind: \"data\" as const, data: turn }];\n const message = await database.createMessage({\n conversationId: state.conversationId,\n senderId: `agent:${ownUser.id}`,\n role: \"agent\",\n parts,\n taskId: state.taskId,\n });\n\n await database.updateTaskState(state.taskId, \"working\");\n\n if (state.opportunityId) {\n emitWide({\n type: \"negotiation_turn\",\n opportunityId: state.opportunityId,\n negotiationConversationId: state.conversationId,\n turnIndex: state.turnCount,\n actor: isSource ? \"source\" : \"candidate\",\n action: turn.action,\n ...(turn.assessment?.reasoning && { reasoning: turn.assessment.reasoning }),\n ...(turn.message && { message: turn.message }),\n ...(turn.assessment?.suggestedRoles && { suggestedRoles: turn.assessment.suggestedRoles }),\n durationMs: Date.now() - agentStart,\n });\n }\n\n return {\n messages: [{\n id: message.id,\n senderId: message.senderId,\n role: \"agent\" as const,\n parts: message.parts,\n createdAt: message.createdAt,\n }],\n turnCount: state.turnCount + 1,\n currentSpeaker: (isSource ? \"candidate\" : \"source\") as \"source\" | \"candidate\",\n lastTurn: turn,\n };\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n logger.error(\"[Graph:Turn] Agent invocation failed\", { error: errMsg, stack: err instanceof Error ? err.stack : undefined, turnCount: state.turnCount });\n traceEmitter?.({ type: \"agent_end\", name: agentName, durationMs: Date.now() - agentStart, summary: `error: ${errMsg}` });\n return {\n lastTurn: {\n action: \"reject\" as const,\n assessment: { reasoning: `Agent error: ${errMsg}`, suggestedRoles: { ownUser: \"peer\" as const, otherUser: \"peer\" as const } },\n },\n turnCount: state.turnCount + 1,\n error: `Turn failed: ${errMsg}`,\n };\n }\n };\n\n const evaluateNode = (state: typeof NegotiationGraphState.State): string => {\n if (state.status === 'waiting_for_agent') return \"finalize\";\n if (state.error) return \"finalize\";\n if (!state.lastTurn) return \"finalize\";\n if (state.lastTurn.action === \"accept\") return \"finalize\";\n if (state.lastTurn.action === \"reject\") return \"finalize\";\n // question routes same as counter — next turn\n if ((state.maxTurns ?? 0) > 0 && state.turnCount >= state.maxTurns!) return \"finalize\";\n return \"turn\";\n };\n\n const finalizeNode = async (state: typeof NegotiationGraphState.State) => {\n const traceEmitter = requestContext.getStore()?.traceEmitter;\n const emitWide = (event: Record<string, unknown>) =>\n (traceEmitter as ((e: Record<string, unknown>) => void) | undefined)?.(event);\n\n if (state.status === 'waiting_for_agent') {\n if (state.opportunityId) {\n emitWide({\n type: \"negotiation_outcome\",\n opportunityId: state.opportunityId,\n outcome: \"waiting_for_agent\",\n turnCount: state.turnCount,\n isContinuation: state.isContinuation,\n });\n }\n return {};\n }\n\n const history: NegotiationTurn[] = turnsFromMessages(state.messages);\n\n const lastTurn = state.lastTurn;\n const hasOpportunity = lastTurn?.action === \"accept\";\n const atCap = (state.maxTurns ?? 0) > 0 && state.turnCount >= state.maxTurns! && lastTurn?.action !== \"accept\" && lastTurn?.action !== \"reject\";\n\n let agreedRoles: NegotiationOutcome[\"agreedRoles\"] = [];\n if (hasOpportunity && history.length >= 2) {\n const acceptTurn = history[history.length - 1];\n const precedingTurn = history[history.length - 2];\n const accepterIsSource = state.currentSpeaker === \"candidate\";\n const [sourceRole, candidateRole] = accepterIsSource\n ? [acceptTurn.assessment.suggestedRoles.ownUser, precedingTurn.assessment.suggestedRoles.ownUser]\n : [precedingTurn.assessment.suggestedRoles.ownUser, acceptTurn.assessment.suggestedRoles.ownUser];\n agreedRoles = [\n { userId: state.sourceUser.id, role: sourceRole },\n { userId: state.candidateUser.id, role: candidateRole },\n ];\n }\n\n const outcome: NegotiationOutcome = {\n hasOpportunity,\n agreedRoles,\n reasoning: lastTurn?.assessment.reasoning ?? \"\",\n turnCount: state.turnCount,\n ...(atCap && { reason: \"turn_cap\" as const }),\n };\n\n try {\n await database.updateTaskState(state.taskId, \"completed\");\n await database.createArtifact({\n taskId: state.taskId,\n name: \"negotiation-outcome\",\n parts: [{ kind: \"data\", data: outcome }],\n metadata: { hasOpportunity, turnCount: state.turnCount },\n });\n\n logger.info('[Graph:Finalize] Session complete', {\n conversationId: state.conversationId,\n taskId: state.taskId,\n isContinuation: state.isContinuation,\n turnsAdded: state.turnCount,\n priorTurnCount: state.priorTurnCount,\n outcome: hasOpportunity ? 'accepted' : (atCap ? 'turn_cap' : (lastTurn?.action ?? 'unknown')),\n opportunityId: state.opportunityId || undefined,\n });\n\n if (state.opportunityId) {\n const nextStatus = lastTurn?.action === 'accept'\n ? 'pending'\n : lastTurn?.action === 'reject'\n ? 'rejected'\n : 'stalled';\n await database.updateOpportunityStatus(state.opportunityId, nextStatus).catch((err) => {\n logger.error(\"[Graph:Finalize] Failed to update opportunity status\", { opportunityId: state.opportunityId, nextStatus, error: err });\n });\n }\n } catch (err) {\n logger.error(\"[Graph:Finalize] Failed to persist outcome\", { error: err });\n }\n\n if (state.opportunityId) {\n const emittedOutcome: \"accepted\" | \"rejected_stalled\" | \"turn_cap\" | \"timed_out\" =\n hasOpportunity\n ? \"accepted\"\n : atCap\n ? \"turn_cap\"\n : state.error && /timeout/i.test(state.error)\n ? \"timed_out\"\n : lastTurn?.action === \"reject\"\n ? \"rejected_stalled\"\n : \"rejected_stalled\";\n\n emitWide({\n type: \"negotiation_outcome\",\n opportunityId: state.opportunityId,\n outcome: emittedOutcome,\n turnCount: state.turnCount,\n isContinuation: state.isContinuation,\n turnsAdded: state.turnCount,\n priorTurnCount: state.priorTurnCount,\n ...(outcome.reasoning && { reasoning: outcome.reasoning }),\n ...(hasOpportunity && agreedRoles.length >= 2 && {\n agreedRoles: {\n ownUser: agreedRoles[0]?.role,\n otherUser: agreedRoles[1]?.role,\n },\n }),\n });\n }\n\n // Enqueue question generation for stalled/capped negotiations (not accepted or explicitly rejected).\n // Require turnCount > 0 so early init/turn errors don't enqueue with empty context.\n if (!hasOpportunity && lastTurn?.action !== 'reject' && state.turnCount > 0 && state.opportunityId && questionerEnqueue) {\n const stallReason: 'turn_cap' | 'timeout' | 'stalled' = atCap\n ? 'turn_cap'\n : (state.error && /timeout/i.test(state.error))\n ? 'timeout'\n : 'stalled';\n\n questionerEnqueue({\n mode: 'negotiation',\n userId: state.sourceUser.id,\n sourceType: 'opportunity',\n sourceId: state.opportunityId,\n context: {\n negotiationId: state.taskId,\n counterpartyHint: `${state.candidateUser.profile.name ?? 'Unknown'}${state.candidateUser.profile.bio ? ', ' + state.candidateUser.profile.bio : ''}`,\n indexContext: state.indexContext.prompt,\n outcomeReason: stallReason,\n keyTake: outcome.reasoning,\n userProfile: state.sourceUser.profile,\n },\n }).catch((err) =>\n logger.error('[Graph:Finalize] Failed to enqueue negotiation question generation', {\n opportunityId: state.opportunityId,\n error: err,\n })\n );\n }\n\n return { outcome, status: 'completed' as const };\n };\n\n const workflow = new StateGraph(NegotiationGraphState)\n .addNode(\"init\", initNode)\n .addNode(\"turn\", turnNode)\n .addNode(\"finalize\", finalizeNode)\n .addConditionalEdges(\"turn\", evaluateNode, {\n turn: \"turn\",\n finalize: \"finalize\",\n })\n .addConditionalEdges(\"init\", (state: typeof NegotiationGraphState.State) => {\n return state.error ? \"finalize\" : \"turn\";\n }, { turn: \"turn\", finalize: \"finalize\" })\n .addEdge(\"__start__\", \"init\")\n .addEdge(\"finalize\", \"__end__\");\n\n return workflow.compile();\n }\n}\n\nexport interface NegotiationCandidate {\n userId: string;\n reasoning: string;\n valencyRole: string;\n networkId?: string;\n candidateUser: UserNegotiationContext;\n /** The explicit search query that triggered discovery (if any). */\n discoveryQuery?: string;\n /**\n * ID of the opportunity this negotiation is for. When set, the negotiation\n * graph's finalize node updates the opportunity's status based on the outcome\n * (`accept` → 'pending', `reject` → 'rejected', otherwise → 'stalled').\n */\n opportunityId?: string;\n}\n\nexport interface NegotiationResult {\n userId: string;\n agreedRoles: NegotiationOutcome[\"agreedRoles\"];\n reasoning: string;\n turnCount: number;\n}\n\n/**\n * Per-candidate resolution hook — fires as each negotiation settles, before\n * Promise.all aggregates. Used by the orchestrator branch to progressively\n * stream `opportunity_draft_ready` events as each candidate resolves, rather\n * than emitting all at once after the full fan-out completes. Awaited so the\n * caller can run async work (DB update, event emit) before the next settle.\n *\n * `turns` and `outcome` are passed through from the underlying negotiation\n * graph so consumers can build per-candidate decision-question inputs without\n * re-walking trace events or DB artifacts. Both are present on every\n * resolution (accepted, rejected, stalled, error); error paths receive a\n * synthesized `outcome` with `hasOpportunity: false`.\n */\nexport type OnNegotiationResolved = (entry: {\n candidate: NegotiationCandidate;\n accepted: NegotiationResult | null;\n turns: NegotiationTurn[];\n outcome: NegotiationOutcome;\n}) => Promise<void>;\n\n/**\n * Runs bilateral negotiation for each candidate in parallel.\n * @returns Only candidates that produced an opportunity\n */\nexport async function negotiateCandidates(\n negotiationGraph: NegotiationGraphLike,\n sourceUser: UserNegotiationContext,\n candidates: NegotiationCandidate[],\n indexContext: { networkId: string; prompt: string },\n opts?: {\n maxTurns?: number;\n traceEmitter?: TraceEmitter;\n indexContextOverrides?: Map<string, string>;\n timeoutMs?: number;\n onCandidateResolved?: OnNegotiationResolved;\n trigger?: \"orchestrator\" | \"ambient\";\n },\n): Promise<NegotiationResult[]> {\n const { maxTurns, traceEmitter, indexContextOverrides, timeoutMs, onCandidateResolved, trigger } = opts ?? {};\n\n // Local helper to emit events whose shape is wider than the declared\n // `TraceEmitter` union (mirrors the cast used in chat.agent at the relay sink\n // and inside turn/finalize nodes above).\n const emitWide = (event: Record<string, unknown>) =>\n (traceEmitter as ((e: Record<string, unknown>) => void) | undefined)?.(event);\n\n const results = await Promise.all(\n candidates.map(async (candidate) => {\n const start = Date.now();\n if (candidate.opportunityId) {\n const candidateName = candidate.candidateUser?.profile?.name;\n emitWide({\n type: \"negotiation_session_start\",\n opportunityId: candidate.opportunityId,\n negotiationConversationId: \"\", // filled in on session_end\n sourceUserId: sourceUser.id,\n candidateUserId: candidate.userId,\n ...(candidateName && { candidateName }),\n trigger: trigger ?? \"ambient\",\n startedAt: start,\n });\n }\n traceEmitter?.({ type: \"agent_start\", name: \"Negotiating candidate\" });\n\n try {\n const candidateIndexContext = candidate.networkId\n ? { networkId: candidate.networkId, prompt: indexContextOverrides?.get(candidate.networkId) ?? '' }\n : indexContext;\n\n const result = await invokeWithAbortSignal(negotiationGraph, {\n sourceUser,\n candidateUser: candidate.candidateUser,\n indexContext: candidateIndexContext,\n seedAssessment: {\n reasoning: candidate.reasoning,\n valencyRole: candidate.valencyRole,\n },\n ...(candidate.discoveryQuery && { discoveryQuery: candidate.discoveryQuery }),\n ...(candidate.opportunityId && { opportunityId: candidate.opportunityId }),\n ...(maxTurns !== undefined && { maxTurns }),\n ...(timeoutMs !== undefined && { timeoutMs }),\n });\n\n const durationMs = Date.now() - start;\n const outcome = result.outcome;\n const hasOpportunity = outcome?.hasOpportunity === true;\n const isContinuation = (result as { isContinuation?: boolean }).isContinuation ?? false;\n const priorTurnCount = (result as { priorTurnCount?: number }).priorTurnCount ?? 0;\n\n const turnFlow = (result.messages ?? [])\n .map((m) => {\n const dataPart = (m.parts as Array<{ kind?: string; data?: Record<string, unknown> }>)?.find((p) => p.kind === \"data\");\n if (!dataPart?.data) return null;\n const turn = dataPart.data as { action?: string };\n return turn.action ?? \"unknown\";\n })\n .filter(Boolean)\n .join(\" → \");\n\n const statusTag = hasOpportunity ? \"✓ opportunity\" : \"✗ rejected\";\n traceEmitter?.({ type: \"agent_end\", name: \"Negotiating candidate\", durationMs, summary: `${candidate.userId}: ${turnFlow} ${statusTag}` });\n\n if (candidate.opportunityId) {\n emitWide({\n type: \"negotiation_session_end\",\n opportunityId: candidate.opportunityId,\n negotiationConversationId: (result as { conversationId?: string }).conversationId ?? \"\",\n durationMs: Date.now() - start,\n isContinuation,\n turnsAdded: outcome?.turnCount ?? 0,\n priorTurnCount,\n });\n }\n\n const accepted: NegotiationResult | null = hasOpportunity && outcome\n ? {\n userId: candidate.userId,\n agreedRoles: outcome.agreedRoles,\n reasoning: outcome.reasoning,\n turnCount: outcome.turnCount,\n }\n : null;\n\n if (onCandidateResolved) {\n const turnHistory: NegotiationTurn[] = turnsFromMessages(result.messages ?? []);\n const resolvedOutcome: NegotiationOutcome = result.outcome ?? {\n hasOpportunity: false,\n agreedRoles: [],\n reasoning: \"no outcome returned by negotiation graph\",\n turnCount: turnHistory.length,\n };\n try {\n await onCandidateResolved({\n candidate,\n accepted,\n turns: turnHistory,\n outcome: resolvedOutcome,\n });\n } catch (hookErr) {\n // Hook failures must not sink the candidate result — the aggregate\n // return is still useful, and the orchestrator branch logs its own\n // failures inline.\n logger.error(\"[negotiateCandidates] onCandidateResolved hook threw\", {\n candidateUserId: candidate.userId,\n error: hookErr,\n });\n }\n }\n\n return accepted;\n } catch (err) {\n const durationMs = Date.now() - start;\n traceEmitter?.({ type: \"agent_end\", name: \"Negotiating candidate\", durationMs, summary: `${candidate.userId}: error` });\n if (candidate.opportunityId) {\n emitWide({\n type: \"negotiation_session_end\",\n opportunityId: candidate.opportunityId,\n negotiationConversationId: \"\",\n durationMs: Date.now() - start,\n });\n }\n logger.error(\"[negotiateCandidates] Negotiation failed\", { candidateUserId: candidate.userId, error: err });\n if (onCandidateResolved) {\n try {\n await onCandidateResolved({\n candidate,\n accepted: null,\n turns: [],\n outcome: {\n hasOpportunity: false,\n agreedRoles: [],\n reasoning: err instanceof Error ? err.message : String(err),\n turnCount: 0,\n },\n });\n } catch {\n // ignore hook failure on error path\n }\n }\n return null;\n }\n }),\n );\n\n return results.filter((r): r is NegotiationResult => r !== null);\n}\n\n/**\n * Creates a negotiation graph with the provided dependencies.\n */\nexport function createDefaultNegotiationGraph(deps: {\n database: NegotiationGraphDatabase;\n dispatcher: AgentDispatcher;\n timeoutQueue?: NegotiationTimeoutQueue;\n}) {\n const factory = new NegotiationGraphFactory(deps.database, deps.dispatcher, deps.timeoutQueue);\n return factory.createGraph();\n}\n"]}
1
+ {"version":3,"file":"negotiation.graph.js","sourceRoot":"/","sources":["negotiation/negotiation.graph.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAElD,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AACxE,OAAO,EAAE,cAAc,EAAqB,MAAM,4CAA4C,CAAC;AAI/F,OAAO,EAAE,qBAAqB,EAA8H,MAAM,wBAAwB,CAAC;AAC3L,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAG5E,MAAM,MAAM,GAAG,cAAc,CAAC,kBAAkB,CAAC,CAAC;AAElD,6EAA6E;AAC7E,SAAS,iBAAiB,CAAC,QAAqC;IAC9D,OAAO,QAAQ;SACZ,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE;QACT,MAAM,QAAQ,GAAI,CAAC,CAAC,KAAkD,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC;QACtG,OAAO,QAAQ,EAAE,IAAuB,CAAC;IAC3C,CAAC,CAAC;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T,QAAQ,EAAE,IAAI;wBACd,KAAK,EAAE,EAAE;wBACT,OAAO,EAAE;4BACP,cAAc,EAAE,KAAK;4BACrB,WAAW,EAAE,EAAE;4BACf,SAAS,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC;4BAC3D,SAAS,EAAE,CAAC;yBACb;qBACF,CAAC,CAAC;gBACL,CAAC;gBAAC,MAAM,CAAC;oBACP,oCAAoC;gBACtC,CAAC;YACH,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC,CAAC,CACH,CAAC;IAEF,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAA0B,EAAE,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC;AACnE,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,6BAA6B,CAAC,IAI7C;IACC,MAAM,OAAO,GAAG,IAAI,uBAAuB,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;IAC/F,OAAO,OAAO,CAAC,WAAW,EAAE,CAAC;AAC/B,CAAC","sourcesContent":["import { StateGraph } from \"@langchain/langgraph\";\n\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\nimport { requestContext, type TraceEmitter } from \"../shared/observability/request-context.js\";\nimport type { NegotiationGraphDatabase } from \"../shared/interfaces/database.interface.js\";\nimport type { NegotiationTimeoutQueue } from \"../shared/interfaces/negotiation-events.interface.js\";\nimport type { AgentDispatcher, NegotiationTurnPayload } from \"../shared/interfaces/agent-dispatcher.interface.js\";\nimport { NegotiationGraphState, type NegotiationTurn, type NegotiationOutcome, type UserNegotiationContext, type SeedAssessment, type NegotiationGraphLike } from \"./negotiation.state.js\";\nimport { IndexNegotiator } from \"./negotiation.agent.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport type { QuestionerEnqueueFn } from \"../questioner/questioner.types.js\";\n\nconst logger = protocolLogger(\"NegotiationGraph\");\n\n/** Extracts the ordered NegotiationTurn list from A2A message data parts. */\nfunction turnsFromMessages(messages: Array<{ parts: unknown[] }>): NegotiationTurn[] {\n return messages\n .map((m) => {\n const dataPart = (m.parts as Array<{ kind?: string; data?: unknown }>).find((p) => p.kind === \"data\");\n return dataPart?.data as NegotiationTurn;\n })\n .filter(Boolean);\n}\n\n/**\n * Factory for the bilateral negotiation LangGraph state machine.\n * @remarks Accepts an AgentDispatcher for per-turn agent resolution.\n */\nexport class NegotiationGraphFactory {\n constructor(\n private database: NegotiationGraphDatabase,\n private dispatcher: AgentDispatcher,\n private timeoutQueue?: NegotiationTimeoutQueue,\n private questionerEnqueue?: QuestionerEnqueueFn,\n ) {}\n\n createGraph() {\n const { database, dispatcher, timeoutQueue, questionerEnqueue } = this;\n const systemAgent = new IndexNegotiator();\n\n const initNode = async (state: typeof NegotiationGraphState.State) => {\n try {\n // Find-or-create the DM conversation for this agent pair (same as user DMs)\n const agentIdA = `agent:${state.sourceUser.id}`;\n const agentIdB = `agent:${state.candidateUser.id}`;\n const conversation = await database.getOrCreateDM(agentIdA, agentIdB, 'agent');\n\n // --- Lock gate: check for an active task on this conversation ---\n const priorMessages = await database.getMessagesForConversation(conversation.id);\n\n let isLocked = false;\n if (state.opportunityId) {\n const priorTask = await database.getNegotiationTaskForOpportunity(state.opportunityId);\n if (priorTask) {\n const activeStates = ['submitted', 'working', 'input_required', 'waiting_for_agent', 'claimed'];\n const isFresh = (Date.now() - new Date(priorTask.updatedAt).getTime()) < 5 * 60 * 1000;\n if (activeStates.includes(priorTask.state) && isFresh) {\n isLocked = true;\n }\n }\n }\n\n if (isLocked) {\n logger.info('[Graph:Init] Conversation locked by active task, returning busy', {\n conversationId: conversation.id,\n opportunityId: state.opportunityId,\n });\n return { error: 'busy' };\n }\n\n // --- Load prior messages and determine continuation ---\n const priorTurns: NegotiationTurn[] = turnsFromMessages(priorMessages);\n\n const isContinuation = priorTurns.length > 0;\n\n // Determine currentSpeaker from last prior message\n let currentSpeaker: 'source' | 'candidate' = 'source';\n if (isContinuation && priorMessages.length > 0) {\n const lastSender = priorMessages[priorMessages.length - 1].senderId;\n currentSpeaker = lastSender === agentIdA ? 'candidate' : 'source';\n }\n\n // Determine scenario-based maxTurns\n const scope = { action: 'manage:negotiations', scopeType: 'network', scopeId: state.indexContext.networkId };\n const [sourceHasAgent, candidateHasAgent] = await Promise.all([\n dispatcher.hasPersonalAgent(state.sourceUser.id, scope),\n dispatcher.hasPersonalAgent(state.candidateUser.id, scope),\n ]);\n\n const ambientMax = Number(process.env.NEGOTIATION_MAX_TURNS_AMBIENT) || 6;\n let maxTurns = state.maxTurns;\n if (maxTurns == null) {\n maxTurns = (sourceHasAgent && candidateHasAgent) ? 0 : ambientMax;\n }\n\n const task = await database.createTask(conversation.id, {\n type: 'negotiation',\n sourceUserId: state.sourceUser.id,\n candidateUserId: state.candidateUser.id,\n networkId: state.indexContext.networkId,\n ...(state.opportunityId && { opportunityId: state.opportunityId }),\n maxTurns,\n isContinuation,\n priorTurnCount: priorTurns.length,\n });\n\n if (state.opportunityId) {\n await database.updateOpportunityStatus(state.opportunityId, 'negotiating').catch((err) => {\n logger.error('[Graph:Init] Failed to set opportunity status to negotiating', { opportunityId: state.opportunityId, error: err });\n });\n }\n\n // Load user answers collected by the questioner between sessions\n const userAnswers = (isContinuation && state.opportunityId)\n ? await database.getOpportunityUserAnswers(state.opportunityId).catch((err) => {\n logger.error('[Graph:Init] Failed to load user answers', { opportunityId: state.opportunityId, error: err });\n return [];\n })\n : [];\n\n // Seed messages with prior turns (additive reducer appends new turns on top)\n const seedMessages = isContinuation ? priorMessages.map((m) => ({\n id: m.id,\n senderId: m.senderId,\n role: 'agent' as const,\n parts: m.parts,\n createdAt: m.createdAt,\n })) : [];\n\n return {\n conversationId: conversation.id,\n taskId: task.id,\n currentSpeaker,\n turnCount: 0,\n maxTurns,\n isContinuation,\n priorTurnCount: priorTurns.length,\n ...(userAnswers.length > 0 && { userAnswers }),\n ...(seedMessages.length > 0 && { messages: seedMessages }),\n };\n } catch (err) {\n return { error: `Init failed: ${err instanceof Error ? err.message : String(err)}` };\n }\n };\n\n const turnNode = async (state: typeof NegotiationGraphState.State) => {\n const traceEmitter = requestContext.getStore()?.traceEmitter;\n // Local helper to emit events whose shape is wider than the declared\n // `TraceEmitter` union. The chat agent already casts at its relay sink;\n // here we localize the cast at the callsite so the rest of the body stays typed.\n const emitWide = (event: Record<string, unknown>) =>\n (traceEmitter as ((e: Record<string, unknown>) => void) | undefined)?.(event);\n const agentName = \"Index negotiator\";\n const agentStart = Date.now();\n traceEmitter?.({ type: \"agent_start\", name: agentName });\n\n try {\n const history: NegotiationTurn[] = turnsFromMessages(state.messages);\n\n const isSource = state.currentSpeaker === \"source\";\n const ownUser = isSource ? state.sourceUser : state.candidateUser;\n const otherUser = isSource ? state.candidateUser : state.sourceUser;\n\n // Determine if this is the system agent's final allowed turn\n const maxTurns = state.maxTurns ?? 0;\n const isFinalTurn = maxTurns > 0 && (state.turnCount + 1) >= maxTurns;\n\n const payload: NegotiationTurnPayload = {\n negotiationId: state.taskId,\n ownUser,\n otherUser,\n indexContext: state.indexContext,\n seedAssessment: state.seedAssessment,\n history,\n isFinalTurn,\n isDiscoverer: isSource,\n ...(state.discoveryQuery && isSource && { discoveryQuery: state.discoveryQuery }),\n };\n\n const scope = { action: 'manage:negotiations', scopeType: 'network', scopeId: state.indexContext.networkId };\n\n const dispatchResult = await dispatcher.dispatch(ownUser.id, scope, payload, { timeoutMs: state.timeoutMs });\n\n let turn: NegotiationTurn;\n\n if (dispatchResult.handled) {\n // Personal agent responded\n turn = dispatchResult.turn;\n } else if (dispatchResult.reason === 'waiting') {\n // Long timeout — graph suspends. Persist the full turn context so the\n // polling agent (and MCP consumers via get_negotiation) reconstruct\n // the same view the in-process system agent would see. The view is\n // stored in absolute source/candidate terms; perspective is projected\n // at pickup time using the claiming user's id.\n traceEmitter?.({ type: \"agent_end\", name: agentName, durationMs: Date.now() - agentStart, summary: \"waiting_for_agent\" });\n await database.setTaskTurnContext(state.taskId, {\n sourceUser: state.sourceUser,\n candidateUser: state.candidateUser,\n indexContext: state.indexContext,\n seedAssessment: state.seedAssessment,\n // Keep discoveryQuery speaker-scoped: include it only when the\n // parked turn belongs to the discoverer (source). Persisting it on\n // candidate-side turns would make the pickup prompt frame the\n // search as \"your user searched for X\" for the wrong user.\n ...(isSource && state.discoveryQuery && { discoveryQuery: state.discoveryQuery }),\n });\n await database.updateTaskState(state.taskId, \"waiting_for_agent\");\n return { status: 'waiting_for_agent' as const };\n } else {\n // No personal agent or timeout — run system agent\n turn = await systemAgent.invoke({\n ownUser,\n otherUser,\n indexContext: state.indexContext,\n seedAssessment: state.seedAssessment,\n history,\n isFinalTurn,\n isDiscoverer: isSource,\n ...(state.discoveryQuery && isSource && { discoveryQuery: state.discoveryQuery }),\n isContinuation: state.isContinuation,\n ...(state.userAnswers.length > 0 && { userAnswers: state.userAnswers }),\n });\n }\n\n traceEmitter?.({ type: \"agent_end\", name: agentName, durationMs: Date.now() - agentStart, summary: `${turn.action}` });\n\n // First turn must be \"propose\" (unless continuing a prior conversation)\n if (state.turnCount === 0 && !state.isContinuation && turn.action !== \"propose\") {\n logger.warn(\"[Graph:Turn] Agent returned unexpected action on turn 0, forcing to propose\", { action: turn.action });\n turn.action = \"propose\";\n }\n\n const parts = [{ kind: \"data\" as const, data: turn }];\n const message = await database.createMessage({\n conversationId: state.conversationId,\n senderId: `agent:${ownUser.id}`,\n role: \"agent\",\n parts,\n taskId: state.taskId,\n });\n\n await database.updateTaskState(state.taskId, \"working\");\n\n if (state.opportunityId) {\n emitWide({\n type: \"negotiation_turn\",\n opportunityId: state.opportunityId,\n negotiationConversationId: state.conversationId,\n turnIndex: state.turnCount,\n actor: isSource ? \"source\" : \"candidate\",\n action: turn.action,\n ...(turn.assessment?.reasoning && { reasoning: turn.assessment.reasoning }),\n ...(turn.message && { message: turn.message }),\n ...(turn.assessment?.suggestedRoles && { suggestedRoles: turn.assessment.suggestedRoles }),\n durationMs: Date.now() - agentStart,\n });\n }\n\n return {\n messages: [{\n id: message.id,\n senderId: message.senderId,\n role: \"agent\" as const,\n parts: message.parts,\n createdAt: message.createdAt,\n }],\n turnCount: state.turnCount + 1,\n currentSpeaker: (isSource ? \"candidate\" : \"source\") as \"source\" | \"candidate\",\n lastTurn: turn,\n };\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n logger.error(\"[Graph:Turn] Agent invocation failed\", { error: errMsg, stack: err instanceof Error ? err.stack : undefined, turnCount: state.turnCount });\n traceEmitter?.({ type: \"agent_end\", name: agentName, durationMs: Date.now() - agentStart, summary: `error: ${errMsg}` });\n return {\n lastTurn: {\n action: \"reject\" as const,\n assessment: { reasoning: `Agent error: ${errMsg}`, suggestedRoles: { ownUser: \"peer\" as const, otherUser: \"peer\" as const } },\n },\n turnCount: state.turnCount + 1,\n error: `Turn failed: ${errMsg}`,\n };\n }\n };\n\n const evaluateNode = (state: typeof NegotiationGraphState.State): string => {\n if (state.status === 'waiting_for_agent') return \"finalize\";\n if (state.error) return \"finalize\";\n if (!state.lastTurn) return \"finalize\";\n if (state.lastTurn.action === \"accept\") return \"finalize\";\n if (state.lastTurn.action === \"reject\") return \"finalize\";\n // question routes same as counter — next turn\n if ((state.maxTurns ?? 0) > 0 && state.turnCount >= state.maxTurns!) return \"finalize\";\n return \"turn\";\n };\n\n const finalizeNode = async (state: typeof NegotiationGraphState.State) => {\n const traceEmitter = requestContext.getStore()?.traceEmitter;\n const emitWide = (event: Record<string, unknown>) =>\n (traceEmitter as ((e: Record<string, unknown>) => void) | undefined)?.(event);\n\n if (state.status === 'waiting_for_agent') {\n if (state.opportunityId) {\n emitWide({\n type: \"negotiation_outcome\",\n opportunityId: state.opportunityId,\n outcome: \"waiting_for_agent\",\n turnCount: state.turnCount,\n isContinuation: state.isContinuation,\n });\n }\n return {};\n }\n\n const history: NegotiationTurn[] = turnsFromMessages(state.messages);\n\n const lastTurn = state.lastTurn;\n const hasOpportunity = lastTurn?.action === \"accept\";\n const atCap = (state.maxTurns ?? 0) > 0 && state.turnCount >= state.maxTurns! && lastTurn?.action !== \"accept\" && lastTurn?.action !== \"reject\";\n\n let agreedRoles: NegotiationOutcome[\"agreedRoles\"] = [];\n if (hasOpportunity && history.length >= 2) {\n const acceptTurn = history[history.length - 1];\n const precedingTurn = history[history.length - 2];\n const accepterIsSource = state.currentSpeaker === \"candidate\";\n const [sourceRole, candidateRole] = accepterIsSource\n ? [acceptTurn.assessment.suggestedRoles.ownUser, precedingTurn.assessment.suggestedRoles.ownUser]\n : [precedingTurn.assessment.suggestedRoles.ownUser, acceptTurn.assessment.suggestedRoles.ownUser];\n agreedRoles = [\n { userId: state.sourceUser.id, role: sourceRole },\n { userId: state.candidateUser.id, role: candidateRole },\n ];\n }\n\n const outcome: NegotiationOutcome = {\n hasOpportunity,\n agreedRoles,\n reasoning: lastTurn?.assessment.reasoning ?? \"\",\n turnCount: state.turnCount,\n ...(atCap && { reason: \"turn_cap\" as const }),\n };\n\n try {\n await database.updateTaskState(state.taskId, \"completed\");\n await database.createArtifact({\n taskId: state.taskId,\n name: \"negotiation-outcome\",\n parts: [{ kind: \"data\", data: outcome }],\n metadata: { hasOpportunity, turnCount: state.turnCount },\n });\n\n logger.info('[Graph:Finalize] Session complete', {\n conversationId: state.conversationId,\n taskId: state.taskId,\n isContinuation: state.isContinuation,\n turnsAdded: state.turnCount,\n priorTurnCount: state.priorTurnCount,\n outcome: hasOpportunity ? 'accepted' : (atCap ? 'turn_cap' : (lastTurn?.action ?? 'unknown')),\n opportunityId: state.opportunityId || undefined,\n });\n\n if (state.opportunityId) {\n const nextStatus = lastTurn?.action === 'accept'\n ? 'pending'\n : lastTurn?.action === 'reject'\n ? 'rejected'\n : 'stalled';\n await database.updateOpportunityStatus(state.opportunityId, nextStatus).catch((err) => {\n logger.error(\"[Graph:Finalize] Failed to update opportunity status\", { opportunityId: state.opportunityId, nextStatus, error: err });\n });\n }\n } catch (err) {\n logger.error(\"[Graph:Finalize] Failed to persist outcome\", { error: err });\n }\n\n if (state.opportunityId) {\n const emittedOutcome: \"accepted\" | \"rejected_stalled\" | \"turn_cap\" | \"timed_out\" =\n hasOpportunity\n ? \"accepted\"\n : atCap\n ? \"turn_cap\"\n : state.error && /timeout/i.test(state.error)\n ? \"timed_out\"\n : lastTurn?.action === \"reject\"\n ? \"rejected_stalled\"\n : \"rejected_stalled\";\n\n emitWide({\n type: \"negotiation_outcome\",\n opportunityId: state.opportunityId,\n outcome: emittedOutcome,\n turnCount: state.turnCount,\n isContinuation: state.isContinuation,\n turnsAdded: state.turnCount,\n priorTurnCount: state.priorTurnCount,\n ...(outcome.reasoning && { reasoning: outcome.reasoning }),\n ...(hasOpportunity && agreedRoles.length >= 2 && {\n agreedRoles: {\n ownUser: agreedRoles[0]?.role,\n otherUser: agreedRoles[1]?.role,\n },\n }),\n });\n }\n\n // Enqueue question generation for stalled/capped negotiations (not accepted or explicitly rejected).\n // Require turnCount > 0 so early init/turn errors don't enqueue with empty context.\n if (!hasOpportunity && lastTurn?.action !== 'reject' && state.turnCount > 0 && state.opportunityId && questionerEnqueue) {\n const stallReason: 'turn_cap' | 'timeout' | 'stalled' = atCap\n ? 'turn_cap'\n : (state.error && /timeout/i.test(state.error))\n ? 'timeout'\n : 'stalled';\n\n const userContext = (await database.getUserContext(state.sourceUser.id, null))?.text ?? '';\n questionerEnqueue({\n mode: 'negotiation',\n userId: state.sourceUser.id,\n sourceType: 'opportunity',\n sourceId: state.opportunityId,\n context: {\n negotiationId: state.taskId,\n counterpartyHint: `${state.candidateUser.profile.name ?? 'Unknown'}${state.candidateUser.profile.bio ? ', ' + state.candidateUser.profile.bio : ''}`,\n indexContext: state.indexContext.prompt,\n outcomeReason: stallReason,\n keyTake: outcome.reasoning,\n userContext,\n },\n }).catch((err) =>\n logger.error('[Graph:Finalize] Failed to enqueue negotiation question generation', {\n opportunityId: state.opportunityId,\n error: err,\n })\n );\n }\n\n return { outcome, status: 'completed' as const };\n };\n\n const workflow = new StateGraph(NegotiationGraphState)\n .addNode(\"init\", initNode)\n .addNode(\"turn\", turnNode)\n .addNode(\"finalize\", finalizeNode)\n .addConditionalEdges(\"turn\", evaluateNode, {\n turn: \"turn\",\n finalize: \"finalize\",\n })\n .addConditionalEdges(\"init\", (state: typeof NegotiationGraphState.State) => {\n return state.error ? \"finalize\" : \"turn\";\n }, { turn: \"turn\", finalize: \"finalize\" })\n .addEdge(\"__start__\", \"init\")\n .addEdge(\"finalize\", \"__end__\");\n\n return workflow.compile();\n }\n}\n\nexport interface NegotiationCandidate {\n userId: string;\n reasoning: string;\n valencyRole: string;\n networkId?: string;\n candidateUser: UserNegotiationContext;\n /** The explicit search query that triggered discovery (if any). */\n discoveryQuery?: string;\n /**\n * ID of the opportunity this negotiation is for. When set, the negotiation\n * graph's finalize node updates the opportunity's status based on the outcome\n * (`accept` → 'pending', `reject` → 'rejected', otherwise → 'stalled').\n */\n opportunityId?: string;\n}\n\nexport interface NegotiationResult {\n userId: string;\n agreedRoles: NegotiationOutcome[\"agreedRoles\"];\n reasoning: string;\n turnCount: number;\n}\n\n/**\n * Per-candidate resolution hook — fires as each negotiation settles, before\n * Promise.all aggregates. Used by the orchestrator branch to progressively\n * stream `opportunity_draft_ready` events as each candidate resolves, rather\n * than emitting all at once after the full fan-out completes. Awaited so the\n * caller can run async work (DB update, event emit) before the next settle.\n *\n * `turns` and `outcome` are passed through from the underlying negotiation\n * graph so consumers can build per-candidate decision-question inputs without\n * re-walking trace events or DB artifacts. Both are present on every\n * resolution (accepted, rejected, stalled, error); error paths receive a\n * synthesized `outcome` with `hasOpportunity: false`.\n */\nexport type OnNegotiationResolved = (entry: {\n candidate: NegotiationCandidate;\n accepted: NegotiationResult | null;\n turns: NegotiationTurn[];\n outcome: NegotiationOutcome;\n}) => Promise<void>;\n\n/**\n * Runs bilateral negotiation for each candidate in parallel.\n * @returns Only candidates that produced an opportunity\n */\nexport async function negotiateCandidates(\n negotiationGraph: NegotiationGraphLike,\n sourceUser: UserNegotiationContext,\n candidates: NegotiationCandidate[],\n indexContext: { networkId: string; prompt: string },\n opts?: {\n maxTurns?: number;\n traceEmitter?: TraceEmitter;\n indexContextOverrides?: Map<string, string>;\n timeoutMs?: number;\n onCandidateResolved?: OnNegotiationResolved;\n trigger?: \"orchestrator\" | \"ambient\";\n },\n): Promise<NegotiationResult[]> {\n const { maxTurns, traceEmitter, indexContextOverrides, timeoutMs, onCandidateResolved, trigger } = opts ?? {};\n\n // Local helper to emit events whose shape is wider than the declared\n // `TraceEmitter` union (mirrors the cast used in chat.agent at the relay sink\n // and inside turn/finalize nodes above).\n const emitWide = (event: Record<string, unknown>) =>\n (traceEmitter as ((e: Record<string, unknown>) => void) | undefined)?.(event);\n\n const results = await Promise.all(\n candidates.map(async (candidate) => {\n const start = Date.now();\n if (candidate.opportunityId) {\n const candidateName = candidate.candidateUser?.profile?.name;\n emitWide({\n type: \"negotiation_session_start\",\n opportunityId: candidate.opportunityId,\n negotiationConversationId: \"\", // filled in on session_end\n sourceUserId: sourceUser.id,\n candidateUserId: candidate.userId,\n ...(candidateName && { candidateName }),\n trigger: trigger ?? \"ambient\",\n startedAt: start,\n });\n }\n traceEmitter?.({ type: \"agent_start\", name: \"Negotiating candidate\" });\n\n try {\n const candidateIndexContext = candidate.networkId\n ? { networkId: candidate.networkId, prompt: indexContextOverrides?.get(candidate.networkId) ?? '' }\n : indexContext;\n\n const result = await invokeWithAbortSignal(negotiationGraph, {\n sourceUser,\n candidateUser: candidate.candidateUser,\n indexContext: candidateIndexContext,\n seedAssessment: {\n reasoning: candidate.reasoning,\n valencyRole: candidate.valencyRole,\n },\n ...(candidate.discoveryQuery && { discoveryQuery: candidate.discoveryQuery }),\n ...(candidate.opportunityId && { opportunityId: candidate.opportunityId }),\n ...(maxTurns !== undefined && { maxTurns }),\n ...(timeoutMs !== undefined && { timeoutMs }),\n });\n\n const durationMs = Date.now() - start;\n const outcome = result.outcome;\n const hasOpportunity = outcome?.hasOpportunity === true;\n const isContinuation = (result as { isContinuation?: boolean }).isContinuation ?? false;\n const priorTurnCount = (result as { priorTurnCount?: number }).priorTurnCount ?? 0;\n\n const turnFlow = (result.messages ?? [])\n .map((m) => {\n const dataPart = (m.parts as Array<{ kind?: string; data?: Record<string, unknown> }>)?.find((p) => p.kind === \"data\");\n if (!dataPart?.data) return null;\n const turn = dataPart.data as { action?: string };\n return turn.action ?? \"unknown\";\n })\n .filter(Boolean)\n .join(\" → \");\n\n const statusTag = hasOpportunity ? \"✓ opportunity\" : \"✗ rejected\";\n traceEmitter?.({ type: \"agent_end\", name: \"Negotiating candidate\", durationMs, summary: `${candidate.userId}: ${turnFlow} ${statusTag}` });\n\n if (candidate.opportunityId) {\n emitWide({\n type: \"negotiation_session_end\",\n opportunityId: candidate.opportunityId,\n negotiationConversationId: (result as { conversationId?: string }).conversationId ?? \"\",\n durationMs: Date.now() - start,\n isContinuation,\n turnsAdded: outcome?.turnCount ?? 0,\n priorTurnCount,\n });\n }\n\n const accepted: NegotiationResult | null = hasOpportunity && outcome\n ? {\n userId: candidate.userId,\n agreedRoles: outcome.agreedRoles,\n reasoning: outcome.reasoning,\n turnCount: outcome.turnCount,\n }\n : null;\n\n if (onCandidateResolved) {\n const turnHistory: NegotiationTurn[] = turnsFromMessages(result.messages ?? []);\n const resolvedOutcome: NegotiationOutcome = result.outcome ?? {\n hasOpportunity: false,\n agreedRoles: [],\n reasoning: \"no outcome returned by negotiation graph\",\n turnCount: turnHistory.length,\n };\n try {\n await onCandidateResolved({\n candidate,\n accepted,\n turns: turnHistory,\n outcome: resolvedOutcome,\n });\n } catch (hookErr) {\n // Hook failures must not sink the candidate result — the aggregate\n // return is still useful, and the orchestrator branch logs its own\n // failures inline.\n logger.error(\"[negotiateCandidates] onCandidateResolved hook threw\", {\n candidateUserId: candidate.userId,\n error: hookErr,\n });\n }\n }\n\n return accepted;\n } catch (err) {\n const durationMs = Date.now() - start;\n traceEmitter?.({ type: \"agent_end\", name: \"Negotiating candidate\", durationMs, summary: `${candidate.userId}: error` });\n if (candidate.opportunityId) {\n emitWide({\n type: \"negotiation_session_end\",\n opportunityId: candidate.opportunityId,\n negotiationConversationId: \"\",\n durationMs: Date.now() - start,\n });\n }\n logger.error(\"[negotiateCandidates] Negotiation failed\", { candidateUserId: candidate.userId, error: err });\n if (onCandidateResolved) {\n try {\n await onCandidateResolved({\n candidate,\n accepted: null,\n turns: [],\n outcome: {\n hasOpportunity: false,\n agreedRoles: [],\n reasoning: err instanceof Error ? err.message : String(err),\n turnCount: 0,\n },\n });\n } catch {\n // ignore hook failure on error path\n }\n }\n return null;\n }\n }),\n );\n\n return results.filter((r): r is NegotiationResult => r !== null);\n}\n\n/**\n * Creates a negotiation graph with the provided dependencies.\n */\nexport function createDefaultNegotiationGraph(deps: {\n database: NegotiationGraphDatabase;\n dispatcher: AgentDispatcher;\n timeoutQueue?: NegotiationTimeoutQueue;\n}) {\n const factory = new NegotiationGraphFactory(deps.database, deps.dispatcher, deps.timeoutQueue);\n return factory.createGraph();\n}\n"]}
@@ -10,18 +10,13 @@ export declare const NetworkRecommenderOutputSchema: z.ZodObject<{
10
10
  rankedNetworkIds: string[];
11
11
  }>;
12
12
  export type NetworkRecommenderOutput = z.infer<typeof NetworkRecommenderOutputSchema>;
13
- export interface NetworkRecommenderUserProfile {
14
- bio: string;
15
- location: string;
16
- interests: string[];
17
- skills: string[];
18
- }
19
13
  export interface NetworkRecommenderNetwork {
20
14
  networkId: string;
21
15
  renderedContext: string;
22
16
  }
23
17
  export interface NetworkRecommenderInput {
24
- userProfile: NetworkRecommenderUserProfile;
18
+ /** The user's global user_context paragraph (profile-replacing identity text). */
19
+ userContext: string;
25
20
  networks: NetworkRecommenderNetwork[];
26
21
  }
27
22
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"network.recommender.d.ts","sourceRoot":"/","sources":["network/network.recommender.ts"],"names":[],"mappings":"AAEA,OAAO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,OAAO,CAAC,KAAK,CAAiD;;IAS9D;;;;;OAKG;IAEU,MAAM,CAAC,KAAK,EAAE,uBAAuB,GAAG,OAAO,CAAC,wBAAwB,GAAG,IAAI,CAAC;CAoC9F"}
@@ -33,7 +33,7 @@ Given a user's profile and a list of communities, rank the communities from most
33
33
  Return ALL provided community IDs in ranked order.
34
34
 
35
35
  INPUTS:
36
- 1. User Profile: bio, location, interests, and skills.
36
+ 1. User Context: a synthesized paragraph describing the user (background, interests, skills, location, goals).
37
37
  2. Communities: a list of communities, each with an ID and a description.
38
38
 
39
39
  SCORING FACTORS (in priority order):
@@ -78,13 +78,8 @@ export class NetworkRecommender {
78
78
  const networkList = input.networks
79
79
  .map((n, i) => `### Community ${i + 1} (ID: ${n.networkId})\n${n.renderedContext}`)
80
80
  .join("\n\n");
81
- const userSection = [
82
- `**Bio**: ${input.userProfile.bio || "(not provided)"}`,
83
- `**Location**: ${input.userProfile.location || "(not provided)"}`,
84
- `**Interests**: ${input.userProfile.interests.join(", ") || "(not provided)"}`,
85
- `**Skills**: ${input.userProfile.skills.join(", ") || "(not provided)"}`,
86
- ].join("\n");
87
- const prompt = `## User Profile\n${userSection}\n\n## Communities to Rank\n${networkList}`;
81
+ const userSection = input.userContext.trim() || "(not provided)";
82
+ const prompt = `## User Context\n${userSection}\n\n## Communities to Rank\n${networkList}`;
88
83
  const messages = [
89
84
  new SystemMessage(systemPrompt),
90
85
  new HumanMessage(prompt),
@@ -1 +1 @@
1
- {"version":3,"file":"network.recommender.js","sourceRoot":"/","sources":["network/network.recommender.ts"],"names":[],"mappings":";;;;;;;;;AACA,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,GAAG,EAAE,MAAM,gCAAgC,CAAC;AACrD,OAAO,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,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OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;CACF;AAzCc;IADZ,KAAK,EAAE;;;;gDAyCP","sourcesContent":["import type { ChatOpenAI } from \"@langchain/openai\";\nimport { HumanMessage, SystemMessage } from \"@langchain/core/messages\";\nimport { z } from \"zod\";\n\nimport { log } from \"../shared/observability/log.js\";\nimport { Timed } from \"../shared/observability/performance.js\";\nimport { createModel } from \"../shared/agent/model.config.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\n\n// ─── Response schema ───────────────────────────────────────────────────────────\n\nexport const NetworkRecommenderOutputSchema = z.object({\n rankedNetworkIds: z\n .array(z.string())\n .describe(\"Network IDs ordered from most to least relevant for this user. Include all provided network IDs.\"),\n reasoning: z\n .string()\n .describe(\"One-sentence explanation of the top recommendation.\"),\n});\n\nexport type NetworkRecommenderOutput = z.infer<typeof NetworkRecommenderOutputSchema>;\n\n// ─── Input types ──────────────────────────────────────────────────────────────\n\nexport interface NetworkRecommenderUserProfile {\n bio: string;\n location: string;\n interests: string[];\n skills: string[];\n}\n\nexport interface NetworkRecommenderNetwork {\n networkId: string;\n renderedContext: string;\n}\n\nexport interface NetworkRecommenderInput {\n userProfile: NetworkRecommenderUserProfile;\n networks: NetworkRecommenderNetwork[];\n}\n\n// ─── Logger ───────────────────────────────────────────────────────────────────\n\nconst logger = log.lib.from(\"NetworkRecommender\");\n\n// ─── System prompt ────────────────────────────────────────────────────────────\n\nconst systemPrompt = `\nYou are a community matching agent for a social discovery network.\n\nTASK:\nGiven a user's profile and a list of communities, rank the communities from most to least relevant for this user.\nReturn ALL provided community IDs in ranked order.\n\nINPUTS:\n1. User Profile: bio, location, interests, and skills.\n2. Communities: a list of communities, each with an ID and a description.\n\nSCORING FACTORS (in priority order):\n1. Thematic alignment — do the community's topics match the user's interests and skills?\n2. Geographic relevance — does the user's location match the community's focus (if any)?\n3. Professional fit — does the community's purpose match the user's professional background?\n\nOUTPUT RULES:\n- Return ALL community IDs in your ranked list (no omissions).\n- If context is insufficient to differentiate, preserve original order.\n- Keep reasoning brief (one sentence about the top recommendation).\n`;\n\n// ─── Agent class ──────────────────────────────────────────────────────────────\n\n/**\n * LLM-based agent that ranks public communities against a user's profile.\n * Used during onboarding step 6 to surface the most relevant communities first.\n *\n * Follows the IntentIndexer pattern: `withStructuredOutput`, `invokeWithAbortSignal`,\n * null-on-error fallback. `createModel` is called inside the constructor (not at\n * module level) so that importing this file does not require OPENROUTER_API_KEY to\n * be set — tests that import `createNetworkTools` without a live LLM env are unaffected.\n */\nexport class NetworkRecommender {\n private model: ReturnType<ChatOpenAI[\"withStructuredOutput\"]>;\n\n constructor() {\n const model = createModel(\"networkRecommender\");\n this.model = model.withStructuredOutput(NetworkRecommenderOutputSchema, {\n name: \"network_recommender\",\n });\n }\n\n /**\n * Ranks the provided networks by relevance to the user's profile.\n *\n * @param input - User profile and list of networks with rendered context.\n * @returns Ranked network IDs and one-sentence reasoning, or null on error.\n */\n @Timed()\n public async invoke(input: NetworkRecommenderInput): Promise<NetworkRecommenderOutput | null> {\n if (input.networks.length === 0) return null;\n\n logger.verbose(\"[NetworkRecommender.invoke] Ranking communities\", {\n networkCount: input.networks.length,\n });\n\n const networkList = input.networks\n .map((n, i) => `### Community ${i + 1} (ID: ${n.networkId})\\n${n.renderedContext}`)\n .join(\"\\n\\n\");\n\n const userSection = [\n `**Bio**: ${input.userProfile.bio || \"(not provided)\"}`,\n `**Location**: ${input.userProfile.location || \"(not provided)\"}`,\n `**Interests**: ${input.userProfile.interests.join(\", \") || \"(not provided)\"}`,\n `**Skills**: ${input.userProfile.skills.join(\", \") || \"(not provided)\"}`,\n ].join(\"\\n\");\n\n const prompt = `## User Profile\\n${userSection}\\n\\n## Communities to Rank\\n${networkList}`;\n\n const messages = [\n new SystemMessage(systemPrompt),\n new HumanMessage(prompt),\n ];\n\n try {\n const result = await invokeWithAbortSignal(this.model, messages);\n const parsed = NetworkRecommenderOutputSchema.safeParse(result);\n if (!parsed.success) {\n logger.error(\"[NetworkRecommender] Schema validation failed\", { error: parsed.error });\n return null;\n }\n logger.verbose(\"[NetworkRecommender.invoke] Ranking complete\", {\n top: parsed.data.rankedNetworkIds[0],\n });\n return parsed.data;\n } catch (error) {\n logger.error(\"[NetworkRecommender] Error during execution\", { error });\n return null;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"network.recommender.js","sourceRoot":"/","sources":["network/network.recommender.ts"],"names":[],"mappings":";;;;;;;;;AACA,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,GAAG,EAAE,MAAM,gCAAgC,CAAC;AACrD,OAAO,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAC9D,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAExE,kFAAkF;AAElF,MAAM,CAAC,MAAM,8BAA8B,GAAG,CAAC,CAAC,MAAM,CAAC;IACrD,gBAAgB,EAAE,CAAC;SAChB,KAAK,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;SACjB,QAAQ,CAAC,kGAAkG,CAAC;IAC/G,SAAS,EAAE,CAAC;SACT,MAAM,EAAE;SACR,QAAQ,CAAC,qDAAqD,CAAC;CACnE,CAAC,CAAC;AAiBH,iFAAiF;AAEjF,MAAM,MAAM,GAAG,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC;AAElD,iFAAiF;AAEjF,MAAM,YAAY,GAAG;;;;;;;;;;;;;;;;;;;;CAoBpB,CAAC;AAEF,iFAAiF;AAEjF;;;;;;;;GAQG;AACH,MAAM,OAAO,kBAAkB;IAG7B;QACE,MAAM,KAAK,GAAG,WAAW,CAAC,oBAAoB,CAAC,CAAC;QAChD,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC,oBAAoB,CAAC,8BAA8B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C,IAAI,CAAC,gBAAgB,CAAC,CAAC,CAAC;aACrC,CAAC,CAAC;YACH,OAAO,MAAM,CAAC,IAAI,CAAC;QACrB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,CAAC,KAAK,CAAC,6CAA6C,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;YACvE,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;CACF;AApCc;IADZ,KAAK,EAAE;;;;gDAoCP","sourcesContent":["import type { ChatOpenAI } from \"@langchain/openai\";\nimport { HumanMessage, SystemMessage } from \"@langchain/core/messages\";\nimport { z } from \"zod\";\n\nimport { log } from \"../shared/observability/log.js\";\nimport { Timed } from \"../shared/observability/performance.js\";\nimport { createModel } from \"../shared/agent/model.config.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\n\n// ─── Response schema ───────────────────────────────────────────────────────────\n\nexport const NetworkRecommenderOutputSchema = z.object({\n rankedNetworkIds: z\n .array(z.string())\n .describe(\"Network IDs ordered from most to least relevant for this user. Include all provided network IDs.\"),\n reasoning: z\n .string()\n .describe(\"One-sentence explanation of the top recommendation.\"),\n});\n\nexport type NetworkRecommenderOutput = z.infer<typeof NetworkRecommenderOutputSchema>;\n\n// ─── Input types ──────────────────────────────────────────────────────────────\n\nexport interface NetworkRecommenderNetwork {\n networkId: string;\n renderedContext: string;\n}\n\nexport interface NetworkRecommenderInput {\n /** The user's global user_context paragraph (profile-replacing identity text). */\n userContext: string;\n networks: NetworkRecommenderNetwork[];\n}\n\n// ─── Logger ───────────────────────────────────────────────────────────────────\n\nconst logger = log.lib.from(\"NetworkRecommender\");\n\n// ─── System prompt ────────────────────────────────────────────────────────────\n\nconst systemPrompt = `\nYou are a community matching agent for a social discovery network.\n\nTASK:\nGiven a user's profile and a list of communities, rank the communities from most to least relevant for this user.\nReturn ALL provided community IDs in ranked order.\n\nINPUTS:\n1. User Context: a synthesized paragraph describing the user (background, interests, skills, location, goals).\n2. Communities: a list of communities, each with an ID and a description.\n\nSCORING FACTORS (in priority order):\n1. Thematic alignment — do the community's topics match the user's interests and skills?\n2. Geographic relevance — does the user's location match the community's focus (if any)?\n3. Professional fit — does the community's purpose match the user's professional background?\n\nOUTPUT RULES:\n- Return ALL community IDs in your ranked list (no omissions).\n- If context is insufficient to differentiate, preserve original order.\n- Keep reasoning brief (one sentence about the top recommendation).\n`;\n\n// ─── Agent class ──────────────────────────────────────────────────────────────\n\n/**\n * LLM-based agent that ranks public communities against a user's profile.\n * Used during onboarding step 6 to surface the most relevant communities first.\n *\n * Follows the IntentIndexer pattern: `withStructuredOutput`, `invokeWithAbortSignal`,\n * null-on-error fallback. `createModel` is called inside the constructor (not at\n * module level) so that importing this file does not require OPENROUTER_API_KEY to\n * be set — tests that import `createNetworkTools` without a live LLM env are unaffected.\n */\nexport class NetworkRecommender {\n private model: ReturnType<ChatOpenAI[\"withStructuredOutput\"]>;\n\n constructor() {\n const model = createModel(\"networkRecommender\");\n this.model = model.withStructuredOutput(NetworkRecommenderOutputSchema, {\n name: \"network_recommender\",\n });\n }\n\n /**\n * Ranks the provided networks by relevance to the user's profile.\n *\n * @param input - User profile and list of networks with rendered context.\n * @returns Ranked network IDs and one-sentence reasoning, or null on error.\n */\n @Timed()\n public async invoke(input: NetworkRecommenderInput): Promise<NetworkRecommenderOutput | null> {\n if (input.networks.length === 0) return null;\n\n logger.verbose(\"[NetworkRecommender.invoke] Ranking communities\", {\n networkCount: input.networks.length,\n });\n\n const networkList = input.networks\n .map((n, i) => `### Community ${i + 1} (ID: ${n.networkId})\\n${n.renderedContext}`)\n .join(\"\\n\\n\");\n\n const userSection = input.userContext.trim() || \"(not provided)\";\n\n const prompt = `## User Context\\n${userSection}\\n\\n## Communities to Rank\\n${networkList}`;\n\n const messages = [\n new SystemMessage(systemPrompt),\n new HumanMessage(prompt),\n ];\n\n try {\n const result = await invokeWithAbortSignal(this.model, messages);\n const parsed = NetworkRecommenderOutputSchema.safeParse(result);\n if (!parsed.success) {\n logger.error(\"[NetworkRecommender] Schema validation failed\", { error: parsed.error });\n return null;\n }\n logger.verbose(\"[NetworkRecommender.invoke] Ranking complete\", {\n top: parsed.data.rankedNetworkIds[0],\n });\n return parsed.data;\n } catch (error) {\n logger.error(\"[NetworkRecommender] Error during execution\", { error });\n return null;\n }\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"network.tools.d.ts","sourceRoot":"/","sources":["network/network.tools.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AAQ5E,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,gDAinBxE"}
1
+ {"version":3,"file":"network.tools.d.ts","sourceRoot":"/","sources":["network/network.tools.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AAQ5E,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,gDA+mBxE"}
@@ -68,11 +68,14 @@ export function createNetworkTools(defineTool, deps) {
68
68
  _graphTimings: [{ name: 'index', durationMs: _readIndexGraphMs, agents: result.agentTimings ?? [] }],
69
69
  });
70
70
  }
71
- // Onboarding-only: rank public networks by profile relevance.
72
- // Guard: only when isOnboarding, userProfile exists, not scoped, and there are public networks to rank.
71
+ // Onboarding-only: rank public networks by relevance to the user's global
72
+ // user_context paragraph (the profile-replacing identity text). Guard: only
73
+ // when isOnboarding, not scoped, there are public networks to rank, and a
74
+ // user_context is resolvable (generated on demand by the injected resolver).
73
75
  let orderedNetworkIds;
76
+ const userContext = deps.getUserContextText ? await deps.getUserContextText(context.userId) : "";
74
77
  if (context.isOnboarding &&
75
- context.userProfile &&
78
+ userContext &&
76
79
  Array.isArray(enriched.publicNetworks) &&
77
80
  enriched.publicNetworks.length > 0) {
78
81
  // Cap at 50 to bound LLM context window usage (matches the UI's discoverPublicIndexes(1, 50)).
@@ -94,12 +97,7 @@ export function createNetworkTools(defineTool, deps) {
94
97
  }
95
98
  });
96
99
  const rankingResult = await rankFn({
97
- userProfile: {
98
- bio: context.userProfile.identity.bio,
99
- location: context.userProfile.identity.location || context.user.location || "",
100
- interests: context.userProfile.attributes.interests,
101
- skills: context.userProfile.attributes.skills,
102
- },
100
+ userContext,
103
101
  networks: publicNetworksForRanking,
104
102
  }).catch((err) => {
105
103
  // Catches errors from a custom deps.networkRanker (the default fallback