@indexnetwork/protocol 4.5.0-rc.333.1 → 4.5.0-rc.335.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/negotiation/negotiation.graph.d.ts +19 -2
- package/dist/negotiation/negotiation.graph.d.ts.map +1 -1
- package/dist/negotiation/negotiation.graph.js +106 -2
- package/dist/negotiation/negotiation.graph.js.map +1 -1
- package/dist/negotiation/negotiation.screen.d.ts +128 -0
- package/dist/negotiation/negotiation.screen.d.ts.map +1 -0
- package/dist/negotiation/negotiation.screen.js +131 -0
- package/dist/negotiation/negotiation.screen.js.map +1 -0
- package/dist/negotiation/negotiation.state.d.ts +7 -0
- package/dist/negotiation/negotiation.state.d.ts.map +1 -1
- package/dist/negotiation/negotiation.state.js +9 -0
- package/dist/negotiation/negotiation.state.js.map +1 -1
- package/dist/questioner/questioner.presets.d.ts.map +1 -1
- package/dist/questioner/questioner.presets.js +66 -0
- package/dist/questioner/questioner.presets.js.map +1 -1
- package/dist/questioner/questioner.types.d.ts +21 -1
- package/dist/questioner/questioner.types.d.ts.map +1 -1
- package/dist/questioner/questioner.types.js.map +1 -1
- package/dist/shared/agent/model.config.d.ts +5 -0
- package/dist/shared/agent/model.config.d.ts.map +1 -1
- package/dist/shared/agent/model.config.js +1 -0
- package/dist/shared/agent/model.config.js.map +1 -1
- package/dist/shared/interfaces/database.interface.d.ts +9 -0
- package/dist/shared/interfaces/database.interface.d.ts.map +1 -1
- package/dist/shared/interfaces/database.interface.js.map +1 -1
- package/dist/shared/schemas/question.schema.d.ts +4 -4
- package/dist/shared/schemas/question.schema.d.ts.map +1 -1
- package/dist/shared/schemas/question.schema.js +3 -0
- package/dist/shared/schemas/question.schema.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"neg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E,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,6BAA6B,CAAC,IAI7C;IACC,MAAM,OAAO,GAAG,IAAI,uBAAuB,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;IAC/F,OAAO,OAAO,CAAC,WAAW,EAAE,CAAC;AAC/B,CAAC","sourcesContent":["import { StateGraph } from \"@langchain/langgraph\";\n\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\nimport { requestContext, type TraceEmitter } from \"../shared/observability/request-context.js\";\nimport type { NegotiationGraphDatabase } from \"../shared/interfaces/database.interface.js\";\nimport type { NegotiationTimeoutQueue } from \"../shared/interfaces/negotiation-events.interface.js\";\nimport type { AgentDispatcher, NegotiationTurnPayload } from \"../shared/interfaces/agent-dispatcher.interface.js\";\nimport { NegotiationGraphState, type NegotiationTurn, type NegotiationOutcome, type UserNegotiationContext, type SeedAssessment, type NegotiationGraphLike } from \"./negotiation.state.js\";\nimport { IndexNegotiator } from \"./negotiation.agent.js\";\nimport { allowedActionsFor, configuredProtocolVersion, fallbackActionFor, isRejectLikeAction, isTerminalAction, readProtocolVersion, rejectActionFor } from \"./negotiation.protocol.js\";\nimport type { NegotiationSeat, NegotiationProtocolVersion } from \"../shared/schemas/negotiation-state.schema.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport type { QuestionerEnqueueFn } from \"../questioner/questioner.types.js\";\n\nconst logger = protocolLogger(\"NegotiationGraph\");\nconst initLog = protocolLogger(\"NegotiationGraph:Init\");\nconst turnLog = protocolLogger(\"NegotiationGraph:Turn\");\nconst finalizeLog = protocolLogger(\"NegotiationGraph:Finalize\");\nconst negotiateCandidatesLog = protocolLogger(\"NegotiationGraph:negotiateCandidates\");\n\n/** Extracts the ordered NegotiationTurn list from A2A message data parts. */\nfunction turnsFromMessages(messages: Array<{ parts: unknown[] }>): NegotiationTurn[] {\n return messages\n .map((m) => {\n const dataPart = (m.parts as Array<{ kind?: string; data?: unknown }>).find((p) => p.kind === \"data\");\n return dataPart?.data as NegotiationTurn;\n })\n .filter(Boolean);\n}\n\n/**\n * Factory for the bilateral negotiation LangGraph state machine.\n * @remarks Accepts an AgentDispatcher for per-turn agent resolution.\n */\nexport class NegotiationGraphFactory {\n constructor(\n private database: NegotiationGraphDatabase,\n private dispatcher: AgentDispatcher,\n private timeoutQueue?: NegotiationTimeoutQueue,\n private questionerEnqueue?: QuestionerEnqueueFn,\n ) {}\n\n createGraph() {\n const { database, dispatcher, timeoutQueue, questionerEnqueue } = this;\n const systemAgent = new IndexNegotiator();\n\n const initNode = async (state: typeof NegotiationGraphState.State) => {\n try {\n // Find-or-create the DM conversation for this agent pair (same as user DMs)\n const agentIdA = `agent:${state.sourceUser.id}`;\n const agentIdB = `agent:${state.candidateUser.id}`;\n const conversation = await database.getOrCreateDM(agentIdA, agentIdB, 'agent');\n\n // --- Lock gate: check for an active task on this conversation ---\n const priorMessages = await database.getMessagesForConversation(conversation.id);\n\n const activeStates = ['submitted', 'working', 'input_required', 'waiting_for_agent', 'claimed'];\n const isActiveAndFresh = (t: { state: string; updatedAt: Date }) =>\n activeStates.includes(t.state) && (Date.now() - new Date(t.updatedAt).getTime()) < 5 * 60 * 1000;\n\n const priorTask = state.opportunityId\n ? await database.getNegotiationTaskForOpportunity(state.opportunityId)\n : null;\n const isLocked = !!priorTask && isActiveAndFresh(priorTask);\n\n if (isLocked) {\n initLog.info('Conversation locked by active task, returning busy', {\n conversationId: conversation.id,\n opportunityId: state.opportunityId,\n });\n return { error: 'busy' };\n }\n\n // --- Load prior messages and determine continuation ---\n const priorTurns: NegotiationTurn[] = turnsFromMessages(priorMessages);\n\n const isContinuation = priorTurns.length > 0;\n\n // Determine currentSpeaker from last prior message\n let currentSpeaker: 'source' | 'candidate' = 'source';\n if (isContinuation && priorMessages.length > 0) {\n const lastSender = priorMessages[priorMessages.length - 1].senderId;\n currentSpeaker = lastSender === agentIdA ? 'candidate' : 'source';\n }\n\n // Determine scenario-based maxTurns\n const scope = { action: 'manage:negotiations', scopeType: 'network', scopeId: state.indexContext.networkId };\n const [sourceHasAgent, candidateHasAgent] = await Promise.all([\n dispatcher.hasExternalAgent(state.sourceUser.id, scope),\n dispatcher.hasExternalAgent(state.candidateUser.id, scope),\n ]);\n\n const ambientMax = Number(process.env.NEGOTIATION_MAX_TURNS_AMBIENT) || 6;\n let maxTurns = state.maxTurns;\n if (maxTurns == null) {\n maxTurns = (sourceHasAgent && candidateHasAgent) ? 0 : ambientMax;\n }\n\n // --- Initiator seat resolution (v2: rigid per match, stamped at discovery) ---\n // 1. Continuations inherit from the prior task for the same opportunity —\n // never re-derive, so the seat cannot flip between sessions.\n // 2. Conversation-scoped tie-break: if another negotiation on this DM is\n // active and fresh (symmetric concurrent start under a different\n // opportunityId — the opportunity-scoped lock above cannot see it),\n // the first created task keeps the seat; this run inherits its stamp.\n // 3. Otherwise: explicit stamp from the caller, falling back to the\n // session's sourceUser (pre-stamp heuristic behavior, unchanged).\n const readInitiator = (metadata: Record<string, unknown> | null | undefined): string | null => {\n const v = metadata?.initiatorUserId;\n return typeof v === 'string' && v.length > 0 ? v : null;\n };\n let initiatorUserId = readInitiator(priorTask?.metadata) ?? state.initiatorUserId ?? state.sourceUser.id;\n // Conversation-scoped prior task: reused for both the initiator tie-break\n // (only when active+fresh) and protocol-version inheritance (any prior\n // task on the conversation pins the version).\n const convTask = (!readInitiator(priorTask?.metadata) || !readProtocolVersion(priorTask?.metadata))\n ? await database.getLatestNegotiationTaskForConversation?.(conversation.id).catch(() => null)\n : null;\n if (!readInitiator(priorTask?.metadata)) {\n if (convTask && convTask.id !== priorTask?.id && isActiveAndFresh(convTask)) {\n const convInitiator = readInitiator(convTask.metadata);\n if (convInitiator) {\n initLog.info('Conversation-scoped tie-break: inheriting initiator seat from concurrent task', {\n conversationId: conversation.id,\n winningTaskId: convTask.id,\n initiatorUserId: convInitiator,\n });\n initiatorUserId = convInitiator;\n }\n }\n }\n\n // --- Protocol version: inherited, never re-stamped ---\n // Every session (including continuations) creates a new task row, so a\n // naïve \"stamp from env at init\" would flip a v1 conversation to v2\n // mid-flight. Rule: any prior negotiation task on this conversation pins\n // the version (absent field on a genuine prior = pre-v2 task = v1);\n // prior turns without a readable task also grandfather to v1; only\n // genuinely fresh negotiations stamp from NEGOTIATION_PROTOCOL_VERSION.\n let protocolVersion: NegotiationProtocolVersion;\n const priorVersionSource = priorTask ?? convTask;\n if (priorVersionSource) {\n protocolVersion = readProtocolVersion(priorVersionSource.metadata) ?? 'v1';\n } else if (isContinuation) {\n protocolVersion = 'v1';\n } else {\n protocolVersion = configuredProtocolVersion();\n }\n\n const task = await database.createTask(conversation.id, {\n type: 'negotiation',\n sourceUserId: state.sourceUser.id,\n initiatorUserId,\n protocolVersion,\n candidateUserId: state.candidateUser.id,\n networkId: state.indexContext.networkId,\n ...(state.opportunityId && { opportunityId: state.opportunityId }),\n maxTurns,\n isContinuation,\n priorTurnCount: priorTurns.length,\n });\n\n if (state.opportunityId) {\n await database.updateOpportunityStatus(state.opportunityId, 'negotiating').catch((err) => {\n initLog.error('Failed to set opportunity status to negotiating', { opportunityId: state.opportunityId, error: err });\n });\n }\n\n // Load user answers collected by the questioner between sessions\n const userAnswers = (isContinuation && state.opportunityId)\n ? await database.getOpportunityUserAnswers(state.opportunityId).catch((err) => {\n initLog.error('Failed to load user answers', { opportunityId: state.opportunityId, error: err });\n return [];\n })\n : [];\n\n // Seed messages with prior turns (additive reducer appends new turns on top)\n const seedMessages = isContinuation ? priorMessages.map((m) => ({\n id: m.id,\n senderId: m.senderId,\n role: 'agent' as const,\n parts: m.parts,\n createdAt: m.createdAt,\n })) : [];\n\n return {\n conversationId: conversation.id,\n taskId: task.id,\n currentSpeaker,\n turnCount: 0,\n maxTurns,\n isContinuation,\n initiatorUserId,\n protocolVersion,\n priorTurnCount: priorTurns.length,\n ...(userAnswers.length > 0 && { userAnswers }),\n ...(seedMessages.length > 0 && { messages: seedMessages }),\n };\n } catch (err) {\n return { error: `Init failed: ${err instanceof Error ? err.message : String(err)}` };\n }\n };\n\n const turnNode = async (state: typeof NegotiationGraphState.State) => {\n const traceEmitter = requestContext.getStore()?.traceEmitter;\n // Local helper to emit events whose shape is wider than the declared\n // `TraceEmitter` union. The chat agent already casts at its relay sink;\n // here we localize the cast at the callsite so the rest of the body stays typed.\n const emitWide = (event: Record<string, unknown>) =>\n (traceEmitter as ((e: Record<string, unknown>) => void) | undefined)?.(event);\n const agentName = \"Index negotiator\";\n const agentStart = Date.now();\n traceEmitter?.({ type: \"agent_start\", name: agentName });\n\n try {\n const history: NegotiationTurn[] = turnsFromMessages(state.messages);\n\n const isSource = state.currentSpeaker === \"source\";\n const ownUser = isSource ? state.sourceUser : state.candidateUser;\n const otherUser = isSource ? state.candidateUser : state.sourceUser;\n\n // Determine if this is the system agent's final allowed turn\n const maxTurns = state.maxTurns ?? 0;\n const isFinalTurn = maxTurns > 0 && (state.turnCount + 1) >= maxTurns;\n\n // Seat attribution keys on initiatorUserId (rigid v2 stamp), never on\n // parity or source/candidate position — under the conversation-scoped\n // tie-break this run's source may hold the counterparty seat.\n const version = state.protocolVersion ?? 'v1';\n const seat: NegotiationSeat = ownUser.id === (state.initiatorUserId ?? state.sourceUser.id)\n ? 'initiator'\n : 'counterparty';\n\n const payload: NegotiationTurnPayload = {\n negotiationId: state.taskId,\n ownUser,\n otherUser,\n indexContext: state.indexContext,\n seedAssessment: state.seedAssessment,\n history,\n isFinalTurn,\n isDiscoverer: isSource,\n seat,\n protocolVersion: version,\n allowedActions: [...allowedActionsFor(version, seat, isFinalTurn)],\n ...(state.discoveryQuery && isSource && { discoveryQuery: state.discoveryQuery }),\n };\n\n const scope = { action: 'manage:negotiations', scopeType: 'network', scopeId: state.indexContext.networkId };\n\n const dispatchResult = await dispatcher.dispatch(ownUser.id, scope, payload, { timeoutMs: state.timeoutMs });\n\n let turn: NegotiationTurn;\n\n if (dispatchResult.handled) {\n // Personal agent responded. Under v2, coerce out-of-seat actions to\n // the conservative fallback — the polling/respond surfaces reject\n // these with a 400, but locally-dispatched turns land here directly.\n turn = dispatchResult.turn;\n if (version === 'v2' && !allowedActionsFor(version, seat, isFinalTurn).includes(turn.action)) {\n turnLog.warn('Personal agent returned out-of-seat action, coercing to conservative fallback', {\n action: turn.action, seat, isFinalTurn,\n });\n turn = { ...turn, action: fallbackActionFor(version, seat, isFinalTurn) };\n }\n } else if (dispatchResult.reason === 'waiting') {\n // Long timeout — graph suspends. Persist the full turn context so the\n // polling agent (and MCP consumers via get_negotiation) reconstruct\n // the same view the in-process system agent would see. The view is\n // stored in absolute source/candidate terms; perspective is projected\n // at pickup time using the claiming user's id.\n traceEmitter?.({ type: \"agent_end\", name: agentName, durationMs: Date.now() - agentStart, summary: \"waiting_for_agent\" });\n await database.setTaskTurnContext(state.taskId, {\n sourceUser: state.sourceUser,\n candidateUser: state.candidateUser,\n indexContext: state.indexContext,\n seedAssessment: state.seedAssessment,\n // Keep discoveryQuery speaker-scoped: include it only when the\n // parked turn belongs to the discoverer (source). Persisting it on\n // candidate-side turns would make the pickup prompt frame the\n // search as \"your user searched for X\" for the wrong user.\n ...(isSource && state.discoveryQuery && { discoveryQuery: state.discoveryQuery }),\n });\n await database.updateTaskState(state.taskId, \"waiting_for_agent\");\n return { status: 'waiting_for_agent' as const };\n } else {\n // No personal agent or timeout — run system agent\n turn = await systemAgent.invoke({\n ownUser,\n otherUser,\n indexContext: state.indexContext,\n seedAssessment: state.seedAssessment,\n history,\n isFinalTurn,\n isDiscoverer: isSource,\n seat,\n protocolVersion: version,\n ...(state.discoveryQuery && isSource && { discoveryQuery: state.discoveryQuery }),\n isContinuation: state.isContinuation,\n ...(state.userAnswers.length > 0 && { userAnswers: state.userAnswers }),\n });\n }\n\n traceEmitter?.({ type: \"agent_end\", name: agentName, durationMs: Date.now() - agentStart, summary: `${turn.action}` });\n\n // First turn must open the negotiation (unless continuing a prior\n // conversation): v1 → \"propose\"; v2 initiator → \"outreach\". A v2 turn-0\n // speaker holding the counterparty seat (tie-break inheritance) is left\n // unforced — it is responding, not opening.\n if (state.turnCount === 0 && !state.isContinuation) {\n const openingAction = version === 'v2' ? 'outreach' : 'propose';\n if ((version !== 'v2' || seat === 'initiator') && turn.action !== openingAction) {\n turnLog.warn(`Agent returned unexpected action on turn 0, forcing to ${openingAction}`, { action: turn.action });\n turn.action = openingAction;\n }\n }\n\n const parts = [{ kind: \"data\" as const, data: turn }];\n const message = await database.createMessage({\n conversationId: state.conversationId,\n senderId: `agent:${ownUser.id}`,\n role: \"agent\",\n parts,\n taskId: state.taskId,\n });\n\n await database.updateTaskState(state.taskId, \"working\");\n\n if (state.opportunityId) {\n emitWide({\n type: \"negotiation_turn\",\n opportunityId: state.opportunityId,\n negotiationConversationId: state.conversationId,\n turnIndex: state.turnCount,\n actor: isSource ? \"source\" : \"candidate\",\n action: turn.action,\n ...(turn.assessment?.reasoning && { reasoning: turn.assessment.reasoning }),\n ...(turn.message && { message: turn.message }),\n ...(turn.assessment?.suggestedRoles && { suggestedRoles: turn.assessment.suggestedRoles }),\n durationMs: Date.now() - agentStart,\n });\n }\n\n return {\n messages: [{\n id: message.id,\n senderId: message.senderId,\n role: \"agent\" as const,\n parts: message.parts,\n createdAt: message.createdAt,\n }],\n turnCount: state.turnCount + 1,\n currentSpeaker: (isSource ? \"candidate\" : \"source\") as \"source\" | \"candidate\",\n lastTurn: turn,\n };\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n turnLog.error(\"Agent invocation failed\", { error: errMsg, stack: err instanceof Error ? err.stack : undefined, turnCount: state.turnCount });\n traceEmitter?.({ type: \"agent_end\", name: agentName, durationMs: Date.now() - agentStart, summary: `error: ${errMsg}` });\n const errorSeat: NegotiationSeat = (state.currentSpeaker === 'source' ? state.sourceUser.id : state.candidateUser.id) === (state.initiatorUserId ?? state.sourceUser.id)\n ? 'initiator'\n : 'counterparty';\n return {\n lastTurn: {\n action: rejectActionFor(state.protocolVersion ?? 'v1', errorSeat),\n assessment: { reasoning: `Agent error: ${errMsg}`, suggestedRoles: { ownUser: \"peer\" as const, otherUser: \"peer\" as const } },\n },\n turnCount: state.turnCount + 1,\n error: `Turn failed: ${errMsg}`,\n };\n }\n };\n\n const evaluateNode = (state: typeof NegotiationGraphState.State): string => {\n if (state.status === 'waiting_for_agent') return \"finalize\";\n if (state.error) return \"finalize\";\n if (!state.lastTurn) return \"finalize\";\n // Terminal actions: accept (v1+v2), reject (v1), withdraw/decline (v2)\n if (isTerminalAction(state.lastTurn.action)) return \"finalize\";\n // question routes same as counter — next turn\n if ((state.maxTurns ?? 0) > 0 && state.turnCount >= state.maxTurns!) return \"finalize\";\n return \"turn\";\n };\n\n const finalizeNode = async (state: typeof NegotiationGraphState.State) => {\n const traceEmitter = requestContext.getStore()?.traceEmitter;\n const emitWide = (event: Record<string, unknown>) =>\n (traceEmitter as ((e: Record<string, unknown>) => void) | undefined)?.(event);\n\n if (state.status === 'waiting_for_agent') {\n if (state.opportunityId) {\n emitWide({\n type: \"negotiation_outcome\",\n opportunityId: state.opportunityId,\n outcome: \"waiting_for_agent\",\n turnCount: state.turnCount,\n isContinuation: state.isContinuation,\n });\n }\n return {};\n }\n\n const history: NegotiationTurn[] = turnsFromMessages(state.messages);\n\n const lastTurn = state.lastTurn;\n const hasOpportunity = lastTurn?.action === \"accept\";\n const atCap = (state.maxTurns ?? 0) > 0 && state.turnCount >= state.maxTurns! && !isTerminalAction(lastTurn?.action);\n\n let agreedRoles: NegotiationOutcome[\"agreedRoles\"] = [];\n if (hasOpportunity && history.length >= 2) {\n const acceptTurn = history[history.length - 1];\n const precedingTurn = history[history.length - 2];\n const accepterIsSource = state.currentSpeaker === \"candidate\";\n const [sourceRole, candidateRole] = accepterIsSource\n ? [acceptTurn.assessment.suggestedRoles.ownUser, precedingTurn.assessment.suggestedRoles.ownUser]\n : [precedingTurn.assessment.suggestedRoles.ownUser, acceptTurn.assessment.suggestedRoles.ownUser];\n agreedRoles = [\n { userId: state.sourceUser.id, role: sourceRole },\n { userId: state.candidateUser.id, role: candidateRole },\n ];\n }\n\n const outcome: NegotiationOutcome = {\n hasOpportunity,\n agreedRoles,\n reasoning: lastTurn?.assessment.reasoning ?? \"\",\n turnCount: state.turnCount,\n ...(atCap && { reason: \"turn_cap\" as const }),\n };\n\n try {\n await database.updateTaskState(state.taskId, \"completed\");\n await database.createArtifact({\n taskId: state.taskId,\n name: \"negotiation-outcome\",\n parts: [{ kind: \"data\", data: outcome }],\n metadata: { hasOpportunity, turnCount: state.turnCount },\n });\n\n finalizeLog.info('Session complete', {\n conversationId: state.conversationId,\n taskId: state.taskId,\n isContinuation: state.isContinuation,\n turnsAdded: state.turnCount,\n priorTurnCount: state.priorTurnCount,\n outcome: hasOpportunity ? 'accepted' : (atCap ? 'turn_cap' : (lastTurn?.action ?? 'unknown')),\n opportunityId: state.opportunityId || undefined,\n });\n\n if (state.opportunityId) {\n const nextStatus = lastTurn?.action === 'accept'\n ? 'pending'\n : isRejectLikeAction(lastTurn?.action)\n ? 'rejected'\n : 'stalled';\n await database.updateOpportunityStatus(state.opportunityId, nextStatus).catch((err) => {\n finalizeLog.error(\"Failed to update opportunity status\", { opportunityId: state.opportunityId, nextStatus, error: err });\n });\n }\n } catch (err) {\n finalizeLog.error(\"Failed to persist outcome\", { error: err });\n }\n\n if (state.opportunityId) {\n const emittedOutcome: \"accepted\" | \"rejected_stalled\" | \"turn_cap\" | \"timed_out\" =\n hasOpportunity\n ? \"accepted\"\n : atCap\n ? \"turn_cap\"\n : state.error && /timeout/i.test(state.error)\n ? \"timed_out\"\n : \"rejected_stalled\";\n\n emitWide({\n type: \"negotiation_outcome\",\n opportunityId: state.opportunityId,\n outcome: emittedOutcome,\n turnCount: state.turnCount,\n isContinuation: state.isContinuation,\n turnsAdded: state.turnCount,\n priorTurnCount: state.priorTurnCount,\n ...(outcome.reasoning && { reasoning: outcome.reasoning }),\n ...(hasOpportunity && agreedRoles.length >= 2 && {\n agreedRoles: {\n ownUser: agreedRoles[0]?.role,\n otherUser: agreedRoles[1]?.role,\n },\n }),\n });\n }\n\n // Enqueue question generation for stalled/capped negotiations (not accepted or explicitly rejected).\n // Require turnCount > 0 so early init/turn errors don't enqueue with empty context.\n if (!hasOpportunity && !isRejectLikeAction(lastTurn?.action) && state.turnCount > 0 && state.opportunityId && questionerEnqueue) {\n const stallReason: 'turn_cap' | 'timeout' | 'stalled' = atCap\n ? 'turn_cap'\n : (state.error && /timeout/i.test(state.error))\n ? 'timeout'\n : 'stalled';\n\n const userContext = (await database.getUserContext(state.sourceUser.id, null))?.text ?? '';\n questionerEnqueue({\n mode: 'negotiation',\n userId: state.sourceUser.id,\n sourceType: 'opportunity',\n sourceId: state.opportunityId,\n context: {\n negotiationId: state.taskId,\n counterpartyHint: `${state.candidateUser.profile.name ?? 'Unknown'}${state.candidateUser.profile.bio ? ', ' + state.candidateUser.profile.bio : ''}`,\n indexContext: state.indexContext.prompt,\n outcomeReason: stallReason,\n keyTake: outcome.reasoning,\n userContext,\n },\n }).catch((err) =>\n finalizeLog.error('Failed to enqueue negotiation question generation', {\n opportunityId: state.opportunityId,\n error: err,\n })\n );\n }\n\n return { outcome, status: 'completed' as const };\n };\n\n const workflow = new StateGraph(NegotiationGraphState)\n .addNode(\"init\", initNode)\n .addNode(\"turn\", turnNode)\n .addNode(\"finalize\", finalizeNode)\n .addConditionalEdges(\"turn\", evaluateNode, {\n turn: \"turn\",\n finalize: \"finalize\",\n })\n .addConditionalEdges(\"init\", (state: typeof NegotiationGraphState.State) => {\n return state.error ? \"finalize\" : \"turn\";\n }, { turn: \"turn\", finalize: \"finalize\" })\n .addEdge(\"__start__\", \"init\")\n .addEdge(\"finalize\", \"__end__\");\n\n return workflow.compile();\n }\n}\n\nexport interface NegotiationCandidate {\n userId: string;\n reasoning: string;\n valencyRole: string;\n networkId?: string;\n candidateUser: UserNegotiationContext;\n /** The explicit search query that triggered discovery (if any). */\n discoveryQuery?: string;\n /**\n * ID of the opportunity this negotiation is for. When set, the negotiation\n * graph's finalize node updates the opportunity's status based on the outcome\n * (`accept` → 'pending', `reject` → 'rejected', otherwise → 'stalled').\n */\n opportunityId?: string;\n}\n\nexport interface NegotiationResult {\n userId: string;\n agreedRoles: NegotiationOutcome[\"agreedRoles\"];\n reasoning: string;\n turnCount: number;\n}\n\n/**\n * Per-candidate resolution hook — fires as each negotiation settles, before\n * Promise.all aggregates. Used by the orchestrator branch to progressively\n * stream `opportunity_draft_ready` events as each candidate resolves, rather\n * than emitting all at once after the full fan-out completes. Awaited so the\n * caller can run async work (DB update, event emit) before the next settle.\n *\n * `turns` and `outcome` are passed through from the underlying negotiation\n * graph so consumers can build per-candidate decision-question inputs without\n * re-walking trace events or DB artifacts. Both are present on every\n * resolution (accepted, rejected, stalled, error); error paths receive a\n * synthesized `outcome` with `hasOpportunity: false`.\n */\nexport type OnNegotiationResolved = (entry: {\n candidate: NegotiationCandidate;\n accepted: NegotiationResult | null;\n turns: NegotiationTurn[];\n outcome: NegotiationOutcome;\n}) => Promise<void>;\n\n/**\n * Runs bilateral negotiation for each candidate in parallel.\n * @returns Only candidates that produced an opportunity\n */\nexport async function negotiateCandidates(\n negotiationGraph: NegotiationGraphLike,\n sourceUser: UserNegotiationContext,\n candidates: NegotiationCandidate[],\n indexContext: { networkId: string; prompt: string },\n opts?: {\n maxTurns?: number;\n traceEmitter?: TraceEmitter;\n indexContextOverrides?: Map<string, string>;\n timeoutMs?: number;\n onCandidateResolved?: OnNegotiationResolved;\n trigger?: \"orchestrator\" | \"ambient\";\n /**\n * Initiator seat for every candidate session in this fan-out (v2 stamp).\n * Passed through to the negotiation graph, which may still override it by\n * inheriting from a prior task on the same opportunity/conversation.\n */\n initiatorUserId?: string;\n },\n): Promise<NegotiationResult[]> {\n const { maxTurns, traceEmitter, indexContextOverrides, timeoutMs, onCandidateResolved, trigger, initiatorUserId } = opts ?? {};\n\n // Local helper to emit events whose shape is wider than the declared\n // `TraceEmitter` union (mirrors the cast used in chat.agent at the relay sink\n // and inside turn/finalize nodes above).\n const emitWide = (event: Record<string, unknown>) =>\n (traceEmitter as ((e: Record<string, unknown>) => void) | undefined)?.(event);\n\n const results = await Promise.all(\n candidates.map(async (candidate) => {\n const start = Date.now();\n if (candidate.opportunityId) {\n const candidateName = candidate.candidateUser?.profile?.name;\n emitWide({\n type: \"negotiation_session_start\",\n opportunityId: candidate.opportunityId,\n negotiationConversationId: \"\", // filled in on session_end\n sourceUserId: sourceUser.id,\n candidateUserId: candidate.userId,\n initiatorUserId: initiatorUserId ?? sourceUser.id,\n ...(candidateName && { candidateName }),\n trigger: trigger ?? \"ambient\",\n startedAt: start,\n });\n }\n traceEmitter?.({ type: \"agent_start\", name: \"Negotiating candidate\" });\n\n try {\n const candidateIndexContext = candidate.networkId\n ? { networkId: candidate.networkId, prompt: indexContextOverrides?.get(candidate.networkId) ?? '' }\n : indexContext;\n\n const result = await invokeWithAbortSignal(negotiationGraph, {\n sourceUser,\n candidateUser: candidate.candidateUser,\n indexContext: candidateIndexContext,\n seedAssessment: {\n reasoning: candidate.reasoning,\n valencyRole: candidate.valencyRole,\n },\n ...(candidate.discoveryQuery && { discoveryQuery: candidate.discoveryQuery }),\n ...(candidate.opportunityId && { opportunityId: candidate.opportunityId }),\n ...(initiatorUserId && { initiatorUserId }),\n ...(maxTurns !== undefined && { maxTurns }),\n ...(timeoutMs !== undefined && { timeoutMs }),\n });\n\n const durationMs = Date.now() - start;\n const outcome = result.outcome;\n const hasOpportunity = outcome?.hasOpportunity === true;\n const isContinuation = (result as { isContinuation?: boolean }).isContinuation ?? false;\n const priorTurnCount = (result as { priorTurnCount?: number }).priorTurnCount ?? 0;\n\n const turnFlow = (result.messages ?? [])\n .map((m) => {\n const dataPart = (m.parts as Array<{ kind?: string; data?: Record<string, unknown> }>)?.find((p) => p.kind === \"data\");\n if (!dataPart?.data) return null;\n const turn = dataPart.data as { action?: string };\n return turn.action ?? \"unknown\";\n })\n .filter(Boolean)\n .join(\" → \");\n\n const statusTag = hasOpportunity ? \"✓ opportunity\" : \"✗ rejected\";\n traceEmitter?.({ type: \"agent_end\", name: \"Negotiating candidate\", durationMs, summary: `${candidate.userId}: ${turnFlow} ${statusTag}` });\n\n if (candidate.opportunityId) {\n emitWide({\n type: \"negotiation_session_end\",\n opportunityId: candidate.opportunityId,\n negotiationConversationId: (result as { conversationId?: string }).conversationId ?? \"\",\n durationMs: Date.now() - start,\n isContinuation,\n turnsAdded: outcome?.turnCount ?? 0,\n priorTurnCount,\n });\n }\n\n const accepted: NegotiationResult | null = hasOpportunity && outcome\n ? {\n userId: candidate.userId,\n agreedRoles: outcome.agreedRoles,\n reasoning: outcome.reasoning,\n turnCount: outcome.turnCount,\n }\n : null;\n\n if (onCandidateResolved) {\n const turnHistory: NegotiationTurn[] = turnsFromMessages(result.messages ?? []);\n const resolvedOutcome: NegotiationOutcome = result.outcome ?? {\n hasOpportunity: false,\n agreedRoles: [],\n reasoning: \"no outcome returned by negotiation graph\",\n turnCount: turnHistory.length,\n };\n try {\n await onCandidateResolved({\n candidate,\n accepted,\n turns: turnHistory,\n outcome: resolvedOutcome,\n });\n } catch (hookErr) {\n // Hook failures must not sink the candidate result — the aggregate\n // return is still useful, and the orchestrator branch logs its own\n // failures inline.\n negotiateCandidatesLog.error(\"onCandidateResolved hook threw\", {\n candidateUserId: candidate.userId,\n error: hookErr,\n });\n }\n }\n\n return accepted;\n } catch (err) {\n const durationMs = Date.now() - start;\n traceEmitter?.({ type: \"agent_end\", name: \"Negotiating candidate\", durationMs, summary: `${candidate.userId}: error` });\n if (candidate.opportunityId) {\n emitWide({\n type: \"negotiation_session_end\",\n opportunityId: candidate.opportunityId,\n negotiationConversationId: \"\",\n durationMs: Date.now() - start,\n });\n }\n negotiateCandidatesLog.error(\"Negotiation failed\", { candidateUserId: candidate.userId, error: err });\n if (onCandidateResolved) {\n try {\n await onCandidateResolved({\n candidate,\n accepted: null,\n turns: [],\n outcome: {\n hasOpportunity: false,\n agreedRoles: [],\n reasoning: err instanceof Error ? err.message : String(err),\n turnCount: 0,\n },\n });\n } catch {\n // ignore hook failure on error path\n }\n }\n return null;\n }\n }),\n );\n\n return results.filter((r): r is NegotiationResult => r !== null);\n}\n\n/**\n * Creates a negotiation graph with the provided dependencies.\n */\nexport function createDefaultNegotiationGraph(deps: {\n database: NegotiationGraphDatabase;\n dispatcher: AgentDispatcher;\n timeoutQueue?: NegotiationTimeoutQueue;\n}) {\n const factory = new NegotiationGraphFactory(deps.database, deps.dispatcher, deps.timeoutQueue);\n return factory.createGraph();\n}\n"]}
|
|
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,iBAAiB,EAAE,yBAAyB,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AACxL,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAkD,MAAM,yBAAyB,CAAC;AAEpI,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAG5E,MAAM,MAAM,GAAG,cAAc,CAAC,kBAAkB,CAAC,CAAC;AAClD,MAAM,OAAO,GAAG,cAAc,CAAC,uBAAuB,CAAC,CAAC;AACxD,MAAM,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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W,EAAE,EAAE;4BACf,SAAS,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC;4BAC3D,SAAS,EAAE,CAAC;yBACb;qBACF,CAAC,CAAC;gBACL,CAAC;gBAAC,MAAM,CAAC;oBACP,oCAAoC;gBACtC,CAAC;YACH,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC,CAAC,CACH,CAAC;IAEF,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAA0B,EAAE,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC;AACnE,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,6BAA6B,CAAC,IAI7C;IACC,MAAM,OAAO,GAAG,IAAI,uBAAuB,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;IAC/F,OAAO,OAAO,CAAC,WAAW,EAAE,CAAC;AAC/B,CAAC","sourcesContent":["import { StateGraph } from \"@langchain/langgraph\";\n\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\nimport { requestContext, type TraceEmitter } from \"../shared/observability/request-context.js\";\nimport type { NegotiationGraphDatabase } from \"../shared/interfaces/database.interface.js\";\nimport type { NegotiationTimeoutQueue } from \"../shared/interfaces/negotiation-events.interface.js\";\nimport type { AgentDispatcher, NegotiationTurnPayload } from \"../shared/interfaces/agent-dispatcher.interface.js\";\nimport { NegotiationGraphState, type NegotiationTurn, type NegotiationOutcome, type UserNegotiationContext, type SeedAssessment, type NegotiationGraphLike } from \"./negotiation.state.js\";\nimport { IndexNegotiator } from \"./negotiation.agent.js\";\nimport { allowedActionsFor, 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\";\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 * Factory for the bilateral negotiation LangGraph state machine.\n * @remarks Accepts an AgentDispatcher for per-turn agent resolution.\n */\nexport class NegotiationGraphFactory {\n constructor(\n private database: NegotiationGraphDatabase,\n private dispatcher: AgentDispatcher,\n private timeoutQueue?: NegotiationTimeoutQueue,\n private questionerEnqueue?: QuestionerEnqueueFn,\n ) {}\n\n createGraph() {\n const { database, dispatcher, timeoutQueue, questionerEnqueue } = this;\n const systemAgent = new IndexNegotiator();\n const screener = new NegotiationScreener();\n\n const initNode = async (state: typeof NegotiationGraphState.State) => {\n try {\n // Find-or-create the DM conversation for this agent pair (same as user DMs)\n const agentIdA = `agent:${state.sourceUser.id}`;\n const agentIdB = `agent:${state.candidateUser.id}`;\n const conversation = await database.getOrCreateDM(agentIdA, agentIdB, 'agent');\n\n // --- Lock gate: check for an active task on this conversation ---\n const priorMessages = await database.getMessagesForConversation(conversation.id);\n\n const activeStates = ['submitted', 'working', 'input_required', 'waiting_for_agent', 'claimed'];\n const isActiveAndFresh = (t: { state: string; updatedAt: Date }) =>\n activeStates.includes(t.state) && (Date.now() - new Date(t.updatedAt).getTime()) < 5 * 60 * 1000;\n\n const priorTask = state.opportunityId\n ? await database.getNegotiationTaskForOpportunity(state.opportunityId)\n : null;\n const isLocked = !!priorTask && isActiveAndFresh(priorTask);\n\n if (isLocked) {\n initLog.info('Conversation locked by active task, returning busy', {\n conversationId: conversation.id,\n opportunityId: state.opportunityId,\n });\n return { error: 'busy' };\n }\n\n // --- Load prior messages and determine continuation ---\n const priorTurns: NegotiationTurn[] = turnsFromMessages(priorMessages);\n\n const isContinuation = priorTurns.length > 0;\n\n // Determine currentSpeaker from last prior message\n let currentSpeaker: 'source' | 'candidate' = 'source';\n if (isContinuation && priorMessages.length > 0) {\n const lastSender = priorMessages[priorMessages.length - 1].senderId;\n currentSpeaker = lastSender === agentIdA ? 'candidate' : 'source';\n }\n\n // Determine scenario-based maxTurns\n const scope = { action: 'manage:negotiations', scopeType: 'network', scopeId: state.indexContext.networkId };\n const [sourceHasAgent, candidateHasAgent] = await Promise.all([\n dispatcher.hasExternalAgent(state.sourceUser.id, scope),\n dispatcher.hasExternalAgent(state.candidateUser.id, scope),\n ]);\n\n const ambientMax = Number(process.env.NEGOTIATION_MAX_TURNS_AMBIENT) || 6;\n let maxTurns = state.maxTurns;\n if (maxTurns == null) {\n maxTurns = (sourceHasAgent && candidateHasAgent) ? 0 : ambientMax;\n }\n\n // --- Initiator seat resolution (v2: rigid per match, stamped at discovery) ---\n // 1. Continuations inherit from the prior task for the same opportunity —\n // never re-derive, so the seat cannot flip between sessions.\n // 2. Conversation-scoped tie-break: if another negotiation on this DM is\n // active and fresh (symmetric concurrent start under a different\n // opportunityId — the opportunity-scoped lock above cannot see it),\n // the first created task keeps the seat; this run inherits its stamp.\n // 3. Otherwise: explicit stamp from the caller, falling back to the\n // session's sourceUser (pre-stamp heuristic behavior, unchanged).\n const readInitiator = (metadata: Record<string, unknown> | null | undefined): string | null => {\n const v = metadata?.initiatorUserId;\n return typeof v === 'string' && v.length > 0 ? v : null;\n };\n let initiatorUserId = readInitiator(priorTask?.metadata) ?? state.initiatorUserId ?? state.sourceUser.id;\n // Conversation-scoped prior task: reused for both the initiator tie-break\n // (only when active+fresh) and protocol-version inheritance (any prior\n // task on the conversation pins the version).\n const convTask = (!readInitiator(priorTask?.metadata) || !readProtocolVersion(priorTask?.metadata))\n ? await database.getLatestNegotiationTaskForConversation?.(conversation.id).catch(() => null)\n : null;\n if (!readInitiator(priorTask?.metadata)) {\n if (convTask && convTask.id !== priorTask?.id && isActiveAndFresh(convTask)) {\n const convInitiator = readInitiator(convTask.metadata);\n if (convInitiator) {\n initLog.info('Conversation-scoped tie-break: inheriting initiator seat from concurrent task', {\n conversationId: conversation.id,\n winningTaskId: convTask.id,\n initiatorUserId: convInitiator,\n });\n initiatorUserId = convInitiator;\n }\n }\n }\n\n // --- Protocol version: inherited, never re-stamped ---\n // Every session (including continuations) creates a new task row, so a\n // naïve \"stamp from env at init\" would flip a v1 conversation to v2\n // mid-flight. Rule: any prior negotiation task on this conversation pins\n // the version (absent field on a genuine prior = pre-v2 task = v1);\n // prior turns without a readable task also grandfather to v1; only\n // genuinely fresh negotiations stamp from NEGOTIATION_PROTOCOL_VERSION.\n let protocolVersion: NegotiationProtocolVersion;\n const priorVersionSource = priorTask ?? convTask;\n if (priorVersionSource) {\n protocolVersion = readProtocolVersion(priorVersionSource.metadata) ?? 'v1';\n } else if (isContinuation) {\n protocolVersion = 'v1';\n } else {\n protocolVersion = configuredProtocolVersion();\n }\n\n const task = await database.createTask(conversation.id, {\n type: 'negotiation',\n sourceUserId: state.sourceUser.id,\n initiatorUserId,\n protocolVersion,\n candidateUserId: state.candidateUser.id,\n networkId: state.indexContext.networkId,\n ...(state.opportunityId && { opportunityId: state.opportunityId }),\n maxTurns,\n isContinuation,\n priorTurnCount: priorTurns.length,\n });\n\n if (state.opportunityId) {\n await database.updateOpportunityStatus(state.opportunityId, 'negotiating').catch((err) => {\n initLog.error('Failed to set opportunity status to negotiating', { opportunityId: state.opportunityId, error: err });\n });\n }\n\n // Load user answers collected by the questioner between sessions\n const userAnswers = (isContinuation && state.opportunityId)\n ? await database.getOpportunityUserAnswers(state.opportunityId).catch((err) => {\n initLog.error('Failed to load user answers', { opportunityId: state.opportunityId, error: err });\n return [];\n })\n : [];\n\n // Seed messages with prior turns (additive reducer appends new turns on top)\n const seedMessages = isContinuation ? priorMessages.map((m) => ({\n id: m.id,\n senderId: m.senderId,\n role: 'agent' as const,\n parts: m.parts,\n createdAt: m.createdAt,\n })) : [];\n\n return {\n conversationId: conversation.id,\n taskId: task.id,\n currentSpeaker,\n turnCount: 0,\n maxTurns,\n isContinuation,\n initiatorUserId,\n protocolVersion,\n priorTurnCount: priorTurns.length,\n ...(userAnswers.length > 0 && { userAnswers }),\n ...(seedMessages.length > 0 && { messages: seedMessages }),\n };\n } catch (err) {\n return { error: `Init failed: ${err instanceof Error ? err.message : String(err)}` };\n }\n };\n\n /**\n * Screen node (P2.1) — the outreach gate. Runs between init and the first\n * turn on FRESH negotiations only (routing skips it on continuations and\n * when NEGOTIATION_SCREEN_MODE=off). The reaching client's negotiator\n * decides whether the match is worth its client's name; in shadow mode the\n * decision is recorded (task metadata + trace event + log line) but never\n * blocks — the negotiation always proceeds to the first turn. `enforce`\n * runs identically until P2.2 lands enforcement (by the time this node\n * runs, init has already created the task and flipped the opportunity to\n * `negotiating` — P2.2 owns making a blocking `pass` quiet/correct).\n */\n const screenNode = async (state: typeof NegotiationGraphState.State) => {\n const traceEmitter = requestContext.getStore()?.traceEmitter;\n const emitWide = (event: Record<string, unknown>) =>\n (traceEmitter as ((e: Record<string, unknown>) => void) | undefined)?.(event);\n\n const mode = configuredScreenMode();\n if (mode === \"enforce\") {\n screenNodeLog.warn(\"NEGOTIATION_SCREEN_MODE=enforce requested but enforcement lands in P2.2; running shadow\", {\n taskId: state.taskId,\n });\n }\n\n const start = Date.now();\n // The client is the initiator seat's user — the side whose negotiator is\n // reaching out. Fresh runs stamp initiatorUserId in init; fall back to\n // sourceUser (what the stamp defaults to anyway).\n const initiatorId = state.initiatorUserId ?? state.sourceUser.id;\n const clientIsSource = initiatorId !== state.candidateUser.id;\n const clientUser = clientIsSource ? state.sourceUser : state.candidateUser;\n const counterpartyUser = clientIsSource ? state.candidateUser : state.sourceUser;\n\n let decision: ScreenDecision;\n let failedOpen = false;\n let screenError: string | undefined;\n try {\n const counterpartyContext = (await database.getUserContext(counterpartyUser.id, null).catch(() => null))?.text ?? \"\";\n decision = await screener.invoke({\n clientUser,\n counterpartyUser,\n ...(counterpartyContext && { counterpartyContext }),\n // discoveryQuery belongs to the discovery session's source user; only\n // meaningful for the client when the client holds the source side.\n ...(clientIsSource && state.discoveryQuery && { discoveryQuery: state.discoveryQuery }),\n seedAssessment: state.seedAssessment,\n indexContext: state.indexContext,\n });\n } catch (err) {\n // Fail open: a screen failure must never block a negotiation.\n failedOpen = true;\n screenError = err instanceof Error ? err.message : String(err);\n screenNodeLog.warn(\"Screen failed; proceeding open (reach_out)\", {\n taskId: state.taskId,\n opportunityId: state.opportunityId || undefined,\n error: screenError,\n });\n decision = {\n decision: \"reach_out\",\n reasoning: `screen_error: ${screenError}`,\n evidence: { counterpartyPremiseFit: \"\", intentAlignment: \"\" },\n };\n }\n\n const durationMs = Date.now() - start;\n const record: ScreenDecisionRecord = {\n ...decision,\n mode,\n ...(failedOpen && { failedOpen, error: screenError }),\n screenedAt: new Date().toISOString(),\n durationMs,\n };\n\n await database.setTaskScreenDecision?.(state.taskId, record as unknown as Record<string, unknown>).catch((err) => {\n screenNodeLog.error(\"Failed to persist screen decision\", { taskId: state.taskId, error: err });\n });\n\n screenNodeLog.info(\"negotiation_screen\", {\n taskId: state.taskId,\n opportunityId: state.opportunityId || undefined,\n decision: decision.decision,\n mode,\n failedOpen,\n durationMs,\n });\n\n if (state.opportunityId) {\n emitWide({\n type: \"negotiation_screen\",\n opportunityId: state.opportunityId,\n negotiationConversationId: state.conversationId,\n decision: decision.decision,\n reasoning: decision.reasoning,\n mode,\n failedOpen,\n durationMs,\n });\n }\n\n // Shadow (and pre-P2.2 enforce): always proceed to the first turn.\n return { screenDecision: record };\n };\n\n const turnNode = async (state: typeof NegotiationGraphState.State) => {\n const traceEmitter = requestContext.getStore()?.traceEmitter;\n // Local helper to emit events whose shape is wider than the declared\n // `TraceEmitter` union. The chat agent already casts at its relay sink;\n // here we localize the cast at the callsite so the rest of the body stays typed.\n const emitWide = (event: Record<string, unknown>) =>\n (traceEmitter as ((e: Record<string, unknown>) => void) | undefined)?.(event);\n const agentName = \"Index negotiator\";\n const agentStart = Date.now();\n traceEmitter?.({ type: \"agent_start\", name: agentName });\n\n try {\n const history: NegotiationTurn[] = turnsFromMessages(state.messages);\n\n const isSource = state.currentSpeaker === \"source\";\n const ownUser = isSource ? state.sourceUser : state.candidateUser;\n const otherUser = isSource ? state.candidateUser : state.sourceUser;\n\n // Determine if this is the system agent's final allowed turn\n const maxTurns = state.maxTurns ?? 0;\n const isFinalTurn = maxTurns > 0 && (state.turnCount + 1) >= maxTurns;\n\n // Seat attribution keys on initiatorUserId (rigid v2 stamp), never on\n // parity or source/candidate position — under the conversation-scoped\n // tie-break this run's source may hold the counterparty seat.\n const version = state.protocolVersion ?? 'v1';\n const seat: NegotiationSeat = ownUser.id === (state.initiatorUserId ?? state.sourceUser.id)\n ? 'initiator'\n : 'counterparty';\n\n const payload: NegotiationTurnPayload = {\n negotiationId: state.taskId,\n ownUser,\n otherUser,\n indexContext: state.indexContext,\n seedAssessment: state.seedAssessment,\n history,\n isFinalTurn,\n isDiscoverer: isSource,\n seat,\n protocolVersion: version,\n allowedActions: [...allowedActionsFor(version, seat, isFinalTurn)],\n ...(state.discoveryQuery && isSource && { discoveryQuery: state.discoveryQuery }),\n };\n\n const scope = { action: 'manage:negotiations', scopeType: 'network', scopeId: state.indexContext.networkId };\n\n const dispatchResult = await dispatcher.dispatch(ownUser.id, scope, payload, { timeoutMs: state.timeoutMs });\n\n let turn: NegotiationTurn;\n\n if (dispatchResult.handled) {\n // Personal agent responded. Under v2, coerce out-of-seat actions to\n // the conservative fallback — the polling/respond surfaces reject\n // these with a 400, but locally-dispatched turns land here directly.\n turn = dispatchResult.turn;\n if (version === 'v2' && !allowedActionsFor(version, seat, isFinalTurn).includes(turn.action)) {\n turnLog.warn('Personal agent returned out-of-seat action, coercing to conservative fallback', {\n action: turn.action, seat, isFinalTurn,\n });\n turn = { ...turn, action: fallbackActionFor(version, seat, isFinalTurn) };\n }\n } else if (dispatchResult.reason === 'waiting') {\n // Long timeout — graph suspends. Persist the full turn context so the\n // polling agent (and MCP consumers via get_negotiation) reconstruct\n // the same view the in-process system agent would see. The view is\n // stored in absolute source/candidate terms; perspective is projected\n // at pickup time using the claiming user's id.\n traceEmitter?.({ type: \"agent_end\", name: agentName, durationMs: Date.now() - agentStart, summary: \"waiting_for_agent\" });\n await database.setTaskTurnContext(state.taskId, {\n sourceUser: state.sourceUser,\n candidateUser: state.candidateUser,\n indexContext: state.indexContext,\n seedAssessment: state.seedAssessment,\n // Keep discoveryQuery speaker-scoped: include it only when the\n // parked turn belongs to the discoverer (source). Persisting it on\n // candidate-side turns would make the pickup prompt frame the\n // search as \"your user searched for X\" for the wrong user.\n ...(isSource && state.discoveryQuery && { discoveryQuery: state.discoveryQuery }),\n });\n await database.updateTaskState(state.taskId, \"waiting_for_agent\");\n return { status: 'waiting_for_agent' as const };\n } else {\n // No personal agent or timeout — run system agent\n turn = await systemAgent.invoke({\n ownUser,\n otherUser,\n indexContext: state.indexContext,\n seedAssessment: state.seedAssessment,\n history,\n isFinalTurn,\n isDiscoverer: isSource,\n seat,\n protocolVersion: version,\n ...(state.discoveryQuery && isSource && { discoveryQuery: state.discoveryQuery }),\n isContinuation: state.isContinuation,\n ...(state.userAnswers.length > 0 && { userAnswers: state.userAnswers }),\n });\n }\n\n traceEmitter?.({ type: \"agent_end\", name: agentName, durationMs: Date.now() - agentStart, summary: `${turn.action}` });\n\n // First turn must open the negotiation (unless continuing a prior\n // conversation): v1 → \"propose\"; v2 initiator → \"outreach\". A v2 turn-0\n // speaker holding the counterparty seat (tie-break inheritance) is left\n // unforced — it is responding, not opening.\n if (state.turnCount === 0 && !state.isContinuation) {\n const openingAction = version === 'v2' ? 'outreach' : 'propose';\n if ((version !== 'v2' || seat === 'initiator') && turn.action !== openingAction) {\n turnLog.warn(`Agent returned unexpected action on turn 0, forcing to ${openingAction}`, { action: turn.action });\n turn.action = openingAction;\n }\n }\n\n const parts = [{ kind: \"data\" as const, data: turn }];\n const message = await database.createMessage({\n conversationId: state.conversationId,\n senderId: `agent:${ownUser.id}`,\n role: \"agent\",\n parts,\n taskId: state.taskId,\n });\n\n await database.updateTaskState(state.taskId, \"working\");\n\n if (state.opportunityId) {\n emitWide({\n type: \"negotiation_turn\",\n opportunityId: state.opportunityId,\n negotiationConversationId: state.conversationId,\n turnIndex: state.turnCount,\n actor: isSource ? \"source\" : \"candidate\",\n action: turn.action,\n ...(turn.assessment?.reasoning && { reasoning: turn.assessment.reasoning }),\n ...(turn.message && { message: turn.message }),\n ...(turn.assessment?.suggestedRoles && { suggestedRoles: turn.assessment.suggestedRoles }),\n durationMs: Date.now() - agentStart,\n });\n }\n\n return {\n messages: [{\n id: message.id,\n senderId: message.senderId,\n role: \"agent\" as const,\n parts: message.parts,\n createdAt: message.createdAt,\n }],\n turnCount: state.turnCount + 1,\n currentSpeaker: (isSource ? \"candidate\" : \"source\") as \"source\" | \"candidate\",\n lastTurn: turn,\n };\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n turnLog.error(\"Agent invocation failed\", { error: errMsg, stack: err instanceof Error ? err.stack : undefined, turnCount: state.turnCount });\n traceEmitter?.({ type: \"agent_end\", name: agentName, durationMs: Date.now() - agentStart, summary: `error: ${errMsg}` });\n const errorSeat: NegotiationSeat = (state.currentSpeaker === 'source' ? state.sourceUser.id : state.candidateUser.id) === (state.initiatorUserId ?? state.sourceUser.id)\n ? 'initiator'\n : 'counterparty';\n return {\n lastTurn: {\n action: rejectActionFor(state.protocolVersion ?? 'v1', errorSeat),\n assessment: { reasoning: `Agent error: ${errMsg}`, suggestedRoles: { ownUser: \"peer\" as const, otherUser: \"peer\" as const } },\n },\n turnCount: state.turnCount + 1,\n error: `Turn failed: ${errMsg}`,\n };\n }\n };\n\n const evaluateNode = (state: typeof NegotiationGraphState.State): string => {\n if (state.status === 'waiting_for_agent') return \"finalize\";\n if (state.error) return \"finalize\";\n if (!state.lastTurn) return \"finalize\";\n // Terminal actions: accept (v1+v2), reject (v1), withdraw/decline (v2)\n if (isTerminalAction(state.lastTurn.action)) return \"finalize\";\n // question routes same as counter — next turn\n if ((state.maxTurns ?? 0) > 0 && state.turnCount >= state.maxTurns!) return \"finalize\";\n return \"turn\";\n };\n\n const finalizeNode = async (state: typeof NegotiationGraphState.State) => {\n const traceEmitter = requestContext.getStore()?.traceEmitter;\n const emitWide = (event: Record<string, unknown>) =>\n (traceEmitter as ((e: Record<string, unknown>) => void) | undefined)?.(event);\n\n if (state.status === 'waiting_for_agent') {\n if (state.opportunityId) {\n emitWide({\n type: \"negotiation_outcome\",\n opportunityId: state.opportunityId,\n outcome: \"waiting_for_agent\",\n turnCount: state.turnCount,\n isContinuation: state.isContinuation,\n });\n }\n return {};\n }\n\n const history: NegotiationTurn[] = turnsFromMessages(state.messages);\n\n const lastTurn = state.lastTurn;\n const hasOpportunity = lastTurn?.action === \"accept\";\n const atCap = (state.maxTurns ?? 0) > 0 && state.turnCount >= state.maxTurns! && !isTerminalAction(lastTurn?.action);\n\n let agreedRoles: NegotiationOutcome[\"agreedRoles\"] = [];\n if (hasOpportunity && history.length >= 2) {\n const acceptTurn = history[history.length - 1];\n const precedingTurn = history[history.length - 2];\n const accepterIsSource = state.currentSpeaker === \"candidate\";\n const [sourceRole, candidateRole] = accepterIsSource\n ? [acceptTurn.assessment.suggestedRoles.ownUser, precedingTurn.assessment.suggestedRoles.ownUser]\n : [precedingTurn.assessment.suggestedRoles.ownUser, acceptTurn.assessment.suggestedRoles.ownUser];\n agreedRoles = [\n { userId: state.sourceUser.id, role: sourceRole },\n { userId: state.candidateUser.id, role: candidateRole },\n ];\n }\n\n const outcome: NegotiationOutcome = {\n hasOpportunity,\n agreedRoles,\n reasoning: lastTurn?.assessment.reasoning ?? \"\",\n turnCount: state.turnCount,\n ...(atCap && { reason: \"turn_cap\" as const }),\n };\n\n try {\n await database.updateTaskState(state.taskId, \"completed\");\n await database.createArtifact({\n taskId: state.taskId,\n name: \"negotiation-outcome\",\n parts: [{ kind: \"data\", data: outcome }],\n metadata: { hasOpportunity, turnCount: state.turnCount },\n });\n\n finalizeLog.info('Session complete', {\n conversationId: state.conversationId,\n taskId: state.taskId,\n isContinuation: state.isContinuation,\n turnsAdded: state.turnCount,\n priorTurnCount: state.priorTurnCount,\n outcome: hasOpportunity ? 'accepted' : (atCap ? 'turn_cap' : (lastTurn?.action ?? 'unknown')),\n opportunityId: state.opportunityId || undefined,\n });\n\n if (state.opportunityId) {\n const nextStatus = lastTurn?.action === 'accept'\n ? 'pending'\n : isRejectLikeAction(lastTurn?.action)\n ? 'rejected'\n : 'stalled';\n await database.updateOpportunityStatus(state.opportunityId, nextStatus).catch((err) => {\n finalizeLog.error(\"Failed to update opportunity status\", { opportunityId: state.opportunityId, nextStatus, error: err });\n });\n }\n } catch (err) {\n finalizeLog.error(\"Failed to persist outcome\", { error: err });\n }\n\n if (state.opportunityId) {\n const emittedOutcome: \"accepted\" | \"rejected_stalled\" | \"turn_cap\" | \"timed_out\" =\n hasOpportunity\n ? \"accepted\"\n : atCap\n ? \"turn_cap\"\n : state.error && /timeout/i.test(state.error)\n ? \"timed_out\"\n : \"rejected_stalled\";\n\n emitWide({\n type: \"negotiation_outcome\",\n opportunityId: state.opportunityId,\n outcome: emittedOutcome,\n turnCount: state.turnCount,\n isContinuation: state.isContinuation,\n turnsAdded: state.turnCount,\n priorTurnCount: state.priorTurnCount,\n ...(outcome.reasoning && { reasoning: outcome.reasoning }),\n ...(hasOpportunity && agreedRoles.length >= 2 && {\n agreedRoles: {\n ownUser: agreedRoles[0]?.role,\n otherUser: agreedRoles[1]?.role,\n },\n }),\n });\n }\n\n // Enqueue question generation for stalled/capped negotiations (not accepted or explicitly rejected).\n // Require turnCount > 0 so early init/turn errors don't enqueue with empty context.\n if (!hasOpportunity && !isRejectLikeAction(lastTurn?.action) && state.turnCount > 0 && state.opportunityId && questionerEnqueue) {\n const stallReason: 'turn_cap' | 'timeout' | 'stalled' = atCap\n ? 'turn_cap'\n : (state.error && /timeout/i.test(state.error))\n ? 'timeout'\n : 'stalled';\n\n const userContext = (await database.getUserContext(state.sourceUser.id, null))?.text ?? '';\n questionerEnqueue({\n mode: 'negotiation',\n userId: state.sourceUser.id,\n sourceType: 'opportunity',\n sourceId: state.opportunityId,\n context: {\n negotiationId: state.taskId,\n counterpartyHint: `${state.candidateUser.profile.name ?? 'Unknown'}${state.candidateUser.profile.bio ? ', ' + state.candidateUser.profile.bio : ''}`,\n indexContext: state.indexContext.prompt,\n outcomeReason: stallReason,\n keyTake: outcome.reasoning,\n userContext,\n },\n }).catch((err) =>\n finalizeLog.error('Failed to enqueue negotiation question generation', {\n opportunityId: state.opportunityId,\n error: err,\n })\n );\n }\n\n return { outcome, status: 'completed' as const };\n };\n\n const workflow = new StateGraph(NegotiationGraphState)\n .addNode(\"init\", initNode)\n .addNode(\"screen\", screenNode)\n .addNode(\"turn\", turnNode)\n .addNode(\"finalize\", finalizeNode)\n .addConditionalEdges(\"turn\", evaluateNode, {\n turn: \"turn\",\n finalize: \"finalize\",\n })\n .addConditionalEdges(\"init\", (state: typeof NegotiationGraphState.State) => {\n if (state.error) return \"finalize\";\n // Screen gate: fresh negotiations only (continuations already passed\n // the gate when the dialogue opened); off disables the node entirely.\n if (!state.isContinuation && configuredScreenMode() !== \"off\") return \"screen\";\n return \"turn\";\n }, { screen: \"screen\", turn: \"turn\", finalize: \"finalize\" })\n .addEdge(\"screen\", \"turn\")\n .addEdge(\"__start__\", \"init\")\n .addEdge(\"finalize\", \"__end__\");\n\n return workflow.compile();\n }\n}\n\nexport interface NegotiationCandidate {\n userId: string;\n reasoning: string;\n valencyRole: string;\n networkId?: string;\n candidateUser: UserNegotiationContext;\n /** The explicit search query that triggered discovery (if any). */\n discoveryQuery?: string;\n /**\n * ID of the opportunity this negotiation is for. When set, the negotiation\n * graph's finalize node updates the opportunity's status based on the outcome\n * (`accept` → 'pending', `reject` → 'rejected', otherwise → 'stalled').\n */\n opportunityId?: string;\n}\n\nexport interface NegotiationResult {\n userId: string;\n agreedRoles: NegotiationOutcome[\"agreedRoles\"];\n reasoning: string;\n turnCount: number;\n}\n\n/**\n * Per-candidate resolution hook — fires as each negotiation settles, before\n * Promise.all aggregates. Used by the orchestrator branch to progressively\n * stream `opportunity_draft_ready` events as each candidate resolves, rather\n * than emitting all at once after the full fan-out completes. Awaited so the\n * caller can run async work (DB update, event emit) before the next settle.\n *\n * `turns` and `outcome` are passed through from the underlying negotiation\n * graph so consumers can build per-candidate decision-question inputs without\n * re-walking trace events or DB artifacts. Both are present on every\n * resolution (accepted, rejected, stalled, error); error paths receive a\n * synthesized `outcome` with `hasOpportunity: false`.\n */\nexport type OnNegotiationResolved = (entry: {\n candidate: NegotiationCandidate;\n accepted: NegotiationResult | null;\n turns: NegotiationTurn[];\n outcome: NegotiationOutcome;\n}) => Promise<void>;\n\n/**\n * Runs bilateral negotiation for each candidate in parallel.\n * @returns Only candidates that produced an opportunity\n */\nexport async function negotiateCandidates(\n negotiationGraph: NegotiationGraphLike,\n sourceUser: UserNegotiationContext,\n candidates: NegotiationCandidate[],\n indexContext: { networkId: string; prompt: string },\n opts?: {\n maxTurns?: number;\n traceEmitter?: TraceEmitter;\n indexContextOverrides?: Map<string, string>;\n timeoutMs?: number;\n onCandidateResolved?: OnNegotiationResolved;\n trigger?: \"orchestrator\" | \"ambient\";\n /**\n * Initiator seat for every candidate session in this fan-out (v2 stamp).\n * Passed through to the negotiation graph, which may still override it by\n * inheriting from a prior task on the same opportunity/conversation.\n */\n initiatorUserId?: string;\n },\n): Promise<NegotiationResult[]> {\n const { maxTurns, traceEmitter, indexContextOverrides, timeoutMs, onCandidateResolved, trigger, initiatorUserId } = opts ?? {};\n\n // Local helper to emit events whose shape is wider than the declared\n // `TraceEmitter` union (mirrors the cast used in chat.agent at the relay sink\n // and inside turn/finalize nodes above).\n const emitWide = (event: Record<string, unknown>) =>\n (traceEmitter as ((e: Record<string, unknown>) => void) | undefined)?.(event);\n\n const results = await Promise.all(\n candidates.map(async (candidate) => {\n const start = Date.now();\n if (candidate.opportunityId) {\n const candidateName = candidate.candidateUser?.profile?.name;\n emitWide({\n type: \"negotiation_session_start\",\n opportunityId: candidate.opportunityId,\n negotiationConversationId: \"\", // filled in on session_end\n sourceUserId: sourceUser.id,\n candidateUserId: candidate.userId,\n initiatorUserId: initiatorUserId ?? sourceUser.id,\n ...(candidateName && { candidateName }),\n trigger: trigger ?? \"ambient\",\n startedAt: start,\n });\n }\n traceEmitter?.({ type: \"agent_start\", name: \"Negotiating candidate\" });\n\n try {\n const candidateIndexContext = candidate.networkId\n ? { networkId: candidate.networkId, prompt: indexContextOverrides?.get(candidate.networkId) ?? '' }\n : indexContext;\n\n const result = await invokeWithAbortSignal(negotiationGraph, {\n sourceUser,\n candidateUser: candidate.candidateUser,\n indexContext: candidateIndexContext,\n seedAssessment: {\n reasoning: candidate.reasoning,\n valencyRole: candidate.valencyRole,\n },\n ...(candidate.discoveryQuery && { discoveryQuery: candidate.discoveryQuery }),\n ...(candidate.opportunityId && { opportunityId: candidate.opportunityId }),\n ...(initiatorUserId && { initiatorUserId }),\n ...(maxTurns !== undefined && { maxTurns }),\n ...(timeoutMs !== undefined && { timeoutMs }),\n });\n\n const durationMs = Date.now() - start;\n const outcome = result.outcome;\n const hasOpportunity = outcome?.hasOpportunity === true;\n const isContinuation = (result as { isContinuation?: boolean }).isContinuation ?? false;\n const priorTurnCount = (result as { priorTurnCount?: number }).priorTurnCount ?? 0;\n\n const turnFlow = (result.messages ?? [])\n .map((m) => {\n const dataPart = (m.parts as Array<{ kind?: string; data?: Record<string, unknown> }>)?.find((p) => p.kind === \"data\");\n if (!dataPart?.data) return null;\n const turn = dataPart.data as { action?: string };\n return turn.action ?? \"unknown\";\n })\n .filter(Boolean)\n .join(\" → \");\n\n const statusTag = hasOpportunity ? \"✓ opportunity\" : \"✗ rejected\";\n traceEmitter?.({ type: \"agent_end\", name: \"Negotiating candidate\", durationMs, summary: `${candidate.userId}: ${turnFlow} ${statusTag}` });\n\n if (candidate.opportunityId) {\n emitWide({\n type: \"negotiation_session_end\",\n opportunityId: candidate.opportunityId,\n negotiationConversationId: (result as { conversationId?: string }).conversationId ?? \"\",\n durationMs: Date.now() - start,\n isContinuation,\n turnsAdded: outcome?.turnCount ?? 0,\n priorTurnCount,\n });\n }\n\n const accepted: NegotiationResult | null = hasOpportunity && outcome\n ? {\n userId: candidate.userId,\n agreedRoles: outcome.agreedRoles,\n reasoning: outcome.reasoning,\n turnCount: outcome.turnCount,\n }\n : null;\n\n if (onCandidateResolved) {\n const turnHistory: NegotiationTurn[] = turnsFromMessages(result.messages ?? []);\n const resolvedOutcome: NegotiationOutcome = result.outcome ?? {\n hasOpportunity: false,\n agreedRoles: [],\n reasoning: \"no outcome returned by negotiation graph\",\n turnCount: turnHistory.length,\n };\n try {\n await onCandidateResolved({\n candidate,\n accepted,\n turns: turnHistory,\n outcome: resolvedOutcome,\n });\n } catch (hookErr) {\n // Hook failures must not sink the candidate result — the aggregate\n // return is still useful, and the orchestrator branch logs its own\n // failures inline.\n negotiateCandidatesLog.error(\"onCandidateResolved hook threw\", {\n candidateUserId: candidate.userId,\n error: hookErr,\n });\n }\n }\n\n return accepted;\n } catch (err) {\n const durationMs = Date.now() - start;\n traceEmitter?.({ type: \"agent_end\", name: \"Negotiating candidate\", durationMs, summary: `${candidate.userId}: error` });\n if (candidate.opportunityId) {\n emitWide({\n type: \"negotiation_session_end\",\n opportunityId: candidate.opportunityId,\n negotiationConversationId: \"\",\n durationMs: Date.now() - start,\n });\n }\n negotiateCandidatesLog.error(\"Negotiation failed\", { candidateUserId: candidate.userId, error: err });\n if (onCandidateResolved) {\n try {\n await onCandidateResolved({\n candidate,\n accepted: null,\n turns: [],\n outcome: {\n hasOpportunity: false,\n agreedRoles: [],\n reasoning: err instanceof Error ? err.message : String(err),\n turnCount: 0,\n },\n });\n } catch {\n // ignore hook failure on error path\n }\n }\n return null;\n }\n }),\n );\n\n return results.filter((r): r is NegotiationResult => r !== null);\n}\n\n/**\n * Creates a negotiation graph with the provided dependencies.\n */\nexport function createDefaultNegotiationGraph(deps: {\n database: NegotiationGraphDatabase;\n dispatcher: AgentDispatcher;\n timeoutQueue?: NegotiationTimeoutQueue;\n}) {\n const factory = new NegotiationGraphFactory(deps.database, deps.dispatcher, deps.timeoutQueue);\n return factory.createGraph();\n}\n"]}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { createStructuredModel } from "../shared/agent/model.config.js";
|
|
3
|
+
import type { UserNegotiationContext, SeedAssessment } from "../shared/schemas/negotiation-state.schema.js";
|
|
4
|
+
/**
|
|
5
|
+
* Screen-gate modes (P2.1 — client-advocate protocol).
|
|
6
|
+
*
|
|
7
|
+
* - `off` — the screen node is skipped entirely; no LLM call, no telemetry.
|
|
8
|
+
* - `shadow` — the screen decision is made and recorded (task metadata +
|
|
9
|
+
* trace event + log line) but NEVER blocks: every fresh negotiation still
|
|
10
|
+
* proceeds to the first turn. Used to measure pass rates against observed
|
|
11
|
+
* reject rates before enforcement.
|
|
12
|
+
* - `enforce` — reserved for P2.2. Until enforcement lands, `enforce` runs
|
|
13
|
+
* identically to `shadow` (decision recorded, negotiation proceeds) and the
|
|
14
|
+
* screen node logs a warning that enforcement is not yet implemented.
|
|
15
|
+
*/
|
|
16
|
+
export declare const NEGOTIATION_SCREEN_MODES: readonly ["off", "shadow", "enforce"];
|
|
17
|
+
export type NegotiationScreenMode = (typeof NEGOTIATION_SCREEN_MODES)[number];
|
|
18
|
+
/**
|
|
19
|
+
* Resolve the screen mode from `NEGOTIATION_SCREEN_MODE`.
|
|
20
|
+
*
|
|
21
|
+
* Defaults to `off` when unset or unrecognized — the screen gate is an
|
|
22
|
+
* explicit opt-in flip (same operational pattern as
|
|
23
|
+
* `NEGOTIATION_PROTOCOL_VERSION` / `NEGOTIATOR_CHAT_ENABLED`): code ships
|
|
24
|
+
* inert, the environment turns it on.
|
|
25
|
+
*/
|
|
26
|
+
export declare function configuredScreenMode(): NegotiationScreenMode;
|
|
27
|
+
/**
|
|
28
|
+
* Structured screen decision — the outreach gate's verdict on whether this
|
|
29
|
+
* match is worth the client's name before any turn is exchanged.
|
|
30
|
+
*/
|
|
31
|
+
export declare const ScreenDecisionSchema: z.ZodObject<{
|
|
32
|
+
decision: z.ZodEnum<["reach_out", "pass"]>;
|
|
33
|
+
reasoning: z.ZodString;
|
|
34
|
+
/** Suggested opening angle for the outreach turn (only when reaching out). */
|
|
35
|
+
outreachAngle: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
36
|
+
evidence: z.ZodObject<{
|
|
37
|
+
/** How well the counterparty's context/premises fit the client's need. */
|
|
38
|
+
counterpartyPremiseFit: z.ZodString;
|
|
39
|
+
/** How the client's intents align with what the counterparty seeks. */
|
|
40
|
+
intentAlignment: z.ZodString;
|
|
41
|
+
/** Prior-negotiation memory signals. Wired in P5.3 — always absent today. */
|
|
42
|
+
memoryHints: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
43
|
+
}, "strip", z.ZodTypeAny, {
|
|
44
|
+
counterpartyPremiseFit: string;
|
|
45
|
+
intentAlignment: string;
|
|
46
|
+
memoryHints?: string | null | undefined;
|
|
47
|
+
}, {
|
|
48
|
+
counterpartyPremiseFit: string;
|
|
49
|
+
intentAlignment: string;
|
|
50
|
+
memoryHints?: string | null | undefined;
|
|
51
|
+
}>;
|
|
52
|
+
}, "strip", z.ZodTypeAny, {
|
|
53
|
+
reasoning: string;
|
|
54
|
+
decision: "reach_out" | "pass";
|
|
55
|
+
evidence: {
|
|
56
|
+
counterpartyPremiseFit: string;
|
|
57
|
+
intentAlignment: string;
|
|
58
|
+
memoryHints?: string | null | undefined;
|
|
59
|
+
};
|
|
60
|
+
outreachAngle?: string | null | undefined;
|
|
61
|
+
}, {
|
|
62
|
+
reasoning: string;
|
|
63
|
+
decision: "reach_out" | "pass";
|
|
64
|
+
evidence: {
|
|
65
|
+
counterpartyPremiseFit: string;
|
|
66
|
+
intentAlignment: string;
|
|
67
|
+
memoryHints?: string | null | undefined;
|
|
68
|
+
};
|
|
69
|
+
outreachAngle?: string | null | undefined;
|
|
70
|
+
}>;
|
|
71
|
+
export type ScreenDecision = z.infer<typeof ScreenDecisionSchema>;
|
|
72
|
+
/**
|
|
73
|
+
* The record persisted to `tasks.metadata.screenDecision` and returned into
|
|
74
|
+
* graph state. Extends the LLM decision with operational context so pass-rate
|
|
75
|
+
* queries can group by mode and exclude failed-open rows.
|
|
76
|
+
*/
|
|
77
|
+
export interface ScreenDecisionRecord extends ScreenDecision {
|
|
78
|
+
mode: NegotiationScreenMode;
|
|
79
|
+
/** True when the screen LLM call failed and the gate defaulted open. */
|
|
80
|
+
failedOpen?: boolean;
|
|
81
|
+
/** Error message when `failedOpen` is set. */
|
|
82
|
+
error?: string;
|
|
83
|
+
screenedAt: string;
|
|
84
|
+
durationMs: number;
|
|
85
|
+
}
|
|
86
|
+
export interface NegotiationScreenerInput {
|
|
87
|
+
/** The client — the user whose negotiator is deciding whether to reach out. */
|
|
88
|
+
clientUser: UserNegotiationContext;
|
|
89
|
+
/** The counterparty the client's negotiator would be reaching out to. */
|
|
90
|
+
counterpartyUser: UserNegotiationContext;
|
|
91
|
+
/** The counterparty's `user_contexts` paragraph (empty string when absent). */
|
|
92
|
+
counterpartyContext?: string;
|
|
93
|
+
/** The explicit search query that triggered discovery (if any). */
|
|
94
|
+
discoveryQuery?: string;
|
|
95
|
+
seedAssessment: Omit<SeedAssessment, "actors">;
|
|
96
|
+
indexContext: {
|
|
97
|
+
networkId: string;
|
|
98
|
+
prompt?: string;
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
export interface NegotiationScreenerConfig {
|
|
102
|
+
/** Hard ceiling on the screen LLM round-trip, in ms (default 15000). */
|
|
103
|
+
timeoutMs?: number;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* The outreach gate (P2.1). One structured LLM call deciding
|
|
107
|
+
* `reach_out | pass` for a fresh negotiation, from the reaching client's
|
|
108
|
+
* perspective. Throws on LLM/validation failure — the screen graph node owns
|
|
109
|
+
* the fail-open policy (a failed screen never blocks the negotiation).
|
|
110
|
+
*/
|
|
111
|
+
export declare class NegotiationScreener {
|
|
112
|
+
private readonly timeoutMs;
|
|
113
|
+
constructor(config?: NegotiationScreenerConfig);
|
|
114
|
+
/**
|
|
115
|
+
* Produce a screen decision for a fresh match.
|
|
116
|
+
* @throws When the LLM call times out or returns schema-invalid output.
|
|
117
|
+
*/
|
|
118
|
+
invoke(input: NegotiationScreenerInput): Promise<ScreenDecision>;
|
|
119
|
+
/**
|
|
120
|
+
* Raw structured-model round trip. Split out as a seam so tests can drive
|
|
121
|
+
* the schema-validation and fail-open paths without a live provider.
|
|
122
|
+
*/
|
|
123
|
+
protected callModel(model: ReturnType<typeof createStructuredModel>, chatMessages: Array<{
|
|
124
|
+
role: string;
|
|
125
|
+
content: string;
|
|
126
|
+
}>): Promise<unknown>;
|
|
127
|
+
}
|
|
128
|
+
//# sourceMappingURL=negotiation.screen.d.ts.map
|
|
@@ -0,0 +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,cA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,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;IAgDtE;;;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"}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { createStructuredModel } from "../shared/agent/model.config.js";
|
|
3
|
+
import { invokeWithAbortSignal } from "../shared/agent/model-signal.js";
|
|
4
|
+
import { protocolLogger } from "../shared/observability/protocol.logger.js";
|
|
5
|
+
const screenLog = protocolLogger("NegotiationScreener");
|
|
6
|
+
/**
|
|
7
|
+
* Screen-gate modes (P2.1 — client-advocate protocol).
|
|
8
|
+
*
|
|
9
|
+
* - `off` — the screen node is skipped entirely; no LLM call, no telemetry.
|
|
10
|
+
* - `shadow` — the screen decision is made and recorded (task metadata +
|
|
11
|
+
* trace event + log line) but NEVER blocks: every fresh negotiation still
|
|
12
|
+
* proceeds to the first turn. Used to measure pass rates against observed
|
|
13
|
+
* reject rates before enforcement.
|
|
14
|
+
* - `enforce` — reserved for P2.2. Until enforcement lands, `enforce` runs
|
|
15
|
+
* identically to `shadow` (decision recorded, negotiation proceeds) and the
|
|
16
|
+
* screen node logs a warning that enforcement is not yet implemented.
|
|
17
|
+
*/
|
|
18
|
+
export const NEGOTIATION_SCREEN_MODES = ["off", "shadow", "enforce"];
|
|
19
|
+
/**
|
|
20
|
+
* Resolve the screen mode from `NEGOTIATION_SCREEN_MODE`.
|
|
21
|
+
*
|
|
22
|
+
* Defaults to `off` when unset or unrecognized — the screen gate is an
|
|
23
|
+
* explicit opt-in flip (same operational pattern as
|
|
24
|
+
* `NEGOTIATION_PROTOCOL_VERSION` / `NEGOTIATOR_CHAT_ENABLED`): code ships
|
|
25
|
+
* inert, the environment turns it on.
|
|
26
|
+
*/
|
|
27
|
+
export function configuredScreenMode() {
|
|
28
|
+
const raw = process.env.NEGOTIATION_SCREEN_MODE;
|
|
29
|
+
if (raw === "shadow" || raw === "enforce" || raw === "off")
|
|
30
|
+
return raw;
|
|
31
|
+
return "off";
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Structured screen decision — the outreach gate's verdict on whether this
|
|
35
|
+
* match is worth the client's name before any turn is exchanged.
|
|
36
|
+
*/
|
|
37
|
+
export const ScreenDecisionSchema = z.object({
|
|
38
|
+
decision: z.enum(["reach_out", "pass"]),
|
|
39
|
+
reasoning: z.string(),
|
|
40
|
+
/** Suggested opening angle for the outreach turn (only when reaching out). */
|
|
41
|
+
outreachAngle: z.string().nullable().optional(),
|
|
42
|
+
evidence: z.object({
|
|
43
|
+
/** How well the counterparty's context/premises fit the client's need. */
|
|
44
|
+
counterpartyPremiseFit: z.string(),
|
|
45
|
+
/** How the client's intents align with what the counterparty seeks. */
|
|
46
|
+
intentAlignment: z.string(),
|
|
47
|
+
/** Prior-negotiation memory signals. Wired in P5.3 — always absent today. */
|
|
48
|
+
memoryHints: z.string().nullable().optional(),
|
|
49
|
+
}),
|
|
50
|
+
});
|
|
51
|
+
const 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.
|
|
52
|
+
|
|
53
|
+
Network context: {networkContext}
|
|
54
|
+
|
|
55
|
+
Decide:
|
|
56
|
+
- "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.
|
|
57
|
+
- "pass" when the match is generic, one-sided, or rests on vague overlap that would waste both parties' attention.
|
|
58
|
+
|
|
59
|
+
Rules:
|
|
60
|
+
{queryRule}
|
|
61
|
+
- Judge concrete intent alignment, not topical adjacency.
|
|
62
|
+
- 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.
|
|
63
|
+
- Do NOT reference internal system details like scores, pre-screens, or evaluator outputs in reasoning that could be shown to users.`;
|
|
64
|
+
const 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.`;
|
|
65
|
+
const NO_QUERY_RULE = `- No explicit search query: judge against {clientName}'s active intents.`;
|
|
66
|
+
const DEFAULT_SCREEN_TIMEOUT_MS = 15000;
|
|
67
|
+
/**
|
|
68
|
+
* The outreach gate (P2.1). One structured LLM call deciding
|
|
69
|
+
* `reach_out | pass` for a fresh negotiation, from the reaching client's
|
|
70
|
+
* perspective. Throws on LLM/validation failure — the screen graph node owns
|
|
71
|
+
* the fail-open policy (a failed screen never blocks the negotiation).
|
|
72
|
+
*/
|
|
73
|
+
export class NegotiationScreener {
|
|
74
|
+
constructor(config) {
|
|
75
|
+
this.timeoutMs = config?.timeoutMs && Number.isFinite(config.timeoutMs) && config.timeoutMs > 0
|
|
76
|
+
? config.timeoutMs
|
|
77
|
+
: DEFAULT_SCREEN_TIMEOUT_MS;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Produce a screen decision for a fresh match.
|
|
81
|
+
* @throws When the LLM call times out or returns schema-invalid output.
|
|
82
|
+
*/
|
|
83
|
+
async invoke(input) {
|
|
84
|
+
const model = createStructuredModel("negotiationScreener", ScreenDecisionSchema, { name: "negotiation_screener" });
|
|
85
|
+
const clientName = input.clientUser.profile.name ?? "your client";
|
|
86
|
+
const counterpartyName = input.counterpartyUser.profile.name ?? "the counterparty";
|
|
87
|
+
const networkContext = input.indexContext.prompt || "General discovery";
|
|
88
|
+
const queryRule = (input.discoveryQuery ? QUERY_RULE : NO_QUERY_RULE)
|
|
89
|
+
.replace(/{clientName}/g, clientName)
|
|
90
|
+
.replace(/{discoveryQuery}/g, input.discoveryQuery ?? "");
|
|
91
|
+
const systemPrompt = SYSTEM_PROMPT
|
|
92
|
+
.replace(/{clientName}/g, clientName)
|
|
93
|
+
.replace("{networkContext}", networkContext)
|
|
94
|
+
.replace("{queryRule}", queryRule);
|
|
95
|
+
const formatIntents = (intents) => intents.length > 0 ? intents.map((i) => `- ${i.title}: ${i.description}`).join("\n") : "- (none)";
|
|
96
|
+
const userMessage = `YOUR CLIENT (${clientName}):
|
|
97
|
+
Bio: ${input.clientUser.profile.bio ?? "N/A"}
|
|
98
|
+
${input.discoveryQuery ? `Search query: "${input.discoveryQuery}"\nBackground intents (secondary to the query):` : "Active intents:"}
|
|
99
|
+
${formatIntents(input.clientUser.intents)}
|
|
100
|
+
|
|
101
|
+
COUNTERPARTY (${counterpartyName}):
|
|
102
|
+
Bio: ${input.counterpartyUser.profile.bio ?? "N/A"}
|
|
103
|
+
${input.counterpartyContext ? `Context: ${input.counterpartyContext}\n` : ""}Active intents:
|
|
104
|
+
${formatIntents(input.counterpartyUser.intents)}
|
|
105
|
+
|
|
106
|
+
Why this match was suggested: ${input.seedAssessment.reasoning}
|
|
107
|
+
|
|
108
|
+
Decide whether reaching out serves ${clientName}.`;
|
|
109
|
+
const chatMessages = [
|
|
110
|
+
{ role: "system", content: systemPrompt },
|
|
111
|
+
{ role: "user", content: userMessage },
|
|
112
|
+
];
|
|
113
|
+
const result = await this.callModel(model, chatMessages);
|
|
114
|
+
const parsed = ScreenDecisionSchema.safeParse(result);
|
|
115
|
+
if (!parsed.success) {
|
|
116
|
+
screenLog.warn("Screen output failed schema validation", {
|
|
117
|
+
issues: parsed.error.issues.map((i) => i.message).slice(0, 3),
|
|
118
|
+
});
|
|
119
|
+
throw new Error(`Screen decision failed validation: ${parsed.error.issues[0]?.message ?? "unknown"}`);
|
|
120
|
+
}
|
|
121
|
+
return parsed.data;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Raw structured-model round trip. Split out as a seam so tests can drive
|
|
125
|
+
* the schema-validation and fail-open paths without a live provider.
|
|
126
|
+
*/
|
|
127
|
+
async callModel(model, chatMessages) {
|
|
128
|
+
return invokeWithAbortSignal(model, chatMessages, AbortSignal.timeout(this.timeoutMs));
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
//# sourceMappingURL=negotiation.screen.js.map
|
|
@@ -0,0 +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;AAE5E,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,CAAC,CAAC,IAAI,CAAC,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;IACvC,SAAS,E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,CAAC,cAAc,CAAC,SAAS;;qCAEzB,UAAU,GAAG,CAAC;QAE/C,MAAM,YAAY,GAAG;YACnB,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,YAAY,EAAE;YACzC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE;SACvC,CAAC;QAEF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;QACzD,MAAM,MAAM,GAAG,oBAAoB,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\";\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. Wired in P5.3 — always absent today. */\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\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.`;\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\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"]}
|