@indexnetwork/protocol 4.5.0-rc.337.1 → 4.5.0-rc.339.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 (46) hide show
  1. package/dist/chat/negotiator.persona.d.ts.map +1 -1
  2. package/dist/chat/negotiator.persona.js +15 -1
  3. package/dist/chat/negotiator.persona.js.map +1 -1
  4. package/dist/chat/negotiator.prompt.d.ts +15 -0
  5. package/dist/chat/negotiator.prompt.d.ts.map +1 -1
  6. package/dist/chat/negotiator.prompt.js +22 -2
  7. package/dist/chat/negotiator.prompt.js.map +1 -1
  8. package/dist/chat/negotiator.tools.d.ts +45 -0
  9. package/dist/chat/negotiator.tools.d.ts.map +1 -0
  10. package/dist/chat/negotiator.tools.js +137 -0
  11. package/dist/chat/negotiator.tools.js.map +1 -0
  12. package/dist/index.d.ts +4 -0
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +2 -0
  15. package/dist/index.js.map +1 -1
  16. package/dist/negotiation/negotiation.agent.d.ts +7 -0
  17. package/dist/negotiation/negotiation.agent.d.ts.map +1 -1
  18. package/dist/negotiation/negotiation.agent.js +4 -2
  19. package/dist/negotiation/negotiation.agent.js.map +1 -1
  20. package/dist/negotiation/negotiation.graph.d.ts +21 -3
  21. package/dist/negotiation/negotiation.graph.d.ts.map +1 -1
  22. package/dist/negotiation/negotiation.graph.js +51 -3
  23. package/dist/negotiation/negotiation.graph.js.map +1 -1
  24. package/dist/negotiation/negotiation.memory.d.ts +58 -0
  25. package/dist/negotiation/negotiation.memory.d.ts.map +1 -0
  26. package/dist/negotiation/negotiation.memory.js +71 -0
  27. package/dist/negotiation/negotiation.memory.js.map +1 -0
  28. package/dist/negotiation/negotiation.screen.d.ts +8 -1
  29. package/dist/negotiation/negotiation.screen.d.ts.map +1 -1
  30. package/dist/negotiation/negotiation.screen.js +5 -3
  31. package/dist/negotiation/negotiation.screen.js.map +1 -1
  32. package/dist/negotiation/negotiation.state.d.ts +9 -0
  33. package/dist/negotiation/negotiation.state.d.ts.map +1 -1
  34. package/dist/negotiation/negotiation.state.js +11 -0
  35. package/dist/negotiation/negotiation.state.js.map +1 -1
  36. package/dist/shared/agent/tool.helpers.d.ts +9 -0
  37. package/dist/shared/agent/tool.helpers.d.ts.map +1 -1
  38. package/dist/shared/agent/tool.helpers.js.map +1 -1
  39. package/dist/shared/interfaces/agent-dispatcher.interface.d.ts +8 -0
  40. package/dist/shared/interfaces/agent-dispatcher.interface.d.ts.map +1 -1
  41. package/dist/shared/interfaces/agent-dispatcher.interface.js.map +1 -1
  42. package/dist/shared/interfaces/negotiator-memory.interface.d.ts +59 -0
  43. package/dist/shared/interfaces/negotiator-memory.interface.d.ts.map +1 -0
  44. package/dist/shared/interfaces/negotiator-memory.interface.js +12 -0
  45. package/dist/shared/interfaces/negotiator-memory.interface.js.map +1 -0
  46. 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,sBAAsB,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,wBAAwB,EAAE,yBAAyB,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AACjQ,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAkD,MAAM,yBAAyB,CAAC;AAEpI,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAI5E,MAAM,M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ACd,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 { ASK_USER_LOCK_SLACK_MS, allowedActionsFor, askUserAnswerWindowMs, configuredAskUserEnabled, configuredProtocolVersion, fallbackActionFor, isRejectLikeAction, isTerminalAction, readProtocolVersion, rejectActionFor } from \"./negotiation.protocol.js\";\nimport { NegotiationScreener, configuredScreenMode, type ScreenDecision, type ScreenDecisionRecord } from \"./negotiation.screen.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\";\nimport type { ReflectEnqueueFn } from \"./negotiation.reflect.js\";\n\nconst logger = protocolLogger(\"NegotiationGraph\");\nconst initLog = protocolLogger(\"NegotiationGraph:Init\");\nconst screenNodeLog = protocolLogger(\"NegotiationGraph:Screen\");\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 * Whether `userId`'s side has already spent its one `ask_user` client\n * consultation in this conversation (P3.2 rationing: max one per negotiation\n * per side, checked against the full message history so continuations count\n * prior sessions' consultations too).\n */\nfunction hasPriorAskUser(\n messages: Array<{ senderId: string; parts: unknown[] }>,\n userId: string,\n): boolean {\n const sender = `agent:${userId}`;\n return messages.some((m) => {\n if (m.senderId !== sender) return false;\n const dataPart = (m.parts as Array<{ kind?: string; data?: { action?: string } }>).find((p) => p.kind === \"data\");\n return dataPart?.data?.action === \"ask_user\";\n });\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 private reflectEnqueue?: ReflectEnqueueFn,\n ) {}\n\n createGraph() {\n const { database, dispatcher, timeoutQueue, questionerEnqueue, reflectEnqueue } = this;\n const systemAgent = new IndexNegotiator();\n const screener = new NegotiationScreener();\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 if (!activeStates.includes(t.state)) return false;\n // State-aware freshness (IND-401): an `input_required` task is an\n // ask_user pause — it holds the conversation lock for its full answer\n // window (+ slack for the expiry worker), not the 5-min turn window.\n // Otherwise ambient rediscovery / chat negotiate_existing would start\n // a fresh negotiation right past the pause after 5 minutes.\n const freshnessMs = t.state === 'input_required'\n ? askUserAnswerWindowMs() + ASK_USER_LOCK_SLACK_MS\n : 5 * 60 * 1000;\n return (Date.now() - new Date(t.updatedAt).getTime()) < freshnessMs;\n };\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. An `ask_user` last\n // turn does NOT pass the floor: the sender paused to consult its own\n // client, so on resume the same side speaks again — now armed with the\n // client's answer (or its recorded absence). Flipping here would hand\n // the turn to the counterparty, who has nothing to respond to.\n let currentSpeaker: 'source' | 'candidate' = 'source';\n if (isContinuation && priorMessages.length > 0) {\n const lastMessage = priorMessages[priorMessages.length - 1];\n const lastAction = turnsFromMessages([lastMessage])[0]?.action;\n if (lastAction === 'ask_user') {\n currentSpeaker = lastMessage.senderId === agentIdA ? 'source' : 'candidate';\n } else {\n currentSpeaker = lastMessage.senderId === agentIdA ? 'candidate' : 'source';\n }\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 /**\n * Screen node (P2.1) — the outreach gate. Runs between init and the first\n * turn on FRESH negotiations only (routing skips it on continuations and\n * when NEGOTIATION_SCREEN_MODE=off). The reaching client's negotiator\n * decides whether the match is worth its client's name; in shadow mode the\n * decision is recorded (task metadata + trace event + log line) but never\n * blocks — the negotiation always proceeds to the first turn. `enforce`\n * runs identically until P2.2 lands enforcement (by the time this node\n * runs, init has already created the task and flipped the opportunity to\n * `negotiating` — P2.2 owns making a blocking `pass` quiet/correct).\n */\n const screenNode = 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 const mode = configuredScreenMode();\n if (mode === \"enforce\") {\n screenNodeLog.warn(\"NEGOTIATION_SCREEN_MODE=enforce requested but enforcement lands in P2.2; running shadow\", {\n taskId: state.taskId,\n });\n }\n\n const start = Date.now();\n // The client is the initiator seat's user — the side whose negotiator is\n // reaching out. Fresh runs stamp initiatorUserId in init; fall back to\n // sourceUser (what the stamp defaults to anyway).\n const initiatorId = state.initiatorUserId ?? state.sourceUser.id;\n const clientIsSource = initiatorId !== state.candidateUser.id;\n const clientUser = clientIsSource ? state.sourceUser : state.candidateUser;\n const counterpartyUser = clientIsSource ? state.candidateUser : state.sourceUser;\n\n let decision: ScreenDecision;\n let failedOpen = false;\n let screenError: string | undefined;\n try {\n const counterpartyContext = (await database.getUserContext(counterpartyUser.id, null).catch(() => null))?.text ?? \"\";\n decision = await screener.invoke({\n clientUser,\n counterpartyUser,\n ...(counterpartyContext && { counterpartyContext }),\n // discoveryQuery belongs to the discovery session's source user; only\n // meaningful for the client when the client holds the source side.\n ...(clientIsSource && state.discoveryQuery && { discoveryQuery: state.discoveryQuery }),\n seedAssessment: state.seedAssessment,\n indexContext: state.indexContext,\n });\n } catch (err) {\n // Fail open: a screen failure must never block a negotiation.\n failedOpen = true;\n screenError = err instanceof Error ? err.message : String(err);\n screenNodeLog.warn(\"Screen failed; proceeding open (reach_out)\", {\n taskId: state.taskId,\n opportunityId: state.opportunityId || undefined,\n error: screenError,\n });\n decision = {\n decision: \"reach_out\",\n reasoning: `screen_error: ${screenError}`,\n evidence: { counterpartyPremiseFit: \"\", intentAlignment: \"\" },\n };\n }\n\n const durationMs = Date.now() - start;\n const record: ScreenDecisionRecord = {\n ...decision,\n mode,\n ...(failedOpen && { failedOpen, error: screenError }),\n screenedAt: new Date().toISOString(),\n durationMs,\n };\n\n await database.setTaskScreenDecision?.(state.taskId, record as unknown as Record<string, unknown>).catch((err) => {\n screenNodeLog.error(\"Failed to persist screen decision\", { taskId: state.taskId, error: err });\n });\n\n screenNodeLog.info(\"negotiation_screen\", {\n taskId: state.taskId,\n opportunityId: state.opportunityId || undefined,\n decision: decision.decision,\n mode,\n failedOpen,\n durationMs,\n });\n\n if (state.opportunityId) {\n emitWide({\n type: \"negotiation_screen\",\n opportunityId: state.opportunityId,\n negotiationConversationId: state.conversationId,\n decision: decision.decision,\n reasoning: decision.reasoning,\n mode,\n failedOpen,\n durationMs,\n });\n }\n\n // Shadow (and pre-P2.2 enforce): always proceed to the first turn.\n return { screenDecision: record };\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 // ask_user availability (P3.2): flag on, full pause loop wired\n // (questioner + answer-window timer + an opportunity to resume\n // against), v2 non-final non-opening turn, and this side's one client\n // consultation not yet spent (rationing). Chat-triggered runs get no\n // special casing — the pause exits the graph at the turn boundary, so\n // the stream never blocks on a question; the resume is always an async\n // continuation.\n const askUserAvailable =\n version === 'v2'\n && !isFinalTurn\n && configuredAskUserEnabled()\n && !!questionerEnqueue\n && !!timeoutQueue?.enqueueAskUserExpiry\n && !!state.opportunityId\n && !(state.turnCount === 0 && !state.isContinuation)\n && !hasPriorAskUser(state.messages, ownUser.id);\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, { askUser: askUserAvailable })],\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, { askUser: askUserAvailable }).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 ...(askUserAvailable && { canAskUser: true }),\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 // Safety net: an ask_user that slipped past availability gating (e.g. a\n // locally-dispatched agent ignoring allowedActions, or rationing already\n // spent) is coerced to the conservative fallback BEFORE persisting — a\n // pause we cannot resume must never enter the turn history.\n if (turn.action === 'ask_user' && !askUserAvailable) {\n turnLog.warn('ask_user emitted while unavailable, coercing to conservative fallback', {\n seat, isFinalTurn, taskId: state.taskId,\n });\n turn = { ...turn, action: fallbackActionFor(version, seat, isFinalTurn) };\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 // ─── ask_user pause (P3.2) ────────────────────────────────────────────\n // The negotiator consults its OWN client: persist the turn (done above),\n // park the full turn context, arm the answer-window timer, enqueue the\n // question through the negotiation_inflight preset, then suspend the\n // task as input_required. The graph exits at this turn boundary exactly\n // like the waiting_for_agent suspend; the answer (or window expiry)\n // resumes via the run-existing continuation path.\n if (turn.action === 'ask_user') {\n const disclosureSubject = turn.askUser?.disclosureSubject?.trim()\n || turn.message\n || turn.assessment.reasoning;\n const draftQuestion = turn.askUser?.draftQuestion ?? turn.message ?? undefined;\n\n await database.setTaskTurnContext(state.taskId, {\n sourceUser: state.sourceUser,\n candidateUser: state.candidateUser,\n indexContext: state.indexContext,\n seedAssessment: state.seedAssessment,\n ...(isSource && state.discoveryQuery && { discoveryQuery: state.discoveryQuery }),\n });\n\n // Arm the timer BEFORE flipping state: a timer against a task that\n // never reaches input_required no-ops harmlessly at fire time, while\n // an input_required task without a timer would strand until the lock\n // slack expires.\n const windowMs = askUserAnswerWindowMs();\n await timeoutQueue!.enqueueAskUserExpiry!(state.taskId, {\n opportunityId: state.opportunityId,\n userId: ownUser.id,\n disclosureSubject,\n }, windowMs);\n\n // Counterparty referenced by attributes, never identity — the\n // negotiation_inflight preset's referential-closure contract.\n const counterpartyHint = [\n otherUser.profile.bio,\n otherUser.profile.location,\n otherUser.profile.skills?.length ? `skills: ${otherUser.profile.skills.join(', ')}` : undefined,\n ].filter(Boolean).join('; ') || 'a potential match on the network';\n const userContext = (await database.getUserContext(ownUser.id, null).catch(() => null))?.text ?? '';\n\n await questionerEnqueue!({\n mode: 'negotiation_inflight',\n userId: ownUser.id,\n sourceType: 'opportunity',\n sourceId: state.opportunityId,\n context: {\n negotiationId: state.taskId,\n counterpartyHint,\n disclosureSubject,\n ...(draftQuestion && { draftQuestion }),\n indexContext: state.indexContext.prompt,\n ...(userContext && { userContext }),\n },\n });\n\n await database.updateTaskState(state.taskId, 'input_required');\n\n turnLog.info('negotiation_ask_user_pause', {\n taskId: state.taskId,\n opportunityId: state.opportunityId,\n seat,\n askingUserId: ownUser.id,\n windowMs,\n });\n traceEmitter?.({ type: \"agent_end\", name: agentName, durationMs: Date.now() - agentStart, summary: \"ask_user\" });\n emitWide({\n type: 'negotiation_ask_user',\n opportunityId: state.opportunityId,\n negotiationConversationId: state.conversationId,\n turnIndex: state.turnCount,\n actor: isSource ? 'source' : 'candidate',\n disclosureSubject,\n windowMs,\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 lastTurn: turn,\n status: 'input_required' as const,\n };\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.status === 'input_required') 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 // ask_user pause: no outcome, no completed state — the task stays\n // input_required until the client answers or the window expires.\n if (state.status === 'input_required') {\n if (state.opportunityId) {\n emitWide({\n type: \"negotiation_outcome\",\n opportunityId: state.opportunityId,\n outcome: \"input_required\",\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 post-negotiation reflection (P5.2 memory write path) — fire\n // and forget: a reflection failure must never affect the outcome. Only\n // sessions that actually exchanged turns teach anything; init/turn\n // errors with turnCount 0 are skipped.\n if (reflectEnqueue && state.turnCount > 0) {\n reflectEnqueue({\n negotiationId: state.taskId,\n conversationId: state.conversationId,\n ...(state.opportunityId && { opportunityId: state.opportunityId }),\n sourceUser: {\n id: state.sourceUser.id,\n ...(state.sourceUser.profile.name && { name: state.sourceUser.profile.name }),\n ...(state.sourceUser.profile.bio && { bio: state.sourceUser.profile.bio }),\n },\n candidateUser: {\n id: state.candidateUser.id,\n ...(state.candidateUser.profile.name && { name: state.candidateUser.profile.name }),\n ...(state.candidateUser.profile.bio && { bio: state.candidateUser.profile.bio }),\n },\n initiatorUserId: state.initiatorUserId ?? state.sourceUser.id,\n outcome: { hasOpportunity, reasoning: outcome.reasoning, turnCount: state.turnCount },\n }).catch((err) =>\n finalizeLog.error('Failed to enqueue negotiation reflection', {\n taskId: state.taskId,\n error: err,\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(\"screen\", screenNode)\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 if (state.error) return \"finalize\";\n // Screen gate: fresh negotiations only (continuations already passed\n // the gate when the dialogue opened); off disables the node entirely.\n if (!state.isContinuation && configuredScreenMode() !== \"off\") return \"screen\";\n return \"turn\";\n }, { screen: \"screen\", turn: \"turn\", finalize: \"finalize\" })\n .addEdge(\"screen\", \"turn\")\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"]}
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,qB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Graph } 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 { ASK_USER_LOCK_SLACK_MS, allowedActionsFor, askUserAnswerWindowMs, configuredAskUserEnabled, configuredProtocolVersion, fallbackActionFor, isRejectLikeAction, isTerminalAction, readProtocolVersion, rejectActionFor } from \"./negotiation.protocol.js\";\nimport { NegotiationScreener, configuredScreenMode, type ScreenDecision, type ScreenDecisionRecord } from \"./negotiation.screen.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\";\nimport type { ReflectEnqueueFn } from \"./negotiation.reflect.js\";\nimport type { NegotiatorMemoryEntry, NegotiatorMemoryRetrieveFn, NegotiatorMemoryScope } from \"./negotiation.memory.js\";\n\nconst logger = protocolLogger(\"NegotiationGraph\");\nconst initLog = protocolLogger(\"NegotiationGraph:Init\");\nconst screenNodeLog = protocolLogger(\"NegotiationGraph:Screen\");\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 * Whether `userId`'s side has already spent its one `ask_user` client\n * consultation in this conversation (P3.2 rationing: max one per negotiation\n * per side, checked against the full message history so continuations count\n * prior sessions' consultations too).\n */\nfunction hasPriorAskUser(\n messages: Array<{ senderId: string; parts: unknown[] }>,\n userId: string,\n): boolean {\n const sender = `agent:${userId}`;\n return messages.some((m) => {\n if (m.senderId !== sender) return false;\n const dataPart = (m.parts as Array<{ kind?: string; data?: { action?: string } }>).find((p) => p.kind === \"data\");\n return dataPart?.data?.action === \"ask_user\";\n });\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 private reflectEnqueue?: ReflectEnqueueFn,\n private memoryRetrieve?: NegotiatorMemoryRetrieveFn,\n ) {}\n\n createGraph() {\n const { database, dispatcher, timeoutQueue, questionerEnqueue, reflectEnqueue, memoryRetrieve } = this;\n const systemAgent = new IndexNegotiator();\n const screener = new NegotiationScreener();\n\n /**\n * P5.3 memory retrieval — never throws, never blocks a negotiation. The\n * injected fn already resolves [] when NEGOTIATOR_MEMORY_INJECT is off;\n * this wrapper adds the graph-side failure guard.\n */\n const retrieveMemory = async (\n userId: string,\n counterpartyUserId: string,\n queryText: string,\n scope: NegotiatorMemoryScope,\n ): Promise<NegotiatorMemoryEntry[]> => {\n if (!memoryRetrieve) return [];\n try {\n return await memoryRetrieve({ userId, counterpartyUserId, queryText, scope });\n } catch (err) {\n logger.warn(\"Negotiator memory retrieval failed; proceeding without memory\", {\n userId,\n scope,\n error: err instanceof Error ? err.message : String(err),\n });\n return [];\n }\n };\n\n /** Similarity query text: seed reasoning + counterparty context. */\n const memoryQueryText = (\n state: typeof NegotiationGraphState.State,\n counterparty: UserNegotiationContext,\n ): string => [\n state.discoveryQuery ? `Search: ${state.discoveryQuery}` : \"\",\n state.seedAssessment?.reasoning ?? \"\",\n counterparty?.profile?.name ?? \"\",\n counterparty?.profile?.bio ?? \"\",\n (counterparty?.intents ?? []).slice(0, 5).map((i) => `${i.title}: ${i.description}`).join(\"\\n\"),\n ].filter(Boolean).join(\"\\n\");\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 if (!activeStates.includes(t.state)) return false;\n // State-aware freshness (IND-401): an `input_required` task is an\n // ask_user pause — it holds the conversation lock for its full answer\n // window (+ slack for the expiry worker), not the 5-min turn window.\n // Otherwise ambient rediscovery / chat negotiate_existing would start\n // a fresh negotiation right past the pause after 5 minutes.\n const freshnessMs = t.state === 'input_required'\n ? askUserAnswerWindowMs() + ASK_USER_LOCK_SLACK_MS\n : 5 * 60 * 1000;\n return (Date.now() - new Date(t.updatedAt).getTime()) < freshnessMs;\n };\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. An `ask_user` last\n // turn does NOT pass the floor: the sender paused to consult its own\n // client, so on resume the same side speaks again — now armed with the\n // client's answer (or its recorded absence). Flipping here would hand\n // the turn to the counterparty, who has nothing to respond to.\n let currentSpeaker: 'source' | 'candidate' = 'source';\n if (isContinuation && priorMessages.length > 0) {\n const lastMessage = priorMessages[priorMessages.length - 1];\n const lastAction = turnsFromMessages([lastMessage])[0]?.action;\n if (lastAction === 'ask_user') {\n currentSpeaker = lastMessage.senderId === agentIdA ? 'source' : 'candidate';\n } else {\n currentSpeaker = lastMessage.senderId === agentIdA ? 'candidate' : 'source';\n }\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 /**\n * Screen node (P2.1) — the outreach gate. Runs between init and the first\n * turn on FRESH negotiations only (routing skips it on continuations and\n * when NEGOTIATION_SCREEN_MODE=off). The reaching client's negotiator\n * decides whether the match is worth its client's name; in shadow mode the\n * decision is recorded (task metadata + trace event + log line) but never\n * blocks — the negotiation always proceeds to the first turn. `enforce`\n * runs identically until P2.2 lands enforcement (by the time this node\n * runs, init has already created the task and flipped the opportunity to\n * `negotiating` — P2.2 owns making a blocking `pass` quiet/correct).\n */\n const screenNode = 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 const mode = configuredScreenMode();\n if (mode === \"enforce\") {\n screenNodeLog.warn(\"NEGOTIATION_SCREEN_MODE=enforce requested but enforcement lands in P2.2; running shadow\", {\n taskId: state.taskId,\n });\n }\n\n const start = Date.now();\n // The client is the initiator seat's user — the side whose negotiator is\n // reaching out. Fresh runs stamp initiatorUserId in init; fall back to\n // sourceUser (what the stamp defaults to anyway).\n const initiatorId = state.initiatorUserId ?? state.sourceUser.id;\n const clientIsSource = initiatorId !== state.candidateUser.id;\n const clientUser = clientIsSource ? state.sourceUser : state.candidateUser;\n const counterpartyUser = clientIsSource ? state.candidateUser : state.sourceUser;\n\n // P5.3: the client's own negotiator memory informs the outreach gate.\n // Cached into state so the client's first turn reuses it.\n const clientSide: \"source\" | \"candidate\" = clientIsSource ? \"source\" : \"candidate\";\n const clientMemory = state.memoryBySide?.[clientSide]\n ?? (memoryRetrieve\n ? await retrieveMemory(clientUser.id, counterpartyUser.id, memoryQueryText(state, counterpartyUser), \"screen\")\n : []);\n\n let decision: ScreenDecision;\n let failedOpen = false;\n let screenError: string | undefined;\n try {\n const counterpartyContext = (await database.getUserContext(counterpartyUser.id, null).catch(() => null))?.text ?? \"\";\n decision = await screener.invoke({\n clientUser,\n counterpartyUser,\n ...(counterpartyContext && { counterpartyContext }),\n ...(clientMemory.length > 0 && { memory: clientMemory }),\n // discoveryQuery belongs to the discovery session's source user; only\n // meaningful for the client when the client holds the source side.\n ...(clientIsSource && state.discoveryQuery && { discoveryQuery: state.discoveryQuery }),\n seedAssessment: state.seedAssessment,\n indexContext: state.indexContext,\n });\n } catch (err) {\n // Fail open: a screen failure must never block a negotiation.\n failedOpen = true;\n screenError = err instanceof Error ? err.message : String(err);\n screenNodeLog.warn(\"Screen failed; proceeding open (reach_out)\", {\n taskId: state.taskId,\n opportunityId: state.opportunityId || undefined,\n error: screenError,\n });\n decision = {\n decision: \"reach_out\",\n reasoning: `screen_error: ${screenError}`,\n evidence: { counterpartyPremiseFit: \"\", intentAlignment: \"\" },\n };\n }\n\n const durationMs = Date.now() - start;\n const record: ScreenDecisionRecord = {\n ...decision,\n mode,\n ...(failedOpen && { failedOpen, error: screenError }),\n screenedAt: new Date().toISOString(),\n durationMs,\n };\n\n await database.setTaskScreenDecision?.(state.taskId, record as unknown as Record<string, unknown>).catch((err) => {\n screenNodeLog.error(\"Failed to persist screen decision\", { taskId: state.taskId, error: err });\n });\n\n screenNodeLog.info(\"negotiation_screen\", {\n taskId: state.taskId,\n opportunityId: state.opportunityId || undefined,\n decision: decision.decision,\n mode,\n failedOpen,\n durationMs,\n });\n\n if (state.opportunityId) {\n emitWide({\n type: \"negotiation_screen\",\n opportunityId: state.opportunityId,\n negotiationConversationId: state.conversationId,\n decision: decision.decision,\n reasoning: decision.reasoning,\n mode,\n failedOpen,\n durationMs,\n });\n }\n\n // Shadow (and pre-P2.2 enforce): always proceed to the first turn.\n return { screenDecision: record, memoryBySide: { [clientSide]: clientMemory } };\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 // ask_user availability (P3.2): flag on, full pause loop wired\n // (questioner + answer-window timer + an opportunity to resume\n // against), v2 non-final non-opening turn, and this side's one client\n // consultation not yet spent (rationing). Chat-triggered runs get no\n // special casing — the pause exits the graph at the turn boundary, so\n // the stream never blocks on a question; the resume is always an async\n // continuation.\n const askUserAvailable =\n version === 'v2'\n && !isFinalTurn\n && configuredAskUserEnabled()\n && !!questionerEnqueue\n && !!timeoutQueue?.enqueueAskUserExpiry\n && !!state.opportunityId\n && !(state.turnCount === 0 && !state.isContinuation)\n && !hasPriorAskUser(state.messages, ownUser.id);\n\n // P5.3: the speaker's own negotiator memory (cached per side across\n // turns). Injected into both the dispatch payload (the user's own\n // agent — scope-correct) and the system-agent prompt.\n const ownSide: \"source\" | \"candidate\" = isSource ? \"source\" : \"candidate\";\n const ownMemory = state.memoryBySide?.[ownSide]\n ?? (memoryRetrieve\n ? await retrieveMemory(ownUser.id, otherUser.id, memoryQueryText(state, otherUser), \"turn\")\n : []);\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, { askUser: askUserAvailable })],\n ...(state.discoveryQuery && isSource && { discoveryQuery: state.discoveryQuery }),\n ...(ownMemory.length > 0 && { negotiatorMemory: ownMemory }),\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, { askUser: askUserAvailable }).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 ...(askUserAvailable && { canAskUser: true }),\n ...(ownMemory.length > 0 && { memory: ownMemory }),\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 // Safety net: an ask_user that slipped past availability gating (e.g. a\n // locally-dispatched agent ignoring allowedActions, or rationing already\n // spent) is coerced to the conservative fallback BEFORE persisting — a\n // pause we cannot resume must never enter the turn history.\n if (turn.action === 'ask_user' && !askUserAvailable) {\n turnLog.warn('ask_user emitted while unavailable, coercing to conservative fallback', {\n seat, isFinalTurn, taskId: state.taskId,\n });\n turn = { ...turn, action: fallbackActionFor(version, seat, isFinalTurn) };\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 // ─── ask_user pause (P3.2) ────────────────────────────────────────────\n // The negotiator consults its OWN client: persist the turn (done above),\n // park the full turn context, arm the answer-window timer, enqueue the\n // question through the negotiation_inflight preset, then suspend the\n // task as input_required. The graph exits at this turn boundary exactly\n // like the waiting_for_agent suspend; the answer (or window expiry)\n // resumes via the run-existing continuation path.\n if (turn.action === 'ask_user') {\n const disclosureSubject = turn.askUser?.disclosureSubject?.trim()\n || turn.message\n || turn.assessment.reasoning;\n const draftQuestion = turn.askUser?.draftQuestion ?? turn.message ?? undefined;\n\n await database.setTaskTurnContext(state.taskId, {\n sourceUser: state.sourceUser,\n candidateUser: state.candidateUser,\n indexContext: state.indexContext,\n seedAssessment: state.seedAssessment,\n ...(isSource && state.discoveryQuery && { discoveryQuery: state.discoveryQuery }),\n });\n\n // Arm the timer BEFORE flipping state: a timer against a task that\n // never reaches input_required no-ops harmlessly at fire time, while\n // an input_required task without a timer would strand until the lock\n // slack expires.\n const windowMs = askUserAnswerWindowMs();\n await timeoutQueue!.enqueueAskUserExpiry!(state.taskId, {\n opportunityId: state.opportunityId,\n userId: ownUser.id,\n disclosureSubject,\n }, windowMs);\n\n // Counterparty referenced by attributes, never identity — the\n // negotiation_inflight preset's referential-closure contract.\n const counterpartyHint = [\n otherUser.profile.bio,\n otherUser.profile.location,\n otherUser.profile.skills?.length ? `skills: ${otherUser.profile.skills.join(', ')}` : undefined,\n ].filter(Boolean).join('; ') || 'a potential match on the network';\n const userContext = (await database.getUserContext(ownUser.id, null).catch(() => null))?.text ?? '';\n\n await questionerEnqueue!({\n mode: 'negotiation_inflight',\n userId: ownUser.id,\n sourceType: 'opportunity',\n sourceId: state.opportunityId,\n context: {\n negotiationId: state.taskId,\n counterpartyHint,\n disclosureSubject,\n ...(draftQuestion && { draftQuestion }),\n indexContext: state.indexContext.prompt,\n ...(userContext && { userContext }),\n },\n });\n\n await database.updateTaskState(state.taskId, 'input_required');\n\n turnLog.info('negotiation_ask_user_pause', {\n taskId: state.taskId,\n opportunityId: state.opportunityId,\n seat,\n askingUserId: ownUser.id,\n windowMs,\n });\n traceEmitter?.({ type: \"agent_end\", name: agentName, durationMs: Date.now() - agentStart, summary: \"ask_user\" });\n emitWide({\n type: 'negotiation_ask_user',\n opportunityId: state.opportunityId,\n negotiationConversationId: state.conversationId,\n turnIndex: state.turnCount,\n actor: isSource ? 'source' : 'candidate',\n disclosureSubject,\n windowMs,\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 lastTurn: turn,\n status: 'input_required' as const,\n };\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 memoryBySide: { [ownSide]: ownMemory },\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.status === 'input_required') 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 // ask_user pause: no outcome, no completed state — the task stays\n // input_required until the client answers or the window expires.\n if (state.status === 'input_required') {\n if (state.opportunityId) {\n emitWide({\n type: \"negotiation_outcome\",\n opportunityId: state.opportunityId,\n outcome: \"input_required\",\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 post-negotiation reflection (P5.2 memory write path) — fire\n // and forget: a reflection failure must never affect the outcome. Only\n // sessions that actually exchanged turns teach anything; init/turn\n // errors with turnCount 0 are skipped.\n if (reflectEnqueue && state.turnCount > 0) {\n reflectEnqueue({\n negotiationId: state.taskId,\n conversationId: state.conversationId,\n ...(state.opportunityId && { opportunityId: state.opportunityId }),\n sourceUser: {\n id: state.sourceUser.id,\n ...(state.sourceUser.profile.name && { name: state.sourceUser.profile.name }),\n ...(state.sourceUser.profile.bio && { bio: state.sourceUser.profile.bio }),\n },\n candidateUser: {\n id: state.candidateUser.id,\n ...(state.candidateUser.profile.name && { name: state.candidateUser.profile.name }),\n ...(state.candidateUser.profile.bio && { bio: state.candidateUser.profile.bio }),\n },\n initiatorUserId: state.initiatorUserId ?? state.sourceUser.id,\n outcome: { hasOpportunity, reasoning: outcome.reasoning, turnCount: state.turnCount },\n }).catch((err) =>\n finalizeLog.error('Failed to enqueue negotiation reflection', {\n taskId: state.taskId,\n error: err,\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(\"screen\", screenNode)\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 if (state.error) return \"finalize\";\n // Screen gate: fresh negotiations only (continuations already passed\n // the gate when the dialogue opened); off disables the node entirely.\n if (!state.isContinuation && configuredScreenMode() !== \"off\") return \"screen\";\n return \"turn\";\n }, { screen: \"screen\", turn: \"turn\", finalize: \"finalize\" })\n .addEdge(\"screen\", \"turn\")\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,58 @@
1
+ import type { DistilledMemoryKind } from "./negotiation.reflect.js";
2
+ /**
3
+ * A single memory entry as injected into prompts. A projection of the
4
+ * `negotiator_memories` row: content + kind + confidence only — ids,
5
+ * embeddings, and provenance never enter the prompt.
6
+ */
7
+ export interface NegotiatorMemoryEntry {
8
+ kind: DistilledMemoryKind;
9
+ content: string;
10
+ /** Anti-poisoning weight (0..1); rendered so the model can weigh hints. */
11
+ confidence?: number;
12
+ }
13
+ /** Where a retrieval is happening — lets the read service tune top-k/scope. */
14
+ export type NegotiatorMemoryScope = "screen" | "turn";
15
+ /** Query the graph hands to the injected retrieval function. */
16
+ export interface NegotiatorMemoryQuery {
17
+ /** The user whose negotiator's own memory is being retrieved. */
18
+ userId: string;
19
+ /** The other side of this negotiation (dossier subject). */
20
+ counterpartyUserId: string;
21
+ /** Free-text similarity query (seed reasoning + counterparty context). */
22
+ queryText: string;
23
+ scope: NegotiatorMemoryScope;
24
+ }
25
+ /**
26
+ * Injected retrieval seam (services/api implements it over the
27
+ * `negotiator_memories` store). MUST resolve to `[]` on any failure or when
28
+ * `NEGOTIATOR_MEMORY_INJECT` is off — memory must never break a negotiation.
29
+ */
30
+ export type NegotiatorMemoryRetrieveFn = (query: NegotiatorMemoryQuery) => Promise<NegotiatorMemoryEntry[]>;
31
+ export interface RenderNegotiatorMemoryOptions {
32
+ /**
33
+ * When true (screen node), instructs the model to reflect memory influence
34
+ * into `evidence.memoryHints` — without copying sensitive text verbatim.
35
+ */
36
+ memoryHintsInstruction?: boolean;
37
+ }
38
+ /**
39
+ * Renders the private negotiator-memory section for counterparty-facing
40
+ * prompts (the negotiation turn agent and the screen gate).
41
+ *
42
+ * Disclosure rules are HARD constraints — never soft hints; everything else
43
+ * is advisory, weighted by confidence. The section leads with the leak
44
+ * guard: memory text must never reach counterparty-visible fields.
45
+ *
46
+ * @returns Empty string when there are no entries (byte-identical prompts).
47
+ */
48
+ export declare function renderNegotiatorMemorySection(entries: NegotiatorMemoryEntry[], opts?: RenderNegotiatorMemoryOptions): string;
49
+ /**
50
+ * Renders the memory section for the negotiator CHAT persona — the audience
51
+ * is the client themself, so disclosure rules are their own standing
52
+ * instructions (context, not secrets), and the client's live word always
53
+ * outranks a stored note.
54
+ *
55
+ * @returns Empty string when there are no entries (byte-identical prompts).
56
+ */
57
+ export declare function renderNegotiatorChatMemorySection(entries: NegotiatorMemoryEntry[]): string;
58
+ //# sourceMappingURL=negotiation.memory.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"negotiation.memory.d.ts","sourceRoot":"/","sources":["negotiation/negotiation.memory.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAgBpE;;;;GAIG;AACH,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,mBAAmB,CAAC;IAC1B,OAAO,EAAE,MAAM,CAAC;IAChB,2EAA2E;IAC3E,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,+EAA+E;AAC/E,MAAM,MAAM,qBAAqB,GAAG,QAAQ,GAAG,MAAM,CAAC;AAEtD,gEAAgE;AAChE,MAAM,WAAW,qBAAqB;IACpC,iEAAiE;IACjE,MAAM,EAAE,MAAM,CAAC;IACf,4DAA4D;IAC5D,kBAAkB,EAAE,MAAM,CAAC;IAC3B,0EAA0E;IAC1E,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,qBAAqB,CAAC;CAC9B;AAED;;;;GAIG;AACH,MAAM,MAAM,0BAA0B,GAAG,CACvC,KAAK,EAAE,qBAAqB,KACzB,OAAO,CAAC,qBAAqB,EAAE,CAAC,CAAC;AAetC,MAAM,WAAW,6BAA6B;IAC5C;;;OAGG;IACH,sBAAsB,CAAC,EAAE,OAAO,CAAC;CAClC;AAED;;;;;;;;;GASG;AACH,wBAAgB,6BAA6B,CAC3C,OAAO,EAAE,qBAAqB,EAAE,EAChC,IAAI,CAAC,EAAE,6BAA6B,GACnC,MAAM,CA+BR;AAED;;;;;;;GAOG;AACH,wBAAgB,iCAAiC,CAAC,OAAO,EAAE,qBAAqB,EAAE,GAAG,MAAM,CAc1F"}
@@ -0,0 +1,71 @@
1
+ const KIND_LABELS = {
2
+ playbook: "playbook",
3
+ disclosure_rule: "disclosure rule",
4
+ counterparty_dossier: "counterparty note",
5
+ threshold: "threshold",
6
+ };
7
+ function confidenceSuffix(entry) {
8
+ return typeof entry.confidence === "number"
9
+ ? ` (confidence ${Math.round(entry.confidence * 100) / 100})`
10
+ : "";
11
+ }
12
+ /**
13
+ * Renders the private negotiator-memory section for counterparty-facing
14
+ * prompts (the negotiation turn agent and the screen gate).
15
+ *
16
+ * Disclosure rules are HARD constraints — never soft hints; everything else
17
+ * is advisory, weighted by confidence. The section leads with the leak
18
+ * guard: memory text must never reach counterparty-visible fields.
19
+ *
20
+ * @returns Empty string when there are no entries (byte-identical prompts).
21
+ */
22
+ export function renderNegotiatorMemorySection(entries, opts) {
23
+ if (entries.length === 0)
24
+ return "";
25
+ const disclosureRules = entries.filter((e) => e.kind === "disclosure_rule");
26
+ const advisory = entries.filter((e) => e.kind !== "disclosure_rule");
27
+ const lines = [
28
+ "",
29
+ "",
30
+ "PRIVATE NEGOTIATOR MEMORY — for your reasoning only. Never quote, paraphrase, or reveal any of it to the counterparty, and never mention that these notes exist.",
31
+ ];
32
+ if (disclosureRules.length > 0) {
33
+ lines.push("HARD DISCLOSURE CONSTRAINTS (absolute — these override every other goal, including reaching a deal):");
34
+ for (const rule of disclosureRules) {
35
+ lines.push(`- ${rule.content}`);
36
+ }
37
+ }
38
+ if (advisory.length > 0) {
39
+ lines.push("Advisory notes from prior negotiations and client conversations (weigh by confidence; the live context wins on conflict):");
40
+ for (const entry of advisory) {
41
+ lines.push(`- [${KIND_LABELS[entry.kind]}] ${entry.content}${confidenceSuffix(entry)}`);
42
+ }
43
+ }
44
+ if (opts?.memoryHintsInstruction) {
45
+ lines.push("Set evidence.memoryHints to a short note on how these memories informed your decision — describe the influence, never copy sensitive contents verbatim.");
46
+ }
47
+ return lines.join("\n");
48
+ }
49
+ /**
50
+ * Renders the memory section for the negotiator CHAT persona — the audience
51
+ * is the client themself, so disclosure rules are their own standing
52
+ * instructions (context, not secrets), and the client's live word always
53
+ * outranks a stored note.
54
+ *
55
+ * @returns Empty string when there are no entries (byte-identical prompts).
56
+ */
57
+ export function renderNegotiatorChatMemorySection(entries) {
58
+ if (entries.length === 0)
59
+ return "";
60
+ const lines = [
61
+ "",
62
+ "## Your negotiator memory",
63
+ "Notes you have accumulated from negotiations and prior conversations with your client (private to the two of you; weigh by confidence):",
64
+ ];
65
+ for (const entry of entries) {
66
+ lines.push(`- [${KIND_LABELS[entry.kind]}] ${entry.content}${confidenceSuffix(entry)}`);
67
+ }
68
+ lines.push("Use these to inform reports and recommendations. If the client contradicts one, trust the client — their current word always outranks a stored note.");
69
+ return lines.join("\n");
70
+ }
71
+ //# sourceMappingURL=negotiation.memory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"negotiation.memory.js","sourceRoot":"/","sources":["negotiation/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M,KAAK,IAAI,QAAQ,EAAE,CAAC;YAC7B,KAAK,CAAC,IAAI,CAAC,MAAM,WAAW,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,KAAK,CAAC,OAAO,GAAG,gBAAgB,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAC1F,CAAC;IACH,CAAC;IAED,IAAI,IAAI,EAAE,sBAAsB,EAAE,CAAC;QACjC,KAAK,CAAC,IAAI,CAAC,yJAAyJ,CAAC,CAAC;IACxK,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,iCAAiC,CAAC,OAAgC;IAChF,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IAEpC,MAAM,KAAK,GAAa;QACtB,EAAE;QACF,2BAA2B;QAC3B,yIAAyI;KAC1I,CAAC;IACF,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC5B,KAAK,CAAC,IAAI,CAAC,MAAM,WAAW,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,KAAK,CAAC,OAAO,GAAG,gBAAgB,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAC1F,CAAC;IACD,KAAK,CAAC,IAAI,CAAC,sJAAsJ,CAAC,CAAC;IAEnK,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC","sourcesContent":["import type { DistilledMemoryKind } from \"./negotiation.reflect.js\";\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// NEGOTIATOR MEMORY INJECTION (P5.3 — read path)\n// ═══════════════════════════════════════════════════════════════════════════════\n//\n// Pure prompt-side counterpart of the P5.2 write path: retrieved\n// `negotiator_memories` rows shape how the negotiator screens, argues, and\n// chats. Retrieval itself lives in services/api (the protocol package has no\n// DB access) and is injected via `NegotiatorMemoryRetrieveFn` — the same\n// composition-root pattern as `questionerEnqueue`/`reflectEnqueue`.\n//\n// Contract: when the entry list is empty (memory empty, flag off, retrieval\n// failed) every renderer returns the empty string, so prompts are\n// byte-identical to the pre-P5.3 build.\n\n/**\n * A single memory entry as injected into prompts. A projection of the\n * `negotiator_memories` row: content + kind + confidence only — ids,\n * embeddings, and provenance never enter the prompt.\n */\nexport interface NegotiatorMemoryEntry {\n kind: DistilledMemoryKind;\n content: string;\n /** Anti-poisoning weight (0..1); rendered so the model can weigh hints. */\n confidence?: number;\n}\n\n/** Where a retrieval is happening — lets the read service tune top-k/scope. */\nexport type NegotiatorMemoryScope = \"screen\" | \"turn\";\n\n/** Query the graph hands to the injected retrieval function. */\nexport interface NegotiatorMemoryQuery {\n /** The user whose negotiator's own memory is being retrieved. */\n userId: string;\n /** The other side of this negotiation (dossier subject). */\n counterpartyUserId: string;\n /** Free-text similarity query (seed reasoning + counterparty context). */\n queryText: string;\n scope: NegotiatorMemoryScope;\n}\n\n/**\n * Injected retrieval seam (services/api implements it over the\n * `negotiator_memories` store). MUST resolve to `[]` on any failure or when\n * `NEGOTIATOR_MEMORY_INJECT` is off — memory must never break a negotiation.\n */\nexport type NegotiatorMemoryRetrieveFn = (\n query: NegotiatorMemoryQuery,\n) => Promise<NegotiatorMemoryEntry[]>;\n\nconst KIND_LABELS: Record<DistilledMemoryKind, string> = {\n playbook: \"playbook\",\n disclosure_rule: \"disclosure rule\",\n counterparty_dossier: \"counterparty note\",\n threshold: \"threshold\",\n};\n\nfunction confidenceSuffix(entry: NegotiatorMemoryEntry): string {\n return typeof entry.confidence === \"number\"\n ? ` (confidence ${Math.round(entry.confidence * 100) / 100})`\n : \"\";\n}\n\nexport interface RenderNegotiatorMemoryOptions {\n /**\n * When true (screen node), instructs the model to reflect memory influence\n * into `evidence.memoryHints` — without copying sensitive text verbatim.\n */\n memoryHintsInstruction?: boolean;\n}\n\n/**\n * Renders the private negotiator-memory section for counterparty-facing\n * prompts (the negotiation turn agent and the screen gate).\n *\n * Disclosure rules are HARD constraints — never soft hints; everything else\n * is advisory, weighted by confidence. The section leads with the leak\n * guard: memory text must never reach counterparty-visible fields.\n *\n * @returns Empty string when there are no entries (byte-identical prompts).\n */\nexport function renderNegotiatorMemorySection(\n entries: NegotiatorMemoryEntry[],\n opts?: RenderNegotiatorMemoryOptions,\n): string {\n if (entries.length === 0) return \"\";\n\n const disclosureRules = entries.filter((e) => e.kind === \"disclosure_rule\");\n const advisory = entries.filter((e) => e.kind !== \"disclosure_rule\");\n\n const lines: string[] = [\n \"\",\n \"\",\n \"PRIVATE NEGOTIATOR MEMORY — for your reasoning only. Never quote, paraphrase, or reveal any of it to the counterparty, and never mention that these notes exist.\",\n ];\n\n if (disclosureRules.length > 0) {\n lines.push(\"HARD DISCLOSURE CONSTRAINTS (absolute — these override every other goal, including reaching a deal):\");\n for (const rule of disclosureRules) {\n lines.push(`- ${rule.content}`);\n }\n }\n\n if (advisory.length > 0) {\n lines.push(\"Advisory notes from prior negotiations and client conversations (weigh by confidence; the live context wins on conflict):\");\n for (const entry of advisory) {\n lines.push(`- [${KIND_LABELS[entry.kind]}] ${entry.content}${confidenceSuffix(entry)}`);\n }\n }\n\n if (opts?.memoryHintsInstruction) {\n lines.push(\"Set evidence.memoryHints to a short note on how these memories informed your decision — describe the influence, never copy sensitive contents verbatim.\");\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Renders the memory section for the negotiator CHAT persona — the audience\n * is the client themself, so disclosure rules are their own standing\n * instructions (context, not secrets), and the client's live word always\n * outranks a stored note.\n *\n * @returns Empty string when there are no entries (byte-identical prompts).\n */\nexport function renderNegotiatorChatMemorySection(entries: NegotiatorMemoryEntry[]): string {\n if (entries.length === 0) return \"\";\n\n const lines: string[] = [\n \"\",\n \"## Your negotiator memory\",\n \"Notes you have accumulated from negotiations and prior conversations with your client (private to the two of you; weigh by confidence):\",\n ];\n for (const entry of entries) {\n lines.push(`- [${KIND_LABELS[entry.kind]}] ${entry.content}${confidenceSuffix(entry)}`);\n }\n lines.push(\"Use these to inform reports and recommendations. If the client contradicts one, trust the client — their current word always outranks a stored note.\");\n\n return lines.join(\"\\n\");\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { createStructuredModel } from "../shared/agent/model.config.js";
3
3
  import type { UserNegotiationContext, SeedAssessment } from "../shared/schemas/negotiation-state.schema.js";
4
+ import { type NegotiatorMemoryEntry } from "./negotiation.memory.js";
4
5
  /**
5
6
  * Screen-gate modes (P2.1 — client-advocate protocol).
6
7
  *
@@ -38,7 +39,7 @@ export declare const ScreenDecisionSchema: z.ZodObject<{
38
39
  counterpartyPremiseFit: z.ZodString;
39
40
  /** How the client's intents align with what the counterparty seeks. */
40
41
  intentAlignment: z.ZodString;
41
- /** Prior-negotiation memory signals. Wired in P5.3 always absent today. */
42
+ /** Prior-negotiation memory signals (P5.3). Filled only when negotiator memory was injected into the screen prompt. */
42
43
  memoryHints: z.ZodOptional<z.ZodNullable<z.ZodString>>;
43
44
  }, "strip", z.ZodTypeAny, {
44
45
  counterpartyPremiseFit: string;
@@ -97,6 +98,12 @@ export interface NegotiationScreenerInput {
97
98
  networkId: string;
98
99
  prompt?: string;
99
100
  };
101
+ /**
102
+ * Retrieved negotiator memories for the client (P5.3 read path). Rendered
103
+ * as a private prompt section with a memoryHints instruction. Absent/empty
104
+ * → the prompt is byte-identical to before.
105
+ */
106
+ memory?: NegotiatorMemoryEntry[];
100
107
  }
101
108
  export interface NegotiationScreenerConfig {
102
109
  /** Hard ceiling on the screen LLM round-trip, in ms (default 15000). */