@indexnetwork/protocol 14.3.2-rc.477.1 → 16.1.1-rc.478.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 (140) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/IMPLEMENTATION.md +50 -52
  3. package/STABILITY.md +3 -3
  4. package/dist/chat/chat.agent.js +2 -2
  5. package/dist/chat/chat.graph.d.ts +41 -1
  6. package/dist/chat/chat.graph.js +108 -127
  7. package/dist/discovery/hyde.frame.d.ts +4 -4
  8. package/dist/discovery/hyde.graph.d.ts +71 -12
  9. package/dist/discovery/hyde.graph.js +337 -335
  10. package/dist/discovery/lens.inferrer.d.ts +6 -6
  11. package/dist/enrichment/enrichment.graph.d.ts +127 -9
  12. package/dist/enrichment/enrichment.graph.js +633 -655
  13. package/dist/enrichment/enrichment.state.d.ts +1 -1
  14. package/dist/enrichment/enrichment.tools.context-read.d.ts +10 -0
  15. package/dist/enrichment/enrichment.tools.context-read.js +353 -0
  16. package/dist/enrichment/enrichment.tools.context-write.d.ts +9 -0
  17. package/dist/enrichment/enrichment.tools.context-write.js +417 -0
  18. package/dist/enrichment/enrichment.tools.d.ts +11 -1
  19. package/dist/enrichment/enrichment.tools.helpers.d.ts +139 -0
  20. package/dist/enrichment/enrichment.tools.helpers.js +234 -0
  21. package/dist/enrichment/enrichment.tools.js +16 -975
  22. package/dist/index.d.ts +27 -48
  23. package/dist/index.js +17 -27
  24. package/dist/intents/application/intent.graph.d.ts +71 -67
  25. package/dist/intents/application/intent.graph.execute.d.ts +59 -0
  26. package/dist/intents/application/intent.graph.execute.js +301 -0
  27. package/dist/intents/application/intent.graph.infer.d.ts +44 -0
  28. package/dist/intents/application/intent.graph.infer.js +97 -0
  29. package/dist/intents/application/intent.graph.js +96 -888
  30. package/dist/intents/application/intent.graph.reconcile.d.ts +71 -0
  31. package/dist/intents/application/intent.graph.reconcile.js +274 -0
  32. package/dist/intents/application/intent.graph.shared.d.ts +70 -0
  33. package/dist/intents/application/intent.graph.shared.js +153 -0
  34. package/dist/intents/domain/intent.state.d.ts +1 -1
  35. package/dist/maintenance/maintenance.graph.d.ts +66 -3
  36. package/dist/maintenance/maintenance.graph.js +155 -156
  37. package/dist/mcp/mcp.authorization-policy.d.ts +24 -28
  38. package/dist/mcp/mcp.authorization-policy.js +14 -34
  39. package/dist/mcp/mcp.server.d.ts +3 -3
  40. package/dist/mcp/mcp.server.js +12 -16
  41. package/dist/negotiations/application/negotiation.candidates.d.ts +83 -0
  42. package/dist/negotiations/application/negotiation.candidates.js +162 -0
  43. package/dist/negotiations/application/negotiation.graph.d.ts +91 -157
  44. package/dist/negotiations/application/negotiation.graph.finalize.d.ts +5 -0
  45. package/dist/negotiations/application/negotiation.graph.finalize.js +280 -0
  46. package/dist/negotiations/application/negotiation.graph.init.d.ts +54 -0
  47. package/dist/negotiations/application/negotiation.graph.init.js +227 -0
  48. package/dist/negotiations/application/negotiation.graph.js +69 -1388
  49. package/dist/negotiations/application/negotiation.graph.screen.d.ts +23 -0
  50. package/dist/negotiations/application/negotiation.graph.screen.js +108 -0
  51. package/dist/negotiations/application/negotiation.graph.shared.d.ts +75 -0
  52. package/dist/negotiations/application/negotiation.graph.shared.js +125 -0
  53. package/dist/negotiations/application/negotiation.graph.turn.d.ts +105 -0
  54. package/dist/negotiations/application/negotiation.graph.turn.js +484 -0
  55. package/dist/negotiations/domain/negotiation.state.d.ts +1 -1
  56. package/dist/negotiations/domain/negotiation.state.js +0 -1
  57. package/dist/networks/application/indexer.graph.d.ts +165 -7
  58. package/dist/networks/application/indexer.graph.js +339 -388
  59. package/dist/networks/application/indexer.state.d.ts +1 -1
  60. package/dist/networks/application/membership.graph.d.ts +83 -5
  61. package/dist/networks/application/membership.graph.js +177 -207
  62. package/dist/networks/application/network.graph.d.ts +148 -5
  63. package/dist/networks/application/network.graph.js +249 -278
  64. package/dist/networks/domain/membership.state.d.ts +1 -1
  65. package/dist/networks/domain/network.state.d.ts +1 -1
  66. package/dist/opportunities/application/delivery-card.cache.d.ts +1 -1
  67. package/dist/opportunities/application/delivery-card.cache.js +2 -2
  68. package/dist/opportunities/application/index.d.ts +2 -2
  69. package/dist/opportunities/application/index.js +2 -2
  70. package/dist/opportunities/application/opportunity.evaluator.js +1 -1
  71. package/dist/opportunities/application/opportunity.graph.d.ts +686 -473
  72. package/dist/opportunities/application/opportunity.graph.discovery-strategies.d.ts +109 -0
  73. package/dist/opportunities/application/opportunity.graph.discovery-strategies.js +451 -0
  74. package/dist/opportunities/application/opportunity.graph.discovery.d.ts +69 -0
  75. package/dist/opportunities/application/opportunity.graph.discovery.js +397 -0
  76. package/dist/opportunities/application/opportunity.graph.evaluation.d.ts +82 -0
  77. package/dist/opportunities/application/opportunity.graph.evaluation.js +608 -0
  78. package/dist/opportunities/application/opportunity.graph.js +120 -3690
  79. package/dist/opportunities/application/opportunity.graph.modes.d.ts +538 -0
  80. package/dist/opportunities/application/opportunity.graph.modes.js +538 -0
  81. package/dist/opportunities/application/opportunity.graph.negotiate.d.ts +109 -0
  82. package/dist/opportunities/application/opportunity.graph.negotiate.js +392 -0
  83. package/dist/opportunities/application/opportunity.graph.persist-node.d.ts +93 -0
  84. package/dist/opportunities/application/opportunity.graph.persist-node.js +765 -0
  85. package/dist/opportunities/application/opportunity.graph.prep.d.ts +150 -0
  86. package/dist/opportunities/application/opportunity.graph.prep.js +381 -0
  87. package/dist/opportunities/application/opportunity.graph.shared.d.ts +173 -0
  88. package/dist/opportunities/application/opportunity.graph.shared.js +199 -0
  89. package/dist/opportunities/application/opportunity.presentation.d.ts +399 -0
  90. package/dist/opportunities/application/{opportunity.presenter.js → opportunity.presentation.js} +735 -9
  91. package/dist/opportunities/application/opportunity.tools.cards.d.ts +152 -0
  92. package/dist/opportunities/application/opportunity.tools.cards.js +235 -0
  93. package/dist/opportunities/application/opportunity.tools.d.ts +8 -114
  94. package/dist/opportunities/application/opportunity.tools.js +28 -711
  95. package/dist/opportunities/application/opportunity.tools.list.d.ts +10 -0
  96. package/dist/opportunities/application/opportunity.tools.list.js +493 -0
  97. package/dist/opportunities/domain/index.d.ts +3 -3
  98. package/dist/opportunities/domain/index.js +3 -3
  99. package/dist/opportunities/domain/opportunity.state.d.ts +19 -19
  100. package/dist/opportunities/index.d.ts +6 -6
  101. package/dist/opportunities/index.js +4 -4
  102. package/dist/opportunities/ports/opportunity.tools.port.d.ts +1 -1
  103. package/dist/opportunities/radar/radar.graph.d.ts +57 -13
  104. package/dist/opportunities/radar/radar.graph.js +470 -471
  105. package/dist/premises/premise.graph.d.ts +88 -20
  106. package/dist/premises/premise.graph.js +207 -218
  107. package/dist/questions/domain/question.schema.d.ts +40 -40
  108. package/dist/shared/agent/tool.helpers.d.ts +21 -0
  109. package/dist/shared/agent/tool.registry.d.ts +4 -3
  110. package/dist/shared/agent/tool.registry.js +1 -1
  111. package/dist/shared/interfaces/database.capabilities.d.ts +100 -0
  112. package/dist/shared/interfaces/database.capabilities.js +7 -0
  113. package/dist/shared/interfaces/database.entities.d.ts +533 -0
  114. package/dist/shared/interfaces/database.entities.js +10 -0
  115. package/dist/shared/interfaces/database.identity-queries.d.ts +294 -0
  116. package/dist/shared/interfaces/database.identity-queries.js +4 -0
  117. package/dist/shared/interfaces/database.interface.d.ts +15 -2277
  118. package/dist/shared/interfaces/database.interface.js +8 -0
  119. package/dist/shared/interfaces/database.member-queries.d.ts +228 -0
  120. package/dist/shared/interfaces/database.member-queries.js +4 -0
  121. package/dist/shared/interfaces/database.negotiation.d.ts +305 -0
  122. package/dist/shared/interfaces/database.negotiation.js +26 -0
  123. package/dist/shared/interfaces/database.network-queries.d.ts +277 -0
  124. package/dist/shared/interfaces/database.network-queries.js +4 -0
  125. package/dist/shared/interfaces/database.opportunity-queries.d.ts +285 -0
  126. package/dist/shared/interfaces/database.opportunity-queries.js +4 -0
  127. package/dist/shared/interfaces/database.port.d.ts +322 -0
  128. package/dist/shared/interfaces/database.port.js +29 -0
  129. package/dist/shared/schemas/discovery-question.schema.d.ts +14 -14
  130. package/dist/shared/schemas/negotiation-digest.schema.d.ts +2 -2
  131. package/package.json +2 -15
  132. package/dist/opportunities/application/opportunity.card-presentation.d.ts +0 -44
  133. package/dist/opportunities/application/opportunity.card-presentation.js +0 -93
  134. package/dist/opportunities/application/opportunity.presenter.d.ts +0 -156
  135. package/dist/opportunities/domain/opportunity.presentation-cache.d.ts +0 -5
  136. package/dist/opportunities/domain/opportunity.presentation-cache.js +0 -11
  137. package/dist/opportunities/domain/opportunity.presentation.d.ts +0 -76
  138. package/dist/opportunities/domain/opportunity.presentation.js +0 -516
  139. package/dist/opportunities/domain/opportunity.safe-presentation.d.ts +0 -104
  140. package/dist/opportunities/domain/opportunity.safe-presentation.js +0 -102
@@ -0,0 +1,538 @@
1
+ /**
2
+ * The opportunity operations that are not discovery.
3
+ *
4
+ * These used to be graph nodes reached through an `operationMode` conditional
5
+ * edge at START — nine one-node paths sharing a state machine they never used.
6
+ * They are plain async functions now; callers invoke the one they mean. Only
7
+ * the discovery pipeline still needs a graph.
8
+ *
9
+ * Each returns the same shape the corresponding node returned, so callers read
10
+ * `readResult` / `mutationResult` exactly as before.
11
+ */
12
+ import { timed } from '../../shared/observability/performance.js';
13
+ import { requestContext } from '../../shared/observability/request-context.js';
14
+ import { getAbortSignalConfig } from '../../shared/agent/model-signal.js';
15
+ import { safeFallbackSummary } from './opportunity.presentation.js';
16
+ import { AMBIENT_PARK_WINDOW_MS, negotiateCandidates } from '../../negotiations/index.js';
17
+ import { approveOpportunityIntroduction, deleteOpportunityLifecycle, sendOpportunityLifecycle, updateOpportunityLifecycle } from './opportunity.lifecycle.js';
18
+ import { negotiateExistingOpportunity } from './opportunity.existing-negotiation.js';
19
+ import { buildNetworkContexts, deleteLog, introEvaluationLog, introValidationLog, negotiateExistingLog, readLog, sendLog, updateLog } from './opportunity.graph.shared.js';
20
+ import { persistNode } from './opportunity.graph.persist-node.js';
21
+ /**
22
+ * Read mode: list opportunities for the user, optionally filtered by networkId.
23
+ * Fast path — no LLM calls.
24
+ */
25
+ export async function readOpportunities(deps, request) {
26
+ return timed("OpportunityGraph.read", async () => {
27
+ readLog.verbose('Listing opportunities', {
28
+ userId: request.userId,
29
+ networkId: request.networkId,
30
+ });
31
+ try {
32
+ let indexIdFilter;
33
+ if (request.networkId) {
34
+ const [isMember, isOwner] = await Promise.all([
35
+ deps.database.isNetworkMember(request.networkId, request.userId),
36
+ deps.database.isIndexOwner(request.networkId, request.userId),
37
+ ]);
38
+ if (!isMember && !isOwner) {
39
+ return {
40
+ readResult: { count: 0, opportunities: [], message: 'Network not found or you are not a member.' },
41
+ };
42
+ }
43
+ indexIdFilter = request.networkId;
44
+ }
45
+ const rawList = await deps.database.getOpportunitiesForUser(request.userId, {
46
+ limit: 30,
47
+ ...(indexIdFilter ? { networkId: indexIdFilter } : {}),
48
+ });
49
+ const list = rawList.filter((opp) => opp.status !== 'expired');
50
+ if (list.length === 0) {
51
+ return {
52
+ readResult: {
53
+ count: 0,
54
+ message: 'You have no opportunities yet. Create or refine an approved signal; matching runs in the background. Use list_opportunities later to review persisted results.',
55
+ opportunities: [],
56
+ },
57
+ };
58
+ }
59
+ // Dedupe by counterpart set (same people = one row) so chat does not show "You and X" per index
60
+ const counterpartKey = (opp) => opp.actors
61
+ .filter((a) => a.userId !== request.userId && a.role !== 'introducer')
62
+ .map((a) => a.userId)
63
+ .sort()
64
+ .join(',');
65
+ const byKey = new Map();
66
+ for (const opp of list) {
67
+ const key = counterpartKey(opp);
68
+ const existing = byKey.get(key);
69
+ const conf = Number(opp.interpretation?.confidence ?? opp.confidence ?? 0);
70
+ const existingConf = existing ? Number(existing.interpretation?.confidence ?? existing.confidence ?? 0) : 0;
71
+ const oppTime = opp.updatedAt instanceof Date ? opp.updatedAt.getTime() : new Date(opp.updatedAt).getTime();
72
+ const existingTime = existing
73
+ ? (existing.updatedAt instanceof Date ? existing.updatedAt.getTime() : new Date(existing.updatedAt).getTime())
74
+ : 0;
75
+ if (!existing || conf > existingConf || (conf === existingConf && oppTime > existingTime)) {
76
+ byKey.set(key, opp);
77
+ }
78
+ }
79
+ const dedupedList = [...byKey.values()];
80
+ const enriched = await Promise.all(dedupedList.map(async (opp) => {
81
+ // "Other parties" = all actors who are not the current user (exclude introducer for suggestedBy).
82
+ // Opportunity graph persists roles as 'agent'|'patient'|'peer'; manual/createManual use 'party'.
83
+ const otherParties = opp.actors.filter((a) => a.userId !== request.userId && a.role !== 'introducer');
84
+ const introducer = opp.actors.find((a) => a.role === 'introducer');
85
+ const partyIds = otherParties.map((a) => a.userId);
86
+ const idsToResolve = introducer ? [...partyIds, introducer.userId] : partyIds;
87
+ // Use the counterpart's (non-viewer) networkId — it reflects where the match was found.
88
+ // actors[0] is typically the viewer with an arbitrary first-target-index value.
89
+ const counterpartActor = opp.actors.find((a) => a.userId !== request.userId);
90
+ const actorIndexId = counterpartActor?.networkId ?? opp.actors[0]?.networkId;
91
+ const [indexRecord, ...profileAndUserPairs] = await Promise.all([
92
+ actorIndexId ? deps.database.getNetwork(actorIndexId) : Promise.resolve(null),
93
+ ...idsToResolve.map(async (uid) => {
94
+ const [profile, user] = await Promise.all([
95
+ deps.database.getProfile(uid),
96
+ deps.database.getUser(uid),
97
+ ]);
98
+ return (profile?.identity?.name ?? user?.name ?? 'Unknown');
99
+ }),
100
+ ]);
101
+ const connectedWith = profileAndUserPairs.slice(0, partyIds.length);
102
+ const suggestedBy = introducer ? profileAndUserPairs[partyIds.length] ?? null : null;
103
+ const category = opp.interpretation?.category ?? 'connection';
104
+ const confidence = opp.interpretation?.confidence ?? (opp.confidence ? Number(opp.confidence) : null);
105
+ const source = opp.detection?.source ? (OPPORTUNITY_SOURCE_LABEL[opp.detection.source] ?? opp.detection.source) : null;
106
+ return {
107
+ id: opp.id,
108
+ indexName: indexRecord?.title ?? (actorIndexId ?? ''),
109
+ connectedWith,
110
+ suggestedBy,
111
+ reasoning: safeFallbackSummary(opp.interpretation?.reasoning, {
112
+ counterpartName: connectedWith.join(' and '),
113
+ emptyText: 'Connection opportunity',
114
+ }),
115
+ status: opp.status,
116
+ category,
117
+ confidence: confidence != null ? confidence : null,
118
+ source,
119
+ };
120
+ }));
121
+ return {
122
+ readResult: {
123
+ count: enriched.length,
124
+ message: `You have ${enriched.length} opportunity(ies).`,
125
+ opportunities: enriched,
126
+ },
127
+ };
128
+ }
129
+ catch (err) {
130
+ readLog.error('Failed', { error: err });
131
+ return {
132
+ readResult: { count: 0, opportunities: [], message: 'Failed to list opportunities.' },
133
+ };
134
+ }
135
+ });
136
+ }
137
+ /** Human-readable label per detection source, for the read-mode listing. */
138
+ const OPPORTUNITY_SOURCE_LABEL = {
139
+ chat: 'Suggested in chat',
140
+ opportunity_graph: 'System match',
141
+ manual: 'Manual',
142
+ cron: 'Scheduled',
143
+ member_added: 'Member added',
144
+ introducer_discovery: 'Suggested by contact',
145
+ };
146
+ /**
147
+ * Update mode: change opportunity status (accept, reject, etc.).
148
+ * For 'accepted', enforces the self-accept guard: the caller's actor entry
149
+ * must not already have `actedAt` set — i.e. the caller has not yet been
150
+ * the one to advance this opportunity's state. Stamps `actedAt` on accept
151
+ * atomically with the status change via `stampOpportunityActorAction`.
152
+ */
153
+ export async function updateOpportunityStatus(deps, request) {
154
+ return timed("OpportunityGraph.update", async () => {
155
+ updateLog.verbose('Updating opportunity status', {
156
+ userId: request.userId,
157
+ opportunityId: request.opportunityId,
158
+ newStatus: request.newStatus,
159
+ });
160
+ try {
161
+ return {
162
+ mutationResult: await updateOpportunityLifecycle(deps.database, {
163
+ opportunityId: request.opportunityId,
164
+ actorUserId: request.userId,
165
+ newStatus: request.newStatus,
166
+ }),
167
+ };
168
+ }
169
+ catch (err) {
170
+ updateLog.error('Failed', { error: err });
171
+ return { mutationResult: { success: false, error: 'Failed to update opportunity.' } };
172
+ }
173
+ });
174
+ }
175
+ /** Delete mode: expire/archive an opportunity. */
176
+ export async function deleteOpportunity(deps, request) {
177
+ return timed("OpportunityGraph.delete", async () => {
178
+ deleteLog.verbose('Expiring opportunity', {
179
+ userId: request.userId,
180
+ opportunityId: request.opportunityId,
181
+ });
182
+ try {
183
+ return {
184
+ mutationResult: await deleteOpportunityLifecycle(deps.database, {
185
+ opportunityId: request.opportunityId,
186
+ actorUserId: request.userId,
187
+ }),
188
+ };
189
+ }
190
+ catch (err) {
191
+ deleteLog.error('Failed', { error: err });
192
+ return { mutationResult: { success: false, error: 'Failed to delete opportunity.' } };
193
+ }
194
+ });
195
+ }
196
+ /** Send mode: promote a latent or draft opportunity to pending + queue notification. */
197
+ export async function sendOpportunity(deps, request) {
198
+ return timed("OpportunityGraph.send", async () => {
199
+ sendLog.verbose('Sending opportunity', {
200
+ userId: request.userId,
201
+ opportunityId: request.opportunityId,
202
+ });
203
+ try {
204
+ return {
205
+ mutationResult: await sendOpportunityLifecycle(deps.database, { opportunityId: request.opportunityId, actorUserId: request.userId }, deps.queueNotification),
206
+ };
207
+ }
208
+ catch (err) {
209
+ sendLog.error('Failed', { error: err });
210
+ return { mutationResult: { success: false, error: 'Failed to send opportunity.' } };
211
+ }
212
+ });
213
+ }
214
+ /**
215
+ * Approve-introduction mode.
216
+ * Called by the introducer to approve a latent introducer-pattern opportunity.
217
+ * Sets approved=true on the introducer actor (status stays latent), then
218
+ * enqueues a negotiate_existing job so the parties negotiate normally.
219
+ */
220
+ export async function approveIntroduction(deps, request) {
221
+ return {
222
+ mutationResult: await approveOpportunityIntroduction(deps.database, { opportunityId: request.opportunityId, actorUserId: request.userId }, deps.queueNegotiateExisting),
223
+ };
224
+ }
225
+ /**
226
+ * Negotiate-existing mode: load an existing opportunity by ID and run bilateral negotiation.
227
+ * Used after introducer approval to trigger the normal negotiation flow for a latent opportunity.
228
+ */
229
+ export async function negotiateExisting(deps, request) {
230
+ if (!request.opportunityId)
231
+ return {};
232
+ if (!deps.negotiationGraph) {
233
+ negotiateExistingLog.warn('No negotiationGraph wired; skipping', {
234
+ opportunityId: request.opportunityId,
235
+ });
236
+ return {};
237
+ }
238
+ try {
239
+ const continuation = request.continuation;
240
+ const result = await negotiateExistingOpportunity(deps.database, async ({ sourceUser, candidate, indexContextOverrides, continuation: execution }) => {
241
+ let receipt;
242
+ // Deliberately no `initiatorUserId`: re-entries inherit the prior task's
243
+ // stamped seat in negotiation initialization, never re-deriving it here.
244
+ const acceptedResults = await negotiateCandidates(deps.negotiationGraph, sourceUser, [candidate], { networkId: '', prompt: '' }, {
245
+ maxTurns: Number(process.env.NEGOTIATION_MAX_TURNS_AMBIENT) || 6,
246
+ indexContextOverrides,
247
+ timeoutMs: AMBIENT_PARK_WINDOW_MS,
248
+ ...(execution ? {
249
+ resumeFromTaskId: execution.taskId,
250
+ continuationSettlementId: execution.settlementId,
251
+ continuationExecution: execution,
252
+ onCandidateResolved: async ({ continuationReceipt }) => {
253
+ if (continuationReceipt?.successorTaskId === execution.successorTaskId)
254
+ receipt = continuationReceipt;
255
+ },
256
+ } : {}),
257
+ });
258
+ return { accepted: acceptedResults.length > 0, ...(receipt ? { receipt } : {}) };
259
+ }, { opportunityId: request.opportunityId, actorUserId: request.userId, continuation }, deps.queueNotification, {
260
+ onNotificationFailure: ({ actorId, error }) => {
261
+ negotiateExistingLog.warn('Failed to queue notification', { actorId, error });
262
+ },
263
+ });
264
+ if (result.kind === 'skipped') {
265
+ const messages = {
266
+ not_found: 'Opportunity not found',
267
+ stale_continuation: 'Exact continuation actor binding is stale',
268
+ no_source_actor: 'No source actor found',
269
+ no_candidate_actor: 'No candidate actor found',
270
+ };
271
+ negotiateExistingLog.warn(messages[result.reason], {
272
+ opportunityId: request.opportunityId,
273
+ ...(result.reason === 'stale_continuation' && continuation ? { taskId: continuation.taskId } : {}),
274
+ });
275
+ return {};
276
+ }
277
+ negotiateExistingLog.info('Negotiation complete', {
278
+ opportunityId: result.opportunityId,
279
+ accepted: result.accepted,
280
+ continuationFence: result.continuationFence,
281
+ });
282
+ return result.receipt ? { negotiationContinuationReceipt: result.receipt } : {};
283
+ }
284
+ catch (err) {
285
+ negotiateExistingLog.error('Failed', { opportunityId: request.opportunityId, error: err });
286
+ return { error: `Failed to load opportunity: ${err instanceof Error ? err.message : String(err)}` };
287
+ }
288
+ }
289
+ /**
290
+ * Introduction mode: validate → evaluate → persist.
291
+ *
292
+ * Validation gates on scope and membership; evaluation asks the evaluator to
293
+ * justify the pairing (falling back to the introducer's own word); persistence
294
+ * reuses the discovery pipeline's persist stage.
295
+ */
296
+ export async function createIntroduction(deps, request) {
297
+ const state = introductionState(request);
298
+ const validation = await validateIntroduction(deps, state);
299
+ // Mirrors what the graph produced on this path: the error, and empty results.
300
+ if (validation.error)
301
+ return { opportunities: [], evaluatedOpportunities: [], agentTimings: [], ...validation };
302
+ const evaluation = await evaluateIntroduction(deps, { ...state, ...validation });
303
+ const persisted = await persistNode({ ...state, ...evaluation }, deps);
304
+ return { ...evaluation, ...persisted };
305
+ }
306
+ /**
307
+ * Introduction validation: network scope, membership for introducer and all
308
+ * party users, and no existing opportunity between the parties.
309
+ */
310
+ export async function validateIntroduction(deps, state) {
311
+ return timed("OpportunityGraph.introValidation", async () => {
312
+ introValidationLog.verbose('Starting', {
313
+ userId: state.userId,
314
+ networkId: state.networkId,
315
+ entitiesCount: state.introductionEntities?.length ?? 0,
316
+ });
317
+ try {
318
+ const entities = state.introductionEntities ?? [];
319
+ const primaryNetworkId = (state.networkId ?? entities[0]?.networkId);
320
+ const partyUserIds = [...new Set(entities.map((e) => e.userId).filter((id) => id !== state.userId))];
321
+ if (!primaryNetworkId || partyUserIds.length < 1) {
322
+ return {
323
+ error: 'Introduction requires networkId and at least two entities (introducer + one counterpart).',
324
+ };
325
+ }
326
+ if (state.requiredNetworkId && primaryNetworkId !== state.requiredNetworkId) {
327
+ return {
328
+ error: 'This chat is scoped to a different community. You can only introduce members of the current community.',
329
+ };
330
+ }
331
+ const [introducerIsMember, introducerIsOwner] = await Promise.all([
332
+ deps.database.isNetworkMember(primaryNetworkId, state.userId),
333
+ deps.database.isIndexOwner(primaryNetworkId, state.userId),
334
+ ]);
335
+ if (!introducerIsMember && !introducerIsOwner) {
336
+ return {
337
+ error: 'One or more users are not members of the specified community. You can only introduce members who share a network.',
338
+ };
339
+ }
340
+ const partyInScope = await Promise.all(partyUserIds.map(async (userId) => {
341
+ const [isMember, isOwner] = await Promise.all([
342
+ deps.database.isNetworkMember(primaryNetworkId, userId),
343
+ deps.database.isIndexOwner(primaryNetworkId, userId),
344
+ ]);
345
+ return isMember || isOwner;
346
+ }));
347
+ const allPartyMembers = partyInScope.every(Boolean);
348
+ if (!allPartyMembers) {
349
+ return {
350
+ error: 'One or more users are not members of the specified community. You can only introduce members who share a network.',
351
+ };
352
+ }
353
+ const exists = await deps.database.opportunityExistsBetweenActors(partyUserIds, primaryNetworkId);
354
+ if (exists) {
355
+ return { error: 'An opportunity already exists between these people.' };
356
+ }
357
+ introValidationLog.verbose('Validation passed');
358
+ return {};
359
+ }
360
+ catch (err) {
361
+ const errMsg = err instanceof Error ? err.message : String(err);
362
+ introValidationLog.error('Failed', {
363
+ userId: state.userId,
364
+ networkId: state.networkId,
365
+ error: err,
366
+ });
367
+ return {
368
+ error: 'Introduction validation failed.',
369
+ trace: [{
370
+ node: "intro_validation_fatal",
371
+ detail: `IntroValidation failed: ${errMsg}`,
372
+ data: { error: errMsg },
373
+ }],
374
+ };
375
+ }
376
+ });
377
+ }
378
+ /**
379
+ * Build fallback reasoning and actors when the evaluator returns empty or throws.
380
+ */
381
+ function buildIntroFallback(entities, state, primaryNetworkId, introducerName) {
382
+ const reasoning = `${introducerName ?? 'A member'} believes these people should connect.` +
383
+ (state.introductionHint ? ` Context: ${state.introductionHint}` : '');
384
+ const score = 70;
385
+ const partyUserIds = entities.map((e) => e.userId).filter((id) => id !== state.userId);
386
+ const actors = partyUserIds.map((uid) => ({
387
+ userId: uid,
388
+ role: 'peer',
389
+ networkId: primaryNetworkId,
390
+ }));
391
+ return { reasoning, score, actors };
392
+ }
393
+ /**
394
+ * Introduction evaluation: runs the entity-bundle evaluator and sets
395
+ * evaluatedOpportunities (one) + introductionContext.
396
+ */
397
+ export async function evaluateIntroduction(deps, state) {
398
+ return timed("OpportunityGraph.introEvaluation", async () => {
399
+ introEvaluationLog.verbose('Starting', { userId: state.userId });
400
+ if (state.error) {
401
+ return { evaluatedOpportunities: [], agentTimings: [] };
402
+ }
403
+ const entities = state.introductionEntities ?? [];
404
+ const primaryNetworkId = (state.networkId ?? entities[0]?.networkId);
405
+ if (!primaryNetworkId || entities.length < 2) {
406
+ return { evaluatedOpportunities: [], error: 'Missing entities or network for introduction.', agentTimings: [] };
407
+ }
408
+ const agentTimingsAccum = [];
409
+ let introducerName;
410
+ let reasoning;
411
+ let score;
412
+ let actors = [];
413
+ const _traceEmitterIntro = requestContext.getStore()?.traceEmitter;
414
+ let _introEvalStarted = false;
415
+ let _evalStart = Date.now();
416
+ try {
417
+ const introducerUser = await deps.database.getUser(state.userId);
418
+ introducerName = introducerUser?.name ?? undefined;
419
+ const networkContexts = await buildNetworkContexts(entities, deps.database);
420
+ const input = {
421
+ discovererId: state.userId,
422
+ entities,
423
+ introductionMode: true,
424
+ introducerName,
425
+ introductionHint: state.introductionHint ?? undefined,
426
+ networkContexts,
427
+ };
428
+ _evalStart = Date.now();
429
+ _traceEmitterIntro?.({ type: "agent_start", name: "intro-evaluator" });
430
+ _introEvalStarted = true;
431
+ const evaluated = await deps.evaluatorAgent.invokeEntityBundle(input, { minScore: 0, ...getAbortSignalConfig() });
432
+ const _introDuration = Date.now() - _evalStart;
433
+ agentTimingsAccum.push({ name: 'opportunity.evaluator', durationMs: _introDuration });
434
+ _traceEmitterIntro?.({ type: "agent_end", name: "intro-evaluator", durationMs: _introDuration, summary: "Evaluated introduction" });
435
+ if (evaluated.length > 0) {
436
+ const best = evaluated[0];
437
+ reasoning = best.reasoning;
438
+ score = best.score;
439
+ actors = best.actors.map((a) => ({
440
+ userId: a.userId,
441
+ role: a.role,
442
+ intentId: a.intentId ?? undefined,
443
+ networkId: primaryNetworkId,
444
+ }));
445
+ }
446
+ else {
447
+ const fallback = buildIntroFallback(entities, state, primaryNetworkId, introducerName);
448
+ reasoning = fallback.reasoning;
449
+ score = fallback.score;
450
+ actors = fallback.actors;
451
+ }
452
+ }
453
+ catch (evalErr) {
454
+ const errMsg = evalErr instanceof Error ? evalErr.message : String(evalErr);
455
+ // Close the intro-evaluator span if it was started before the error
456
+ if (_introEvalStarted) {
457
+ const _introErrDuration = Date.now() - _evalStart;
458
+ _traceEmitterIntro?.({ type: "agent_end", name: "intro-evaluator", durationMs: _introErrDuration, summary: `error — ${errMsg}` });
459
+ agentTimingsAccum.push({ name: 'opportunity.evaluator', durationMs: _introErrDuration });
460
+ }
461
+ introEvaluationLog.warn('Evaluator or getUser failed, using fallback', { error: evalErr });
462
+ const fallback = buildIntroFallback(entities, state, primaryNetworkId, introducerName);
463
+ reasoning = fallback.reasoning;
464
+ score = fallback.score;
465
+ actors = fallback.actors;
466
+ return {
467
+ evaluatedOpportunities: [{ actors, score, reasoning }],
468
+ introductionContext: { createdByName: introducerName },
469
+ options: { ...state.options, initialStatus: state.options.initialStatus ?? 'latent' },
470
+ agentTimings: agentTimingsAccum,
471
+ trace: [{
472
+ node: "intro_evaluation_fatal",
473
+ detail: `IntroEvaluation failed (using fallback): ${errMsg}`,
474
+ data: { error: errMsg },
475
+ }],
476
+ };
477
+ }
478
+ const evaluatedOpportunity = { actors, score, reasoning };
479
+ return {
480
+ evaluatedOpportunities: [evaluatedOpportunity],
481
+ introductionContext: { createdByName: introducerName },
482
+ options: { ...state.options, initialStatus: state.options.initialStatus ?? 'latent' },
483
+ agentTimings: agentTimingsAccum,
484
+ };
485
+ });
486
+ }
487
+ /**
488
+ * The channel defaults the introduction path relies on. Discovery-only channels
489
+ * stay at their empty values because the introduction path never fills them.
490
+ */
491
+ function introductionState(request) {
492
+ return {
493
+ userId: request.userId,
494
+ searchQuery: undefined,
495
+ networkId: request.networkId,
496
+ indexScope: undefined,
497
+ triggerIntentId: undefined,
498
+ targetUserId: undefined,
499
+ onBehalfOfUserId: undefined,
500
+ options: { ...(request.options ?? {}) },
501
+ operationMode: 'create_introduction',
502
+ introductionEntities: request.introductionEntities,
503
+ introductionHint: request.introductionHint,
504
+ requiredNetworkId: request.requiredNetworkId,
505
+ introductionContext: undefined,
506
+ opportunityId: undefined,
507
+ newStatus: undefined,
508
+ indexedIntents: [],
509
+ userNetworks: [],
510
+ targetNetworks: [],
511
+ indexRelevancyScores: {},
512
+ discoverySource: 'context',
513
+ resolvedTriggerIntentId: undefined,
514
+ sourceProfile: null,
515
+ sourcePremises: [],
516
+ sourceContexts: [],
517
+ resolvedIntentInIndex: false,
518
+ createIntentSuggested: false,
519
+ suggestedIntentDescription: undefined,
520
+ hydeEmbeddings: {},
521
+ candidates: [],
522
+ remainingCandidates: [],
523
+ discoveryId: null,
524
+ evaluatedCandidates: [],
525
+ evaluatedOpportunities: [],
526
+ opportunities: [],
527
+ existingBetweenActors: [],
528
+ persistenceOutcome: undefined,
529
+ negotiationContinuationReceipt: undefined,
530
+ error: undefined,
531
+ readResult: undefined,
532
+ mutationResult: undefined,
533
+ trace: [],
534
+ agentTimings: [],
535
+ discoveryNegotiations: [],
536
+ discoverySummary: null,
537
+ };
538
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Discovery pipeline, stage 7: post-persist negotiation.
3
+ *
4
+ * Runs bilateral negotiation per persisted opportunity, passing opportunityId so the
5
+ * negotiation graph's finalize node updates each opportunity's status:
6
+ * accept → 'pending' (sender notification follows the pending → notification path)
7
+ * reject → 'rejected'
8
+ * timeout/turn_cap → 'stalled'
9
+ * Status updates land in the DB; in-memory state.opportunities is not mutated.
10
+ */
11
+ import { type OpportunityGraphDeps, type OpportunityState } from './opportunity.graph.shared.js';
12
+ /**
13
+ * Node 3b: Negotiate (post-persist)
14
+ */
15
+ export declare function negotiateNode(state: OpportunityState, deps: OpportunityGraphDeps): Promise<{
16
+ trace?: undefined;
17
+ discoveryNegotiations?: undefined;
18
+ discoverySummary?: undefined;
19
+ } | {
20
+ trace: {
21
+ node: string;
22
+ detail: string;
23
+ data: {
24
+ negotiateTimeoutMs: number;
25
+ candidateCount: number;
26
+ durationMs: number;
27
+ };
28
+ }[];
29
+ discoveryNegotiations: {
30
+ indexContext: string;
31
+ outcome: {
32
+ reasoning: string;
33
+ hasOpportunity: boolean;
34
+ reason?: "timeout" | "turn_cap" | "screened_out" | undefined;
35
+ agreedRoles?: {
36
+ userId: string;
37
+ role: "agent" | "patient" | "peer";
38
+ }[] | undefined;
39
+ };
40
+ counterpartyHint: string;
41
+ counterpartyId: string;
42
+ turns: {
43
+ reasoning: string;
44
+ action: "propose" | "accept" | "reject" | "counter" | "question" | "outreach" | "withdraw" | "decline" | "ask_user";
45
+ suggestedRoles: {
46
+ ownUser: "agent" | "patient" | "peer";
47
+ otherUser: "agent" | "patient" | "peer";
48
+ };
49
+ }[];
50
+ seedAssessmentScore?: number | undefined;
51
+ }[];
52
+ discoverySummary: import("../../shared/schemas/discovery-question.schema.js").DiscoverySummary;
53
+ } | {
54
+ trace: ({
55
+ node: string;
56
+ detail: string;
57
+ data: {
58
+ userId: string;
59
+ opportunityId: string | undefined;
60
+ name: string;
61
+ outcome: string;
62
+ turns: number;
63
+ };
64
+ } | {
65
+ node: string;
66
+ detail: string;
67
+ data: {
68
+ durationMs: number;
69
+ candidateCount: number;
70
+ acceptedCount: number;
71
+ otherCount: number;
72
+ };
73
+ })[];
74
+ discoveryNegotiations: {
75
+ indexContext: string;
76
+ outcome: {
77
+ reasoning: string;
78
+ hasOpportunity: boolean;
79
+ reason?: "timeout" | "turn_cap" | "screened_out" | undefined;
80
+ agreedRoles?: {
81
+ userId: string;
82
+ role: "agent" | "patient" | "peer";
83
+ }[] | undefined;
84
+ };
85
+ counterpartyHint: string;
86
+ counterpartyId: string;
87
+ turns: {
88
+ reasoning: string;
89
+ action: "propose" | "accept" | "reject" | "counter" | "question" | "outreach" | "withdraw" | "decline" | "ask_user";
90
+ suggestedRoles: {
91
+ ownUser: "agent" | "patient" | "peer";
92
+ otherUser: "agent" | "patient" | "peer";
93
+ };
94
+ }[];
95
+ seedAssessmentScore?: number | undefined;
96
+ }[];
97
+ discoverySummary: import("../../shared/schemas/discovery-question.schema.js").DiscoverySummary;
98
+ } | {
99
+ trace: {
100
+ node: string;
101
+ detail: string;
102
+ data: {
103
+ durationMs: number;
104
+ error: boolean;
105
+ };
106
+ }[];
107
+ discoveryNegotiations: never[];
108
+ discoverySummary: import("../../shared/schemas/discovery-question.schema.js").DiscoverySummary;
109
+ }>;