@indexnetwork/protocol 4.5.0-rc.331.1 → 4.5.0-rc.333.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 (49) hide show
  1. package/dist/chat/chat-streaming.types.d.ts +3 -1
  2. package/dist/chat/chat-streaming.types.d.ts.map +1 -1
  3. package/dist/chat/chat-streaming.types.js.map +1 -1
  4. package/dist/chat/chat.agent.d.ts +1 -1
  5. package/dist/chat/chat.agent.d.ts.map +1 -1
  6. package/dist/chat/chat.agent.js.map +1 -1
  7. package/dist/index.d.ts +3 -0
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +3 -0
  10. package/dist/index.js.map +1 -1
  11. package/dist/negotiation/negotiation.agent.d.ts +21 -0
  12. package/dist/negotiation/negotiation.agent.d.ts.map +1 -1
  13. package/dist/negotiation/negotiation.agent.js +79 -11
  14. package/dist/negotiation/negotiation.agent.js.map +1 -1
  15. package/dist/negotiation/negotiation.graph.d.ts +55 -24
  16. package/dist/negotiation/negotiation.graph.d.ts.map +1 -1
  17. package/dist/negotiation/negotiation.graph.js +106 -27
  18. package/dist/negotiation/negotiation.graph.js.map +1 -1
  19. package/dist/negotiation/negotiation.protocol.d.ts +287 -0
  20. package/dist/negotiation/negotiation.protocol.d.ts.map +1 -0
  21. package/dist/negotiation/negotiation.protocol.js +152 -0
  22. package/dist/negotiation/negotiation.protocol.js.map +1 -0
  23. package/dist/negotiation/negotiation.state.d.ts +34 -9
  24. package/dist/negotiation/negotiation.state.d.ts.map +1 -1
  25. package/dist/negotiation/negotiation.state.js +28 -4
  26. package/dist/negotiation/negotiation.state.js.map +1 -1
  27. package/dist/negotiation/negotiation.tools.d.ts.map +1 -1
  28. package/dist/negotiation/negotiation.tools.js +86 -31
  29. package/dist/negotiation/negotiation.tools.js.map +1 -1
  30. package/dist/opportunity/opportunity.graph.d.ts.map +1 -1
  31. package/dist/opportunity/opportunity.graph.js +9 -0
  32. package/dist/opportunity/opportunity.graph.js.map +1 -1
  33. package/dist/opportunity/question.prompt.d.ts +1 -1
  34. package/dist/opportunity/question.prompt.d.ts.map +1 -1
  35. package/dist/opportunity/question.prompt.js.map +1 -1
  36. package/dist/shared/interfaces/agent-dispatcher.interface.d.ts +6 -0
  37. package/dist/shared/interfaces/agent-dispatcher.interface.d.ts.map +1 -1
  38. package/dist/shared/interfaces/agent-dispatcher.interface.js.map +1 -1
  39. package/dist/shared/interfaces/database.interface.d.ts +17 -0
  40. package/dist/shared/interfaces/database.interface.d.ts.map +1 -1
  41. package/dist/shared/interfaces/database.interface.js.map +1 -1
  42. package/dist/shared/schemas/discovery-question.schema.d.ts +8 -8
  43. package/dist/shared/schemas/discovery-question.schema.js +1 -1
  44. package/dist/shared/schemas/discovery-question.schema.js.map +1 -1
  45. package/dist/shared/schemas/negotiation-state.schema.d.ts +19 -3
  46. package/dist/shared/schemas/negotiation-state.schema.d.ts.map +1 -1
  47. package/dist/shared/schemas/negotiation-state.schema.js +15 -1
  48. package/dist/shared/schemas/negotiation-state.schema.js.map +1 -1
  49. 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;AAClD,MAAM,OAAO,GAAG,cAAc,CAAC,uBAAuB,CAAC,CAAC;AACxD,MAAM,OAAO,GAAG,cAAc,CAA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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\");\nconst initLog = protocolLogger(\"NegotiationGraph:Init\");\nconst turnLog = protocolLogger(\"NegotiationGraph:Turn\");\nconst finalizeLog = protocolLogger(\"NegotiationGraph:Finalize\");\nconst negotiateCandidatesLog = protocolLogger(\"NegotiationGraph:negotiateCandidates\");\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 initLog.info('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.hasExternalAgent(state.sourceUser.id, scope),\n dispatcher.hasExternalAgent(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 initLog.error('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 initLog.error('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 turnLog.warn(\"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 turnLog.error(\"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 finalizeLog.info('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 finalizeLog.error(\"Failed to update opportunity status\", { opportunityId: state.opportunityId, nextStatus, error: err });\n });\n }\n } catch (err) {\n finalizeLog.error(\"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 finalizeLog.error('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 negotiateCandidatesLog.error(\"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 negotiateCandidatesLog.error(\"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"]}
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I,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 { allowedActionsFor, configuredProtocolVersion, fallbackActionFor, isRejectLikeAction, isTerminalAction, readProtocolVersion, rejectActionFor } from \"./negotiation.protocol.js\";\nimport type { NegotiationSeat, NegotiationProtocolVersion } from \"../shared/schemas/negotiation-state.schema.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport type { QuestionerEnqueueFn } from \"../questioner/questioner.types.js\";\n\nconst logger = protocolLogger(\"NegotiationGraph\");\nconst initLog = protocolLogger(\"NegotiationGraph:Init\");\nconst turnLog = protocolLogger(\"NegotiationGraph:Turn\");\nconst finalizeLog = protocolLogger(\"NegotiationGraph:Finalize\");\nconst negotiateCandidatesLog = protocolLogger(\"NegotiationGraph:negotiateCandidates\");\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 const activeStates = ['submitted', 'working', 'input_required', 'waiting_for_agent', 'claimed'];\n const isActiveAndFresh = (t: { state: string; updatedAt: Date }) =>\n activeStates.includes(t.state) && (Date.now() - new Date(t.updatedAt).getTime()) < 5 * 60 * 1000;\n\n const priorTask = state.opportunityId\n ? await database.getNegotiationTaskForOpportunity(state.opportunityId)\n : null;\n const isLocked = !!priorTask && isActiveAndFresh(priorTask);\n\n if (isLocked) {\n initLog.info('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.hasExternalAgent(state.sourceUser.id, scope),\n dispatcher.hasExternalAgent(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 // --- Initiator seat resolution (v2: rigid per match, stamped at discovery) ---\n // 1. Continuations inherit from the prior task for the same opportunity —\n // never re-derive, so the seat cannot flip between sessions.\n // 2. Conversation-scoped tie-break: if another negotiation on this DM is\n // active and fresh (symmetric concurrent start under a different\n // opportunityId — the opportunity-scoped lock above cannot see it),\n // the first created task keeps the seat; this run inherits its stamp.\n // 3. Otherwise: explicit stamp from the caller, falling back to the\n // session's sourceUser (pre-stamp heuristic behavior, unchanged).\n const readInitiator = (metadata: Record<string, unknown> | null | undefined): string | null => {\n const v = metadata?.initiatorUserId;\n return typeof v === 'string' && v.length > 0 ? v : null;\n };\n let initiatorUserId = readInitiator(priorTask?.metadata) ?? state.initiatorUserId ?? state.sourceUser.id;\n // Conversation-scoped prior task: reused for both the initiator tie-break\n // (only when active+fresh) and protocol-version inheritance (any prior\n // task on the conversation pins the version).\n const convTask = (!readInitiator(priorTask?.metadata) || !readProtocolVersion(priorTask?.metadata))\n ? await database.getLatestNegotiationTaskForConversation?.(conversation.id).catch(() => null)\n : null;\n if (!readInitiator(priorTask?.metadata)) {\n if (convTask && convTask.id !== priorTask?.id && isActiveAndFresh(convTask)) {\n const convInitiator = readInitiator(convTask.metadata);\n if (convInitiator) {\n initLog.info('Conversation-scoped tie-break: inheriting initiator seat from concurrent task', {\n conversationId: conversation.id,\n winningTaskId: convTask.id,\n initiatorUserId: convInitiator,\n });\n initiatorUserId = convInitiator;\n }\n }\n }\n\n // --- Protocol version: inherited, never re-stamped ---\n // Every session (including continuations) creates a new task row, so a\n // naïve \"stamp from env at init\" would flip a v1 conversation to v2\n // mid-flight. Rule: any prior negotiation task on this conversation pins\n // the version (absent field on a genuine prior = pre-v2 task = v1);\n // prior turns without a readable task also grandfather to v1; only\n // genuinely fresh negotiations stamp from NEGOTIATION_PROTOCOL_VERSION.\n let protocolVersion: NegotiationProtocolVersion;\n const priorVersionSource = priorTask ?? convTask;\n if (priorVersionSource) {\n protocolVersion = readProtocolVersion(priorVersionSource.metadata) ?? 'v1';\n } else if (isContinuation) {\n protocolVersion = 'v1';\n } else {\n protocolVersion = configuredProtocolVersion();\n }\n\n const task = await database.createTask(conversation.id, {\n type: 'negotiation',\n sourceUserId: state.sourceUser.id,\n initiatorUserId,\n protocolVersion,\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 initLog.error('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 initLog.error('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 initiatorUserId,\n protocolVersion,\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 // Seat attribution keys on initiatorUserId (rigid v2 stamp), never on\n // parity or source/candidate position — under the conversation-scoped\n // tie-break this run's source may hold the counterparty seat.\n const version = state.protocolVersion ?? 'v1';\n const seat: NegotiationSeat = ownUser.id === (state.initiatorUserId ?? state.sourceUser.id)\n ? 'initiator'\n : 'counterparty';\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 seat,\n protocolVersion: version,\n allowedActions: [...allowedActionsFor(version, seat, isFinalTurn)],\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. Under v2, coerce out-of-seat actions to\n // the conservative fallback — the polling/respond surfaces reject\n // these with a 400, but locally-dispatched turns land here directly.\n turn = dispatchResult.turn;\n if (version === 'v2' && !allowedActionsFor(version, seat, isFinalTurn).includes(turn.action)) {\n turnLog.warn('Personal agent returned out-of-seat action, coercing to conservative fallback', {\n action: turn.action, seat, isFinalTurn,\n });\n turn = { ...turn, action: fallbackActionFor(version, seat, isFinalTurn) };\n }\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 seat,\n protocolVersion: version,\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 open the negotiation (unless continuing a prior\n // conversation): v1 → \"propose\"; v2 initiator → \"outreach\". A v2 turn-0\n // speaker holding the counterparty seat (tie-break inheritance) is left\n // unforced — it is responding, not opening.\n if (state.turnCount === 0 && !state.isContinuation) {\n const openingAction = version === 'v2' ? 'outreach' : 'propose';\n if ((version !== 'v2' || seat === 'initiator') && turn.action !== openingAction) {\n turnLog.warn(`Agent returned unexpected action on turn 0, forcing to ${openingAction}`, { action: turn.action });\n turn.action = openingAction;\n }\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 turnLog.error(\"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 const errorSeat: NegotiationSeat = (state.currentSpeaker === 'source' ? state.sourceUser.id : state.candidateUser.id) === (state.initiatorUserId ?? state.sourceUser.id)\n ? 'initiator'\n : 'counterparty';\n return {\n lastTurn: {\n action: rejectActionFor(state.protocolVersion ?? 'v1', errorSeat),\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 // Terminal actions: accept (v1+v2), reject (v1), withdraw/decline (v2)\n if (isTerminalAction(state.lastTurn.action)) 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! && !isTerminalAction(lastTurn?.action);\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 finalizeLog.info('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 : isRejectLikeAction(lastTurn?.action)\n ? 'rejected'\n : 'stalled';\n await database.updateOpportunityStatus(state.opportunityId, nextStatus).catch((err) => {\n finalizeLog.error(\"Failed to update opportunity status\", { opportunityId: state.opportunityId, nextStatus, error: err });\n });\n }\n } catch (err) {\n finalizeLog.error(\"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 : \"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 && !isRejectLikeAction(lastTurn?.action) && 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 finalizeLog.error('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 * Initiator seat for every candidate session in this fan-out (v2 stamp).\n * Passed through to the negotiation graph, which may still override it by\n * inheriting from a prior task on the same opportunity/conversation.\n */\n initiatorUserId?: string;\n },\n): Promise<NegotiationResult[]> {\n const { maxTurns, traceEmitter, indexContextOverrides, timeoutMs, onCandidateResolved, trigger, initiatorUserId } = 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 initiatorUserId: initiatorUserId ?? sourceUser.id,\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 ...(initiatorUserId && { initiatorUserId }),\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 negotiateCandidatesLog.error(\"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 negotiateCandidatesLog.error(\"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"]}
@@ -0,0 +1,287 @@
1
+ /**
2
+ * Seat-scoped negotiation protocol rules (v2 client-advocate protocol).
3
+ *
4
+ * v2 fixes exactly one initiating seat per match (`metadata.initiatorUserId`,
5
+ * stamped at discovery time — IND-396) and makes consent asymmetric:
6
+ * **accept can only come from the counterparty seat**, schema-enforced.
7
+ *
8
+ * Vocabulary per seat (v2):
9
+ * - initiator: `outreach | counter | question | withdraw` (no accept)
10
+ * - counterparty: `accept | decline | counter | question`
11
+ * - final turn: initiator `withdraw | counter`; counterparty `accept | decline`
12
+ *
13
+ * v1 tasks keep the legacy vocabulary (`propose | accept | reject | counter |
14
+ * question`) — the version is inherited per conversation, never re-stamped, so
15
+ * in-flight v1 negotiations are grandfathered untouched.
16
+ *
17
+ * Outcome mapping is version-independent: `accept` → opportunity `pending`,
18
+ * `reject`/`withdraw`/`decline` → `rejected`, turn-cap → `stalled`.
19
+ */
20
+ import { z } from "zod";
21
+ import type { NegotiationAction, NegotiationSeat, NegotiationProtocolVersion } from "../shared/schemas/negotiation-state.schema.js";
22
+ /** Initiator seat, non-final turn: may reach out, push back, ask, or walk away — never accept. */
23
+ export declare const InitiatorTurnSchema: z.ZodObject<{
24
+ action: z.ZodEnum<["outreach", "counter", "question", "withdraw"]>;
25
+ assessment: z.ZodObject<{
26
+ reasoning: z.ZodString;
27
+ suggestedRoles: z.ZodObject<{
28
+ ownUser: z.ZodEnum<["agent", "patient", "peer"]>;
29
+ otherUser: z.ZodEnum<["agent", "patient", "peer"]>;
30
+ }, "strip", z.ZodTypeAny, {
31
+ ownUser: "agent" | "patient" | "peer";
32
+ otherUser: "agent" | "patient" | "peer";
33
+ }, {
34
+ ownUser: "agent" | "patient" | "peer";
35
+ otherUser: "agent" | "patient" | "peer";
36
+ }>;
37
+ }, "strip", z.ZodTypeAny, {
38
+ reasoning: string;
39
+ suggestedRoles: {
40
+ ownUser: "agent" | "patient" | "peer";
41
+ otherUser: "agent" | "patient" | "peer";
42
+ };
43
+ }, {
44
+ reasoning: string;
45
+ suggestedRoles: {
46
+ ownUser: "agent" | "patient" | "peer";
47
+ otherUser: "agent" | "patient" | "peer";
48
+ };
49
+ }>;
50
+ message: z.ZodOptional<z.ZodNullable<z.ZodString>>;
51
+ }, "strip", z.ZodTypeAny, {
52
+ action: "counter" | "question" | "outreach" | "withdraw";
53
+ assessment: {
54
+ reasoning: string;
55
+ suggestedRoles: {
56
+ ownUser: "agent" | "patient" | "peer";
57
+ otherUser: "agent" | "patient" | "peer";
58
+ };
59
+ };
60
+ message?: string | null | undefined;
61
+ }, {
62
+ action: "counter" | "question" | "outreach" | "withdraw";
63
+ assessment: {
64
+ reasoning: string;
65
+ suggestedRoles: {
66
+ ownUser: "agent" | "patient" | "peer";
67
+ otherUser: "agent" | "patient" | "peer";
68
+ };
69
+ };
70
+ message?: string | null | undefined;
71
+ }>;
72
+ /** Counterparty seat, non-final turn: the only seat that can accept. */
73
+ export declare const CounterpartyTurnSchema: z.ZodObject<{
74
+ action: z.ZodEnum<["accept", "decline", "counter", "question"]>;
75
+ assessment: z.ZodObject<{
76
+ reasoning: z.ZodString;
77
+ suggestedRoles: z.ZodObject<{
78
+ ownUser: z.ZodEnum<["agent", "patient", "peer"]>;
79
+ otherUser: z.ZodEnum<["agent", "patient", "peer"]>;
80
+ }, "strip", z.ZodTypeAny, {
81
+ ownUser: "agent" | "patient" | "peer";
82
+ otherUser: "agent" | "patient" | "peer";
83
+ }, {
84
+ ownUser: "agent" | "patient" | "peer";
85
+ otherUser: "agent" | "patient" | "peer";
86
+ }>;
87
+ }, "strip", z.ZodTypeAny, {
88
+ reasoning: string;
89
+ suggestedRoles: {
90
+ ownUser: "agent" | "patient" | "peer";
91
+ otherUser: "agent" | "patient" | "peer";
92
+ };
93
+ }, {
94
+ reasoning: string;
95
+ suggestedRoles: {
96
+ ownUser: "agent" | "patient" | "peer";
97
+ otherUser: "agent" | "patient" | "peer";
98
+ };
99
+ }>;
100
+ message: z.ZodOptional<z.ZodNullable<z.ZodString>>;
101
+ }, "strip", z.ZodTypeAny, {
102
+ action: "accept" | "counter" | "question" | "decline";
103
+ assessment: {
104
+ reasoning: string;
105
+ suggestedRoles: {
106
+ ownUser: "agent" | "patient" | "peer";
107
+ otherUser: "agent" | "patient" | "peer";
108
+ };
109
+ };
110
+ message?: string | null | undefined;
111
+ }, {
112
+ action: "accept" | "counter" | "question" | "decline";
113
+ assessment: {
114
+ reasoning: string;
115
+ suggestedRoles: {
116
+ ownUser: "agent" | "patient" | "peer";
117
+ otherUser: "agent" | "patient" | "peer";
118
+ };
119
+ };
120
+ message?: string | null | undefined;
121
+ }>;
122
+ /** Initiator seat, final allowed turn: commit to walking away or leave the door open. */
123
+ export declare const FinalInitiatorTurnSchema: z.ZodObject<{
124
+ action: z.ZodEnum<["withdraw", "counter"]>;
125
+ assessment: z.ZodObject<{
126
+ reasoning: z.ZodString;
127
+ suggestedRoles: z.ZodObject<{
128
+ ownUser: z.ZodEnum<["agent", "patient", "peer"]>;
129
+ otherUser: z.ZodEnum<["agent", "patient", "peer"]>;
130
+ }, "strip", z.ZodTypeAny, {
131
+ ownUser: "agent" | "patient" | "peer";
132
+ otherUser: "agent" | "patient" | "peer";
133
+ }, {
134
+ ownUser: "agent" | "patient" | "peer";
135
+ otherUser: "agent" | "patient" | "peer";
136
+ }>;
137
+ }, "strip", z.ZodTypeAny, {
138
+ reasoning: string;
139
+ suggestedRoles: {
140
+ ownUser: "agent" | "patient" | "peer";
141
+ otherUser: "agent" | "patient" | "peer";
142
+ };
143
+ }, {
144
+ reasoning: string;
145
+ suggestedRoles: {
146
+ ownUser: "agent" | "patient" | "peer";
147
+ otherUser: "agent" | "patient" | "peer";
148
+ };
149
+ }>;
150
+ message: z.ZodOptional<z.ZodNullable<z.ZodString>>;
151
+ }, "strip", z.ZodTypeAny, {
152
+ action: "counter" | "withdraw";
153
+ assessment: {
154
+ reasoning: string;
155
+ suggestedRoles: {
156
+ ownUser: "agent" | "patient" | "peer";
157
+ otherUser: "agent" | "patient" | "peer";
158
+ };
159
+ };
160
+ message?: string | null | undefined;
161
+ }, {
162
+ action: "counter" | "withdraw";
163
+ assessment: {
164
+ reasoning: string;
165
+ suggestedRoles: {
166
+ ownUser: "agent" | "patient" | "peer";
167
+ otherUser: "agent" | "patient" | "peer";
168
+ };
169
+ };
170
+ message?: string | null | undefined;
171
+ }>;
172
+ /** Counterparty seat, final allowed turn: must decide. */
173
+ export declare const FinalCounterpartyTurnSchema: z.ZodObject<{
174
+ action: z.ZodEnum<["accept", "decline"]>;
175
+ assessment: z.ZodObject<{
176
+ reasoning: z.ZodString;
177
+ suggestedRoles: z.ZodObject<{
178
+ ownUser: z.ZodEnum<["agent", "patient", "peer"]>;
179
+ otherUser: z.ZodEnum<["agent", "patient", "peer"]>;
180
+ }, "strip", z.ZodTypeAny, {
181
+ ownUser: "agent" | "patient" | "peer";
182
+ otherUser: "agent" | "patient" | "peer";
183
+ }, {
184
+ ownUser: "agent" | "patient" | "peer";
185
+ otherUser: "agent" | "patient" | "peer";
186
+ }>;
187
+ }, "strip", z.ZodTypeAny, {
188
+ reasoning: string;
189
+ suggestedRoles: {
190
+ ownUser: "agent" | "patient" | "peer";
191
+ otherUser: "agent" | "patient" | "peer";
192
+ };
193
+ }, {
194
+ reasoning: string;
195
+ suggestedRoles: {
196
+ ownUser: "agent" | "patient" | "peer";
197
+ otherUser: "agent" | "patient" | "peer";
198
+ };
199
+ }>;
200
+ message: z.ZodOptional<z.ZodNullable<z.ZodString>>;
201
+ }, "strip", z.ZodTypeAny, {
202
+ action: "accept" | "decline";
203
+ assessment: {
204
+ reasoning: string;
205
+ suggestedRoles: {
206
+ ownUser: "agent" | "patient" | "peer";
207
+ otherUser: "agent" | "patient" | "peer";
208
+ };
209
+ };
210
+ message?: string | null | undefined;
211
+ }, {
212
+ action: "accept" | "decline";
213
+ assessment: {
214
+ reasoning: string;
215
+ suggestedRoles: {
216
+ ownUser: "agent" | "patient" | "peer";
217
+ otherUser: "agent" | "patient" | "peer";
218
+ };
219
+ };
220
+ message?: string | null | undefined;
221
+ }>;
222
+ /**
223
+ * The set of actions a given seat may submit under a given protocol version.
224
+ *
225
+ * v1 ignores the seat entirely (legacy symmetric vocabulary) so pre-v2
226
+ * negotiations behave exactly as before.
227
+ */
228
+ export declare function allowedActionsFor(version: NegotiationProtocolVersion, seat: NegotiationSeat, isFinalTurn?: boolean): readonly NegotiationAction[];
229
+ /**
230
+ * Zod turn schema for a system-agent turn, selected by version + seat +
231
+ * final-turn flag. v1 returns the legacy schemas (seat-agnostic); v2 returns
232
+ * the seat-scoped schemas above, making an initiator `accept` structurally
233
+ * impossible rather than prompt-discouraged.
234
+ *
235
+ * The v1 legacy schemas are passed in by the caller (they live in
236
+ * `negotiation.state.ts`) to keep this module free of a state-module import.
237
+ */
238
+ export declare function turnSchemaFor(version: NegotiationProtocolVersion, seat: NegotiationSeat, isFinalTurn: boolean, v1Schemas: {
239
+ system: z.ZodTypeAny;
240
+ final: z.ZodTypeAny;
241
+ }): z.ZodTypeAny;
242
+ /** Terminal actions end the negotiation immediately. */
243
+ export declare function isTerminalAction(action: string | undefined | null): boolean;
244
+ /** Reject-like actions map the opportunity to `rejected` (v1 reject, v2 withdraw/decline). */
245
+ export declare function isRejectLikeAction(action: string | undefined | null): boolean;
246
+ /**
247
+ * Conservative action when an agent produced schema-invalid output (after the
248
+ * retry) or an internal error needs a seat-valid terminal placeholder.
249
+ *
250
+ * Non-final turns fall back to `counter` (keeps the dialogue open — the AC's
251
+ * "conservative counter"). Final turns must decide: v1 → `reject`, v2
252
+ * counterparty → `decline`, v2 initiator → `counter` is still legal on the
253
+ * final turn so it stays `counter` (finalizes as turn-cap/stalled).
254
+ */
255
+ export declare function fallbackActionFor(version: NegotiationProtocolVersion, seat: NegotiationSeat, isFinalTurn: boolean): NegotiationAction;
256
+ /** Seat-appropriate reject-like action for error paths. */
257
+ export declare function rejectActionFor(version: NegotiationProtocolVersion, seat: NegotiationSeat): NegotiationAction;
258
+ /**
259
+ * Read the protocol version off task metadata. Returns null when the task
260
+ * predates version stamping (treat as v1 at the call site when the task is a
261
+ * genuine prior; fresh tasks stamp from {@link configuredProtocolVersion}).
262
+ */
263
+ export declare function readProtocolVersion(metadata: {
264
+ protocolVersion?: unknown;
265
+ } | null | undefined): NegotiationProtocolVersion | null;
266
+ /**
267
+ * Protocol version for genuinely fresh negotiations, from the
268
+ * `NEGOTIATION_PROTOCOL_VERSION` env switch. Defaults to `v1` when unset —
269
+ * v2 is opt-in per environment, and rolling back is the same single switch.
270
+ */
271
+ export declare function configuredProtocolVersion(): NegotiationProtocolVersion;
272
+ /**
273
+ * Resolve the seat of `userId` on a negotiation task.
274
+ *
275
+ * Keys on `metadata.initiatorUserId` (the rigid v2 stamp), **never on turn
276
+ * parity** — continuations can start with either side speaking first, so
277
+ * parity misattributes seats across sessions. Pre-stamp tasks fall back to
278
+ * `sourceUserId` (the discovery-session opener), which is what the stamp
279
+ * defaults to anyway.
280
+ */
281
+ export declare function resolveSeat(userId: string, metadata: {
282
+ initiatorUserId?: unknown;
283
+ sourceUserId?: unknown;
284
+ } | null | undefined): NegotiationSeat;
285
+ /** Human-readable seat-violation message shared by respond surfaces. */
286
+ export declare function seatViolationMessage(action: string, seat: NegotiationSeat, version: NegotiationProtocolVersion): string;
287
+ //# sourceMappingURL=negotiation.protocol.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"negotiation.protocol.d.ts","sourceRoot":"/","sources":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