@indexnetwork/protocol 6.15.0-rc.407.1 → 8.0.2-rc.418.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 (110) hide show
  1. package/CHANGELOG.md +309 -0
  2. package/IMPLEMENTATION.md +7 -4
  3. package/dist/capabilities/opportunities.facade.d.ts +4 -0
  4. package/dist/capabilities/opportunities.facade.js +4 -0
  5. package/dist/chat/chat-streaming.types.d.ts +4 -5
  6. package/dist/chat/chat.agent.d.ts +0 -19
  7. package/dist/chat/chat.agent.js +1 -70
  8. package/dist/chat/chat.persona.d.ts +0 -6
  9. package/dist/chat/chat.persona.js +0 -1
  10. package/dist/chat/chat.prompt.js +10 -10
  11. package/dist/chat/chat.prompt.modules.js +0 -104
  12. package/dist/chat/chat.tools.js +11 -7
  13. package/dist/chat/negotiator.persona.js +0 -1
  14. package/dist/chat/onboarding.persona.js +0 -1
  15. package/dist/chat/reporter.persona.d.ts +1 -1
  16. package/dist/chat/reporter.persona.js +1 -2
  17. package/dist/chat/reporter.prompt.js +5 -5
  18. package/dist/chat/signal.persona.js +0 -1
  19. package/dist/communities/application/network.tools.js +48 -27
  20. package/dist/contacts/application/contact.tools.js +9 -9
  21. package/dist/index.d.ts +9 -2
  22. package/dist/index.js +5 -0
  23. package/dist/maintenance/maintenance.graph.js +7 -0
  24. package/dist/mcp/mcp.authorization-policy.d.ts +250 -0
  25. package/dist/mcp/mcp.authorization-policy.js +522 -0
  26. package/dist/mcp/mcp.server.d.ts +6 -29
  27. package/dist/mcp/mcp.server.js +202 -228
  28. package/dist/negotiation/application/negotiation.agent.js +29 -5
  29. package/dist/negotiation/application/negotiation.graph.d.ts +2 -5
  30. package/dist/negotiation/application/negotiation.graph.js +53 -23
  31. package/dist/negotiation/domain/index.d.ts +3 -0
  32. package/dist/negotiation/domain/index.js +3 -0
  33. package/dist/negotiation/domain/negotiation.deadlock.d.ts +7 -1
  34. package/dist/negotiation/domain/negotiation.deadlock.js +48 -1
  35. package/dist/negotiation/domain/negotiation.stance.contracts.d.ts +85 -0
  36. package/dist/negotiation/domain/negotiation.stance.contracts.js +140 -0
  37. package/dist/negotiation/domain/negotiation.state.d.ts +2 -3
  38. package/dist/negotiation/domain/negotiation.state.js +2 -3
  39. package/dist/negotiation/public/index.d.ts +2 -0
  40. package/dist/negotiation/public/index.js +2 -0
  41. package/dist/opportunity/application/index.d.ts +0 -3
  42. package/dist/opportunity/application/index.js +0 -3
  43. package/dist/opportunity/application/opportunity.graph.d.ts +0 -43
  44. package/dist/opportunity/application/opportunity.graph.js +7 -113
  45. package/dist/opportunity/application/opportunity.introducer-feature.d.ts +2 -0
  46. package/dist/opportunity/application/opportunity.introducer-feature.js +4 -0
  47. package/dist/opportunity/application/opportunity.owner-approval.d.ts +118 -0
  48. package/dist/opportunity/application/opportunity.owner-approval.js +34 -0
  49. package/dist/opportunity/application/opportunity.owner-provenance.d.ts +6 -0
  50. package/dist/opportunity/application/opportunity.owner-provenance.js +28 -0
  51. package/dist/opportunity/application/opportunity.tools.d.ts +3 -3
  52. package/dist/opportunity/application/opportunity.tools.js +77 -870
  53. package/dist/opportunity/discriminator/discriminator.shadow.js +17 -10
  54. package/dist/opportunity/discriminator/discriminator.types.d.ts +2 -0
  55. package/dist/opportunity/domain/index.d.ts +0 -2
  56. package/dist/opportunity/domain/index.js +0 -2
  57. package/dist/opportunity/domain/opportunity.state.d.ts +2 -70
  58. package/dist/opportunity/domain/opportunity.state.js +2 -55
  59. package/dist/opportunity/opportunity.owner-approval.d.ts +5 -0
  60. package/dist/opportunity/opportunity.owner-approval.js +5 -0
  61. package/dist/opportunity/ports/opportunity.tools.port.d.ts +12 -1
  62. package/dist/opportunity/public/index.d.ts +3 -3
  63. package/dist/opportunity/public/index.js +2 -1
  64. package/dist/participant-agents/application/agent.tools.d.ts +1 -1
  65. package/dist/participant-agents/application/agent.tools.js +44 -6
  66. package/dist/participant-agents/application/index.d.ts +5 -3
  67. package/dist/participant-agents/application/index.js +5 -3
  68. package/dist/questions/application/question.tools.js +31 -2
  69. package/dist/runtime/foreground/composition/tool.factory.d.ts +2 -1
  70. package/dist/runtime/foreground/composition/tool.factory.js +9 -2
  71. package/dist/runtime/foreground/composition/tool.registry.d.ts +16 -2
  72. package/dist/runtime/foreground/composition/tool.registry.js +41 -38
  73. package/dist/shared/agent/activity-projection.d.ts +271 -0
  74. package/dist/shared/agent/activity-projection.js +248 -0
  75. package/dist/shared/agent/canonical-guidance.d.ts +30 -0
  76. package/dist/shared/agent/canonical-guidance.js +249 -0
  77. package/dist/shared/agent/tool.helpers.d.ts +9 -17
  78. package/dist/shared/agent/tool.runtime.js +1 -3
  79. package/dist/shared/agent/utility.tools.d.ts +11 -1
  80. package/dist/shared/agent/utility.tools.js +126 -90
  81. package/dist/shared/interfaces/auth.interface.d.ts +2 -8
  82. package/dist/shared/interfaces/chat-session.interface.js +5 -0
  83. package/dist/shared/interfaces/database.interface.d.ts +12 -5
  84. package/dist/shared/observability/request-context.d.ts +4 -40
  85. package/dist/shared/schemas/mcp-auth.schema.d.ts +87 -15
  86. package/dist/shared/schemas/mcp-auth.schema.js +49 -1
  87. package/dist/signals/application/intent.tools.js +7 -8
  88. package/package.json +10 -9
  89. package/dist/opportunity/application/opportunity.discover.d.ts +0 -215
  90. package/dist/opportunity/application/opportunity.discover.js +0 -793
  91. package/dist/opportunity/application/opportunity.discovery-continuation-finalization.d.ts +0 -34
  92. package/dist/opportunity/application/opportunity.discovery-continuation-finalization.js +0 -74
  93. package/dist/opportunity/application/opportunity.discovery-mcp-lifecycle-finalization.d.ts +0 -44
  94. package/dist/opportunity/application/opportunity.discovery-mcp-lifecycle-finalization.js +0 -92
  95. package/dist/opportunity/domain/opportunity.discovery-run-coalescing.d.ts +0 -33
  96. package/dist/opportunity/domain/opportunity.discovery-run-coalescing.js +0 -33
  97. package/dist/opportunity/domain/opportunity.discovery.contracts.d.ts +0 -45
  98. package/dist/opportunity/domain/opportunity.discovery.contracts.js +0 -1
  99. package/dist/opportunity/opportunity.discover.d.ts +0 -5
  100. package/dist/opportunity/opportunity.discover.js +0 -5
  101. package/dist/opportunity/opportunity.discovery-continuation-finalization.d.ts +0 -5
  102. package/dist/opportunity/opportunity.discovery-continuation-finalization.js +0 -5
  103. package/dist/opportunity/opportunity.discovery-mcp-lifecycle-finalization.d.ts +0 -5
  104. package/dist/opportunity/opportunity.discovery-mcp-lifecycle-finalization.js +0 -5
  105. package/dist/opportunity/opportunity.discovery-run-coalescing.d.ts +0 -5
  106. package/dist/opportunity/opportunity.discovery-run-coalescing.js +0 -5
  107. package/dist/opportunity/opportunity.discovery.contracts.d.ts +0 -5
  108. package/dist/opportunity/opportunity.discovery.contracts.js +0 -5
  109. package/dist/shared/interfaces/discovery-run.interface.d.ts +0 -70
  110. package/dist/shared/interfaces/discovery-run.interface.js +0 -1
@@ -1,793 +0,0 @@
1
- /**
2
- * Run discovery from an ad-hoc query (e.g. chat "find me a mentor", "who needs a React developer").
3
- *
4
- * Invokes the opportunity graph with the query as sourceText. The HyDE graph's
5
- * LensInferrer automatically infers search lenses from the query, replacing the
6
- * old hardcoded strategy selection. Returns formatted candidates (enriched with
7
- * profile name/bio) for chat display.
8
- *
9
- * Used by the discover_opportunities chat tool.
10
- */
11
- import { discoveryQuestionsInputMode, discoveryQuestionsTimeoutMs } from "../../capabilities/questions.runtime.facade.js";
12
- import { gatherPresenterContext } from "./opportunity.presenter.js";
13
- import { MINIMAL_MAIN_TEXT_MAX_CHARS, getPrimaryActionLabel, SECONDARY_ACTION_LABEL } from "../domain/opportunity.labels.js";
14
- import { narratorRemarkFromReasoning } from "../domain/opportunity.presentation.js";
15
- import { safeFallbackSummary } from "../domain/opportunity.safe-presentation.js";
16
- import { protocolLogger, withCallLogging } from "../../shared/observability/protocol.logger.js";
17
- import { traceAgent, tracePhase } from "../../shared/observability/trace.js";
18
- import { requestContext } from "../../shared/observability/request-context.js";
19
- import { buildDiscoveryQuestionInput } from "../domain/discovery-question.helper.js";
20
- import { invokeWithAbortSignal } from "../../shared/agent/model-signal.js";
21
- import { summarizeDiscoveryNegotiations } from "./opportunity.discovery-negotiation-summary.js";
22
- import { finalizeDiscoveryContinuation } from './opportunity.discovery-continuation-finalization.js';
23
- const logger = protocolLogger("OpportunityDiscover");
24
- const discoverFromQueryLog = protocolLogger("OpportunityDiscover:runDiscoverFromQuery");
25
- const enrichLog = protocolLogger("OpportunityDiscover:enrichOpportunities");
26
- function combineWithDeadline(callerSignal, deadlineMs) {
27
- const deadline = AbortSignal.timeout(deadlineMs);
28
- if (!callerSignal)
29
- return deadline;
30
- return AbortSignal.any([callerSignal, deadline]);
31
- }
32
- /** Max chars for bio and matchReason in chat tool results to keep context manageable. */
33
- const MAX_FIELD_CHARS = 100;
34
- function truncateForChat(s, max = MAX_FIELD_CHARS) {
35
- if (s == null || s === "")
36
- return undefined;
37
- const trimmed = s.trim();
38
- if (trimmed.length <= max)
39
- return trimmed;
40
- return trimmed.slice(0, max) + "...";
41
- }
42
- /** Statuses for which an existing connection may be shown as a card; others (accepted, rejected, expired) are only mentioned in text. */
43
- const EXISTING_CONNECTION_CARD_STATUSES = ['draft', 'latent', 'pending'];
44
- /**
45
- * Enrich raw opportunities with profile data, presentation (LLM or minimal),
46
- * and narrator chips. Shared by both `runDiscoverFromQuery` and `continueDiscovery`
47
- * to avoid duplicating the profile-lookup / presenter / card-formatting logic.
48
- *
49
- * @param input - Enrichment context (opportunities, database, viewer, presentation options).
50
- * @returns Formatted discovery candidates ready for chat or home card display.
51
- */
52
- async function enrichOpportunities(input) {
53
- const { opportunities, database, userId, chatSessionId, minimalForChat, presenter, useHomeCardFormat, debugSteps, existingOpportunityIds, preserveLifecycleStatus, targetUserId, } = input;
54
- const baseEnrichedRaw = await Promise.all(opportunities.map(async (opp) => {
55
- const viewerIsIntroducer = opp.actors.some((a) => a.role === 'introducer' && a.userId === userId);
56
- // When the viewer is the introducer, the "candidate" for the card is the agent
57
- // (the discovered person), not the patient (the intro target / onBehalfOfUserId).
58
- // For non-introducer views, pick the first non-viewer, non-introducer actor.
59
- const nonViewerNonIntroducerActors = opp.actors.filter((a) => a.userId !== userId && a.role !== 'introducer');
60
- const candidateActor = viewerIsIntroducer
61
- ? (nonViewerNonIntroducerActors.find((a) => a.role === 'agent') ?? nonViewerNonIntroducerActors[0])
62
- : nonViewerNonIntroducerActors[0];
63
- const candidateUserId = candidateActor?.userId ?? "";
64
- const viewerActor = opp.actors.find((a) => a.userId === userId);
65
- const [profile, candidateUser] = candidateUserId
66
- ? await Promise.all([database.getProfile(candidateUserId), database.getUser(candidateUserId)])
67
- : [null, null];
68
- // Skip soft-deleted users (deletedAt is set)
69
- if (candidateUser && 'deletedAt' in candidateUser && candidateUser.deletedAt)
70
- return null;
71
- const isDirectTarget = targetUserId && candidateUserId === targetUserId;
72
- if (!isDirectTarget && !candidateUser?.isGhost && !profile)
73
- return null;
74
- const confidence = typeof opp.interpretation?.confidence === "number"
75
- ? opp.interpretation.confidence
76
- : parseFloat(String(opp.interpretation?.confidence ?? 0)) || 0;
77
- return {
78
- opportunity: opp,
79
- candidateUserId,
80
- viewerRole: viewerActor?.role ?? "party",
81
- viewerApproved: viewerActor?.approved === true,
82
- viewerActedAt: viewerActor?.actedAt ?? null,
83
- candidateUser,
84
- profile,
85
- confidence,
86
- };
87
- }));
88
- const baseEnriched = baseEnrichedRaw.filter((item) => item !== null);
89
- debugSteps.push({
90
- step: "enrich_profiles",
91
- detail: `${baseEnriched.length} profile(s)`,
92
- });
93
- // Batch-fetch user records (candidates, introducers, and other party actors) for name/avatar fallback.
94
- const allActorUserIds = new Set();
95
- for (const item of baseEnriched) {
96
- for (const actor of item.opportunity.actors) {
97
- if (actor.userId && actor.userId !== userId) {
98
- allActorUserIds.add(actor.userId);
99
- }
100
- }
101
- }
102
- const candidateUserIds = [...allActorUserIds];
103
- const [viewerUser, ...userResults] = await Promise.all([
104
- database.getUser(userId),
105
- ...candidateUserIds.map((id) => database.getUser(id)),
106
- ]);
107
- const avatarByUserId = new Map();
108
- const nameByUserId = new Map();
109
- const isGhostByUserId = new Map();
110
- candidateUserIds.forEach((id, i) => {
111
- const user = userResults[i] ?? null;
112
- avatarByUserId.set(id, user?.avatar ?? null);
113
- nameByUserId.set(id, user?.name ?? null);
114
- isGhostByUserId.set(id, user?.isGhost ?? false);
115
- });
116
- const viewerName = viewerUser?.name ?? undefined;
117
- // Retry name resolution for candidates whose name is still missing.
118
- // The profile or user record may not have been ready on the first fetch
119
- // (e.g. profile generation still in flight). One retry covers transient gaps.
120
- const missingNameIds = baseEnriched
121
- .map((item) => item.candidateUserId)
122
- .filter((id) => id && !nameByUserId.get(id) && !baseEnriched.find((b) => b.candidateUserId === id && b.profile?.identity?.name));
123
- if (missingNameIds.length > 0) {
124
- const retried = await Promise.all(missingNameIds.map(async (id) => {
125
- const [profile, user] = await Promise.all([
126
- database.getProfile(id),
127
- database.getUser(id),
128
- ]);
129
- return { id, profile, user };
130
- }));
131
- for (const r of retried) {
132
- const name = r.profile?.identity?.name ?? r.user?.name ?? null;
133
- if (name)
134
- nameByUserId.set(r.id, name);
135
- // Also update the baseEnriched profile so counterpartName picks it up
136
- if (r.profile) {
137
- const item = baseEnriched.find((b) => b.candidateUserId === r.id);
138
- if (item && !item.profile)
139
- item.profile = r.profile;
140
- }
141
- if (r.user?.avatar && !avatarByUserId.get(r.id)) {
142
- avatarByUserId.set(r.id, r.user.avatar);
143
- }
144
- }
145
- enrichLog.verbose("Retried name lookup for candidates with missing names", {
146
- attempted: missingNameIds.length,
147
- resolved: retried.filter((r) => r.profile?.identity?.name ?? r.user?.name).length,
148
- });
149
- }
150
- let presentations;
151
- let homeCardPresentations;
152
- let presenterContexts;
153
- if (minimalForChat && baseEnriched.length > 0) {
154
- // Minimal path: no LLM, viewer-centric card text (introduce counterpart to viewer)
155
- const counterpartName = (n) => n.profile?.identity?.name ?? nameByUserId.get(n.candidateUserId) ?? "";
156
- homeCardPresentations = baseEnriched.map((item) => {
157
- const name = counterpartName(item)?.trim();
158
- const reasoning = item.opportunity.interpretation?.reasoning ?? "";
159
- const introducerName = item.opportunity.detection?.createdByName ?? undefined;
160
- const viewerIsIntroducer = item.opportunity.actors.some((a) => a.role === "introducer" && a.userId === userId);
161
- // For introducer view, find the second party (target user) name
162
- let secondPartyName;
163
- if (viewerIsIntroducer) {
164
- const otherPartyActors = item.opportunity.actors.filter((a) => a.role !== "introducer" && a.userId !== item.candidateUserId);
165
- if (otherPartyActors.length > 0) {
166
- const otherUserId = otherPartyActors[0].userId;
167
- secondPartyName = nameByUserId.get(otherUserId) ?? undefined;
168
- }
169
- }
170
- // Shared sanitization standard — see opportunity.safe-presentation.ts.
171
- const personalizedSummary = safeFallbackSummary(reasoning, {
172
- counterpartName: name,
173
- viewerName,
174
- introducerName,
175
- maxChars: MINIMAL_MAIN_TEXT_MAX_CHARS,
176
- emptyText: "A suggested connection.",
177
- });
178
- return {
179
- headline: viewerIsIntroducer && secondPartyName
180
- ? `${name} → ${secondPartyName}`
181
- : (name ? `Connection with ${name}` : "Suggested connection"),
182
- personalizedSummary,
183
- digestSummary: name
184
- ? `You might like meeting ${name} based on your current interests.`
185
- : "This connection may be relevant to your current interests.",
186
- suggestedAction: "Start a conversation to connect.",
187
- narratorRemark: narratorRemarkFromReasoning(reasoning, name, viewerName),
188
- primaryActionLabel: getPrimaryActionLabel(viewerIsIntroducer ? "introducer" : "party"),
189
- secondaryActionLabel: SECONDARY_ACTION_LABEL,
190
- mutualIntentsLabel: "Suggested connection",
191
- greeting: "",
192
- };
193
- });
194
- presenterContexts = baseEnriched.map((item) => ({
195
- introducerName: item.opportunity.detection.createdByName ?? undefined,
196
- }));
197
- }
198
- else if (presenter && baseEnriched.length > 0) {
199
- try {
200
- presenterContexts = await Promise.all(baseEnriched.map(({ opportunity }) => gatherPresenterContext(database, opportunity, userId)));
201
- if (useHomeCardFormat) {
202
- // Use full home card format with action labels, narrator remark, etc.
203
- const fullContexts = presenterContexts;
204
- const homeCardInputs = fullContexts.map((ctx, idx) => ({
205
- ...ctx,
206
- mutualIntentCount: undefined,
207
- opportunityStatus: baseEnriched[idx].opportunity.status,
208
- }));
209
- const llmResults = await presenter.presentHomeCardBatch(homeCardInputs, { concurrency: 5 });
210
- // Append hardcoded button labels to LLM results
211
- homeCardPresentations = llmResults.map((llm, idx) => ({
212
- ...llm,
213
- primaryActionLabel: getPrimaryActionLabel(baseEnriched[idx].viewerRole),
214
- secondaryActionLabel: SECONDARY_ACTION_LABEL,
215
- }));
216
- }
217
- else {
218
- // Use basic presentation format
219
- presentations = await presenter.presentBatch(presenterContexts, {
220
- concurrency: 5,
221
- });
222
- }
223
- }
224
- catch (error) {
225
- logger.warn("Presenter enrichment failed during opportunity discovery; returning base results without presentations", {
226
- userId,
227
- opportunitiesCount: baseEnriched.length,
228
- useHomeCardFormat,
229
- error: error instanceof Error ? error.message : String(error),
230
- });
231
- presentations = undefined;
232
- homeCardPresentations = undefined;
233
- }
234
- }
235
- const enriched = baseEnriched.map((item, idx) => {
236
- const homeCard = homeCardPresentations?.[idx];
237
- const ctx = presenterContexts?.[idx];
238
- // Build narrator chip for home card format
239
- let narratorChip;
240
- if (homeCard) {
241
- const viewerIsIntroducer = item.opportunity.actors.some((a) => a.role === "introducer" && a.userId === userId);
242
- if (viewerIsIntroducer) {
243
- narratorChip = {
244
- name: "You",
245
- text: homeCard.narratorRemark,
246
- userId: userId,
247
- };
248
- }
249
- else {
250
- const introducerActor = item.opportunity.actors.find((a) => a.role === "introducer" && a.userId !== userId);
251
- if (introducerActor) {
252
- const introducerName = ctx?.introducerName ??
253
- nameByUserId.get(introducerActor.userId) ??
254
- "Someone";
255
- narratorChip = {
256
- name: introducerName,
257
- text: homeCard.narratorRemark,
258
- userId: introducerActor.userId,
259
- avatar: avatarByUserId.get(introducerActor.userId) ?? null,
260
- };
261
- }
262
- else {
263
- narratorChip = {
264
- name: "Index",
265
- text: homeCard.narratorRemark,
266
- };
267
- }
268
- }
269
- }
270
- const isGhost = isGhostByUserId.get(item.candidateUserId) ?? false;
271
- // Build secondParty for introducer view (the other non-introducer party)
272
- let secondParty;
273
- const viewerIsIntroducerForCard = item.opportunity.actors.some((a) => a.role === "introducer" && a.userId === userId);
274
- if (viewerIsIntroducerForCard) {
275
- const otherPartyActor = item.opportunity.actors.find((a) => a.role !== "introducer" && a.userId !== item.candidateUserId);
276
- if (otherPartyActor) {
277
- const otherName = nameByUserId.get(otherPartyActor.userId) ?? undefined;
278
- if (otherName) {
279
- secondParty = {
280
- name: otherName,
281
- avatar: avatarByUserId.get(otherPartyActor.userId) ?? null,
282
- userId: otherPartyActor.userId,
283
- };
284
- }
285
- }
286
- }
287
- return {
288
- opportunityId: item.opportunity.id,
289
- userId: item.candidateUserId,
290
- name: item.profile?.identity?.name ?? nameByUserId.get(item.candidateUserId) ?? undefined,
291
- avatar: avatarByUserId.get(item.candidateUserId) ?? null,
292
- bio: truncateForChat(item.profile?.identity?.bio),
293
- matchReason: safeFallbackSummary(item.opportunity.interpretation?.reasoning, {
294
- counterpartName: item.profile?.identity?.name ?? nameByUserId.get(item.candidateUserId) ?? undefined,
295
- viewerName,
296
- maxChars: MAX_FIELD_CHARS,
297
- emptyText: "A suggested connection.",
298
- }),
299
- score: item.confidence,
300
- status: !preserveLifecycleStatus && chatSessionId && !existingOpportunityIds?.has(item.opportunity.id)
301
- ? "draft"
302
- : item.opportunity.status,
303
- viewerRole: item.viewerRole,
304
- viewerApproved: item.viewerApproved,
305
- viewerActedAt: item.viewerActedAt,
306
- candidateUser: item.candidateUser,
307
- isGhost,
308
- ...(presentations?.[idx] && { presentation: presentations[idx] }),
309
- ...(homeCard && {
310
- homeCardPresentation: homeCard,
311
- }),
312
- ...(narratorChip && { narratorChip }),
313
- ...(secondParty && { secondParty }),
314
- };
315
- });
316
- debugSteps.push({
317
- step: "format_cards",
318
- detail: `${enriched.length} card(s)`,
319
- });
320
- return enriched;
321
- }
322
- /**
323
- * Run discovery from an ad-hoc query (e.g. "find me a mentor", "who needs a React developer").
324
- * The HyDE graph's LensInferrer automatically infers search lenses from the query.
325
- * Invokes the opportunity graph and returns formatted candidates suitable for chat display.
326
- */
327
- export async function runDiscoverFromQuery(input) {
328
- const { opportunityGraph, database, userId, query, indexScope, limit = 5, triggerIntentId, targetUserId, onBehalfOfUserId, chatSessionId, trigger, negotiateTimeoutMs, } = input;
329
- if (indexScope.length === 0) {
330
- return {
331
- found: false,
332
- count: 0,
333
- message: "You need to join at least one network (community) to discover opportunities. Use read_networks to see available networks, or create one.",
334
- };
335
- }
336
- const debugSteps = [];
337
- // When query is empty, the opportunity graph uses the user's intents in scope (indexedIntents[0].payload)
338
- // Lens inference is handled automatically by the HyDE graph's LensInferrer
339
- const queryOrEmpty = query?.trim() ?? "";
340
- // Orchestrator discovery defers the initial status to the graph's
341
- // trigger-aware `resolveInitialStatus`, which opens at 'negotiating' so
342
- // the accepted-draft streaming flow can run. Ambient chat discovery still
343
- // wants the legacy 'draft' status so the chat-only lifecycle holds; other
344
- // ambient callers keep 'latent'.
345
- const isOrchestrator = trigger === 'orchestrator';
346
- const options = {
347
- limit,
348
- ...(!isOrchestrator && { initialStatus: chatSessionId ? "draft" : "latent" }),
349
- ...(chatSessionId ? { conversationId: chatSessionId } : {}),
350
- ...(negotiateTimeoutMs !== undefined && { negotiateTimeoutMs }),
351
- };
352
- return withCallLogging(logger, "runDiscoverFromQuery", {
353
- userId,
354
- queryPreview: queryOrEmpty
355
- ? queryOrEmpty.substring(0, 50)
356
- : "(using user intents in scope)",
357
- indexScopeCount: indexScope.length,
358
- limit,
359
- }, async () => {
360
- const result = await invokeWithAbortSignal(opportunityGraph, {
361
- userId,
362
- searchQuery: queryOrEmpty || undefined,
363
- // A single index resolves to the strict networkId override (membership-
364
- // validated in the scope node). Multiple indexes (e.g. a network-scoped
365
- // agent's bound network + personal network) pass through as indexScope so
366
- // the graph stays bounded instead of falling back to all networks.
367
- networkId: indexScope.length === 1 ? indexScope[0] : undefined,
368
- ...(indexScope.length > 1 ? { indexScope } : {}),
369
- triggerIntentId,
370
- targetUserId,
371
- onBehalfOfUserId,
372
- options,
373
- ...(trigger && { trigger }),
374
- });
375
- // Extract trace from graph and append to debugSteps
376
- const graphTrace = Array.isArray(result.trace) ? result.trace : [];
377
- for (const t of graphTrace) {
378
- debugSteps.push({
379
- step: t.node,
380
- detail: t.detail,
381
- ...(t.data ? { data: t.data } : {}),
382
- });
383
- }
384
- // Bail early if the graph returned an error
385
- if (result.error) {
386
- logger.warn("runDiscoverFromQuery graph returned error", { error: result.error });
387
- return {
388
- found: false,
389
- count: 0,
390
- message: "Failed to find opportunities. Please try again.",
391
- debugSteps,
392
- };
393
- }
394
- // Cache remaining candidates for pagination
395
- let pagination;
396
- const remainingCandidates = result.remainingCandidates || [];
397
- if (remainingCandidates.length > 0 && input.cache) {
398
- try {
399
- const discoveryId = crypto.randomUUID();
400
- const cacheKey = `discovery:${userId}:${discoveryId}`;
401
- await input.cache.set(cacheKey, {
402
- candidates: remainingCandidates,
403
- userId,
404
- onBehalfOfUserId,
405
- query: queryOrEmpty,
406
- indexScope,
407
- options,
408
- ...(trigger && { trigger }),
409
- }, { ttl: 1800 }); // 30 minutes
410
- pagination = {
411
- discoveryId,
412
- evaluated: (result.candidates?.length ?? 0) - remainingCandidates.length,
413
- remaining: remainingCandidates.length,
414
- };
415
- }
416
- catch (cacheErr) {
417
- logger.warn("Failed to cache discovery pagination", {
418
- userId,
419
- error: cacheErr instanceof Error ? cacheErr.message : String(cacheErr),
420
- });
421
- }
422
- }
423
- // Refine phase: a sibling of the opportunity graph in the trace tree.
424
- // Holds the three post-discovery summarization steps. Each step is its
425
- // own traced agent so it appears as a leaf in the trace UI.
426
- //
427
- // Negotiation summary: compress each raw negotiation into a fixed-size
428
- // structured digest so the question generator's prompt stays small
429
- // (a 10-candidate turn used to balloon past 60 KB and stall upstream).
430
- // Decision questions: generate up to 3 clarifying questions from the
431
- // digests + chat context.
432
- const { questionPayload } = await tracePhase("Refine", async () => {
433
- const negotiations = result.discoveryNegotiations ?? [];
434
- const negotiationDigests = input.enableQuestions && trigger === 'orchestrator' && negotiations.length > 0
435
- ? await summarizeDiscoveryNegotiations({
436
- negotiations,
437
- summarizer: input.negotiationSummary,
438
- callerSignal: requestContext.getStore()?.abortSignal,
439
- })
440
- : [];
441
- const questionPayload = await maybeBuildQuestions({
442
- trigger,
443
- enableQuestions: input.enableQuestions ?? false,
444
- chatSummary: input.chatSummary,
445
- questionGenerator: input.questionGenerator,
446
- chatSessionId,
447
- graphResult: result,
448
- negotiationDigests,
449
- query: queryOrEmpty,
450
- questionerEnqueue: input.questionerEnqueue,
451
- userId: input.userId,
452
- scopeType: input.scopeType,
453
- scopeId: input.scopeId,
454
- triggerIntentId,
455
- userContext: input.userId
456
- ? ((await input.database.getUserContext(input.userId, null))?.text ?? '')
457
- : '',
458
- });
459
- return { negotiationDigests, questionPayload };
460
- });
461
- if (result.createIntentSuggested && result.suggestedIntentDescription) {
462
- if (chatSessionId) {
463
- return {
464
- found: false,
465
- count: 0,
466
- message: "No matching opportunities found. Try a different query.",
467
- pagination,
468
- ...(questionPayload.questions !== undefined ? { questions: questionPayload.questions } : {}),
469
- ...(questionPayload.debug !== undefined ? { discoveryQuestionsDebug: questionPayload.debug } : {}),
470
- };
471
- }
472
- return {
473
- found: false,
474
- count: 0,
475
- createIntentSuggested: true,
476
- suggestedIntentDescription: result.suggestedIntentDescription,
477
- message: "No matching opportunities; add an intent with the suggested description to improve discovery.",
478
- debugSteps,
479
- pagination,
480
- ...(questionPayload.questions !== undefined ? { questions: questionPayload.questions } : {}),
481
- ...(questionPayload.debug !== undefined ? { discoveryQuestionsDebug: questionPayload.debug } : {}),
482
- };
483
- }
484
- let opportunities = Array.isArray(result.opportunities)
485
- ? result.opportunities
486
- : [];
487
- let existingOpportunityIds;
488
- const rawExistingBetweenActors = Array.isArray(result.existingBetweenActors)
489
- ? result.existingBetweenActors
490
- : [];
491
- // Orchestrator trigger populates this; ambient returns []. Kept as a
492
- // loosely-typed pass-through because DiscoverResult is consumed by
493
- // callers (chat tool, tests) that already model the narrower shape.
494
- const alreadyAcceptedPairs = Array.isArray(result
495
- .dedupAlreadyAccepted)
496
- ? result
497
- .dedupAlreadyAccepted
498
- : [];
499
- // Enrich existing-between-actors with names so the tool can say "You already have a connection with X (pending)."
500
- const existingConnections = await Promise.all(rawExistingBetweenActors.map(async (item) => {
501
- const user = await database.getUser(item.candidateUserId);
502
- return {
503
- userId: item.candidateUserId,
504
- name: user?.name ?? "Someone",
505
- ...(item.existingStatus ? { status: item.existingStatus } : {}),
506
- ...(item.existingOpportunityId ? { opportunityId: item.existingOpportunityId } : {}),
507
- };
508
- }));
509
- if (existingConnections.length > 0) {
510
- discoverFromQueryLog.verbose("Skipped duplicates; existing connections", {
511
- count: existingConnections.length,
512
- userIds: existingConnections.map((c) => c.userId),
513
- });
514
- }
515
- // Only expose existing connections as cards when status is in EXISTING_CONNECTION_CARD_STATUSES (draft, latent, pending); others are mention-only.
516
- const existingConnectionsForCards = existingConnections.filter((c) => c.status != null && EXISTING_CONNECTION_CARD_STATUSES.includes(c.status));
517
- // Fetch full opportunity data for existing connections that should be shown as cards
518
- // and merge them with the newly created opportunities
519
- if (existingConnectionsForCards.length > 0) {
520
- const existingOpps = await Promise.all(existingConnectionsForCards
521
- .filter((c) => c.opportunityId)
522
- .map((c) => database.getOpportunity(c.opportunityId)));
523
- const validExistingOpps = existingOpps.filter((o) => o != null);
524
- if (validExistingOpps.length > 0) {
525
- discoverFromQueryLog.verbose("Including existing opportunities as cards", {
526
- count: validExistingOpps.length,
527
- ids: validExistingOpps.map((o) => o.id),
528
- });
529
- existingOpportunityIds = new Set(validExistingOpps.map((o) => o.id));
530
- opportunities = [...opportunities, ...validExistingOpps];
531
- }
532
- }
533
- // Chat discovery: when we have chatSessionId we just invoked the graph; all result.opportunities
534
- // were created in this call and belong to this session. Do not filter by status: the enricher
535
- // may set status to pending/latent when merging with related opportunities, so filtering to
536
- // "draft" would incorrectly drop them.
537
- if (chatSessionId && (result.opportunities?.length ?? 0) > 0) {
538
- discoverFromQueryLog.verbose("Chat session opportunities from graph", {
539
- count: opportunities.length,
540
- statuses: opportunities.map((o) => o.status),
541
- });
542
- }
543
- debugSteps.push({
544
- step: "opportunity_graph",
545
- detail: `${opportunities.length} opportunity(ies)${existingConnections.length > 0 ? `, ${existingConnections.length} existing` : ""}`,
546
- });
547
- if (opportunities.length === 0) {
548
- if (existingConnections.length > 0) {
549
- return {
550
- found: true,
551
- count: 0,
552
- message: "No new opportunities created; you already have a connection with: " +
553
- existingConnections.map((c) => `${c.name}${c.status ? ` (${c.status})` : ""}`).join(", ") +
554
- ". View on your home page.",
555
- existingConnections: existingConnectionsForCards,
556
- existingConnectionsForMention: existingConnections,
557
- ...(alreadyAcceptedPairs.length > 0 && { alreadyAcceptedPairs }),
558
- debugSteps,
559
- pagination,
560
- ...(questionPayload.questions !== undefined ? { questions: questionPayload.questions } : {}),
561
- ...(questionPayload.debug !== undefined ? { discoveryQuestionsDebug: questionPayload.debug } : {}),
562
- };
563
- }
564
- return {
565
- found: false,
566
- count: 0,
567
- message: "No matching opportunities found. Try a different query or create intents to improve matching.",
568
- ...(alreadyAcceptedPairs.length > 0 && { alreadyAcceptedPairs }),
569
- debugSteps,
570
- pagination,
571
- ...(questionPayload.questions !== undefined ? { questions: questionPayload.questions } : {}),
572
- ...(questionPayload.debug !== undefined ? { discoveryQuestionsDebug: questionPayload.debug } : {}),
573
- };
574
- }
575
- const enriched = await enrichOpportunities({
576
- opportunities,
577
- database,
578
- userId,
579
- chatSessionId,
580
- minimalForChat: input.minimalForChat,
581
- presenter: input.presenter,
582
- useHomeCardFormat: input.useHomeCardFormat,
583
- debugSteps,
584
- existingOpportunityIds,
585
- targetUserId,
586
- });
587
- return {
588
- found: true,
589
- count: enriched.length,
590
- opportunities: enriched,
591
- ...(existingConnectionsForCards.length > 0 ? { existingConnections: existingConnectionsForCards } : {}),
592
- ...(existingConnections.length > 0 ? { existingConnectionsForMention: existingConnections } : {}),
593
- ...(alreadyAcceptedPairs.length > 0 ? { alreadyAcceptedPairs } : {}),
594
- debugSteps,
595
- pagination,
596
- ...(questionPayload.questions !== undefined ? { questions: questionPayload.questions } : {}),
597
- ...(questionPayload.debug !== undefined ? { discoveryQuestionsDebug: questionPayload.debug } : {}),
598
- };
599
- }, { context: { userId }, logOutput: false }).catch(() => {
600
- return {
601
- found: false,
602
- count: 0,
603
- message: "Failed to find opportunities. Please try again.",
604
- };
605
- });
606
- }
607
- async function maybeBuildQuestions(args) {
608
- if (!args.enableQuestions)
609
- return {};
610
- if (args.trigger !== 'orchestrator')
611
- return {};
612
- // Hardcoded — `insights` mode is planned for a later slice. Warn if the env
613
- // var is set so operators aren't surprised when reporting still says
614
- // "transcripts".
615
- if (discoveryQuestionsInputMode() === "insights") {
616
- logger.warn("QUESTIONER_DISCOVERY_INPUT_MODE=insights is not yet implemented; falling back to transcripts");
617
- }
618
- const inputMode = "transcripts";
619
- let chatContext;
620
- if (args.chatSummary && args.chatSessionId) {
621
- const sessionId = args.chatSessionId;
622
- const summary = args.chatSummary;
623
- chatContext = await traceAgent("Chat summary", async () => {
624
- try {
625
- return (await summary.getDigest(sessionId)) ?? undefined;
626
- }
627
- catch (err) {
628
- logger.warn("chatSummary.getDigest threw — proceeding without digest", {
629
- sessionId,
630
- error: err instanceof Error ? err.message : String(err),
631
- });
632
- return undefined;
633
- }
634
- }, (digest) => (digest ? "loaded" : "empty"));
635
- }
636
- // ── Async enqueue path ──────────────────────────────────────────────────
637
- // When questionerEnqueue is provided, dispatch question generation
638
- // asynchronously to the background QuestionerQueue. This replaces the
639
- // inline generator path. Questions will be persisted to DB by the queue
640
- // worker and served via GET /api/questions.
641
- if (args.questionerEnqueue && args.userId) {
642
- const summary = args.graphResult.discoverySummary ?? {
643
- totalCandidates: 0,
644
- opportunitiesFound: 0,
645
- noOpportunityCount: 0,
646
- timeoutCount: 0,
647
- roleDistribution: {},
648
- };
649
- const enqueueInput = buildDiscoveryQuestionInput({
650
- query: args.query,
651
- userContext: args.userContext ?? '',
652
- negotiationDigests: args.negotiationDigests,
653
- summary,
654
- chatContext,
655
- now: new Date().toISOString(),
656
- });
657
- try {
658
- await args.questionerEnqueue({
659
- mode: 'discovery',
660
- userId: args.userId,
661
- sourceType: 'discovery',
662
- sourceId: args.chatSessionId ?? crypto.randomUUID(),
663
- context: enqueueInput,
664
- ...(args.scopeType && args.scopeId ? { scopeType: args.scopeType, scopeId: args.scopeId } : {}),
665
- ...(args.triggerIntentId ? { triggeredByIntentId: args.triggerIntentId } : {}),
666
- conversationId: args.chatSessionId,
667
- });
668
- logger.info("Question generation enqueued to QuestionerQueue", {
669
- userId: args.userId,
670
- trigger: args.trigger,
671
- });
672
- }
673
- catch (err) {
674
- logger.warn("Failed to enqueue question generation", {
675
- error: err instanceof Error ? err.message : String(err),
676
- });
677
- }
678
- return {};
679
- }
680
- // ── Inline generator path (backward compat) ────────────────────────────
681
- if (!args.questionGenerator)
682
- return {};
683
- const negotiationDigests = args.negotiationDigests;
684
- const summary = args.graphResult.discoverySummary ?? {
685
- totalCandidates: 0,
686
- opportunitiesFound: 0,
687
- noOpportunityCount: 0,
688
- timeoutCount: 0,
689
- roleDistribution: {},
690
- };
691
- const input = buildDiscoveryQuestionInput({
692
- query: args.query,
693
- userContext: args.userContext ?? '',
694
- negotiationDigests,
695
- summary,
696
- chatContext,
697
- now: new Date().toISOString(),
698
- });
699
- const questionGenerator = args.questionGenerator;
700
- const generatorStart = Date.now();
701
- const questionsTimeoutMs = discoveryQuestionsTimeoutMs();
702
- const questionsSignal = combineWithDeadline(requestContext.getStore()?.abortSignal, questionsTimeoutMs);
703
- const genResult = await traceAgent("Decision questions", async () => {
704
- try {
705
- return await questionGenerator.generate(input, { signal: questionsSignal });
706
- }
707
- catch (err) {
708
- logger.warn("questionGenerator.generate threw — suppressing questions", {
709
- error: err instanceof Error ? err.message : String(err),
710
- });
711
- return null;
712
- }
713
- }, (r) => {
714
- const count = r?.questions?.length ?? 0;
715
- return `${count} question${count === 1 ? "" : "s"}`;
716
- });
717
- const durationMs = Date.now() - generatorStart;
718
- const finalCount = genResult?.questions?.length ?? 0;
719
- const strategies = genResult?.strategies ?? [];
720
- return {
721
- ...(genResult && genResult.questions.length > 0 ? { questions: genResult.questions } : {}),
722
- debug: {
723
- inputMode,
724
- finalCount,
725
- strategies,
726
- durationMs,
727
- },
728
- };
729
- }
730
- /**
731
- * Continue a paginated discovery by evaluating the next batch of cached candidates.
732
- * Loads candidates from Redis, invokes the opportunity graph in continue_discovery mode,
733
- * then enriches and returns the results with updated pagination metadata.
734
- *
735
- * @param input - Continuation context (graph, database, cache, discoveryId, etc.).
736
- * @returns Discovery result with enriched opportunities and pagination state.
737
- */
738
- export async function continueDiscovery(input) {
739
- const { opportunityGraph, database, cache, userId, discoveryId, expectedIndexId, limit = 20, chatSessionId, } = input;
740
- const cacheKey = `discovery:${userId}:${discoveryId}`;
741
- const cached = await cache.get(cacheKey);
742
- if (!cached) {
743
- return {
744
- found: false,
745
- count: 0,
746
- message: "Discovery session expired or not found. Please start a new search.",
747
- };
748
- }
749
- // Validate that the cached session's scope matches the current chat context
750
- if (expectedIndexId && !cached.indexScope.includes(expectedIndexId)) {
751
- return {
752
- found: false,
753
- count: 0,
754
- message: "Discovery session was created in a different context. Please start a new search.",
755
- };
756
- }
757
- const result = await invokeWithAbortSignal(opportunityGraph, {
758
- userId,
759
- searchQuery: cached.query || undefined,
760
- candidates: cached.candidates,
761
- operationMode: 'continue_discovery',
762
- onBehalfOfUserId: cached.onBehalfOfUserId,
763
- // Carry the original trigger so page 2+ stays on the same flow as page
764
- // 1 (orchestrator negotiations with 60s park window + accepted-pair
765
- // dedup, or ambient with 5-min park window).
766
- ...(cached.trigger && { trigger: cached.trigger }),
767
- options: {
768
- ...cached.options,
769
- limit,
770
- ...(chatSessionId ? { conversationId: chatSessionId } : {}),
771
- },
772
- });
773
- return finalizeDiscoveryContinuation({
774
- result,
775
- cache,
776
- cacheKey,
777
- cached,
778
- userId,
779
- discoveryId,
780
- database,
781
- enrich: (opportunities, debugSteps) => enrichOpportunities({
782
- opportunities,
783
- database,
784
- userId,
785
- chatSessionId,
786
- minimalForChat: input.minimalForChat,
787
- presenter: input.presenter,
788
- useHomeCardFormat: input.useHomeCardFormat,
789
- debugSteps,
790
- preserveLifecycleStatus: true,
791
- }),
792
- });
793
- }