@indexnetwork/protocol 14.3.2-rc.477.1 → 17.0.0-rc.479.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/CHANGELOG.md +141 -0
  2. package/IMPLEMENTATION.md +50 -52
  3. package/STABILITY.md +3 -3
  4. package/dist/chat/chat.agent.js +2 -3
  5. package/dist/chat/chat.graph.d.ts +41 -1
  6. package/dist/chat/chat.graph.js +108 -127
  7. package/dist/chat/negotiator.persona.d.ts +1 -1
  8. package/dist/chat/negotiator.persona.js +1 -4
  9. package/dist/chat/negotiator.prompt.js +1 -2
  10. package/dist/chat/onboarding.persona.js +0 -1
  11. package/dist/chat/reporter.persona.js +0 -1
  12. package/dist/chat/signal.persona.js +0 -1
  13. package/dist/contacts/application/contact.tools.d.ts +6 -9
  14. package/dist/contacts/application/contact.tools.js +11 -92
  15. package/dist/contacts/application/index.d.ts +2 -14
  16. package/dist/contacts/application/index.js +2 -13
  17. package/dist/contacts/domain/contact.types.d.ts +0 -23
  18. package/dist/contacts/domain/index.d.ts +2 -6
  19. package/dist/contacts/index.d.ts +1 -1
  20. package/dist/contacts/index.js +1 -1
  21. package/dist/contacts/ports/contact.repository.port.d.ts +5 -12
  22. package/dist/contacts/ports/contact.repository.port.js +4 -6
  23. package/dist/contacts/ports/contact.tools.port.d.ts +1 -3
  24. package/dist/contacts/ports/contact.tools.port.js +1 -2
  25. package/dist/contacts/ports/index.d.ts +1 -1
  26. package/dist/contacts/ports/index.js +1 -1
  27. package/dist/discovery/hyde.frame.d.ts +4 -4
  28. package/dist/discovery/hyde.graph.d.ts +71 -12
  29. package/dist/discovery/hyde.graph.js +337 -335
  30. package/dist/discovery/lens.inferrer.d.ts +6 -6
  31. package/dist/enrichment/enrichment.graph.d.ts +127 -9
  32. package/dist/enrichment/enrichment.graph.js +633 -655
  33. package/dist/enrichment/enrichment.state.d.ts +1 -1
  34. package/dist/enrichment/enrichment.tools.context-read.d.ts +10 -0
  35. package/dist/enrichment/enrichment.tools.context-read.js +353 -0
  36. package/dist/enrichment/enrichment.tools.context-write.d.ts +9 -0
  37. package/dist/enrichment/enrichment.tools.context-write.js +417 -0
  38. package/dist/enrichment/enrichment.tools.d.ts +11 -1
  39. package/dist/enrichment/enrichment.tools.helpers.d.ts +139 -0
  40. package/dist/enrichment/enrichment.tools.helpers.js +234 -0
  41. package/dist/enrichment/enrichment.tools.js +16 -975
  42. package/dist/index.d.ts +27 -50
  43. package/dist/index.js +17 -28
  44. package/dist/intents/application/intent.graph.d.ts +71 -67
  45. package/dist/intents/application/intent.graph.execute.d.ts +59 -0
  46. package/dist/intents/application/intent.graph.execute.js +301 -0
  47. package/dist/intents/application/intent.graph.infer.d.ts +44 -0
  48. package/dist/intents/application/intent.graph.infer.js +97 -0
  49. package/dist/intents/application/intent.graph.js +96 -888
  50. package/dist/intents/application/intent.graph.reconcile.d.ts +71 -0
  51. package/dist/intents/application/intent.graph.reconcile.js +274 -0
  52. package/dist/intents/application/intent.graph.shared.d.ts +70 -0
  53. package/dist/intents/application/intent.graph.shared.js +153 -0
  54. package/dist/intents/domain/intent.state.d.ts +1 -1
  55. package/dist/maintenance/maintenance.graph.d.ts +66 -3
  56. package/dist/maintenance/maintenance.graph.js +155 -156
  57. package/dist/mcp/mcp.authorization-policy.d.ts +24 -28
  58. package/dist/mcp/mcp.authorization-policy.js +14 -34
  59. package/dist/mcp/mcp.server.d.ts +3 -3
  60. package/dist/mcp/mcp.server.js +14 -20
  61. package/dist/negotiations/application/negotiation.candidates.d.ts +83 -0
  62. package/dist/negotiations/application/negotiation.candidates.js +162 -0
  63. package/dist/negotiations/application/negotiation.graph.d.ts +91 -157
  64. package/dist/negotiations/application/negotiation.graph.finalize.d.ts +5 -0
  65. package/dist/negotiations/application/negotiation.graph.finalize.js +280 -0
  66. package/dist/negotiations/application/negotiation.graph.init.d.ts +54 -0
  67. package/dist/negotiations/application/negotiation.graph.init.js +227 -0
  68. package/dist/negotiations/application/negotiation.graph.js +69 -1388
  69. package/dist/negotiations/application/negotiation.graph.screen.d.ts +23 -0
  70. package/dist/negotiations/application/negotiation.graph.screen.js +108 -0
  71. package/dist/negotiations/application/negotiation.graph.shared.d.ts +75 -0
  72. package/dist/negotiations/application/negotiation.graph.shared.js +125 -0
  73. package/dist/negotiations/application/negotiation.graph.turn.d.ts +105 -0
  74. package/dist/negotiations/application/negotiation.graph.turn.js +484 -0
  75. package/dist/negotiations/domain/negotiation.state.d.ts +1 -1
  76. package/dist/negotiations/domain/negotiation.state.js +0 -1
  77. package/dist/networks/application/indexer.graph.d.ts +165 -7
  78. package/dist/networks/application/indexer.graph.js +339 -388
  79. package/dist/networks/application/indexer.state.d.ts +1 -1
  80. package/dist/networks/application/membership.graph.d.ts +83 -5
  81. package/dist/networks/application/membership.graph.js +177 -207
  82. package/dist/networks/application/network.graph.d.ts +148 -5
  83. package/dist/networks/application/network.graph.js +249 -278
  84. package/dist/networks/domain/membership.state.d.ts +1 -1
  85. package/dist/networks/domain/network.state.d.ts +1 -1
  86. package/dist/opportunities/application/delivery-card.cache.d.ts +1 -1
  87. package/dist/opportunities/application/delivery-card.cache.js +2 -2
  88. package/dist/opportunities/application/index.d.ts +2 -2
  89. package/dist/opportunities/application/index.js +2 -2
  90. package/dist/opportunities/application/opportunity.evaluator.js +1 -1
  91. package/dist/opportunities/application/opportunity.graph.d.ts +686 -473
  92. package/dist/opportunities/application/opportunity.graph.discovery-strategies.d.ts +109 -0
  93. package/dist/opportunities/application/opportunity.graph.discovery-strategies.js +451 -0
  94. package/dist/opportunities/application/opportunity.graph.discovery.d.ts +69 -0
  95. package/dist/opportunities/application/opportunity.graph.discovery.js +397 -0
  96. package/dist/opportunities/application/opportunity.graph.evaluation.d.ts +82 -0
  97. package/dist/opportunities/application/opportunity.graph.evaluation.js +608 -0
  98. package/dist/opportunities/application/opportunity.graph.js +120 -3690
  99. package/dist/opportunities/application/opportunity.graph.modes.d.ts +538 -0
  100. package/dist/opportunities/application/opportunity.graph.modes.js +538 -0
  101. package/dist/opportunities/application/opportunity.graph.negotiate.d.ts +109 -0
  102. package/dist/opportunities/application/opportunity.graph.negotiate.js +392 -0
  103. package/dist/opportunities/application/opportunity.graph.persist-node.d.ts +93 -0
  104. package/dist/opportunities/application/opportunity.graph.persist-node.js +765 -0
  105. package/dist/opportunities/application/opportunity.graph.prep.d.ts +150 -0
  106. package/dist/opportunities/application/opportunity.graph.prep.js +381 -0
  107. package/dist/opportunities/application/opportunity.graph.shared.d.ts +173 -0
  108. package/dist/opportunities/application/opportunity.graph.shared.js +199 -0
  109. package/dist/opportunities/application/opportunity.presentation.d.ts +399 -0
  110. package/dist/opportunities/application/{opportunity.presenter.js → opportunity.presentation.js} +735 -9
  111. package/dist/opportunities/application/opportunity.tools.cards.d.ts +152 -0
  112. package/dist/opportunities/application/opportunity.tools.cards.js +235 -0
  113. package/dist/opportunities/application/opportunity.tools.d.ts +8 -114
  114. package/dist/opportunities/application/opportunity.tools.js +28 -711
  115. package/dist/opportunities/application/opportunity.tools.list.d.ts +10 -0
  116. package/dist/opportunities/application/opportunity.tools.list.js +493 -0
  117. package/dist/opportunities/domain/index.d.ts +3 -3
  118. package/dist/opportunities/domain/index.js +3 -3
  119. package/dist/opportunities/domain/opportunity.state.d.ts +19 -19
  120. package/dist/opportunities/index.d.ts +6 -6
  121. package/dist/opportunities/index.js +4 -4
  122. package/dist/opportunities/ports/opportunity.tools.port.d.ts +1 -1
  123. package/dist/opportunities/radar/radar.graph.d.ts +57 -13
  124. package/dist/opportunities/radar/radar.graph.js +470 -471
  125. package/dist/premises/premise.graph.d.ts +88 -20
  126. package/dist/premises/premise.graph.js +207 -218
  127. package/dist/questions/domain/question.schema.d.ts +40 -40
  128. package/dist/shared/agent/tool.factory.js +0 -8
  129. package/dist/shared/agent/tool.helpers.d.ts +21 -45
  130. package/dist/shared/agent/tool.helpers.js +1 -2
  131. package/dist/shared/agent/tool.registry.d.ts +4 -3
  132. package/dist/shared/agent/tool.registry.js +2 -4
  133. package/dist/shared/agent/tool.runtime.js +0 -2
  134. package/dist/shared/agent/utility.tools.js +9 -13
  135. package/dist/shared/interfaces/database.capabilities.d.ts +100 -0
  136. package/dist/shared/interfaces/database.capabilities.js +7 -0
  137. package/dist/shared/interfaces/database.entities.d.ts +533 -0
  138. package/dist/shared/interfaces/database.entities.js +10 -0
  139. package/dist/shared/interfaces/database.identity-queries.d.ts +294 -0
  140. package/dist/shared/interfaces/database.identity-queries.js +4 -0
  141. package/dist/shared/interfaces/database.interface.d.ts +15 -2277
  142. package/dist/shared/interfaces/database.interface.js +8 -0
  143. package/dist/shared/interfaces/database.member-queries.d.ts +221 -0
  144. package/dist/shared/interfaces/database.member-queries.js +4 -0
  145. package/dist/shared/interfaces/database.negotiation.d.ts +305 -0
  146. package/dist/shared/interfaces/database.negotiation.js +26 -0
  147. package/dist/shared/interfaces/database.network-queries.d.ts +277 -0
  148. package/dist/shared/interfaces/database.network-queries.js +4 -0
  149. package/dist/shared/interfaces/database.opportunity-queries.d.ts +285 -0
  150. package/dist/shared/interfaces/database.opportunity-queries.js +4 -0
  151. package/dist/shared/interfaces/database.port.d.ts +322 -0
  152. package/dist/shared/interfaces/database.port.js +29 -0
  153. package/dist/shared/schemas/discovery-question.schema.d.ts +14 -14
  154. package/dist/shared/schemas/negotiation-digest.schema.d.ts +2 -2
  155. package/package.json +2 -15
  156. package/dist/contacts/application/contact.inviter.d.ts +0 -49
  157. package/dist/contacts/application/contact.inviter.js +0 -64
  158. package/dist/integrations/application/index.d.ts +0 -14
  159. package/dist/integrations/application/index.js +0 -14
  160. package/dist/integrations/application/integration.tools.d.ts +0 -27
  161. package/dist/integrations/application/integration.tools.js +0 -98
  162. package/dist/integrations/domain/index.d.ts +0 -16
  163. package/dist/integrations/domain/index.js +0 -1
  164. package/dist/integrations/domain/integration.types.d.ts +0 -51
  165. package/dist/integrations/domain/integration.types.js +0 -9
  166. package/dist/integrations/index.d.ts +0 -10
  167. package/dist/integrations/index.js +0 -8
  168. package/dist/integrations/ports/index.d.ts +0 -25
  169. package/dist/integrations/ports/index.js +0 -23
  170. package/dist/integrations/ports/integration.adapter.port.d.ts +0 -62
  171. package/dist/integrations/ports/integration.adapter.port.js +0 -15
  172. package/dist/integrations/ports/integration.importer.port.d.ts +0 -31
  173. package/dist/integrations/ports/integration.importer.port.js +0 -15
  174. package/dist/integrations/ports/integration.tools.port.d.ts +0 -25
  175. package/dist/integrations/ports/integration.tools.port.js +0 -18
  176. package/dist/opportunities/application/opportunity.card-presentation.d.ts +0 -44
  177. package/dist/opportunities/application/opportunity.card-presentation.js +0 -93
  178. package/dist/opportunities/application/opportunity.presenter.d.ts +0 -156
  179. package/dist/opportunities/domain/opportunity.presentation-cache.d.ts +0 -5
  180. package/dist/opportunities/domain/opportunity.presentation-cache.js +0 -11
  181. package/dist/opportunities/domain/opportunity.presentation.d.ts +0 -76
  182. package/dist/opportunities/domain/opportunity.presentation.js +0 -516
  183. package/dist/opportunities/domain/opportunity.safe-presentation.d.ts +0 -104
  184. package/dist/opportunities/domain/opportunity.safe-presentation.js +0 -102
@@ -1,1410 +1,91 @@
1
+ /**
2
+ * Bilateral negotiation graph: init → screen → turn* → finalize.
3
+ *
4
+ * Every node is a top-level function in a sibling module, taking the graph
5
+ * state and an explicit {@link NegotiationGraphDeps}. This file composes the
6
+ * dependency bag and wires the edges — nothing else.
7
+ */
1
8
  import { StateGraph } from "@langchain/langgraph";
2
- import { invokeWithAbortSignal } from "../../shared/agent/model-signal.js";
3
- import { requestContext } from "../../shared/observability/request-context.js";
4
9
  import { NegotiationGraphState } from "../domain/negotiation.state.js";
5
10
  import { IndexNegotiator } from "./negotiation.agent.js";
6
- import { allowedActionsFor, askUserAnswerWindowMs, configuredAskUserEnabled, configuredProtocolVersion, fallbackActionFor, isRejectLikeAction, isTerminalAction, readProtocolVersion, rejectActionFor } from "../domain/negotiation.protocol.js";
7
- import { assessConsultationEligibility, consultationPromptFor, negotiationConsultationPolicyMode } from "../domain/negotiation.consultation-policy.js";
8
11
  import { blocksNegotiationBeforeFirstTurn, NegotiationScreener } from "./negotiation.screen.js";
9
12
  import { configuredScreenMode } from "../domain/negotiation.screen.contracts.js";
10
- import { assessDeadlock, configuredDeadlockShiftEnabled, configuredDeadlockThreshold } from "../domain/negotiation.deadlock.js";
11
- import { protocolLogger } from "../../shared/observability/protocol.logger.js";
12
- import { NEGOTIATION_QUESTION_GENERIC_COUNTERPARTY, NEGOTIATION_QUESTION_GENERIC_NETWORK, negotiationQuestionSettlementId } from '../domain/negotiation.question-safety.js';
13
- import { buildIntentSnapshots } from "../domain/negotiation.intent-snapshot-provenance.js";
14
- import { holdsNegotiationConversationLock } from "../domain/negotiation.task-lock-policy.js";
13
+ import { isTerminalAction } from "../domain/negotiation.protocol.js";
15
14
  import { isNegotiationTurnCapReached } from "../domain/negotiation.turn-cap.js";
16
- import { expectedNegotiationSpeaker } from "../domain/negotiation.expected-speaker.js";
17
- import { attributedDialogueIsEmpty, buildSeededAttribution, combineAttributedDialogue } from '../negotiation.attribution.js';
18
- const logger = protocolLogger("NegotiationGraph");
19
- const initLog = protocolLogger("NegotiationGraph:Init");
20
- const screenNodeLog = protocolLogger("NegotiationGraph:Screen");
21
- const turnLog = protocolLogger("NegotiationGraph:Turn");
22
- const finalizeLog = protocolLogger("NegotiationGraph:Finalize");
23
- const negotiateCandidatesLog = protocolLogger("NegotiationGraph:negotiateCandidates");
24
- /** Extracts the ordered NegotiationTurn list from A2A message data parts. */
25
- function turnsFromMessages(messages) {
26
- return messages
27
- .map((m) => {
28
- const dataPart = m.parts.find((p) => p.kind === "data");
29
- return dataPart?.data;
30
- })
31
- .filter(Boolean);
32
- }
33
- /**
34
- * Whether `userId`'s side has already spent its one `ask_user` client
35
- * consultation in this conversation (P3.2 rationing: max one per negotiation
36
- * per side, checked against the full message history so continuations count
37
- * prior sessions' consultations too).
38
- */
39
- function hasPriorAskUser(messages, userId) {
40
- const sender = `agent:${userId}`;
41
- return messages.some((m) => {
42
- if (m.senderId !== sender)
43
- return false;
44
- const dataPart = m.parts.find((p) => p.kind === "data");
45
- return dataPart?.data?.action === "ask_user";
46
- });
47
- }
15
+ import { initNode } from "./negotiation.graph.init.js";
16
+ import { screenNode } from "./negotiation.graph.screen.js";
17
+ import { turnNode } from "./negotiation.graph.turn.js";
18
+ import { finalizeNode } from "./negotiation.graph.finalize.js";
19
+ export { negotiateCandidates } from "./negotiation.candidates.js";
48
20
  /**
49
21
  * Factory for the bilateral negotiation LangGraph state machine.
50
22
  * @remarks Accepts an AgentDispatcher for per-turn agent resolution.
51
23
  */
52
24
  export class NegotiationGraphFactory {
53
25
  constructor(database, dispatcher, timeoutQueue, questionerEnqueue, reflectEnqueue, memoryRetrieve) {
54
- this.database = database;
55
- this.dispatcher = dispatcher;
56
- this.timeoutQueue = timeoutQueue;
57
- this.questionerEnqueue = questionerEnqueue;
58
- this.reflectEnqueue = reflectEnqueue;
59
- this.memoryRetrieve = memoryRetrieve;
26
+ this.deps = {
27
+ database,
28
+ dispatcher,
29
+ timeoutQueue,
30
+ questionerEnqueue,
31
+ reflectEnqueue,
32
+ memoryRetrieve,
33
+ systemAgent: new IndexNegotiator(),
34
+ screener: new NegotiationScreener(),
35
+ };
60
36
  }
61
37
  createGraph() {
62
- const { database, dispatcher, timeoutQueue, questionerEnqueue, reflectEnqueue, memoryRetrieve } = this;
63
- const systemAgent = new IndexNegotiator();
64
- const screener = new NegotiationScreener();
65
- /**
66
- * P5.3 memory retrieval — never throws, never blocks a negotiation. The
67
- * injected fn already resolves [] when NEGOTIATOR_MEMORY_INJECT is off;
68
- * this wrapper adds the graph-side failure guard.
69
- */
70
- const retrieveMemory = async (userId, counterpartyUserId, queryText, scope) => {
71
- if (!memoryRetrieve)
72
- return [];
73
- try {
74
- return await memoryRetrieve({ userId, counterpartyUserId, queryText, scope });
75
- }
76
- catch (err) {
77
- logger.warn("Negotiator memory retrieval failed; proceeding without memory", {
78
- userId,
79
- scope,
80
- error: err instanceof Error ? err.message : String(err),
81
- });
82
- return [];
83
- }
84
- };
85
- /** Similarity query text: seed reasoning + counterparty context. */
86
- const memoryQueryText = (state, counterparty) => [
87
- state.discoveryQuery ? `Search: ${state.discoveryQuery}` : "",
88
- state.seedAssessment?.reasoning ?? "",
89
- counterparty?.profile?.name ?? "",
90
- counterparty?.profile?.bio ?? "",
91
- (counterparty?.intents ?? []).slice(0, 5).map((i) => `${i.title}: ${i.description}`).join("\n"),
92
- ].filter(Boolean).join("\n");
93
- /**
94
- * IND-569: resolve a prior negotiation task's attribution metadata for the
95
- * per-opportunity prior-dialogue labels. Never throws — any failure returns
96
- * null so the turns degrade to the unattributed block instead of leaking
97
- * into the current opportunity's context.
98
- */
99
- const resolveTaskAttribution = async (taskId) => {
100
- try {
101
- const task = await database.getTask(taskId);
102
- if (!task)
103
- return null;
104
- const md = (task.metadata ?? {});
105
- const opportunityId = typeof md.opportunityId === 'string' && md.opportunityId.length > 0 ? md.opportunityId : null;
106
- const snapshots = Array.isArray(md.intentSnapshots) ? md.intentSnapshots : [];
107
- const sourceIntentId = typeof md.sourceIntentId === 'string' ? md.sourceIntentId : null;
108
- const snap = snapshots.find((s) => s && s.intentId === sourceIntentId) ?? snapshots[0];
109
- const opportunityTitle = snap && typeof snap.title === 'string' && snap.title.trim().length > 0 ? snap.title : null;
110
- let outcome = null;
111
- try {
112
- const artifacts = await database.getArtifactsForTask(taskId);
113
- const outArtifact = artifacts.find((a) => a.name === 'negotiation-outcome');
114
- if (outArtifact) {
115
- const firstPart = Array.isArray(outArtifact.parts) ? outArtifact.parts[0] : undefined;
116
- const data = firstPart?.data;
117
- if (data && typeof data.hasOpportunity === 'boolean') {
118
- outcome = data.hasOpportunity ? 'accepted' : (data.reason === 'screened_out' ? 'not pursued' : 'declined');
119
- }
120
- else if (typeof outArtifact.metadata?.continuationOutcome === 'string') {
121
- outcome = outArtifact.metadata.continuationOutcome;
122
- }
123
- }
124
- }
125
- catch { /* outcome stays null; header degrades to "outcome unknown" */ }
126
- const concludedAt = task.updatedAt instanceof Date
127
- ? task.updatedAt.toISOString()
128
- : (task.updatedAt ? new Date(task.updatedAt).toISOString() : null);
129
- return { opportunityId, opportunityTitle, outcome, concludedAt };
130
- }
131
- catch {
132
- return null;
133
- }
134
- };
135
- /**
136
- * IND-569: build the attributed prior dialogue passed to the screener and
137
- * turn prompts. Combines the immutable seeded attribution (earlier + legacy
138
- * unattributed blocks, resolved once in init) with this session's own turns
139
- * (task-id-matched). Null when there is no seeded attribution.
140
- */
141
- const buildAttributedDialogue = (state) => {
142
- if (!state.isContinuation || !state.priorAttribution)
143
- return null;
144
- const currentSessionTurns = turnsFromMessages(state.messages.filter((m) => m.taskId === state.taskId));
145
- const dialogue = combineAttributedDialogue(state.priorAttribution, currentSessionTurns);
146
- return attributedDialogueIsEmpty(dialogue) ? null : dialogue;
147
- };
148
- const initNode = async (state) => {
149
- try {
150
- // Exact continuations reuse the prior conversation and preclaimed
151
- // successor; they must not create any mutable state before the fence.
152
- const agentIdA = `agent:${state.sourceUser.id}`;
153
- const agentIdB = `agent:${state.candidateUser.id}`;
154
- const execution = state.continuationExecution;
155
- const conversation = execution
156
- ? { id: execution.conversationId }
157
- : await database.getOrCreateDM(agentIdA, agentIdB, 'agent');
158
- // --- Lock gate: check for an active task on this conversation ---
159
- const priorMessages = await database.getMessagesForConversation(conversation.id);
160
- if (Boolean(state.resumeFromTaskId) !== Boolean(state.continuationSettlementId)
161
- || Boolean(state.resumeFromTaskId) !== Boolean(execution))
162
- return { error: 'invalid continuation correlation' };
163
- const exactContinuation = state.resumeFromTaskId && state.continuationSettlementId && execution
164
- ? { taskId: state.resumeFromTaskId, settlementId: state.continuationSettlementId, execution }
165
- : null;
166
- const priorTask = exactContinuation
167
- ? await database.getTask(exactContinuation.taskId)
168
- : state.opportunityId
169
- ? await database.getNegotiationTaskForOpportunity(state.opportunityId)
170
- : null;
171
- const claimedSuccessor = exactContinuation
172
- ? await database.getTask(exactContinuation.execution.successorTaskId)
173
- : null;
174
- if (exactContinuation) {
175
- const settlement = priorTask?.metadata?.questionSettlement;
176
- const storedExecution = claimedSuccessor?.metadata?.continuationExecution;
177
- if (!priorTask
178
- || priorTask.conversationId !== conversation.id
179
- || priorTask.state !== 'canceled'
180
- || priorTask.metadata?.opportunityId !== state.opportunityId
181
- || settlement?.settlementId !== exactContinuation.settlementId
182
- || settlement?.taskId !== exactContinuation.taskId
183
- || !claimedSuccessor
184
- || claimedSuccessor.conversationId !== conversation.id
185
- || storedExecution?.token !== exactContinuation.execution.token
186
- || storedExecution?.fence !== exactContinuation.execution.fence
187
- || storedExecution?.status !== 'claimed')
188
- return { error: 'invalid exact continuation task' };
189
- }
190
- const isLocked = !exactContinuation && !!priorTask && holdsNegotiationConversationLock(priorTask);
191
- if (isLocked) {
192
- initLog.info('Conversation locked by active task, returning busy', {
193
- conversationId: conversation.id,
194
- opportunityId: state.opportunityId,
195
- });
196
- return { error: 'busy' };
197
- }
198
- // --- Load prior messages and determine continuation ---
199
- const priorTurns = turnsFromMessages(priorMessages);
200
- const isContinuation = priorTurns.length > 0;
201
- const expectedSpeaker = expectedNegotiationSpeaker({
202
- sourceUserId: state.sourceUser.id,
203
- candidateUserId: state.candidateUser.id,
204
- }, priorMessages);
205
- if (!expectedSpeaker)
206
- return { error: 'invalid negotiation participants' };
207
- const currentSpeaker = expectedSpeaker === state.sourceUser.id
208
- ? 'source'
209
- : 'candidate';
210
- // Determine scenario-based maxTurns
211
- const scope = { action: 'manage:negotiations', scopeType: 'network', scopeId: state.indexContext.networkId };
212
- const [sourceHasAgent, candidateHasAgent] = await Promise.all([
213
- dispatcher.hasExternalAgent(state.sourceUser.id, scope),
214
- dispatcher.hasExternalAgent(state.candidateUser.id, scope),
215
- ]);
216
- const ambientMax = Number(process.env.NEGOTIATION_MAX_TURNS_AMBIENT) || 6;
217
- let maxTurns = state.maxTurns;
218
- if (maxTurns == null) {
219
- maxTurns = (sourceHasAgent && candidateHasAgent) ? 0 : ambientMax;
220
- }
221
- // --- Initiator seat resolution (v2: rigid per match, stamped at discovery) ---
222
- // 1. Continuations inherit from the prior task for the same opportunity —
223
- // never re-derive, so the seat cannot flip between sessions.
224
- // 2. Conversation-scoped tie-break: if another negotiation on this DM is
225
- // active and fresh (symmetric concurrent start under a different
226
- // opportunityId — the opportunity-scoped lock above cannot see it),
227
- // the first created task keeps the seat; this run inherits its stamp.
228
- // 3. Otherwise: explicit stamp from the caller, falling back to the
229
- // session's sourceUser (pre-stamp heuristic behavior, unchanged).
230
- const readInitiator = (metadata) => {
231
- const v = metadata?.initiatorUserId;
232
- return typeof v === 'string' && v.length > 0 ? v : null;
233
- };
234
- let initiatorUserId = readInitiator(priorTask?.metadata) ?? state.initiatorUserId ?? state.sourceUser.id;
235
- // Conversation-scoped prior task: used only for the initiator tie-break
236
- // (and only when active+fresh).
237
- const convTask = !exactContinuation && !readInitiator(priorTask?.metadata)
238
- ? await database.getLatestNegotiationTaskForConversation?.(conversation.id).catch(() => null)
239
- : null;
240
- if (!readInitiator(priorTask?.metadata)) {
241
- if (convTask && convTask.id !== priorTask?.id && holdsNegotiationConversationLock(convTask)) {
242
- const convInitiator = readInitiator(convTask.metadata);
243
- if (convInitiator) {
244
- initLog.info('Conversation-scoped tie-break: inheriting initiator seat from concurrent task', {
245
- conversationId: conversation.id,
246
- winningTaskId: convTask.id,
247
- initiatorUserId: convInitiator,
248
- });
249
- initiatorUserId = convInitiator;
250
- }
251
- }
252
- }
253
- // --- Protocol version: pinned per negotiation, re-stamped per match ---
254
- // A prior task for this same negotiation (exact continuation resume or
255
- // a re-run of the same opportunity) pins the version, so one
256
- // negotiation never flips semantics mid-flight (absent field on a
257
- // genuine prior = pre-v2 task = v1). Everything else — including
258
- // continuations of older conversations between the same pair — stamps
259
- // fresh from NEGOTIATION_PROTOCOL_VERSION, so a version cutover
260
- // reaches existing pairs on their next new match instead of being
261
- // pinned to v1 forever by conversation history.
262
- const protocolVersion = priorTask
263
- ? (readProtocolVersion(priorTask.metadata) ?? 'v1')
264
- : configuredProtocolVersion();
265
- const taskMetadata = {
266
- type: 'negotiation',
267
- sourceUserId: state.sourceUser.id,
268
- initiatorUserId,
269
- protocolVersion,
270
- candidateUserId: state.candidateUser.id,
271
- networkId: state.indexContext.networkId,
272
- sourceIntentId: state.sourceIntentId,
273
- candidateIntentId: state.candidateIntentId,
274
- participantBindings: [
275
- ...(state.sourceIntentId ? [{ userId: state.sourceUser.id, intentId: state.sourceIntentId, networkId: state.indexContext.networkId }] : []),
276
- ...(state.candidateIntentId ? [{ userId: state.candidateUser.id, intentId: state.candidateIntentId, networkId: state.indexContext.networkId }] : []),
277
- ],
278
- intentSnapshots: buildIntentSnapshots(state.sourceUser, state.candidateUser),
279
- ...(state.opportunityId && { opportunityId: state.opportunityId }),
280
- maxTurns,
281
- isContinuation,
282
- priorTurnCount: priorTurns.length,
283
- ...(exactContinuation ? {
284
- resumeFromTaskId: exactContinuation.taskId,
285
- continuationSettlementId: exactContinuation.settlementId,
286
- } : {}),
287
- };
288
- if (state.opportunityId && Boolean(state.opportunityStatus) !== Boolean(state.opportunityUpdatedAt)) {
289
- throw new Error('Negotiation attempt requires both opportunity status and updatedAt');
290
- }
291
- const task = exactContinuation
292
- ? claimedSuccessor
293
- : state.opportunityId && state.opportunityStatus && state.opportunityUpdatedAt
294
- ? await database.createNegotiationTaskForAttempt({
295
- conversationId: conversation.id,
296
- opportunityId: state.opportunityId,
297
- expectedStatus: state.opportunityStatus,
298
- expectedUpdatedAt: state.opportunityUpdatedAt,
299
- metadata: taskMetadata,
300
- })
301
- : await database.createTask(conversation.id, taskMetadata);
302
- if (!task) {
303
- throw new Error('Negotiation attempt is stale or already claimed');
304
- }
305
- // Attempt-bound discovery atomically promoted the exact persisted state
306
- // to `negotiating` while inserting the task. Legacy/direct invocations
307
- // with only an opportunity ID retain the prior best-effort status update.
308
- if (state.opportunityId && !state.opportunityUpdatedAt) {
309
- await database.updateOpportunityStatus(state.opportunityId, 'negotiating').catch((err) => {
310
- initLog.error('Failed to set opportunity status to negotiating', { opportunityId: state.opportunityId, error: err });
311
- });
312
- }
313
- // Load user answers collected by the questioner between sessions
314
- const userAnswers = (isContinuation && state.opportunityId)
315
- ? await database.getOpportunityUserAnswers(state.opportunityId).catch((err) => {
316
- initLog.error('Failed to load user answers', { opportunityId: state.opportunityId, error: err });
317
- return [];
318
- })
319
- : [];
320
- // Seed messages with prior turns (additive reducer appends new turns on top).
321
- // taskId is preserved so the turn/screen nodes can separate this
322
- // session's turns from seeded prior-task turns (IND-569).
323
- const seedMessages = isContinuation ? priorMessages.map((m) => ({
324
- id: m.id,
325
- senderId: m.senderId,
326
- role: 'agent',
327
- parts: m.parts,
328
- createdAt: m.createdAt,
329
- taskId: m.taskId ?? null,
330
- })) : [];
331
- // IND-569: attribute seeded prior turns to their originating opportunity
332
- // once, up front. Earlier-opportunity and legacy unattributed blocks are
333
- // immutable for the session; the current block is composed per turn.
334
- const priorAttribution = isContinuation
335
- ? await buildSeededAttribution(priorMessages
336
- .map((m) => ({ taskId: m.taskId ?? null, turn: turnsFromMessages([m])[0] }))
337
- .filter((e) => Boolean(e.turn)), state.opportunityId, resolveTaskAttribution)
338
- : null;
339
- return {
340
- conversationId: conversation.id,
341
- taskId: task.id,
342
- currentSpeaker,
343
- turnCount: 0,
344
- maxTurns,
345
- isContinuation,
346
- initiatorUserId,
347
- protocolVersion,
348
- priorTurnCount: priorTurns.length,
349
- ...(priorAttribution && { priorAttribution }),
350
- ...(userAnswers.length > 0 && { userAnswers }),
351
- ...(exactContinuation?.execution.consultation
352
- ? { privateConsultation: exactContinuation.execution.consultation }
353
- : {}),
354
- ...(exactContinuation && (() => {
355
- const turnContext = priorTask?.metadata?.turnContext;
356
- const reason = turnContext?.consultationPolicyReason;
357
- return typeof reason === 'string' ? { consultationPolicyReason: reason } : {};
358
- })()),
359
- ...(seedMessages.length > 0 && { messages: seedMessages }),
360
- };
361
- }
362
- catch (err) {
363
- return { error: `Init failed: ${err instanceof Error ? err.message : String(err)}` };
364
- }
365
- };
366
- /**
367
- * Screen node (P2.1) — the outreach gate. Runs between init and the first
368
- * turn on FRESH negotiations only (routing skips it on continuations and
369
- * when NEGOTIATION_SCREEN_MODE=off). The reaching client's negotiator
370
- * decides whether the match is worth its client's name; in shadow mode the
371
- * decision is recorded (task metadata + trace event + log line) but never
372
- * blocks — the negotiation always proceeds to the first turn. In enforce
373
- * mode (P2.2) a `pass` routes straight to finalize: zero turns, zero
374
- * counterparty involvement, outcome `reason: "screened_out"`, opportunity
375
- * quietly `rejected` (init had already flipped it to `negotiating`).
376
- * A failed screen still fails OPEN in every mode.
377
- */
378
- const screenNode = async (state) => {
379
- const traceEmitter = requestContext.getStore()?.traceEmitter;
380
- const emitWide = (event) => traceEmitter?.(event);
381
- const mode = configuredScreenMode();
382
- const start = Date.now();
383
- // The client is the initiator seat's user — the side whose negotiator is
384
- // reaching out. Fresh runs stamp initiatorUserId in init; fall back to
385
- // sourceUser (what the stamp defaults to anyway).
386
- const initiatorId = state.initiatorUserId ?? state.sourceUser.id;
387
- const clientIsSource = initiatorId !== state.candidateUser.id;
388
- const clientUser = clientIsSource ? state.sourceUser : state.candidateUser;
389
- const counterpartyUser = clientIsSource ? state.candidateUser : state.sourceUser;
390
- // P5.3: the client's own negotiator memory informs the outreach gate.
391
- // Cached into state so the client's first turn reuses it.
392
- const clientSide = clientIsSource ? "source" : "candidate";
393
- const clientMemory = state.memoryBySide?.[clientSide]
394
- ?? (memoryRetrieve
395
- ? await retrieveMemory(clientUser.id, counterpartyUser.id, memoryQueryText(state, counterpartyUser), "screen")
396
- : []);
397
- let decision;
398
- let failedOpen = false;
399
- let screenError;
400
- try {
401
- const counterpartyContext = (await database.getUserContext(counterpartyUser.id, null).catch(() => null))?.text ?? "";
402
- const priorDialogueAttributed = buildAttributedDialogue(state);
403
- decision = await screener.invoke({
404
- clientUser,
405
- counterpartyUser,
406
- ...(counterpartyContext && { counterpartyContext }),
407
- ...(clientMemory.length > 0 && { memory: clientMemory }),
408
- // discoveryQuery belongs to the discovery session's source user; only
409
- // meaningful for the client when the client holds the source side.
410
- ...(clientIsSource && state.discoveryQuery && { discoveryQuery: state.discoveryQuery }),
411
- seedAssessment: state.seedAssessment,
412
- indexContext: state.indexContext,
413
- isContinuation: state.isContinuation,
414
- ...(state.messages.length > 0 && { priorDialogue: turnsFromMessages(state.messages) }),
415
- ...(priorDialogueAttributed && { priorDialogueAttributed }),
416
- });
417
- }
418
- catch (err) {
419
- // Fail open: a screen failure must never block a negotiation.
420
- failedOpen = true;
421
- screenError = err instanceof Error ? err.message : String(err);
422
- screenNodeLog.warn("Screen failed; proceeding open (reach_out)", {
423
- taskId: state.taskId,
424
- opportunityId: state.opportunityId || undefined,
425
- error: screenError,
426
- });
427
- decision = {
428
- decision: "reach_out",
429
- reasoning: `screen_error: ${screenError}`,
430
- evidence: { counterpartyPremiseFit: "", intentAlignment: "" },
431
- };
432
- }
433
- const durationMs = Date.now() - start;
434
- const record = {
435
- ...decision,
436
- mode,
437
- ...(failedOpen && { failedOpen, error: screenError }),
438
- screenedAt: new Date().toISOString(),
439
- durationMs,
440
- };
441
- await database.setTaskScreenDecision?.(state.taskId, record, state.continuationExecution).catch((err) => {
442
- screenNodeLog.error("Failed to persist screen decision", { taskId: state.taskId, error: err });
443
- });
444
- screenNodeLog.info("negotiation_screen", {
445
- taskId: state.taskId,
446
- opportunityId: state.opportunityId || undefined,
447
- decision: decision.decision,
448
- mode,
449
- failedOpen,
450
- durationMs,
451
- });
452
- if (state.opportunityId) {
453
- emitWide({
454
- type: "negotiation_screen",
455
- opportunityId: state.opportunityId,
456
- negotiationConversationId: state.conversationId,
457
- decision: decision.decision,
458
- reasoning: decision.reasoning,
459
- mode,
460
- failedOpen,
461
- durationMs,
462
- });
463
- }
464
- // Routing happens on the conditional edge: shadow always proceeds to
465
- // the first turn; enforce routes a (non-failed-open) pass to finalize.
466
- return { screenDecision: record, memoryBySide: { [clientSide]: clientMemory } };
467
- };
468
- const turnNode = async (state) => {
469
- const traceEmitter = requestContext.getStore()?.traceEmitter;
470
- // Local helper to emit events whose shape is wider than the declared
471
- // `TraceEmitter` union. The chat agent already casts at its relay sink;
472
- // here we localize the cast at the callsite so the rest of the body stays typed.
473
- const emitWide = (event) => traceEmitter?.(event);
474
- const agentName = "Index negotiator";
475
- const agentStart = Date.now();
476
- traceEmitter?.({ type: "agent_start", name: agentName });
477
- try {
478
- const history = turnsFromMessages(state.messages);
479
- const isSource = state.currentSpeaker === "source";
480
- const ownUser = isSource ? state.sourceUser : state.candidateUser;
481
- const otherUser = isSource ? state.candidateUser : state.sourceUser;
482
- const ownIntentId = isSource ? state.sourceIntentId : state.candidateIntentId;
483
- // Determine if this is the system agent's final allowed turn.
484
- const isFinalTurn = isNegotiationTurnCapReached(state.turnCount + 1, state.maxTurns);
485
- // Seat attribution keys on initiatorUserId (rigid v2 stamp), never on
486
- // parity or source/candidate position — under the conversation-scoped
487
- // tie-break this run's source may hold the counterparty seat.
488
- const version = state.protocolVersion ?? 'v1';
489
- const seat = ownUser.id === (state.initiatorUserId ?? state.sourceUser.id)
490
- ? 'initiator'
491
- : 'counterparty';
492
- // Legacy ask_user availability (P3.2): flag on, full pause loop wired
493
- // (questioner + answer-window timer + an opportunity to resume
494
- // against), v2 non-final non-opening turn, and this side's one client
495
- // consultation not yet spent (rationing). Shadow is observational and
496
- // must preserve this legacy path byte-for-byte except for telemetry.
497
- const policyMode = negotiationConsultationPolicyMode();
498
- const askUserAvailable = version === 'v2'
499
- && !isFinalTurn
500
- && configuredAskUserEnabled()
501
- && !!questionerEnqueue
502
- && !!timeoutQueue?.enqueueAskUserExpiry
503
- && !!state.opportunityId
504
- && !!ownIntentId
505
- && !!state.indexContext.networkId
506
- && !(state.turnCount === 0 && !state.isContinuation)
507
- && !hasPriorAskUser(state.messages, ownUser.id);
508
- // ─── Deadlock detection → persuasion→bargaining stance (IND-428) ──────
509
- // Deterministic trailing-run inspection of the persisted history — no
510
- // LLM in the decision. Gated on the strict default-off flag AND v2,
511
- // checked alongside the protocol-version plumbing so v1 semantics stay
512
- // untouched. Fail-open: any detection error means "no deadlock" and
513
- // the legacy path proceeds byte-identically. The shift changes the
514
- // system agent's drafting stance only — allowedActions, the dispatch
515
- // payload, and all termination rules are untouched.
516
- let deadlock = null;
517
- if (version === 'v2' && configuredDeadlockShiftEnabled()) {
518
- try {
519
- deadlock = assessDeadlock(history, configuredDeadlockThreshold());
520
- }
521
- catch (err) {
522
- turnLog.warn('Deadlock detection failed; proceeding without mode shift', {
523
- taskId: state.taskId,
524
- error: err instanceof Error ? err.message : String(err),
525
- });
526
- deadlock = null;
527
- }
528
- }
529
- const bargainingMode = deadlock?.deadlocked === true;
530
- // P5.3: the speaker's own negotiator memory (cached per side across
531
- // turns). Injected into both the dispatch payload (the user's own
532
- // agent — scope-correct) and the system-agent prompt.
533
- const ownSide = isSource ? "source" : "candidate";
534
- const ownMemory = state.memoryBySide?.[ownSide]
535
- ?? (memoryRetrieve
536
- ? await retrieveMemory(ownUser.id, otherUser.id, memoryQueryText(state, otherUser), "turn")
537
- : []);
538
- const payload = {
539
- negotiationId: state.taskId,
540
- ownUser,
541
- otherUser,
542
- indexContext: state.indexContext,
543
- seedAssessment: state.seedAssessment,
544
- history,
545
- isFinalTurn,
546
- isDiscoverer: isSource,
547
- seat,
548
- protocolVersion: version,
549
- allowedActions: [...allowedActionsFor(version, seat, isFinalTurn, { askUser: askUserAvailable })],
550
- ...(state.discoveryQuery && isSource && { discoveryQuery: state.discoveryQuery }),
551
- ...(ownMemory.length > 0 && { negotiatorMemory: ownMemory }),
552
- ...(state.privateConsultation?.recipientUserId === ownUser.id
553
- ? { privateConsultation: state.privateConsultation }
554
- : {}),
555
- ...(state.continuationExecution
556
- ? {
557
- timeoutContinuation: {
558
- priorTaskId: state.continuationExecution.taskId,
559
- settlementId: state.continuationExecution.settlementId,
560
- successorTaskId: state.continuationExecution.successorTaskId,
561
- token: state.continuationExecution.token,
562
- fence: state.continuationExecution.fence,
563
- },
564
- }
565
- : {}),
566
- };
567
- const scope = { action: 'manage:negotiations', scopeType: 'network', scopeId: state.indexContext.networkId };
568
- const dispatchResult = await dispatcher.dispatch(ownUser.id, scope, payload, { timeoutMs: state.timeoutMs });
569
- let turn;
570
- if (dispatchResult.handled) {
571
- // Personal agent responded. Under v2, coerce out-of-seat actions to
572
- // the conservative fallback — the polling/respond surfaces reject
573
- // these with a 400, but locally-dispatched turns land here directly.
574
- turn = dispatchResult.turn;
575
- if (version === 'v2' && !allowedActionsFor(version, seat, isFinalTurn, { askUser: askUserAvailable }).includes(turn.action)) {
576
- turnLog.warn('Personal agent returned out-of-seat action, coercing to conservative fallback', {
577
- action: turn.action, seat, isFinalTurn,
578
- });
579
- turn = { ...turn, action: fallbackActionFor(version, seat, isFinalTurn) };
580
- }
581
- }
582
- else if (dispatchResult.reason === 'waiting') {
583
- // Long timeout — graph suspends. Persist the full turn context so the
584
- // polling agent (and MCP consumers via get_negotiation) reconstruct
585
- // the same view the in-process system agent would see. The view is
586
- // stored in absolute source/candidate terms; perspective is projected
587
- // at pickup time using the claiming user's id.
588
- traceEmitter?.({ type: "agent_end", name: agentName, durationMs: Date.now() - agentStart, summary: "waiting_for_agent" });
589
- await database.setTaskTurnContext(state.taskId, {
590
- sourceUser: state.sourceUser,
591
- candidateUser: state.candidateUser,
592
- indexContext: state.indexContext,
593
- seedAssessment: state.seedAssessment,
594
- // Keep discoveryQuery speaker-scoped: include it only when the
595
- // parked turn belongs to the discoverer (source). Persisting it on
596
- // candidate-side turns would make the pickup prompt frame the
597
- // search as "your user searched for X" for the wrong user.
598
- ...(isSource && state.discoveryQuery && { discoveryQuery: state.discoveryQuery }),
599
- ...(state.privateConsultation && state.privateConsultation.recipientUserId === ownUser.id
600
- ? { privateConsultation: state.privateConsultation }
601
- : {}),
602
- }, state.continuationExecution);
603
- await database.updateTaskState(state.taskId, "waiting_for_agent", undefined, state.continuationExecution, dispatchResult.resumeToken);
604
- return { status: 'waiting_for_agent' };
605
- }
606
- else {
607
- // No personal agent or timeout — run system agent
608
- const agentPriorDialogue = buildAttributedDialogue(state);
609
- turn = await systemAgent.invoke({
610
- ownUser,
611
- otherUser,
612
- indexContext: state.indexContext,
613
- seedAssessment: state.seedAssessment,
614
- history,
615
- isFinalTurn,
616
- isDiscoverer: isSource,
617
- seat,
618
- protocolVersion: version,
619
- ...(state.discoveryQuery && isSource && { discoveryQuery: state.discoveryQuery }),
620
- isContinuation: state.isContinuation,
621
- ...(agentPriorDialogue && { priorDialogue: agentPriorDialogue }),
622
- ...(state.userAnswers.length > 0 && { userAnswers: state.userAnswers }),
623
- ...(askUserAvailable && { canAskUser: true }),
624
- ...(bargainingMode && { bargaining: { consecutiveNonConvergent: deadlock.consecutiveNonConvergent } }),
625
- ...(ownMemory.length > 0 && { memory: ownMemory }),
626
- ...(state.privateConsultation?.recipientUserId === ownUser.id
627
- ? { privateConsultation: state.privateConsultation }
628
- : {}),
629
- });
630
- }
631
- traceEmitter?.({ type: "agent_end", name: agentName, durationMs: Date.now() - agentStart, summary: `${turn.action}` });
632
- // IND-564 / IND-611: the opening-withdraw guard runs BEFORE the turn-0
633
- // opening force below. Order matters and used to be inverted: the force
634
- // rewrote a turn-0 `withdraw` into `outreach` first, which (a) made this
635
- // guard dead code for a v2 initiator on turn 0 and (b) sent an outreach
636
- // whose surviving `reasoning` argued against the match to the
637
- // counterparty. An honest turn-0 refusal is now allowed to stand and
638
- // flows into the existing quiet `screened_out` path — no message is
639
- // persisted, so the original guard's intent (never retract a message
640
- // that was never made) is preserved rather than weakened.
641
- //
642
- // Exact ask_user resumes are exempt: the successor is the SAME logical
643
- // negotiation resumed after the client answered, so post-consultation
644
- // withdraw is legitimate.
645
- if (turn.action === 'withdraw' && !state.outreachOpened && !state.continuationExecution) {
646
- turnLog.info('negotiation_opening_withdraw_screened_out', {
647
- taskId: state.taskId,
648
- opportunityId: state.opportunityId || undefined,
649
- seat,
650
- turnCount: state.turnCount,
651
- isContinuation: state.isContinuation,
652
- });
653
- traceEmitter?.({ type: "agent_end", name: agentName, durationMs: Date.now() - agentStart, summary: "screened_out: opening withdraw" });
654
- return { lastTurn: turn, firstTurnScreenedOut: true };
655
- }
656
- // First turn must open the negotiation (unless continuing a prior
657
- // conversation): v1 → "propose"; v2 initiator → "outreach". A v2 turn-0
658
- // speaker holding the counterparty seat (tie-break inheritance) is left
659
- // unforced — it is responding, not opening.
660
- //
661
- // A legitimate turn-0 refusal never reaches here: the opening-withdraw
662
- // guard above already returned. What remains are genuinely malformed
663
- // openings (a turn-0 `counter`/`question`), which are still coerced.
664
- if (state.turnCount === 0 && !state.isContinuation) {
665
- const openingAction = version === 'v2' ? 'outreach' : 'propose';
666
- if ((version !== 'v2' || seat === 'initiator') && turn.action !== openingAction) {
667
- turnLog.warn(`Agent returned unexpected action on turn 0, forcing to ${openingAction}`, { action: turn.action });
668
- turn.action = openingAction;
669
- }
670
- }
671
- // IND-508 deterministic admission is evaluated only after the opening
672
- // guard but before any turn is persisted. It consumes action/role enums
673
- // only; free-form reasoning, messages, profiles, and evaluator inputs
674
- // are intentionally unavailable to the policy.
675
- let consultationPolicyReason;
676
- const policyEligibility = policyMode === 'off' ? { eligible: false } : assessConsultationEligibility({
677
- protocolVersion: version,
678
- seat,
679
- isOpeningTurn: state.turnCount === 0 && !state.isContinuation,
680
- isFinalTurn,
681
- screenedOut: blocksNegotiationBeforeFirstTurn(state.screenDecision, state.turnCount),
682
- action: turn.action,
683
- ownSuggestedRole: turn.assessment?.suggestedRoles?.ownUser,
684
- priorActions: history.map((prior) => prior.action),
685
- previouslyConsulted: hasPriorAskUser(state.messages, ownUser.id),
686
- hasExactResumeCoordinate: Boolean(configuredAskUserEnabled()
687
- && questionerEnqueue
688
- && timeoutQueue?.enqueueAskUserExpiry
689
- && state.taskId
690
- && state.opportunityId
691
- && ownIntentId
692
- && state.indexContext.networkId),
693
- lifecycleValid: Boolean(state.taskId && state.opportunityId && ownIntentId && state.indexContext.networkId),
694
- });
695
- const emitConsultationTelemetry = (stage, reason) => {
696
- turnLog.info('negotiation_consultation_policy', { stage, mode: policyMode, reason });
697
- emitWide({ type: 'negotiation_consultation_policy', stage, mode: policyMode, reason });
698
- };
699
- if (policyEligibility.eligible && policyEligibility.reason) {
700
- emitConsultationTelemetry('eligible', policyEligibility.reason);
701
- if (policyMode === 'on') {
702
- consultationPolicyReason = policyEligibility.reason;
703
- turn = {
704
- ...turn,
705
- action: 'ask_user',
706
- message: null,
707
- assessment: {
708
- reasoning: 'Client consultation required.',
709
- suggestedRoles: turn.assessment.suggestedRoles,
710
- },
711
- askUser: { reason: consultationPolicyReason },
712
- };
713
- emitConsultationTelemetry('asked', consultationPolicyReason);
714
- }
715
- }
716
- // Safety net: off/shadow retain legacy behavior. In on, a spontaneous
717
- // ask_user is admissible only when the deterministic policy just
718
- // authorized it, so no unbounded pause can enter shared history.
719
- if (turn.action === 'ask_user' && (!askUserAvailable || (policyMode === 'on' && !consultationPolicyReason))) {
720
- turnLog.warn('ask_user emitted while unavailable, coercing to conservative fallback', {
721
- seat, isFinalTurn, taskId: state.taskId,
722
- });
723
- turn = { ...turn, action: fallbackActionFor(version, seat, isFinalTurn) };
724
- }
725
- // ─── Deadlock shift record (IND-428) ───────────────────────────────
726
- // Applied-stance analytics: recorded once per session, on the first
727
- // turn actually drafted in the bargaining stance (the system agent —
728
- // externally dispatched turns never receive the stance). Internal
729
- // metadata only: persisted to tasks.metadata.deadlockShift via the
730
- // optional hook; negotiation API surfaces project specific fields and
731
- // never return task metadata verbatim. Every step fails open.
732
- const bargainingApplied = bargainingMode && !dispatchResult.handled;
733
- let deadlockShiftRecord = null;
734
- if (bargainingApplied && !state.deadlockShift) {
735
- deadlockShiftRecord = {
736
- reason: 'consecutive_non_convergent',
737
- consecutiveNonConvergent: deadlock.consecutiveNonConvergent,
738
- threshold: deadlock.threshold,
739
- shiftedAtTurn: state.turnCount,
740
- seat,
741
- detectedAt: new Date().toISOString(),
742
- };
743
- await database.setTaskDeadlockShift?.(state.taskId, deadlockShiftRecord, state.continuationExecution).catch((err) => {
744
- turnLog.error('Failed to persist deadlock shift record', { taskId: state.taskId, error: err });
745
- });
746
- turnLog.info('negotiation_deadlock_shift', {
747
- taskId: state.taskId,
748
- opportunityId: state.opportunityId || undefined,
749
- seat,
750
- consecutiveNonConvergent: deadlockShiftRecord.consecutiveNonConvergent,
751
- threshold: deadlockShiftRecord.threshold,
752
- turnIndex: state.turnCount,
753
- });
754
- if (state.opportunityId) {
755
- emitWide({
756
- type: 'negotiation_deadlock_shift',
757
- opportunityId: state.opportunityId,
758
- negotiationConversationId: state.conversationId,
759
- turnIndex: state.turnCount,
760
- actor: isSource ? 'source' : 'candidate',
761
- consecutiveNonConvergent: deadlockShiftRecord.consecutiveNonConvergent,
762
- threshold: deadlockShiftRecord.threshold,
763
- });
764
- }
765
- }
766
- const parts = [{ kind: "data", data: turn }];
767
- const message = await database.createMessage({
768
- conversationId: state.conversationId,
769
- senderId: `agent:${ownUser.id}`,
770
- role: "agent",
771
- parts,
772
- taskId: state.taskId,
773
- ...(state.continuationExecution ? { continuationExecution: state.continuationExecution } : {}),
774
- });
775
- // ─── ask_user pause (P3.2) ────────────────────────────────────────────
776
- // The negotiator consults its OWN client: persist the turn (done above),
777
- // park the full turn context, arm the answer-window timer, enqueue the
778
- // question through the negotiation_inflight preset, then suspend the
779
- // task as input_required. The graph exits at this turn boundary exactly
780
- // like the waiting_for_agent suspend; the answer (or window expiry)
781
- // resumes via the run-existing continuation path.
782
- if (turn.action === 'ask_user') {
783
- const consultationReason = turn.askUser?.reason;
784
- const safeAskUser = consultationReason
785
- ? consultationPromptFor(consultationReason)
786
- : null;
787
- const settlementId = negotiationQuestionSettlementId(state.taskId);
788
- const askUserBinding = await database.captureNegotiationAskUserBinding({
789
- taskId: state.taskId,
790
- settlementId,
791
- recipientUserId: ownUser.id,
792
- recipientIntentId: ownIntentId,
793
- opportunityId: state.opportunityId,
794
- networkId: state.indexContext.networkId,
795
- turnContext: {
796
- sourceUser: state.sourceUser,
797
- candidateUser: state.candidateUser,
798
- indexContext: state.indexContext,
799
- seedAssessment: state.seedAssessment,
800
- ...(isSource && state.discoveryQuery && { discoveryQuery: state.discoveryQuery }),
801
- ...(consultationReason && { consultationPolicyReason: consultationReason }),
802
- },
803
- ...(state.continuationExecution ? { continuationExecution: state.continuationExecution } : {}),
804
- });
805
- // Arm the timer BEFORE flipping state: it is the durable recovery
806
- // trigger even when generation enqueues no job or persists no row.
807
- const windowMs = askUserAnswerWindowMs();
808
- await timeoutQueue.enqueueAskUserExpiry(state.taskId, {
809
- settlementId,
810
- opportunityId: state.opportunityId,
811
- userId: ownUser.id,
812
- recipientIntentId: ownIntentId,
813
- networkId: state.indexContext.networkId,
814
- intentFingerprint: askUserBinding.intentFingerprint,
815
- opportunityStatus: askUserBinding.opportunityStatus,
816
- opportunityUpdatedAt: askUserBinding.opportunityUpdatedAt,
817
- counterpartyUserId: askUserBinding.counterpartyUserId,
818
- counterpartyIntentId: askUserBinding.counterpartyIntentId,
819
- }, windowMs);
820
- // Persistence admission requires the exact task to be input_required.
821
- // Flip before enqueue; if the structured ask_user fields fail the
822
- // deterministic privacy gate, the timer alone closes the exact task.
823
- await database.updateTaskState(state.taskId, 'input_required', undefined, state.continuationExecution);
824
- if (safeAskUser) {
825
- const userContext = (await database.getUserContext(ownUser.id, null).catch(() => null))?.text ?? '';
826
- await questionerEnqueue({
827
- mode: 'negotiation_inflight',
828
- purpose: 'inflight_consultation',
829
- userId: ownUser.id,
830
- sourceType: 'opportunity',
831
- sourceId: state.opportunityId,
832
- negotiation: {
833
- purpose: 'inflight_consultation',
834
- recipientUserId: ownUser.id,
835
- recipientIntentId: ownIntentId,
836
- opportunityId: state.opportunityId,
837
- taskId: state.taskId,
838
- networkId: state.indexContext.networkId,
839
- },
840
- context: {
841
- negotiationId: state.taskId,
842
- counterpartyHint: NEGOTIATION_QUESTION_GENERIC_COUNTERPARTY,
843
- indexContext: NEGOTIATION_QUESTION_GENERIC_NETWORK,
844
- consultationPolicyReason: consultationReason,
845
- ...(userContext && { userContext }),
846
- },
847
- }).catch((error) => {
848
- turnLog.error('Failed to enqueue safe ask_user question; timeout recovery remains armed', {
849
- taskId: state.taskId,
850
- opportunityId: state.opportunityId,
851
- error,
852
- });
853
- });
854
- }
855
- else {
856
- turnLog.warn('Skipping unsafe or incomplete ask_user question generation', {
857
- taskId: state.taskId,
858
- opportunityId: state.opportunityId,
859
- });
860
- }
861
- turnLog.info('negotiation_ask_user_pause', {
862
- taskId: state.taskId,
863
- opportunityId: state.opportunityId,
864
- seat,
865
- askingUserId: ownUser.id,
866
- windowMs,
867
- });
868
- traceEmitter?.({ type: "agent_end", name: agentName, durationMs: Date.now() - agentStart, summary: "ask_user" });
869
- emitWide({
870
- type: 'negotiation_ask_user',
871
- opportunityId: state.opportunityId,
872
- negotiationConversationId: state.conversationId,
873
- turnIndex: state.turnCount,
874
- actor: isSource ? 'source' : 'candidate',
875
- questionGenerationSafe: Boolean(safeAskUser),
876
- windowMs,
877
- });
878
- return {
879
- messages: [{
880
- id: message.id,
881
- senderId: message.senderId,
882
- role: "agent",
883
- parts: message.parts,
884
- createdAt: message.createdAt,
885
- }],
886
- turnCount: state.turnCount + 1,
887
- lastTurn: turn,
888
- status: 'input_required',
889
- ...(deadlockShiftRecord && { deadlockShift: deadlockShiftRecord }),
890
- };
891
- }
892
- await database.updateTaskState(state.taskId, "working", undefined, state.continuationExecution);
893
- if (state.opportunityId) {
894
- emitWide({
895
- type: "negotiation_turn",
896
- opportunityId: state.opportunityId,
897
- negotiationConversationId: state.conversationId,
898
- turnIndex: state.turnCount,
899
- actor: isSource ? "source" : "candidate",
900
- action: turn.action,
901
- ...(turn.assessment?.reasoning && { reasoning: turn.assessment.reasoning }),
902
- ...(turn.message && { message: turn.message }),
903
- ...(turn.assessment?.suggestedRoles && { suggestedRoles: turn.assessment.suggestedRoles }),
904
- durationMs: Date.now() - agentStart,
905
- });
906
- }
907
- return {
908
- messages: [{
909
- id: message.id,
910
- senderId: message.senderId,
911
- role: "agent",
912
- parts: message.parts,
913
- createdAt: message.createdAt,
914
- }],
915
- turnCount: state.turnCount + 1,
916
- currentSpeaker: (isSource ? "candidate" : "source"),
917
- lastTurn: turn,
918
- memoryBySide: { [ownSide]: ownMemory },
919
- // Record the in-task outreach so a later `withdraw` is legal (IND-564).
920
- ...(turn.action === 'outreach' && { outreachOpened: true }),
921
- ...(deadlockShiftRecord && { deadlockShift: deadlockShiftRecord }),
922
- };
923
- }
924
- catch (err) {
925
- const errMsg = err instanceof Error ? err.message : String(err);
926
- turnLog.error("Agent invocation failed", { error: errMsg, stack: err instanceof Error ? err.stack : undefined, turnCount: state.turnCount });
927
- traceEmitter?.({ type: "agent_end", name: agentName, durationMs: Date.now() - agentStart, summary: `error: ${errMsg}` });
928
- const errorSeat = (state.currentSpeaker === 'source' ? state.sourceUser.id : state.candidateUser.id) === (state.initiatorUserId ?? state.sourceUser.id)
929
- ? 'initiator'
930
- : 'counterparty';
931
- return {
932
- lastTurn: {
933
- action: rejectActionFor(state.protocolVersion ?? 'v1', errorSeat),
934
- assessment: { reasoning: `Agent error: ${errMsg}`, suggestedRoles: { ownUser: "peer", otherUser: "peer" } },
935
- },
936
- turnCount: state.turnCount + 1,
937
- error: `Turn failed: ${errMsg}`,
938
- };
939
- }
940
- };
941
- const evaluateNode = (state) => {
942
- if (state.status === 'waiting_for_agent')
943
- return "finalize";
944
- if (state.status === 'input_required')
945
- return "finalize";
946
- if (state.error)
947
- return "finalize";
948
- if (!state.lastTurn)
949
- return "finalize";
950
- // Terminal actions: accept (v1+v2), reject (v1), withdraw/decline (v2)
951
- if (isTerminalAction(state.lastTurn.action))
952
- return "finalize";
953
- // question routes same as counter — next turn
954
- if (isNegotiationTurnCapReached(state.turnCount, state.maxTurns))
955
- return "finalize";
956
- return "turn";
957
- };
958
- const finalizeNode = async (state) => {
959
- const traceEmitter = requestContext.getStore()?.traceEmitter;
960
- const emitWide = (event) => traceEmitter?.(event);
961
- const pauseReceipt = (outcome) => state.continuationExecution
962
- ? {
963
- continuationReceipt: {
964
- priorTaskId: state.continuationExecution.taskId,
965
- settlementId: state.continuationExecution.settlementId,
966
- successorTaskId: state.continuationExecution.successorTaskId,
967
- fence: state.continuationExecution.fence,
968
- outcome,
969
- },
970
- }
971
- : undefined;
972
- if (state.status === 'waiting_for_agent') {
973
- if (state.opportunityId) {
974
- emitWide({
975
- type: "negotiation_outcome",
976
- opportunityId: state.opportunityId,
977
- outcome: "waiting_for_agent",
978
- turnCount: state.turnCount,
979
- isContinuation: state.isContinuation,
980
- });
981
- }
982
- return pauseReceipt('waiting_for_agent') ?? {};
983
- }
984
- // ask_user pause: no outcome, no completed state — the task stays
985
- // input_required until the client answers or the window expires.
986
- if (state.status === 'input_required') {
987
- if (state.opportunityId) {
988
- emitWide({
989
- type: "negotiation_outcome",
990
- opportunityId: state.opportunityId,
991
- outcome: "input_required",
992
- turnCount: state.turnCount,
993
- isContinuation: state.isContinuation,
994
- });
995
- }
996
- return pauseReceipt('input_required') ?? {};
997
- }
998
- // Init can fail closed before an attempt owns a task. Such a rejection is
999
- // not a completed negotiation and must not write through an empty task ID,
1000
- // create an artifact, or advance the opportunity lifecycle.
1001
- if (!state.taskId) {
1002
- finalizeLog.info('Skipping outcome persistence because no negotiation task was claimed', {
1003
- opportunityId: state.opportunityId || undefined,
1004
- error: state.error || undefined,
1005
- });
1006
- return {};
1007
- }
1008
- const history = turnsFromMessages(state.messages);
1009
- const lastTurn = state.lastTurn;
1010
- const hasOpportunity = lastTurn?.action === "accept";
1011
- // P2.2: the client's own outreach gate declined before any turn — the
1012
- // negotiation never happened from the counterparty's perspective.
1013
- // IND-564: an opening-move `withdraw` blocked before any message was
1014
- // persisted is the same quiet screen-out outcome (no in-task outreach to
1015
- // retract), reached from the turn node rather than the screen node.
1016
- // Two DISTINCT routes reach the same quiet `screened_out` outcome, and
1017
- // they disagree about who authored the decision:
1018
- // - the screen node blocked before any turn was drafted → the screen
1019
- // decision is the reason;
1020
- // - the acting agent refused on its opening turn (IND-611) → the
1021
- // withdrawing TURN is the reason.
1022
- // They are collapsed into `screenedOut` for status/lifecycle purposes but
1023
- // must stay separate when attributing `outcome.reasoning` below.
1024
- const blockedByScreenNode = blocksNegotiationBeforeFirstTurn(state.screenDecision, state.turnCount);
1025
- const refusedAtOpeningTurn = state.firstTurnScreenedOut === true;
1026
- const screenedOut = blockedByScreenNode || refusedAtOpeningTurn;
1027
- const atCap = !screenedOut && isNegotiationTurnCapReached(state.turnCount, state.maxTurns) && !isTerminalAction(lastTurn?.action);
1028
- let agreedRoles = [];
1029
- if (hasOpportunity && history.length >= 2) {
1030
- const acceptTurn = history[history.length - 1];
1031
- const precedingTurn = history[history.length - 2];
1032
- const accepterIsSource = state.currentSpeaker === "candidate";
1033
- const [sourceRole, candidateRole] = accepterIsSource
1034
- ? [acceptTurn.assessment.suggestedRoles.ownUser, precedingTurn.assessment.suggestedRoles.ownUser]
1035
- : [precedingTurn.assessment.suggestedRoles.ownUser, acceptTurn.assessment.suggestedRoles.ownUser];
1036
- agreedRoles = [
1037
- { userId: state.sourceUser.id, role: sourceRole },
1038
- { userId: state.candidateUser.id, role: candidateRole },
1039
- ];
1040
- }
1041
- const outcome = {
1042
- hasOpportunity,
1043
- agreedRoles,
1044
- // IND-611: attribute the reasoning to whoever actually made the
1045
- // decision. Before the turn-0 refusal path existed, `screenedOut`
1046
- // implied the screen node, so preferring `screenDecision.reasoning`
1047
- // was always right. It is now wrong for an opening-turn refusal taken
1048
- // while the screen said `reach_out`: that record argues FOR the match,
1049
- // and surfacing it as the reason the agent did NOT reach out is exactly
1050
- // the dishonesty this work removes (IND-610 renders this string in the
1051
- // owner-only gate-decision card). The screen-node branch is unchanged.
1052
- reasoning: blockedByScreenNode
1053
- ? (state.screenDecision?.reasoning ?? lastTurn?.assessment?.reasoning ?? "")
1054
- : refusedAtOpeningTurn
1055
- ? (lastTurn?.assessment?.reasoning ?? state.screenDecision?.reasoning ?? "")
1056
- : (lastTurn?.assessment.reasoning ?? ""),
1057
- turnCount: state.turnCount,
1058
- ...(screenedOut
1059
- ? { reason: "screened_out" }
1060
- : atCap
1061
- ? { reason: "turn_cap" }
1062
- : {}),
1063
- };
1064
- try {
1065
- await database.updateTaskState(state.taskId, "completed", undefined, state.continuationExecution);
1066
- await database.createArtifact({
1067
- taskId: state.taskId,
1068
- name: "negotiation-outcome",
1069
- parts: [{ kind: "data", data: outcome }],
1070
- metadata: {
1071
- hasOpportunity,
1072
- turnCount: state.turnCount,
1073
- ...(state.continuationExecution ? {
1074
- continuationOutcome: hasOpportunity
1075
- ? 'accepted'
1076
- : (screenedOut || isRejectLikeAction(lastTurn?.action)) ? 'rejected' : 'stalled',
1077
- } : {}),
1078
- },
1079
- ...(state.continuationExecution ? { continuationExecution: state.continuationExecution } : {}),
1080
- });
1081
- finalizeLog.info('Session complete', {
1082
- conversationId: state.conversationId,
1083
- taskId: state.taskId,
1084
- isContinuation: state.isContinuation,
1085
- turnsAdded: state.turnCount,
1086
- priorTurnCount: state.priorTurnCount,
1087
- outcome: hasOpportunity ? 'accepted' : screenedOut ? 'screened_out' : (atCap ? 'turn_cap' : (lastTurn?.action ?? 'unknown')),
1088
- opportunityId: state.opportunityId || undefined,
1089
- });
1090
- if (state.opportunityId) {
1091
- // screened_out → 'rejected': quiet terminal status (hidden from
1092
- // default lists), never 'stalled' — with zero turns the generic
1093
- // mapping would misfile the client's own gate decision.
1094
- const nextStatus = lastTurn?.action === 'accept'
1095
- ? 'pending'
1096
- : (screenedOut || isRejectLikeAction(lastTurn?.action))
1097
- ? 'rejected'
1098
- : 'stalled';
1099
- await database.updateOpportunityStatus(state.opportunityId, nextStatus, undefined, state.continuationExecution).catch((err) => {
1100
- finalizeLog.error("Failed to update opportunity status", { opportunityId: state.opportunityId, nextStatus, error: err });
1101
- });
1102
- }
1103
- }
1104
- catch (err) {
1105
- finalizeLog.error("Failed to persist outcome", { error: err });
1106
- }
1107
- if (state.opportunityId) {
1108
- const emittedOutcome = hasOpportunity
1109
- ? "accepted"
1110
- : screenedOut
1111
- ? "screened_out"
1112
- : atCap
1113
- ? "turn_cap"
1114
- : state.error && /timeout/i.test(state.error)
1115
- ? "timed_out"
1116
- : "rejected_stalled";
1117
- emitWide({
1118
- type: "negotiation_outcome",
1119
- opportunityId: state.opportunityId,
1120
- outcome: emittedOutcome,
1121
- turnCount: state.turnCount,
1122
- isContinuation: state.isContinuation,
1123
- turnsAdded: state.turnCount,
1124
- priorTurnCount: state.priorTurnCount,
1125
- ...(outcome.reasoning && { reasoning: outcome.reasoning }),
1126
- ...(hasOpportunity && agreedRoles.length >= 2 && {
1127
- agreedRoles: {
1128
- ownUser: agreedRoles[0]?.role,
1129
- otherUser: agreedRoles[1]?.role,
1130
- },
1131
- }),
1132
- });
1133
- }
1134
- if (state.consultationPolicyReason) {
1135
- // Stable, content-free terminal funnel telemetry. This executes only
1136
- // after a fenced continuation has reached its terminal outcome.
1137
- finalizeLog.info('negotiation_consultation_policy', {
1138
- stage: 'terminal_outcome',
1139
- reason: state.consultationPolicyReason,
1140
- outcome: hasOpportunity ? 'accepted' : (screenedOut || isRejectLikeAction(lastTurn?.action)) ? 'rejected' : 'stalled',
1141
- });
1142
- emitWide({
1143
- type: 'negotiation_consultation_policy',
1144
- stage: 'terminal_outcome',
1145
- reason: state.consultationPolicyReason,
1146
- outcome: hasOpportunity ? 'accepted' : (screenedOut || isRejectLikeAction(lastTurn?.action)) ? 'rejected' : 'stalled',
1147
- });
1148
- }
1149
- // Enqueue post-negotiation reflection (P5.2 memory write path) — fire
1150
- // and forget: a reflection failure must never affect the outcome. Only
1151
- // sessions that actually exchanged turns teach anything; init/turn
1152
- // errors with turnCount 0 are skipped.
1153
- if (reflectEnqueue && state.turnCount > 0 && !state.continuationExecution) {
1154
- reflectEnqueue({
1155
- negotiationId: state.taskId,
1156
- conversationId: state.conversationId,
1157
- ...(state.opportunityId && { opportunityId: state.opportunityId }),
1158
- sourceUser: {
1159
- id: state.sourceUser.id,
1160
- ...(state.sourceUser.profile.name && { name: state.sourceUser.profile.name }),
1161
- ...(state.sourceUser.profile.bio && { bio: state.sourceUser.profile.bio }),
1162
- },
1163
- candidateUser: {
1164
- id: state.candidateUser.id,
1165
- ...(state.candidateUser.profile.name && { name: state.candidateUser.profile.name }),
1166
- ...(state.candidateUser.profile.bio && { bio: state.candidateUser.profile.bio }),
1167
- },
1168
- initiatorUserId: state.initiatorUserId ?? state.sourceUser.id,
1169
- outcome: { hasOpportunity, reasoning: outcome.reasoning, turnCount: state.turnCount },
1170
- }).catch((err) => finalizeLog.error('Failed to enqueue negotiation reflection', {
1171
- taskId: state.taskId,
1172
- error: err,
1173
- }));
1174
- }
1175
- // Enqueue question generation for stalled/capped negotiations (not accepted or explicitly rejected).
1176
- // Require turnCount > 0 so early init/turn errors don't enqueue with empty context.
1177
- if (!hasOpportunity && !isRejectLikeAction(lastTurn?.action) && state.turnCount > 0 && state.opportunityId && state.sourceIntentId && state.indexContext.networkId && questionerEnqueue && !state.continuationExecution) {
1178
- const stallReason = atCap
1179
- ? 'turn_cap'
1180
- : (state.error && /timeout/i.test(state.error))
1181
- ? 'timeout'
1182
- : 'stalled';
1183
- const userContext = (await database.getUserContext(state.sourceUser.id, null))?.text ?? '';
1184
- const sourceIntent = state.sourceUser.intents.find((intent) => intent.id === state.sourceIntentId);
1185
- questionerEnqueue({
1186
- mode: 'negotiation',
1187
- purpose: 'stalled_followup',
1188
- userId: state.sourceUser.id,
1189
- sourceType: 'opportunity',
1190
- sourceId: state.opportunityId,
1191
- negotiation: {
1192
- purpose: 'stalled_followup',
1193
- recipientUserId: state.sourceUser.id,
1194
- recipientIntentId: state.sourceIntentId,
1195
- opportunityId: state.opportunityId,
1196
- taskId: state.taskId,
1197
- networkId: state.indexContext.networkId,
1198
- },
1199
- context: {
1200
- negotiationId: state.taskId,
1201
- counterpartyHint: NEGOTIATION_QUESTION_GENERIC_COUNTERPARTY,
1202
- indexContext: NEGOTIATION_QUESTION_GENERIC_NETWORK,
1203
- outcomeReason: stallReason,
1204
- recipientIntent: sourceIntent
1205
- ? `${sourceIntent.title}: ${sourceIntent.description}`
1206
- : 'the signal attached to this match',
1207
- userContext,
1208
- },
1209
- }).catch((err) => finalizeLog.error('Failed to enqueue negotiation question generation', {
1210
- opportunityId: state.opportunityId,
1211
- error: err,
1212
- }));
1213
- }
1214
- const terminalReceipt = state.continuationExecution
1215
- ? {
1216
- continuationReceipt: {
1217
- priorTaskId: state.continuationExecution.taskId,
1218
- settlementId: state.continuationExecution.settlementId,
1219
- successorTaskId: state.continuationExecution.successorTaskId,
1220
- fence: state.continuationExecution.fence,
1221
- outcome: hasOpportunity
1222
- ? 'accepted'
1223
- : (screenedOut || isRejectLikeAction(lastTurn?.action)) ? 'rejected' : 'stalled',
1224
- },
1225
- }
1226
- : undefined;
1227
- return { outcome, status: 'completed', ...terminalReceipt };
1228
- };
1229
- const workflow = new StateGraph(NegotiationGraphState)
1230
- .addNode("init", initNode)
1231
- .addNode("screen", screenNode)
1232
- .addNode("turn", turnNode)
1233
- .addNode("finalize", finalizeNode)
1234
- .addConditionalEdges("turn", evaluateNode, {
38
+ const deps = this.deps;
39
+ return new StateGraph(NegotiationGraphState)
40
+ .addNode("init", (state) => initNode(state, deps))
41
+ .addNode("screen", (state) => screenNode(state, deps))
42
+ .addNode("turn", (state) => turnNode(state, deps))
43
+ .addNode("finalize", (state) => finalizeNode(state, deps))
44
+ .addConditionalEdges("turn", routeAfterTurn, {
1235
45
  turn: "turn",
1236
46
  finalize: "finalize",
1237
47
  })
1238
- .addConditionalEdges("init", (state) => {
1239
- if (state.error)
1240
- return "finalize";
1241
- // Screen gate: fresh negotiations only (continuations already passed
1242
- // the gate when the dialogue opened); off disables the node entirely.
1243
- // IND-563: regular continuations (new opportunity, existing dm_pair)
1244
- // also run through the screen gate so stale matches are caught before
1245
- // re-engaging the counterparty. Exact ask_user resumes
1246
- // (continuationExecution) are mid-flight and must never be re-screened.
1247
- if (configuredScreenMode() !== "off" && !state.continuationExecution)
1248
- return "screen";
1249
- return "turn";
1250
- }, { screen: "screen", turn: "turn", finalize: "finalize" })
48
+ .addConditionalEdges("init", routeAfterInit, { screen: "screen", turn: "turn", finalize: "finalize" })
1251
49
  // P2.2: enforce-mode pass → finalize (screened_out); everything else → turn.
1252
- .addConditionalEdges("screen", (state) => blocksNegotiationBeforeFirstTurn(state.screenDecision, state.turnCount) ? "finalize" : "turn", { turn: "turn", finalize: "finalize" })
50
+ .addConditionalEdges("screen", routeAfterScreen, { turn: "turn", finalize: "finalize" })
1253
51
  .addEdge("__start__", "init")
1254
- .addEdge("finalize", "__end__");
1255
- return workflow.compile();
52
+ .addEdge("finalize", "__end__")
53
+ .compile();
1256
54
  }
1257
55
  }
1258
- /**
1259
- * Runs bilateral negotiation for each candidate in parallel.
1260
- * @returns Only candidates that produced an opportunity
1261
- */
1262
- export async function negotiateCandidates(negotiationGraph, sourceUser, candidates, indexContext, opts) {
1263
- const { maxTurns, traceEmitter, indexContextOverrides, timeoutMs, onCandidateResolved, initiatorUserId, resumeFromTaskId, continuationSettlementId, continuationExecution, } = opts ?? {};
1264
- // Local helper to emit events whose shape is wider than the declared
1265
- // `TraceEmitter` union (mirrors the cast used in chat.agent at the relay sink
1266
- // and inside turn/finalize nodes above).
1267
- const emitWide = (event) => traceEmitter?.(event);
1268
- const results = await Promise.all(candidates.map(async (candidate) => {
1269
- const start = Date.now();
1270
- const candidateSourceUser = candidate.sourceUser ?? sourceUser;
1271
- if (candidate.opportunityId) {
1272
- const candidateName = candidate.candidateUser?.profile?.name;
1273
- emitWide({
1274
- type: "negotiation_session_start",
1275
- opportunityId: candidate.opportunityId,
1276
- negotiationConversationId: "", // filled in on session_end
1277
- sourceUserId: candidateSourceUser.id,
1278
- candidateUserId: candidate.userId,
1279
- initiatorUserId: initiatorUserId ?? candidateSourceUser.id,
1280
- ...(candidateName && { candidateName }),
1281
- startedAt: start,
1282
- });
1283
- }
1284
- traceEmitter?.({ type: "agent_start", name: "Negotiating candidate" });
1285
- try {
1286
- const candidateIndexContext = candidate.networkId
1287
- ? { networkId: candidate.networkId, prompt: indexContextOverrides?.get(candidate.networkId) ?? '' }
1288
- : indexContext;
1289
- const result = await invokeWithAbortSignal(negotiationGraph, {
1290
- sourceUser: candidateSourceUser,
1291
- candidateUser: candidate.candidateUser,
1292
- ...(candidate.sourceIntentId && { sourceIntentId: candidate.sourceIntentId }),
1293
- ...(candidate.candidateIntentId && { candidateIntentId: candidate.candidateIntentId }),
1294
- indexContext: candidateIndexContext,
1295
- seedAssessment: {
1296
- reasoning: candidate.reasoning,
1297
- valencyRole: candidate.valencyRole,
1298
- },
1299
- ...(candidate.discoveryQuery && { discoveryQuery: candidate.discoveryQuery }),
1300
- ...(candidate.opportunityId && { opportunityId: candidate.opportunityId }),
1301
- ...(candidate.opportunityStatus && { opportunityStatus: candidate.opportunityStatus }),
1302
- ...(candidate.opportunityUpdatedAt && { opportunityUpdatedAt: candidate.opportunityUpdatedAt }),
1303
- ...(initiatorUserId && { initiatorUserId }),
1304
- ...(resumeFromTaskId && continuationSettlementId && continuationExecution ? {
1305
- resumeFromTaskId,
1306
- continuationSettlementId,
1307
- continuationExecution,
1308
- } : {}),
1309
- ...(maxTurns !== undefined && { maxTurns }),
1310
- ...(timeoutMs !== undefined && { timeoutMs }),
1311
- });
1312
- const durationMs = Date.now() - start;
1313
- const outcome = result.outcome;
1314
- const hasOpportunity = outcome?.hasOpportunity === true;
1315
- const isContinuation = result.isContinuation ?? false;
1316
- const priorTurnCount = result.priorTurnCount ?? 0;
1317
- const turnFlow = (result.messages ?? [])
1318
- .map((m) => {
1319
- const dataPart = m.parts?.find((p) => p.kind === "data");
1320
- if (!dataPart?.data)
1321
- return null;
1322
- const turn = dataPart.data;
1323
- return turn.action ?? "unknown";
1324
- })
1325
- .filter(Boolean)
1326
- .join(" → ");
1327
- const statusTag = hasOpportunity ? "✓ opportunity" : "✗ rejected";
1328
- traceEmitter?.({ type: "agent_end", name: "Negotiating candidate", durationMs, summary: `${candidate.userId}: ${turnFlow} ${statusTag}` });
1329
- if (candidate.opportunityId) {
1330
- emitWide({
1331
- type: "negotiation_session_end",
1332
- opportunityId: candidate.opportunityId,
1333
- negotiationConversationId: result.conversationId ?? "",
1334
- durationMs: Date.now() - start,
1335
- isContinuation,
1336
- turnsAdded: outcome?.turnCount ?? 0,
1337
- priorTurnCount,
1338
- });
1339
- }
1340
- const accepted = hasOpportunity && outcome
1341
- ? {
1342
- userId: candidate.userId,
1343
- agreedRoles: outcome.agreedRoles,
1344
- reasoning: outcome.reasoning,
1345
- turnCount: outcome.turnCount,
1346
- }
1347
- : null;
1348
- if (onCandidateResolved) {
1349
- const turnHistory = turnsFromMessages(result.messages ?? []);
1350
- const resolvedOutcome = result.outcome ?? {
1351
- hasOpportunity: false,
1352
- agreedRoles: [],
1353
- reasoning: "no outcome returned by negotiation graph",
1354
- turnCount: turnHistory.length,
1355
- };
1356
- try {
1357
- await onCandidateResolved({
1358
- candidate,
1359
- accepted,
1360
- turns: turnHistory,
1361
- outcome: resolvedOutcome,
1362
- ...(result.continuationReceipt ? { continuationReceipt: result.continuationReceipt } : {}),
1363
- });
1364
- }
1365
- catch (hookErr) {
1366
- // Hook failures must not sink the candidate result — the aggregate
1367
- // return remains useful to the caller.
1368
- negotiateCandidatesLog.error("onCandidateResolved hook threw", {
1369
- candidateUserId: candidate.userId,
1370
- error: hookErr,
1371
- });
1372
- }
1373
- }
1374
- return accepted;
1375
- }
1376
- catch (err) {
1377
- const durationMs = Date.now() - start;
1378
- traceEmitter?.({ type: "agent_end", name: "Negotiating candidate", durationMs, summary: `${candidate.userId}: error` });
1379
- if (candidate.opportunityId) {
1380
- emitWide({
1381
- type: "negotiation_session_end",
1382
- opportunityId: candidate.opportunityId,
1383
- negotiationConversationId: "",
1384
- durationMs: Date.now() - start,
1385
- });
1386
- }
1387
- negotiateCandidatesLog.error("Negotiation failed", { candidateUserId: candidate.userId, error: err });
1388
- if (onCandidateResolved) {
1389
- try {
1390
- await onCandidateResolved({
1391
- candidate,
1392
- accepted: null,
1393
- turns: [],
1394
- outcome: {
1395
- hasOpportunity: false,
1396
- agreedRoles: [],
1397
- reasoning: err instanceof Error ? err.message : String(err),
1398
- turnCount: 0,
1399
- },
1400
- });
1401
- }
1402
- catch {
1403
- // ignore hook failure on error path
1404
- }
1405
- }
1406
- return null;
1407
- }
1408
- }));
1409
- return results.filter((r) => r !== null);
56
+ /** After init: fail closed, run the outreach gate, or go straight to the first turn. */
57
+ export function routeAfterInit(state) {
58
+ if (state.error)
59
+ return "finalize";
60
+ // Screen gate: fresh negotiations only (continuations already passed
61
+ // the gate when the dialogue opened); off disables the node entirely.
62
+ // IND-563: regular continuations (new opportunity, existing dm_pair)
63
+ // also run through the screen gate so stale matches are caught before
64
+ // re-engaging the counterparty. Exact ask_user resumes
65
+ // (continuationExecution) are mid-flight and must never be re-screened.
66
+ if (configuredScreenMode() !== "off" && !state.continuationExecution)
67
+ return "screen";
68
+ return "turn";
69
+ }
70
+ /** After the outreach gate: an enforced pass ends the negotiation before any turn. */
71
+ export function routeAfterScreen(state) {
72
+ return blocksNegotiationBeforeFirstTurn(state.screenDecision, state.turnCount) ? "finalize" : "turn";
73
+ }
74
+ /** After a turn: keep going, or settle. */
75
+ export function routeAfterTurn(state) {
76
+ if (state.status === 'waiting_for_agent')
77
+ return "finalize";
78
+ if (state.status === 'input_required')
79
+ return "finalize";
80
+ if (state.error)
81
+ return "finalize";
82
+ if (!state.lastTurn)
83
+ return "finalize";
84
+ // Terminal actions: accept (v1+v2), reject (v1), withdraw/decline (v2)
85
+ if (isTerminalAction(state.lastTurn.action))
86
+ return "finalize";
87
+ // question routes same as counter — next turn
88
+ if (isNegotiationTurnCapReached(state.turnCount, state.maxTurns))
89
+ return "finalize";
90
+ return "turn";
1410
91
  }