@indexnetwork/protocol 4.5.0-rc.339.1 → 4.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chat/chat-streaming.types.d.ts +1 -1
- package/dist/chat/chat-streaming.types.d.ts.map +1 -1
- package/dist/chat/chat-streaming.types.js.map +1 -1
- package/dist/chat/chat.agent.d.ts +1 -1
- package/dist/chat/chat.agent.d.ts.map +1 -1
- package/dist/chat/chat.agent.js.map +1 -1
- package/dist/negotiation/negotiation.graph.d.ts +26 -26
- package/dist/negotiation/negotiation.graph.d.ts.map +1 -1
- package/dist/negotiation/negotiation.graph.js +42 -21
- package/dist/negotiation/negotiation.graph.js.map +1 -1
- package/dist/negotiation/negotiation.screen.d.ts +5 -3
- package/dist/negotiation/negotiation.screen.d.ts.map +1 -1
- package/dist/negotiation/negotiation.screen.js +5 -3
- package/dist/negotiation/negotiation.screen.js.map +1 -1
- package/dist/negotiation/negotiation.state.d.ts +6 -6
- package/dist/negotiation/negotiation.state.js +1 -1
- package/dist/negotiation/negotiation.state.js.map +1 -1
- package/dist/negotiation/negotiation.summarizer.js +1 -1
- package/dist/negotiation/negotiation.summarizer.js.map +1 -1
- package/dist/opportunity/negotiation-context.loader.d.ts +5 -0
- package/dist/opportunity/negotiation-context.loader.d.ts.map +1 -1
- package/dist/opportunity/negotiation-context.loader.js +9 -0
- package/dist/opportunity/negotiation-context.loader.js.map +1 -1
- package/dist/opportunity/question.prompt.d.ts +1 -1
- package/dist/opportunity/question.prompt.d.ts.map +1 -1
- package/dist/opportunity/question.prompt.js +2 -0
- package/dist/opportunity/question.prompt.js.map +1 -1
- package/dist/shared/schemas/discovery-question.schema.d.ts +8 -8
- package/dist/shared/schemas/discovery-question.schema.js +1 -1
- package/dist/shared/schemas/discovery-question.schema.js.map +1 -1
- package/dist/shared/schemas/negotiation-digest.schema.d.ts +3 -3
- package/dist/shared/schemas/negotiation-digest.schema.js +1 -1
- package/dist/shared/schemas/negotiation-digest.schema.js.map +1 -1
- package/dist/shared/schemas/negotiation-state.schema.d.ts +3 -3
- package/dist/shared/schemas/negotiation-state.schema.js +1 -1
- package/dist/shared/schemas/negotiation-state.schema.js.map +1 -1
- 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;AAK5E,MAAM,MAAM,GAAG,cAAc,CAAC,kBAAkB,CAAC,CAAC;AAClD,MAAM,OAAO,GAAG,cAAc,CAAC,uBAAuB,CAAC,CAAC;AACxD,MAAM,aAAa,GAAG,cAAc,CAAC,yBAAyB,CAAC,CAAC;AAChE,MAAM,OAAO,GAAG,cAAc,CAAC,uBAAuB,CAAC,CAAC;AACxD,MAAM,WAAW,GAAG,cAAc,CAAC,2BAA2B,CAAC,CAAC;AAChE,MAAM,sBAAsB,GAAG,cAAc,CAAC,sCAAsC,CAAC,CAAC;AAEtF,6EAA6E;AAC7E,SAAS,iBAAiB,CAAC,QAAqC;IAC9D,OAAO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AC,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\";\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"]}
|
|
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,EAA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K,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\";\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. In enforce\n * mode (P2.2) a `pass` routes straight to finalize: zero turns, zero\n * counterparty involvement, outcome `reason: \"screened_out\"`, opportunity\n * quietly `rejected` (init had already flipped it to `negotiating`).\n * A failed screen still fails OPEN in every mode.\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 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 // Routing happens on the conditional edge: shadow always proceeds to\n // the first turn; enforce routes a (non-failed-open) pass to finalize.\n return { screenDecision: record, memoryBySide: { [clientSide]: clientMemory } };\n };\n\n /**\n * P2.2 — true when the screen gate blocked this negotiation: enforce mode,\n * a genuine `pass` (never failed-open), before any turn was exchanged.\n * Shadow-mode passes and fail-open records never block.\n */\n const isScreenBlocked = (state: typeof NegotiationGraphState.State): boolean =>\n state.screenDecision?.mode === \"enforce\"\n && state.screenDecision.decision === \"pass\"\n && state.screenDecision.failedOpen !== true\n && state.turnCount === 0;\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 // P2.2: the client's own outreach gate declined before any turn — the\n // negotiation never happened from the counterparty's perspective.\n const screenedOut = isScreenBlocked(state);\n const atCap = !screenedOut && (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: screenedOut\n ? (state.screenDecision?.reasoning ?? \"\")\n : (lastTurn?.assessment.reasoning ?? \"\"),\n turnCount: state.turnCount,\n ...(screenedOut\n ? { reason: \"screened_out\" as const }\n : atCap\n ? { reason: \"turn_cap\" as const }\n : {}),\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' : screenedOut ? 'screened_out' : (atCap ? 'turn_cap' : (lastTurn?.action ?? 'unknown')),\n opportunityId: state.opportunityId || undefined,\n });\n\n if (state.opportunityId) {\n // screened_out → 'rejected': quiet terminal status (hidden from\n // default lists), never 'stalled' — with zero turns the generic\n // mapping would misfile the client's own gate decision.\n const nextStatus = lastTurn?.action === 'accept'\n ? 'pending'\n : (screenedOut || 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\" | \"screened_out\" =\n hasOpportunity\n ? \"accepted\"\n : screenedOut\n ? \"screened_out\"\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 // P2.2: enforce-mode pass → finalize (screened_out); everything else → turn.\n .addConditionalEdges(\"screen\", (state: typeof NegotiationGraphState.State) =>\n isScreenBlocked(state) ? \"finalize\" : \"turn\",\n { turn: \"turn\", finalize: \"finalize\" })\n .addEdge(\"__start__\", \"init\")\n .addEdge(\"finalize\", \"__end__\");\n\n return workflow.compile();\n }\n}\n\nexport interface NegotiationCandidate {\n userId: string;\n reasoning: string;\n valencyRole: string;\n networkId?: string;\n candidateUser: UserNegotiationContext;\n /** The explicit search query that triggered discovery (if any). */\n discoveryQuery?: string;\n /**\n * ID of the opportunity this negotiation is for. When set, the negotiation\n * graph's finalize node updates the opportunity's status based on the outcome\n * (`accept` → 'pending', `reject` → 'rejected', otherwise → 'stalled').\n */\n opportunityId?: string;\n}\n\nexport interface NegotiationResult {\n userId: string;\n agreedRoles: NegotiationOutcome[\"agreedRoles\"];\n reasoning: string;\n turnCount: number;\n}\n\n/**\n * Per-candidate resolution hook — fires as each negotiation settles, before\n * Promise.all aggregates. Used by the orchestrator branch to progressively\n * stream `opportunity_draft_ready` events as each candidate resolves, rather\n * than emitting all at once after the full fan-out completes. Awaited so the\n * caller can run async work (DB update, event emit) before the next settle.\n *\n * `turns` and `outcome` are passed through from the underlying negotiation\n * graph so consumers can build per-candidate decision-question inputs without\n * re-walking trace events or DB artifacts. Both are present on every\n * resolution (accepted, rejected, stalled, error); error paths receive a\n * synthesized `outcome` with `hasOpportunity: false`.\n */\nexport type OnNegotiationResolved = (entry: {\n candidate: NegotiationCandidate;\n accepted: NegotiationResult | null;\n turns: NegotiationTurn[];\n outcome: NegotiationOutcome;\n}) => Promise<void>;\n\n/**\n * Runs bilateral negotiation for each candidate in parallel.\n * @returns Only candidates that produced an opportunity\n */\nexport async function negotiateCandidates(\n negotiationGraph: NegotiationGraphLike,\n sourceUser: UserNegotiationContext,\n candidates: NegotiationCandidate[],\n indexContext: { networkId: string; prompt: string },\n opts?: {\n maxTurns?: number;\n traceEmitter?: TraceEmitter;\n indexContextOverrides?: Map<string, string>;\n timeoutMs?: number;\n onCandidateResolved?: OnNegotiationResolved;\n trigger?: \"orchestrator\" | \"ambient\";\n /**\n * Initiator seat for every candidate session in this fan-out (v2 stamp).\n * Passed through to the negotiation graph, which may still override it by\n * inheriting from a prior task on the same opportunity/conversation.\n */\n initiatorUserId?: string;\n },\n): Promise<NegotiationResult[]> {\n const { maxTurns, traceEmitter, indexContextOverrides, timeoutMs, onCandidateResolved, trigger, initiatorUserId } = opts ?? {};\n\n // Local helper to emit events whose shape is wider than the declared\n // `TraceEmitter` union (mirrors the cast used in chat.agent at the relay sink\n // and inside turn/finalize nodes above).\n const emitWide = (event: Record<string, unknown>) =>\n (traceEmitter as ((e: Record<string, unknown>) => void) | undefined)?.(event);\n\n const results = await Promise.all(\n candidates.map(async (candidate) => {\n const start = Date.now();\n if (candidate.opportunityId) {\n const candidateName = candidate.candidateUser?.profile?.name;\n emitWide({\n type: \"negotiation_session_start\",\n opportunityId: candidate.opportunityId,\n negotiationConversationId: \"\", // filled in on session_end\n sourceUserId: sourceUser.id,\n candidateUserId: candidate.userId,\n initiatorUserId: initiatorUserId ?? sourceUser.id,\n ...(candidateName && { candidateName }),\n trigger: trigger ?? \"ambient\",\n startedAt: start,\n });\n }\n traceEmitter?.({ type: \"agent_start\", name: \"Negotiating candidate\" });\n\n try {\n const candidateIndexContext = candidate.networkId\n ? { networkId: candidate.networkId, prompt: indexContextOverrides?.get(candidate.networkId) ?? '' }\n : indexContext;\n\n const result = await invokeWithAbortSignal(negotiationGraph, {\n sourceUser,\n candidateUser: candidate.candidateUser,\n indexContext: candidateIndexContext,\n seedAssessment: {\n reasoning: candidate.reasoning,\n valencyRole: candidate.valencyRole,\n },\n ...(candidate.discoveryQuery && { discoveryQuery: candidate.discoveryQuery }),\n ...(candidate.opportunityId && { opportunityId: candidate.opportunityId }),\n ...(initiatorUserId && { initiatorUserId }),\n ...(maxTurns !== undefined && { maxTurns }),\n ...(timeoutMs !== undefined && { timeoutMs }),\n });\n\n const durationMs = Date.now() - start;\n const outcome = result.outcome;\n const hasOpportunity = outcome?.hasOpportunity === true;\n const isContinuation = (result as { isContinuation?: boolean }).isContinuation ?? false;\n const priorTurnCount = (result as { priorTurnCount?: number }).priorTurnCount ?? 0;\n\n const turnFlow = (result.messages ?? [])\n .map((m) => {\n const dataPart = (m.parts as Array<{ kind?: string; data?: Record<string, unknown> }>)?.find((p) => p.kind === \"data\");\n if (!dataPart?.data) return null;\n const turn = dataPart.data as { action?: string };\n return turn.action ?? \"unknown\";\n })\n .filter(Boolean)\n .join(\" → \");\n\n const statusTag = hasOpportunity ? \"✓ opportunity\" : \"✗ rejected\";\n traceEmitter?.({ type: \"agent_end\", name: \"Negotiating candidate\", durationMs, summary: `${candidate.userId}: ${turnFlow} ${statusTag}` });\n\n if (candidate.opportunityId) {\n emitWide({\n type: \"negotiation_session_end\",\n opportunityId: candidate.opportunityId,\n negotiationConversationId: (result as { conversationId?: string }).conversationId ?? \"\",\n durationMs: Date.now() - start,\n isContinuation,\n turnsAdded: outcome?.turnCount ?? 0,\n priorTurnCount,\n });\n }\n\n const accepted: NegotiationResult | null = hasOpportunity && outcome\n ? {\n userId: candidate.userId,\n agreedRoles: outcome.agreedRoles,\n reasoning: outcome.reasoning,\n turnCount: outcome.turnCount,\n }\n : null;\n\n if (onCandidateResolved) {\n const turnHistory: NegotiationTurn[] = turnsFromMessages(result.messages ?? []);\n const resolvedOutcome: NegotiationOutcome = result.outcome ?? {\n hasOpportunity: false,\n agreedRoles: [],\n reasoning: \"no outcome returned by negotiation graph\",\n turnCount: turnHistory.length,\n };\n try {\n await onCandidateResolved({\n candidate,\n accepted,\n turns: turnHistory,\n outcome: resolvedOutcome,\n });\n } catch (hookErr) {\n // Hook failures must not sink the candidate result — the aggregate\n // return is still useful, and the orchestrator branch logs its own\n // failures inline.\n negotiateCandidatesLog.error(\"onCandidateResolved hook threw\", {\n candidateUserId: candidate.userId,\n error: hookErr,\n });\n }\n }\n\n return accepted;\n } catch (err) {\n const durationMs = Date.now() - start;\n traceEmitter?.({ type: \"agent_end\", name: \"Negotiating candidate\", durationMs, summary: `${candidate.userId}: error` });\n if (candidate.opportunityId) {\n emitWide({\n type: \"negotiation_session_end\",\n opportunityId: candidate.opportunityId,\n negotiationConversationId: \"\",\n durationMs: Date.now() - start,\n });\n }\n negotiateCandidatesLog.error(\"Negotiation failed\", { candidateUserId: candidate.userId, error: err });\n if (onCandidateResolved) {\n try {\n await onCandidateResolved({\n candidate,\n accepted: null,\n turns: [],\n outcome: {\n hasOpportunity: false,\n agreedRoles: [],\n reasoning: err instanceof Error ? err.message : String(err),\n turnCount: 0,\n },\n });\n } catch {\n // ignore hook failure on error path\n }\n }\n return null;\n }\n }),\n );\n\n return results.filter((r): r is NegotiationResult => r !== null);\n}\n\n/**\n * Creates a negotiation graph with the provided dependencies.\n */\nexport function createDefaultNegotiationGraph(deps: {\n database: NegotiationGraphDatabase;\n dispatcher: AgentDispatcher;\n timeoutQueue?: NegotiationTimeoutQueue;\n}) {\n const factory = new NegotiationGraphFactory(deps.database, deps.dispatcher, deps.timeoutQueue);\n return factory.createGraph();\n}\n"]}
|
|
@@ -10,9 +10,11 @@ import { type NegotiatorMemoryEntry } from "./negotiation.memory.js";
|
|
|
10
10
|
* trace event + log line) but NEVER blocks: every fresh negotiation still
|
|
11
11
|
* proceeds to the first turn. Used to measure pass rates against observed
|
|
12
12
|
* reject rates before enforcement.
|
|
13
|
-
* - `enforce` —
|
|
14
|
-
*
|
|
15
|
-
*
|
|
13
|
+
* - `enforce` — (P2.2) a `pass` decision blocks the negotiation before the
|
|
14
|
+
* first turn: the graph routes straight to finalize with outcome
|
|
15
|
+
* `reason: "screened_out"` — zero turns, zero counterparty involvement,
|
|
16
|
+
* zero notifications; the opportunity is quietly `rejected`. A failed
|
|
17
|
+
* screen still fails OPEN (never blocks), and `reach_out` proceeds normally.
|
|
16
18
|
*/
|
|
17
19
|
export declare const NEGOTIATION_SCREEN_MODES: readonly ["off", "shadow", "enforce"];
|
|
18
20
|
export type NegotiationScreenMode = (typeof NEGOTIATION_SCREEN_MODES)[number];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"negotiation.screen.d.ts","sourceRoot":"/","sources":["negotiation/negotiation.screen.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAExE,OAAO,KAAK,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,+CAA+C,CAAC;AAE5G,OAAO,EAAiC,KAAK,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAIpG
|
|
1
|
+
{"version":3,"file":"negotiation.screen.d.ts","sourceRoot":"/","sources":["negotiation/negotiation.screen.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAExE,OAAO,KAAK,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,+CAA+C,CAAC;AAE5G,OAAO,EAAiC,KAAK,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAIpG;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,wBAAwB,uCAAwC,CAAC;AAE9E,MAAM,MAAM,qBAAqB,GAAG,CAAC,OAAO,wBAAwB,CAAC,CAAC,MAAM,CAAC,CAAC;AAE9E;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,IAAI,qBAAqB,CAI5D;AAED;;;GAGG;AACH,eAAO,MAAM,oBAAoB;;;IAG/B,8EAA8E;;;QAG5E,0EAA0E;;QAE1E,uEAAuE;;QAEvE,uHAAuH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAGzH,CAAC;AAEH,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,oBAAoB,CAAC,CAAC;AAElE;;;;GAIG;AACH,MAAM,WAAW,oBAAqB,SAAQ,cAAc;IAC1D,IAAI,EAAE,qBAAqB,CAAC;IAC5B,wEAAwE;IACxE,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,8CAA8C;IAC9C,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,wBAAwB;IACvC,+EAA+E;IAC/E,UAAU,EAAE,sBAAsB,CAAC;IACnC,yEAAyE;IACzE,gBAAgB,EAAE,sBAAsB,CAAC;IACzC,+EAA+E;IAC/E,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,mEAAmE;IACnE,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE,QAAQ,CAAC,CAAC;IAC/C,YAAY,EAAE;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IACrD;;;;OAIG;IACH,MAAM,CAAC,EAAE,qBAAqB,EAAE,CAAC;CAClC;AAqBD,MAAM,WAAW,yBAAyB;IACxC,wEAAwE;IACxE,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED;;;;;GAKG;AACH,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;gBAEvB,MAAM,CAAC,EAAE,yBAAyB;IAM9C;;;OAGG;IACG,MAAM,CAAC,KAAK,EAAE,wBAAwB,GAAG,OAAO,CAAC,cAAc,CAAC;IAiDtE;;;OAGG;cACa,SAAS,CACvB,KAAK,EAAE,UAAU,CAAC,OAAO,qBAAqB,CAAC,EAC/C,YAAY,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,GACrD,OAAO,CAAC,OAAO,CAAC;CAGpB"}
|
|
@@ -12,9 +12,11 @@ const screenLog = protocolLogger("NegotiationScreener");
|
|
|
12
12
|
* trace event + log line) but NEVER blocks: every fresh negotiation still
|
|
13
13
|
* proceeds to the first turn. Used to measure pass rates against observed
|
|
14
14
|
* reject rates before enforcement.
|
|
15
|
-
* - `enforce` —
|
|
16
|
-
*
|
|
17
|
-
*
|
|
15
|
+
* - `enforce` — (P2.2) a `pass` decision blocks the negotiation before the
|
|
16
|
+
* first turn: the graph routes straight to finalize with outcome
|
|
17
|
+
* `reason: "screened_out"` — zero turns, zero counterparty involvement,
|
|
18
|
+
* zero notifications; the opportunity is quietly `rejected`. A failed
|
|
19
|
+
* screen still fails OPEN (never blocks), and `reach_out` proceeds normally.
|
|
18
20
|
*/
|
|
19
21
|
export const NEGOTIATION_SCREEN_MODES = ["off", "shadow", "enforce"];
|
|
20
22
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"negotiation.screen.js","sourceRoot":"/","sources":["negotiation/negotiation.screen.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AACxE,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAExE,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,6BAA6B,EAA8B,MAAM,yBAAyB,CAAC;AAEpG,MAAM,SAAS,GAAG,cAAc,CAAC,qBAAqB,CAAC,CAAC;AAExD;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,CAAC,KAAK,EAAE,QAAQ,EAAE,SAAS,CAAU,CAAC;AAI9E;;;;;;;GAOG;AACH,MAAM,UAAU,oBAAoB;IAClC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC;IAChD,IAAI,GAAG,KAAK,QAAQ,IAAI,GAAG,KAAK,SAAS,IAAI,GAAG,KAAK,KAAK;QAAE,OAAO,GAAG,CAAC;IACvE,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,CAAC,MAAM,CAAC;IAC3C,QAAQ,EAAE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{ z } from \"zod\";\n\nimport { createStructuredModel } from \"../shared/agent/model.config.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\nimport type { UserNegotiationContext, SeedAssessment } from \"../shared/schemas/negotiation-state.schema.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport { renderNegotiatorMemorySection, type NegotiatorMemoryEntry } from \"./negotiation.memory.js\";\n\nconst screenLog = protocolLogger(\"NegotiationScreener\");\n\n/**\n * Screen-gate modes (P2.1 — client-advocate protocol).\n *\n * - `off` — the screen node is skipped entirely; no LLM call, no telemetry.\n * - `shadow` — the screen decision is made and recorded (task metadata +\n * trace event + log line) but NEVER blocks: every fresh negotiation still\n * proceeds to the first turn. Used to measure pass rates against observed\n * reject rates before enforcement.\n * - `enforce` — reserved for P2.2. Until enforcement lands, `enforce` runs\n * identically to `shadow` (decision recorded, negotiation proceeds) and the\n * screen node logs a warning that enforcement is not yet implemented.\n */\nexport const NEGOTIATION_SCREEN_MODES = [\"off\", \"shadow\", \"enforce\"] as const;\n\nexport type NegotiationScreenMode = (typeof NEGOTIATION_SCREEN_MODES)[number];\n\n/**\n * Resolve the screen mode from `NEGOTIATION_SCREEN_MODE`.\n *\n * Defaults to `off` when unset or unrecognized — the screen gate is an\n * explicit opt-in flip (same operational pattern as\n * `NEGOTIATION_PROTOCOL_VERSION` / `NEGOTIATOR_CHAT_ENABLED`): code ships\n * inert, the environment turns it on.\n */\nexport function configuredScreenMode(): NegotiationScreenMode {\n const raw = process.env.NEGOTIATION_SCREEN_MODE;\n if (raw === \"shadow\" || raw === \"enforce\" || raw === \"off\") return raw;\n return \"off\";\n}\n\n/**\n * Structured screen decision — the outreach gate's verdict on whether this\n * match is worth the client's name before any turn is exchanged.\n */\nexport const ScreenDecisionSchema = z.object({\n decision: z.enum([\"reach_out\", \"pass\"]),\n reasoning: z.string(),\n /** Suggested opening angle for the outreach turn (only when reaching out). */\n outreachAngle: z.string().nullable().optional(),\n evidence: z.object({\n /** How well the counterparty's context/premises fit the client's need. */\n counterpartyPremiseFit: z.string(),\n /** How the client's intents align with what the counterparty seeks. */\n intentAlignment: z.string(),\n /** Prior-negotiation memory signals (P5.3). Filled only when negotiator memory was injected into the screen prompt. */\n memoryHints: z.string().nullable().optional(),\n }),\n});\n\nexport type ScreenDecision = z.infer<typeof ScreenDecisionSchema>;\n\n/**\n * The record persisted to `tasks.metadata.screenDecision` and returned into\n * graph state. Extends the LLM decision with operational context so pass-rate\n * queries can group by mode and exclude failed-open rows.\n */\nexport interface ScreenDecisionRecord extends ScreenDecision {\n mode: NegotiationScreenMode;\n /** True when the screen LLM call failed and the gate defaulted open. */\n failedOpen?: boolean;\n /** Error message when `failedOpen` is set. */\n error?: string;\n screenedAt: string;\n durationMs: number;\n}\n\nexport interface NegotiationScreenerInput {\n /** The client — the user whose negotiator is deciding whether to reach out. */\n clientUser: UserNegotiationContext;\n /** The counterparty the client's negotiator would be reaching out to. */\n counterpartyUser: UserNegotiationContext;\n /** The counterparty's `user_contexts` paragraph (empty string when absent). */\n counterpartyContext?: string;\n /** The explicit search query that triggered discovery (if any). */\n discoveryQuery?: string;\n seedAssessment: Omit<SeedAssessment, \"actors\">;\n indexContext: { networkId: string; prompt?: string };\n /**\n * Retrieved negotiator memories for the client (P5.3 read path). Rendered\n * as a private prompt section with a memoryHints instruction. Absent/empty\n * → the prompt is byte-identical to before.\n */\n memory?: NegotiatorMemoryEntry[];\n}\n\nconst SYSTEM_PROMPT = `You are the outreach gate for {clientName}'s negotiator agent on a discovery network. Before any negotiation turn is exchanged, you decide whether this match is worth reaching out to on {clientName}'s behalf — their name and attention are spent with every outreach.\n\nNetwork context: {networkContext}\n\nDecide:\n- \"reach_out\" when the counterparty plausibly serves {clientName}'s stated needs and a concrete, honest opening case can be made. When reaching out, set outreachAngle to the strongest specific angle for the opening message.\n- \"pass\" when the match is generic, one-sided, or rests on vague overlap that would waste both parties' attention.\n\nRules:\n{queryRule}\n- Judge concrete intent alignment, not topical adjacency.\n- Fill evidence.counterpartyPremiseFit with what (if anything) in the counterparty's context actually fits, and evidence.intentAlignment with how the intents line up. Be specific; cite the strongest signal either way.\n- Do NOT reference internal system details like scores, pre-screens, or evaluator outputs in reasoning that could be shown to users.{negotiatorMemory}`;\n\nconst QUERY_RULE = `- {clientName} explicitly searched for \"{discoveryQuery}\". This query is the PRIMARY criterion: if the counterparty does not satisfy it, pass — background intents cannot rescue a query mismatch.`;\nconst NO_QUERY_RULE = `- No explicit search query: judge against {clientName}'s active intents.`;\n\nconst DEFAULT_SCREEN_TIMEOUT_MS = 15_000;\n\nexport interface NegotiationScreenerConfig {\n /** Hard ceiling on the screen LLM round-trip, in ms (default 15000). */\n timeoutMs?: number;\n}\n\n/**\n * The outreach gate (P2.1). One structured LLM call deciding\n * `reach_out | pass` for a fresh negotiation, from the reaching client's\n * perspective. Throws on LLM/validation failure — the screen graph node owns\n * the fail-open policy (a failed screen never blocks the negotiation).\n */\nexport class NegotiationScreener {\n private readonly timeoutMs: number;\n\n constructor(config?: NegotiationScreenerConfig) {\n this.timeoutMs = config?.timeoutMs && Number.isFinite(config.timeoutMs) && config.timeoutMs > 0\n ? config.timeoutMs\n : DEFAULT_SCREEN_TIMEOUT_MS;\n }\n\n /**\n * Produce a screen decision for a fresh match.\n * @throws When the LLM call times out or returns schema-invalid output.\n */\n async invoke(input: NegotiationScreenerInput): Promise<ScreenDecision> {\n const model = createStructuredModel(\"negotiationScreener\", ScreenDecisionSchema, { name: \"negotiation_screener\" });\n\n const clientName = input.clientUser.profile.name ?? \"your client\";\n const counterpartyName = input.counterpartyUser.profile.name ?? \"the counterparty\";\n const networkContext = input.indexContext.prompt || \"General discovery\";\n const queryRule = (input.discoveryQuery ? QUERY_RULE : NO_QUERY_RULE)\n .replace(/{clientName}/g, clientName)\n .replace(/{discoveryQuery}/g, input.discoveryQuery ?? \"\");\n\n const systemPrompt = SYSTEM_PROMPT\n .replace(/{clientName}/g, clientName)\n .replace(\"{networkContext}\", networkContext)\n .replace(\"{queryRule}\", queryRule)\n .replace(\"{negotiatorMemory}\", renderNegotiatorMemorySection(input.memory ?? [], { memoryHintsInstruction: true }));\n\n const formatIntents = (intents: UserNegotiationContext[\"intents\"]): string =>\n intents.length > 0 ? intents.map((i) => `- ${i.title}: ${i.description}`).join(\"\\n\") : \"- (none)\";\n\n const userMessage = `YOUR CLIENT (${clientName}):\nBio: ${input.clientUser.profile.bio ?? \"N/A\"}\n${input.discoveryQuery ? `Search query: \"${input.discoveryQuery}\"\\nBackground intents (secondary to the query):` : \"Active intents:\"}\n${formatIntents(input.clientUser.intents)}\n\nCOUNTERPARTY (${counterpartyName}):\nBio: ${input.counterpartyUser.profile.bio ?? \"N/A\"}\n${input.counterpartyContext ? `Context: ${input.counterpartyContext}\\n` : \"\"}Active intents:\n${formatIntents(input.counterpartyUser.intents)}\n\nWhy this match was suggested: ${input.seedAssessment.reasoning}\n\nDecide whether reaching out serves ${clientName}.`;\n\n const chatMessages = [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: userMessage },\n ];\n\n const result = await this.callModel(model, chatMessages);\n const parsed = ScreenDecisionSchema.safeParse(result);\n if (!parsed.success) {\n screenLog.warn(\"Screen output failed schema validation\", {\n issues: parsed.error.issues.map((i) => i.message).slice(0, 3),\n });\n throw new Error(`Screen decision failed validation: ${parsed.error.issues[0]?.message ?? \"unknown\"}`);\n }\n return parsed.data;\n }\n\n /**\n * Raw structured-model round trip. Split out as a seam so tests can drive\n * the schema-validation and fail-open paths without a live provider.\n */\n protected async callModel(\n model: ReturnType<typeof createStructuredModel>,\n chatMessages: Array<{ role: string; content: string }>,\n ): Promise<unknown> {\n return invokeWithAbortSignal(model, chatMessages, AbortSignal.timeout(this.timeoutMs));\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"negotiation.screen.js","sourceRoot":"/","sources":["negotiation/negotiation.screen.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,q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B,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;QACtD,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;YACpB,SAAS,CAAC,IAAI,CAAC,wCAAwC,EAAE;gBACvD,MAAM,EAAE,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC;aAC9D,CAAC,CAAC;YACH,MAAM,IAAI,KAAK,CAAC,sCAAsC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,OAAO,IAAI,SAAS,EAAE,CAAC,CAAC;QACxG,CAAC;QACD,OAAO,MAAM,CAAC,IAAI,CAAC;IACrB,CAAC;IAED;;;OAGG;IACO,KAAK,CAAC,SAAS,CACvB,KAA+C,EAC/C,YAAsD;QAEtD,OAAO,qBAAqB,CAAC,KAAK,EAAE,YAAY,EAAE,WAAW,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IACzF,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\n\nimport { createStructuredModel } from \"../shared/agent/model.config.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\nimport type { UserNegotiationContext, SeedAssessment } from \"../shared/schemas/negotiation-state.schema.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport { renderNegotiatorMemorySection, type NegotiatorMemoryEntry } from \"./negotiation.memory.js\";\n\nconst screenLog = protocolLogger(\"NegotiationScreener\");\n\n/**\n * Screen-gate modes (P2.1 — client-advocate protocol).\n *\n * - `off` — the screen node is skipped entirely; no LLM call, no telemetry.\n * - `shadow` — the screen decision is made and recorded (task metadata +\n * trace event + log line) but NEVER blocks: every fresh negotiation still\n * proceeds to the first turn. Used to measure pass rates against observed\n * reject rates before enforcement.\n * - `enforce` — (P2.2) a `pass` decision blocks the negotiation before the\n * first turn: the graph routes straight to finalize with outcome\n * `reason: \"screened_out\"` — zero turns, zero counterparty involvement,\n * zero notifications; the opportunity is quietly `rejected`. A failed\n * screen still fails OPEN (never blocks), and `reach_out` proceeds normally.\n */\nexport const NEGOTIATION_SCREEN_MODES = [\"off\", \"shadow\", \"enforce\"] as const;\n\nexport type NegotiationScreenMode = (typeof NEGOTIATION_SCREEN_MODES)[number];\n\n/**\n * Resolve the screen mode from `NEGOTIATION_SCREEN_MODE`.\n *\n * Defaults to `off` when unset or unrecognized — the screen gate is an\n * explicit opt-in flip (same operational pattern as\n * `NEGOTIATION_PROTOCOL_VERSION` / `NEGOTIATOR_CHAT_ENABLED`): code ships\n * inert, the environment turns it on.\n */\nexport function configuredScreenMode(): NegotiationScreenMode {\n const raw = process.env.NEGOTIATION_SCREEN_MODE;\n if (raw === \"shadow\" || raw === \"enforce\" || raw === \"off\") return raw;\n return \"off\";\n}\n\n/**\n * Structured screen decision — the outreach gate's verdict on whether this\n * match is worth the client's name before any turn is exchanged.\n */\nexport const ScreenDecisionSchema = z.object({\n decision: z.enum([\"reach_out\", \"pass\"]),\n reasoning: z.string(),\n /** Suggested opening angle for the outreach turn (only when reaching out). */\n outreachAngle: z.string().nullable().optional(),\n evidence: z.object({\n /** How well the counterparty's context/premises fit the client's need. */\n counterpartyPremiseFit: z.string(),\n /** How the client's intents align with what the counterparty seeks. */\n intentAlignment: z.string(),\n /** Prior-negotiation memory signals (P5.3). Filled only when negotiator memory was injected into the screen prompt. */\n memoryHints: z.string().nullable().optional(),\n }),\n});\n\nexport type ScreenDecision = z.infer<typeof ScreenDecisionSchema>;\n\n/**\n * The record persisted to `tasks.metadata.screenDecision` and returned into\n * graph state. Extends the LLM decision with operational context so pass-rate\n * queries can group by mode and exclude failed-open rows.\n */\nexport interface ScreenDecisionRecord extends ScreenDecision {\n mode: NegotiationScreenMode;\n /** True when the screen LLM call failed and the gate defaulted open. */\n failedOpen?: boolean;\n /** Error message when `failedOpen` is set. */\n error?: string;\n screenedAt: string;\n durationMs: number;\n}\n\nexport interface NegotiationScreenerInput {\n /** The client — the user whose negotiator is deciding whether to reach out. */\n clientUser: UserNegotiationContext;\n /** The counterparty the client's negotiator would be reaching out to. */\n counterpartyUser: UserNegotiationContext;\n /** The counterparty's `user_contexts` paragraph (empty string when absent). */\n counterpartyContext?: string;\n /** The explicit search query that triggered discovery (if any). */\n discoveryQuery?: string;\n seedAssessment: Omit<SeedAssessment, \"actors\">;\n indexContext: { networkId: string; prompt?: string };\n /**\n * Retrieved negotiator memories for the client (P5.3 read path). Rendered\n * as a private prompt section with a memoryHints instruction. Absent/empty\n * → the prompt is byte-identical to before.\n */\n memory?: NegotiatorMemoryEntry[];\n}\n\nconst SYSTEM_PROMPT = `You are the outreach gate for {clientName}'s negotiator agent on a discovery network. Before any negotiation turn is exchanged, you decide whether this match is worth reaching out to on {clientName}'s behalf — their name and attention are spent with every outreach.\n\nNetwork context: {networkContext}\n\nDecide:\n- \"reach_out\" when the counterparty plausibly serves {clientName}'s stated needs and a concrete, honest opening case can be made. When reaching out, set outreachAngle to the strongest specific angle for the opening message.\n- \"pass\" when the match is generic, one-sided, or rests on vague overlap that would waste both parties' attention.\n\nRules:\n{queryRule}\n- Judge concrete intent alignment, not topical adjacency.\n- Fill evidence.counterpartyPremiseFit with what (if anything) in the counterparty's context actually fits, and evidence.intentAlignment with how the intents line up. Be specific; cite the strongest signal either way.\n- Do NOT reference internal system details like scores, pre-screens, or evaluator outputs in reasoning that could be shown to users.{negotiatorMemory}`;\n\nconst QUERY_RULE = `- {clientName} explicitly searched for \"{discoveryQuery}\". This query is the PRIMARY criterion: if the counterparty does not satisfy it, pass — background intents cannot rescue a query mismatch.`;\nconst NO_QUERY_RULE = `- No explicit search query: judge against {clientName}'s active intents.`;\n\nconst DEFAULT_SCREEN_TIMEOUT_MS = 15_000;\n\nexport interface NegotiationScreenerConfig {\n /** Hard ceiling on the screen LLM round-trip, in ms (default 15000). */\n timeoutMs?: number;\n}\n\n/**\n * The outreach gate (P2.1). One structured LLM call deciding\n * `reach_out | pass` for a fresh negotiation, from the reaching client's\n * perspective. Throws on LLM/validation failure — the screen graph node owns\n * the fail-open policy (a failed screen never blocks the negotiation).\n */\nexport class NegotiationScreener {\n private readonly timeoutMs: number;\n\n constructor(config?: NegotiationScreenerConfig) {\n this.timeoutMs = config?.timeoutMs && Number.isFinite(config.timeoutMs) && config.timeoutMs > 0\n ? config.timeoutMs\n : DEFAULT_SCREEN_TIMEOUT_MS;\n }\n\n /**\n * Produce a screen decision for a fresh match.\n * @throws When the LLM call times out or returns schema-invalid output.\n */\n async invoke(input: NegotiationScreenerInput): Promise<ScreenDecision> {\n const model = createStructuredModel(\"negotiationScreener\", ScreenDecisionSchema, { name: \"negotiation_screener\" });\n\n const clientName = input.clientUser.profile.name ?? \"your client\";\n const counterpartyName = input.counterpartyUser.profile.name ?? \"the counterparty\";\n const networkContext = input.indexContext.prompt || \"General discovery\";\n const queryRule = (input.discoveryQuery ? QUERY_RULE : NO_QUERY_RULE)\n .replace(/{clientName}/g, clientName)\n .replace(/{discoveryQuery}/g, input.discoveryQuery ?? \"\");\n\n const systemPrompt = SYSTEM_PROMPT\n .replace(/{clientName}/g, clientName)\n .replace(\"{networkContext}\", networkContext)\n .replace(\"{queryRule}\", queryRule)\n .replace(\"{negotiatorMemory}\", renderNegotiatorMemorySection(input.memory ?? [], { memoryHintsInstruction: true }));\n\n const formatIntents = (intents: UserNegotiationContext[\"intents\"]): string =>\n intents.length > 0 ? intents.map((i) => `- ${i.title}: ${i.description}`).join(\"\\n\") : \"- (none)\";\n\n const userMessage = `YOUR CLIENT (${clientName}):\nBio: ${input.clientUser.profile.bio ?? \"N/A\"}\n${input.discoveryQuery ? `Search query: \"${input.discoveryQuery}\"\\nBackground intents (secondary to the query):` : \"Active intents:\"}\n${formatIntents(input.clientUser.intents)}\n\nCOUNTERPARTY (${counterpartyName}):\nBio: ${input.counterpartyUser.profile.bio ?? \"N/A\"}\n${input.counterpartyContext ? `Context: ${input.counterpartyContext}\\n` : \"\"}Active intents:\n${formatIntents(input.counterpartyUser.intents)}\n\nWhy this match was suggested: ${input.seedAssessment.reasoning}\n\nDecide whether reaching out serves ${clientName}.`;\n\n const chatMessages = [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: userMessage },\n ];\n\n const result = await this.callModel(model, chatMessages);\n const parsed = ScreenDecisionSchema.safeParse(result);\n if (!parsed.success) {\n screenLog.warn(\"Screen output failed schema validation\", {\n issues: parsed.error.issues.map((i) => i.message).slice(0, 3),\n });\n throw new Error(`Screen decision failed validation: ${parsed.error.issues[0]?.message ?? \"unknown\"}`);\n }\n return parsed.data;\n }\n\n /**\n * Raw structured-model round trip. Split out as a seam so tests can drive\n * the schema-validation and fail-open paths without a live provider.\n */\n protected async callModel(\n model: ReturnType<typeof createStructuredModel>,\n chatMessages: Array<{ role: string; content: string }>,\n ): Promise<unknown> {\n return invokeWithAbortSignal(model, chatMessages, AbortSignal.timeout(this.timeoutMs));\n }\n}\n"]}
|