@indexnetwork/protocol 4.3.2 → 4.3.4-rc.309.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 (119) hide show
  1. package/dist/chat/chat.agent.d.ts.map +1 -1
  2. package/dist/chat/chat.agent.js +11 -1
  3. package/dist/chat/chat.agent.js.map +1 -1
  4. package/dist/chat/chat.graph.d.ts +16 -0
  5. package/dist/chat/chat.graph.d.ts.map +1 -1
  6. package/dist/chat/chat.graph.js +5 -2
  7. package/dist/chat/chat.graph.js.map +1 -1
  8. package/dist/chat/chat.prompt.d.ts.map +1 -1
  9. package/dist/chat/chat.prompt.js +20 -13
  10. package/dist/chat/chat.prompt.js.map +1 -1
  11. package/dist/chat/chat.state.d.ts +6 -3
  12. package/dist/chat/chat.state.d.ts.map +1 -1
  13. package/dist/chat/chat.state.js +12 -3
  14. package/dist/chat/chat.state.js.map +1 -1
  15. package/dist/chat/chat.streamer.d.ts +5 -0
  16. package/dist/chat/chat.streamer.d.ts.map +1 -1
  17. package/dist/chat/chat.streamer.js +13 -4
  18. package/dist/chat/chat.streamer.js.map +1 -1
  19. package/dist/enrichment/enrichment.tools.d.ts.map +1 -1
  20. package/dist/enrichment/enrichment.tools.js +16 -19
  21. package/dist/enrichment/enrichment.tools.js.map +1 -1
  22. package/dist/index.d.ts +5 -3
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +2 -1
  25. package/dist/index.js.map +1 -1
  26. package/dist/intent/intent.graph.d.ts +10 -0
  27. package/dist/intent/intent.graph.d.ts.map +1 -1
  28. package/dist/intent/intent.graph.js +6 -2
  29. package/dist/intent/intent.graph.js.map +1 -1
  30. package/dist/intent/intent.state.d.ts +5 -1
  31. package/dist/intent/intent.state.d.ts.map +1 -1
  32. package/dist/intent/intent.state.js +11 -1
  33. package/dist/intent/intent.state.js.map +1 -1
  34. package/dist/intent/intent.tools.d.ts.map +1 -1
  35. package/dist/intent/intent.tools.js +63 -39
  36. package/dist/intent/intent.tools.js.map +1 -1
  37. package/dist/mcp/mcp.server.d.ts +45 -18
  38. package/dist/mcp/mcp.server.d.ts.map +1 -1
  39. package/dist/mcp/mcp.server.js +86 -45
  40. package/dist/mcp/mcp.server.js.map +1 -1
  41. package/dist/negotiation/negotiation.tools.d.ts.map +1 -1
  42. package/dist/negotiation/negotiation.tools.js +11 -7
  43. package/dist/negotiation/negotiation.tools.js.map +1 -1
  44. package/dist/network/network.graph.js +2 -2
  45. package/dist/network/network.graph.js.map +1 -1
  46. package/dist/network/network.tools.d.ts.map +1 -1
  47. package/dist/network/network.tools.js +50 -38
  48. package/dist/network/network.tools.js.map +1 -1
  49. package/dist/opportunity/opportunity.discover.d.ts +5 -0
  50. package/dist/opportunity/opportunity.discover.d.ts.map +1 -1
  51. package/dist/opportunity/opportunity.discover.js +3 -0
  52. package/dist/opportunity/opportunity.discover.js.map +1 -1
  53. package/dist/opportunity/opportunity.graph.d.ts +6 -6
  54. package/dist/opportunity/opportunity.graph.js +1 -1
  55. package/dist/opportunity/opportunity.graph.js.map +1 -1
  56. package/dist/opportunity/opportunity.pending-questions.d.ts +3 -0
  57. package/dist/opportunity/opportunity.pending-questions.d.ts.map +1 -1
  58. package/dist/opportunity/opportunity.pending-questions.js +7 -2
  59. package/dist/opportunity/opportunity.pending-questions.js.map +1 -1
  60. package/dist/opportunity/opportunity.state.d.ts +1 -1
  61. package/dist/opportunity/opportunity.tools.d.ts.map +1 -1
  62. package/dist/opportunity/opportunity.tools.js +46 -36
  63. package/dist/opportunity/opportunity.tools.js.map +1 -1
  64. package/dist/premise/premise.graph.d.ts +13 -1
  65. package/dist/premise/premise.graph.d.ts.map +1 -1
  66. package/dist/premise/premise.graph.js +11 -6
  67. package/dist/premise/premise.graph.js.map +1 -1
  68. package/dist/premise/premise.state.d.ts +5 -0
  69. package/dist/premise/premise.state.d.ts.map +1 -1
  70. package/dist/premise/premise.state.js +11 -0
  71. package/dist/premise/premise.state.js.map +1 -1
  72. package/dist/premise/premise.tools.d.ts.map +1 -1
  73. package/dist/premise/premise.tools.js +5 -0
  74. package/dist/premise/premise.tools.js.map +1 -1
  75. package/dist/questioner/questioner.tools.d.ts +1 -1
  76. package/dist/questioner/questioner.tools.d.ts.map +1 -1
  77. package/dist/questioner/questioner.tools.js +24 -13
  78. package/dist/questioner/questioner.tools.js.map +1 -1
  79. package/dist/questioner/questioner.types.d.ts +5 -0
  80. package/dist/questioner/questioner.types.d.ts.map +1 -1
  81. package/dist/questioner/questioner.types.js.map +1 -1
  82. package/dist/shared/agent/tool.factory.d.ts.map +1 -1
  83. package/dist/shared/agent/tool.factory.js +25 -16
  84. package/dist/shared/agent/tool.factory.js.map +1 -1
  85. package/dist/shared/agent/tool.helpers.d.ts +17 -18
  86. package/dist/shared/agent/tool.helpers.d.ts.map +1 -1
  87. package/dist/shared/agent/tool.helpers.js +10 -11
  88. package/dist/shared/agent/tool.helpers.js.map +1 -1
  89. package/dist/shared/agent/tool.registry.js +1 -1
  90. package/dist/shared/agent/tool.registry.js.map +1 -1
  91. package/dist/shared/agent/tool.scope.d.ts +39 -0
  92. package/dist/shared/agent/tool.scope.d.ts.map +1 -0
  93. package/dist/shared/agent/tool.scope.js +41 -0
  94. package/dist/shared/agent/tool.scope.js.map +1 -0
  95. package/dist/shared/assignment/network-assignment.policy.d.ts +8 -5
  96. package/dist/shared/assignment/network-assignment.policy.d.ts.map +1 -1
  97. package/dist/shared/assignment/network-assignment.policy.js +11 -6
  98. package/dist/shared/assignment/network-assignment.policy.js.map +1 -1
  99. package/dist/shared/hyde/hyde.graph.d.ts +6 -6
  100. package/dist/shared/hyde/hyde.state.d.ts +2 -2
  101. package/dist/shared/interfaces/auth.interface.d.ts +3 -3
  102. package/dist/shared/interfaces/auth.interface.js.map +1 -1
  103. package/dist/shared/interfaces/database.interface.d.ts +15 -3
  104. package/dist/shared/interfaces/database.interface.d.ts.map +1 -1
  105. package/dist/shared/interfaces/database.interface.js.map +1 -1
  106. package/dist/shared/interfaces/discovery-run.interface.d.ts +1 -1
  107. package/dist/shared/interfaces/discovery-run.interface.d.ts.map +1 -1
  108. package/dist/shared/interfaces/discovery-run.interface.js.map +1 -1
  109. package/dist/shared/interfaces/enrichment-run.interface.d.ts +1 -1
  110. package/dist/shared/interfaces/enrichment-run.interface.d.ts.map +1 -1
  111. package/dist/shared/interfaces/enrichment-run.interface.js.map +1 -1
  112. package/dist/shared/interfaces/queue.interface.d.ts +8 -2
  113. package/dist/shared/interfaces/queue.interface.d.ts.map +1 -1
  114. package/dist/shared/interfaces/queue.interface.js.map +1 -1
  115. package/dist/shared/schemas/network-assignment.schema.d.ts +2 -2
  116. package/dist/shared/schemas/pending-question.schema.d.ts +5 -0
  117. package/dist/shared/schemas/pending-question.schema.d.ts.map +1 -1
  118. package/dist/shared/schemas/pending-question.schema.js.map +1 -1
  119. package/package.json +1 -1
@@ -2,6 +2,7 @@ import { z } from "zod";
2
2
  import { requestContext } from "../shared/observability/request-context.js";
3
3
  import { renderNetworkContext } from '../shared/network/metadata.renderer.js';
4
4
  import { success, error, UUID_REGEX } from "../shared/agent/tool.helpers.js";
5
+ import { focusedNetworkId, focusedNetworkLabel } from "../shared/agent/tool.scope.js";
5
6
  import { NetworkRecommender } from "./network.recommender.js";
6
7
  // Lazy singleton — only instantiated on first onboarding ranking call so that
7
8
  // importing this module does not require OPENROUTER_API_KEY at load time.
@@ -34,12 +35,14 @@ export function createNetworkTools(defineTool, deps) {
34
35
  if (query.userId && query.userId.trim() !== context.userId) {
35
36
  return error("You can only list your own indexes. Omit userId to see the current user's indexes.");
36
37
  }
38
+ const scopedNetworkId = focusedNetworkId(context);
39
+ const scopedIndexLabel = focusedNetworkLabel(context);
37
40
  const _readIndexGraphStart = Date.now();
38
41
  const _readIndexTraceEmitter = requestContext.getStore()?.traceEmitter;
39
42
  _readIndexTraceEmitter?.({ type: "graph_start", name: "index" });
40
43
  const result = await graphs.index.invoke({
41
44
  userId: context.userId,
42
- networkId: context.networkId || undefined,
45
+ networkId: scopedNetworkId,
43
46
  operationMode: 'read',
44
47
  showAll: false, // Never allow bypass - strict scope enforcement
45
48
  });
@@ -57,13 +60,13 @@ export function createNetworkTools(defineTool, deps) {
57
60
  ...(Array.isArray(rr.publicNetworks) ? { publicNetworks: enrichWithContext(rr.publicNetworks) } : {}),
58
61
  };
59
62
  // When scoped, add clear metadata so model knows results are limited
60
- if (context.networkId) {
63
+ if (scopedNetworkId) {
61
64
  return success({
62
65
  ...enriched,
63
66
  scopeRestriction: {
64
67
  isScoped: true,
65
- scopedToIndex: context.indexName ?? context.networkId,
66
- message: `Results are limited to "${context.indexName ?? 'this index'}" because this chat is scoped to that community. The user may belong to other communities not shown here.`,
68
+ scopedToIndex: scopedIndexLabel,
69
+ message: `Results are limited to "${scopedIndexLabel}" because this chat is scoped to that community. The user may belong to other communities not shown here.`,
67
70
  },
68
71
  _graphTimings: [{ name: 'index', durationMs: _readIndexGraphMs, agents: result.agentTimings ?? [] }],
69
72
  });
@@ -163,6 +166,8 @@ export function createNetworkTools(defineTool, deps) {
163
166
  userId: z.string().optional().describe("User ID — lists that user's index memberships. Omit to get the current user's memberships. When combined with networkId, checks if this user is in that specific index."),
164
167
  }),
165
168
  handler: async ({ context, query }) => {
169
+ const scopedNetworkId = focusedNetworkId(context);
170
+ const scopedIndexLabel = focusedNetworkLabel(context);
166
171
  const networkId = query.networkId?.trim() || undefined;
167
172
  const userId = query.userId?.trim() || undefined;
168
173
  if (networkId && !UUID_REGEX.test(networkId)) {
@@ -171,8 +176,8 @@ export function createNetworkTools(defineTool, deps) {
171
176
  // Mode 1: list members of an index
172
177
  if (networkId && !userId) {
173
178
  // Enforce strict scope: when chat is index-scoped, only allow querying that index
174
- if (context.networkId && networkId !== context.networkId) {
175
- return error(`This chat is scoped to ${context.indexName ?? 'this index'}. You can only query members of this index.`);
179
+ if (scopedNetworkId && networkId !== scopedNetworkId) {
180
+ return error(`This chat is scoped to ${scopedIndexLabel}. You can only query members of this index.`);
176
181
  }
177
182
  const _readMembersGraphStart = Date.now();
178
183
  const _readMembersTraceEmitter = requestContext.getStore()?.traceEmitter;
@@ -201,8 +206,8 @@ export function createNetworkTools(defineTool, deps) {
201
206
  const callerMemberships = await userDb.getNetworkMemberships();
202
207
  if (networkId) {
203
208
  // Strict scope enforcement: when chat is index-scoped, only allow querying that index
204
- if (context.networkId && networkId !== context.networkId) {
205
- return error(`This chat is scoped to ${context.indexName ?? 'this index'}. You can only query membership in this community.`);
209
+ if (scopedNetworkId && networkId !== scopedNetworkId) {
210
+ return error(`This chat is scoped to ${scopedIndexLabel}. You can only query membership in this community.`);
206
211
  }
207
212
  const callerInIndex = callerMemberships.some((m) => m.networkId === networkId);
208
213
  if (!callerInIndex) {
@@ -217,29 +222,29 @@ export function createNetworkTools(defineTool, deps) {
217
222
  }
218
223
  else {
219
224
  // Strict scope enforcement: when chat is index-scoped, only check the scoped index
220
- if (context.networkId) {
221
- const isMember = await systemDb.isNetworkMember(context.networkId, targetUserId);
225
+ if (scopedNetworkId) {
226
+ const isMember = await systemDb.isNetworkMember(scopedNetworkId, targetUserId);
222
227
  if (isMember) {
223
228
  return success({
224
229
  isMember: true,
225
230
  userId: targetUserId,
226
- networkId: context.networkId,
231
+ networkId: scopedNetworkId,
227
232
  scopeRestriction: {
228
233
  isScoped: true,
229
- scopedToIndex: context.indexName ?? context.networkId,
230
- message: `This chat is scoped to "${context.indexName ?? 'this index'}". Only membership in this community is shown.`,
234
+ scopedToIndex: scopedIndexLabel,
235
+ message: `This chat is scoped to "${scopedIndexLabel}". Only membership in this community is shown.`,
231
236
  },
232
237
  });
233
238
  }
234
239
  return success({
235
240
  isMember: false,
236
241
  userId: targetUserId,
237
- networkId: context.networkId,
242
+ networkId: scopedNetworkId,
238
243
  message: "User is not a member of this community.",
239
244
  scopeRestriction: {
240
245
  isScoped: true,
241
- scopedToIndex: context.indexName ?? context.networkId,
242
- message: `This chat is scoped to "${context.indexName ?? 'this index'}". Only membership in this community was checked.`,
246
+ scopedToIndex: scopedIndexLabel,
247
+ message: `This chat is scoped to "${scopedIndexLabel}". Only membership in this community was checked.`,
243
248
  },
244
249
  });
245
250
  }
@@ -268,19 +273,18 @@ export function createNetworkTools(defineTool, deps) {
268
273
  else {
269
274
  // Own memberships - use userDb
270
275
  memberships = await userDb.getNetworkMemberships();
271
- // NOTE: context.networkId here is the *focus* of the scoped chat — it filters
272
- // what we show, not what we can reach. indexScope is the reach; the bound
273
- // network is one element of it. See IND-306 for the equivalent in read_intents.
276
+ // The scope envelope's network id is the focus of the scoped chat — it filters
277
+ // what we show, not what we can reach. Concrete reach is derived separately.
274
278
  // Strict scope enforcement: when chat is index-scoped, only return the scoped index membership
275
- if (context.networkId && !networkId) {
276
- memberships = memberships.filter((m) => m.networkId === context.networkId);
279
+ if (scopedNetworkId && !networkId) {
280
+ memberships = memberships.filter((m) => m.networkId === scopedNetworkId);
277
281
  }
278
282
  }
279
283
  // If both networkId and userId: filter to that specific membership
280
284
  if (networkId) {
281
285
  // Strict scope enforcement: when chat is index-scoped, only allow querying that index
282
- if (context.networkId && networkId !== context.networkId) {
283
- return error(`This chat is scoped to ${context.indexName ?? 'this index'}. You can only query membership in this community.`);
286
+ if (scopedNetworkId && networkId !== scopedNetworkId) {
287
+ return error(`This chat is scoped to ${scopedIndexLabel}. You can only query membership in this community.`);
284
288
  }
285
289
  const callerMemberships = await userDb.getNetworkMemberships();
286
290
  const callerInIndex = targetUserId === context.userId ||
@@ -302,7 +306,7 @@ export function createNetworkTools(defineTool, deps) {
302
306
  });
303
307
  }
304
308
  // When scoped, add clear metadata so model knows results are limited
305
- if (context.networkId && targetUserId === context.userId) {
309
+ if (scopedNetworkId && targetUserId === context.userId) {
306
310
  return success({
307
311
  userId: targetUserId,
308
312
  count: memberships.length,
@@ -314,8 +318,8 @@ export function createNetworkTools(defineTool, deps) {
314
318
  })),
315
319
  scopeRestriction: {
316
320
  isScoped: true,
317
- scopedToIndex: context.indexName ?? context.networkId,
318
- message: `Results are limited to "${context.indexName ?? 'this index'}" because this chat is scoped to that community. The user may belong to other communities not shown here.`,
321
+ scopedToIndex: scopedIndexLabel,
322
+ message: `Results are limited to "${scopedIndexLabel}" because this chat is scoped to that community. The user may belong to other communities not shown here.`,
319
323
  },
320
324
  });
321
325
  }
@@ -353,13 +357,15 @@ export function createNetworkTools(defineTool, deps) {
353
357
  settings: updateNetworkSettingsSchema.describe("Object with fields to update. All fields are optional — only include the ones to change. title: display name. prompt: purpose description (used for intent auto-assignment). imageUrl: community image URL (null to remove). joinPolicy: 'anyone' or 'invite_only'. allowGuestVibeCheck: boolean."),
354
358
  }),
355
359
  handler: async ({ context, query }) => {
356
- const effectiveIndexId = (query.networkId?.trim() || context.networkId) ?? null;
360
+ const scopedNetworkId = focusedNetworkId(context);
361
+ const scopedIndexLabel = focusedNetworkLabel(context);
362
+ const effectiveIndexId = (query.networkId?.trim() || scopedNetworkId) ?? null;
357
363
  if (!effectiveIndexId || !UUID_REGEX.test(effectiveIndexId)) {
358
364
  return error("Valid networkId required.");
359
365
  }
360
366
  // Strict scope enforcement: when chat is index-scoped, only allow updating that index
361
- if (context.networkId && effectiveIndexId !== context.networkId) {
362
- return error(`This chat is scoped to ${context.indexName ?? 'this index'}. You can only update this community's settings.`);
367
+ if (scopedNetworkId && effectiveIndexId !== scopedNetworkId) {
368
+ return error(`This chat is scoped to ${scopedIndexLabel}. You can only update this community's settings.`);
363
369
  }
364
370
  const _updateNetworkGraphStart = Date.now();
365
371
  const _updateNetworkTraceEmitter = requestContext.getStore()?.traceEmitter;
@@ -437,13 +443,15 @@ export function createNetworkTools(defineTool, deps) {
437
443
  networkId: z.string().optional().describe("Index UUID to delete. Get from read_networks. Defaults to the scoped index in index-scoped chats. Cannot be a personal index."),
438
444
  }),
439
445
  handler: async ({ context, query }) => {
440
- const networkId = query.networkId?.trim() || context.networkId;
446
+ const scopedNetworkId = focusedNetworkId(context);
447
+ const scopedIndexLabel = focusedNetworkLabel(context);
448
+ const networkId = query.networkId?.trim() || scopedNetworkId;
441
449
  if (!networkId || !UUID_REGEX.test(networkId)) {
442
450
  return error("Valid networkId required.");
443
451
  }
444
452
  // Strict scope enforcement: when chat is index-scoped, only allow deleting that index
445
- if (context.networkId && networkId !== context.networkId) {
446
- return error(`This chat is scoped to ${context.indexName ?? 'this index'}. You can only delete this community.`);
453
+ if (scopedNetworkId && networkId !== scopedNetworkId) {
454
+ return error(`This chat is scoped to ${scopedIndexLabel}. You can only delete this community.`);
447
455
  }
448
456
  const _deleteNetworkGraphStart = Date.now();
449
457
  const _deleteNetworkTraceEmitter = requestContext.getStore()?.traceEmitter;
@@ -476,14 +484,16 @@ export function createNetworkTools(defineTool, deps) {
476
484
  networkId: z.string().optional().describe("Index UUID to add the member to. Get from read_networks. Defaults to the scoped index in index-scoped chats."),
477
485
  }),
478
486
  handler: async ({ context, query }) => {
479
- const networkId = query.networkId?.trim() || context.networkId;
487
+ const scopedNetworkId = focusedNetworkId(context);
488
+ const scopedIndexLabel = focusedNetworkLabel(context);
489
+ const networkId = query.networkId?.trim() || scopedNetworkId;
480
490
  const targetUserId = query.userId?.trim() || context.userId;
481
491
  if (!networkId || !UUID_REGEX.test(networkId)) {
482
492
  return error("Invalid index ID format. Use the exact UUID from read_networks.");
483
493
  }
484
494
  // Strict scope enforcement: when chat is index-scoped, only allow adding to that index
485
- if (context.networkId && networkId !== context.networkId) {
486
- return error(`This chat is scoped to ${context.indexName ?? 'this index'}. You can only add members to this community.`);
495
+ if (scopedNetworkId && networkId !== scopedNetworkId) {
496
+ return error(`This chat is scoped to ${scopedIndexLabel}. You can only add members to this community.`);
487
497
  }
488
498
  const _createMembershipGraphStart = Date.now();
489
499
  const _createMembershipTraceEmitter = requestContext.getStore()?.traceEmitter;
@@ -523,7 +533,9 @@ export function createNetworkTools(defineTool, deps) {
523
533
  networkId: z.string().optional().describe("Index UUID to remove the member from. Get from read_networks. Defaults to the scoped index in index-scoped chats."),
524
534
  }),
525
535
  handler: async ({ context, query }) => {
526
- const networkId = query.networkId?.trim() || context.networkId;
536
+ const scopedNetworkId = focusedNetworkId(context);
537
+ const scopedIndexLabel = focusedNetworkLabel(context);
538
+ const networkId = query.networkId?.trim() || scopedNetworkId;
527
539
  const targetUserId = query.userId?.trim();
528
540
  if (!networkId || !UUID_REGEX.test(networkId)) {
529
541
  return error("Valid networkId required. Use the exact UUID from read_networks.");
@@ -532,8 +544,8 @@ export function createNetworkTools(defineTool, deps) {
532
544
  return error("userId is required.");
533
545
  }
534
546
  // Strict scope enforcement: when chat is index-scoped, only allow that index
535
- if (context.networkId && networkId !== context.networkId) {
536
- return error(`This chat is scoped to ${context.indexName ?? 'this index'}. You can only manage members of this community.`);
547
+ if (scopedNetworkId && networkId !== scopedNetworkId) {
548
+ return error(`This chat is scoped to ${scopedIndexLabel}. You can only manage members of this community.`);
537
549
  }
538
550
  const _deleteMembershipGraphStart = Date.now();
539
551
  const _deleteMembershipTraceEmitter = requestContext.getStore()?.traceEmitter;
@@ -1 +1 @@
1
- {"version":3,"file":"network.tools.js","sourceRoot":"/","sources":["network/network.tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,oBAAoB,EAAE,MAAM,wCAAwC,CAAC;AAG9E,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAC7E,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAE9D,8EAA8E;AAC9E,0EAA0E;AAC1E,IAAI,WAA2C,CAAC;AAEhD,MAAM,UAAU,kBAAkB,CAAC,UAAsB,EAAE,IAAc;IACvE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC;IAE1C,MAAM,iBAAiB,GAAG,CAAC,QAAwC,EAAE,EAAE,CACrE,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,E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,EAAE,oBAAoB,EAAE,UAAU,EAAE,wBAAwB,EAAE,CAAC,CAAC;YAEzH,IAAI,MAAM,CAAC,cAAc,EAAE,CAAC;gBAC1B,IAAI,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,CAAC;oBAClC,OAAO,OAAO,CAAC;wBACb,OAAO,EAAE,IAAI;wBACb,OAAO,EAAE,MAAM,CAAC,cAAc,CAAC,OAAO;wBACtC,aAAa,EAAE,CAAC,EAAE,IAAI,EAAE,oBAAoB,EAAE,UAAU,EAAE,wBAAwB,EAAE,MAAM,EAAE,MAAM,CAAC,YAAY,IAAI,EAAE,EAAE,CAAC;qBACzH,CAAC,CAAC;gBACL,CAAC;gBACD,OAAO,KAAK,CAAC,MAAM,CAAC,cAAc,CAAC,KAAK,IAAI,0BAA0B,CAAC,CAAC;YAC1E,CAAC;YACD,OAAO,KAAK,CAAC,0BAA0B,CAAC,CAAC;QAC3C,CAAC;KACF,CAAC,CAAC;IAEH,OAAO,CAAC,WAAW,EAAE,oBAAoB,EAAE,aAAa,EAAE,aAAa,EAAE,aAAa,EAAE,uBAAuB,EAAE,uBAAuB,CAAU,CAAC;AACrJ,CAAC","sourcesContent":["import { z } from \"zod\";\n\nimport { requestContext } from \"../shared/observability/request-context.js\";\nimport { renderNetworkContext } from '../shared/network/metadata.renderer.js';\n\nimport type { DefineTool, ToolDeps } from \"../shared/agent/tool.helpers.js\";\nimport { success, error, UUID_REGEX } from \"../shared/agent/tool.helpers.js\";\nimport { NetworkRecommender } from \"./network.recommender.js\";\n\n// Lazy singleton — only instantiated on first onboarding ranking call so that\n// importing this module does not require OPENROUTER_API_KEY at load time.\nlet recommender: NetworkRecommender | undefined;\n\nexport function createNetworkTools(defineTool: DefineTool, deps: ToolDeps) {\n const { graphs, userDb, systemDb } = deps;\n\n const enrichWithContext = (networks: Array<Record<string, unknown>>) =>\n networks.map((n) => ({\n ...n,\n renderedContext: renderNetworkContext({\n type: (n.type as string) ?? 'community',\n title: (n.title as string) ?? '',\n prompt: n.prompt as string | undefined,\n metadata: (n.metadata as Record<string, unknown>) ?? {},\n }),\n }));\n\n const readIndexes = defineTool({\n name: \"read_networks\",\n description:\n \"Lists the authenticated user's networks (communities), including ones they own and public communities they can join.\\n\\n\" +\n \"**When to use:** To find network IDs for scoping other operations (read_intents, discover_opportunities, read_network_memberships), \" +\n \"or to show the user which communities they belong to.\\n\\n\" +\n \"**Returns:** Up to three lists — `memberOf` (networks the user joined), `owns` (networks the user created), and `publicNetworks` \" +\n \"(publicly joinable communities the user is not yet a member of). Entries in `memberOf` include `isPersonal` set to `true` for the user's \" +\n \"personal network.\\n\\n\" +\n \"**Note:** In index-scoped chats, only the scoped network is returned. During onboarding, `orderedNetworkIds` \" +\n \"may be returned alongside `publicNetworks` \\u2014 a ranked array of network IDs ordered by relevance to the user's profile (omitted when ranking is unavailable or fails).\",\n querySchema: z.object({\n userId: z.string().optional().describe(\"Must be the current user's ID or omitted. Cannot list another user's indexes.\"),\n }),\n handler: async ({ context, query }) => {\n if (query.userId && query.userId.trim() !== context.userId) {\n return error(\"You can only list your own indexes. Omit userId to see the current user's indexes.\");\n }\n\n const _readIndexGraphStart = Date.now();\n const _readIndexTraceEmitter = requestContext.getStore()?.traceEmitter;\n _readIndexTraceEmitter?.({ type: \"graph_start\", name: \"index\" });\n const result = await graphs.index.invoke({\n userId: context.userId,\n networkId: context.networkId || undefined,\n operationMode: 'read' as const,\n showAll: false, // Never allow bypass - strict scope enforcement\n });\n const _readIndexGraphMs = Date.now() - _readIndexGraphStart;\n _readIndexTraceEmitter?.({ type: \"graph_end\", name: \"index\", durationMs: _readIndexGraphMs });\n\n if (result.error) {\n return error(result.error);\n }\n if (result.readResult) {\n const rr = result.readResult as Record<string, unknown>;\n const enriched = {\n ...rr,\n ...(Array.isArray(rr.memberOf) ? { memberOf: enrichWithContext(rr.memberOf as Array<Record<string, unknown>>) } : {}),\n ...(Array.isArray(rr.owns) ? { owns: enrichWithContext(rr.owns as Array<Record<string, unknown>>) } : {}),\n ...(Array.isArray(rr.publicNetworks) ? { publicNetworks: enrichWithContext(rr.publicNetworks as Array<Record<string, unknown>>) } : {}),\n };\n\n // When scoped, add clear metadata so model knows results are limited\n if (context.networkId) {\n return success({\n ...enriched,\n scopeRestriction: {\n isScoped: true,\n scopedToIndex: context.indexName ?? context.networkId,\n message: `Results are limited to \"${context.indexName ?? 'this index'}\" because this chat is scoped to that community. The user may belong to other communities not shown here.`,\n },\n _graphTimings: [{ name: 'index', durationMs: _readIndexGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n // Onboarding-only: rank public networks by relevance to the user's global\n // user_context paragraph (the profile-replacing identity text). Guard: only\n // when isOnboarding, not scoped, there are public networks to rank, and a\n // user_context is resolvable (generated on demand by the injected resolver).\n let orderedNetworkIds: string[] | undefined;\n const userContext = deps.getUserContextText ? await deps.getUserContextText(context.userId) : \"\";\n if (\n context.isOnboarding &&\n userContext &&\n Array.isArray(enriched.publicNetworks) &&\n (enriched.publicNetworks as Array<Record<string, unknown>>).length > 0\n ) {\n // Cap at 50 to bound LLM context window usage (matches the UI's discoverPublicIndexes(1, 50)).\n const publicNetworksForRanking = (enriched.publicNetworks as Array<Record<string, unknown>>)\n .slice(0, 50)\n .map((n) => ({\n networkId: n.networkId as string,\n renderedContext: (n.renderedContext as string) ?? `## ${n.title as string}`,\n }));\n const rankFn = deps.networkRanker ?? (async (input) => {\n try {\n recommender ??= new NetworkRecommender();\n return await recommender.invoke(input);\n } catch (err) {\n // e.g. missing OPENROUTER_API_KEY — degrade gracefully, omit orderedNetworkIds\n console.warn(\"[read_networks] NetworkRecommender unavailable, skipping ranking:\", err);\n return null;\n }\n });\n const rankingResult = await rankFn({\n userContext,\n networks: publicNetworksForRanking,\n }).catch((err: unknown) => {\n // Catches errors from a custom deps.networkRanker (the default fallback\n // handles its own errors internally). Degrade gracefully: omit orderedNetworkIds.\n console.warn(\"[read_networks] networkRanker threw, skipping ranking:\", err);\n deps.reportToolError?.(err, { operation: \"network-ranking\", toolName: \"read_networks\", userId: context.userId });\n return null;\n });\n if (rankingResult) {\n // Normalize LLM output against the ranked slice (top 50):\n // keep only IDs from the input set, de-dupe preserving order, then\n // append any slice IDs the model omitted. Networks beyond the top-50\n // slice are not in orderedNetworkIds and will sort to the tail in the\n // frontend (consistent with the UI's own 50-item page size).\n const inputIds = publicNetworksForRanking.map((n) => n.networkId);\n const inputIdSet = new Set(inputIds);\n const seen = new Set<string>();\n const normalized: string[] = [];\n for (const id of rankingResult.rankedNetworkIds) {\n if (inputIdSet.has(id) && !seen.has(id)) {\n normalized.push(id);\n seen.add(id);\n }\n }\n for (const id of inputIds) {\n if (!seen.has(id)) normalized.push(id);\n }\n orderedNetworkIds = normalized;\n }\n }\n\n return success({\n ...enriched,\n ...(orderedNetworkIds !== undefined ? { orderedNetworkIds } : {}),\n _graphTimings: [{ name: 'index', durationMs: _readIndexGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n return error(\"Failed to fetch index information.\");\n },\n });\n\n const readIndexMemberships = defineTool({\n name: \"read_network_memberships\",\n description:\n \"Reads index membership information — who is in which community. Essential for understanding the social graph before \" +\n \"creating introductions or exploring intents.\\n\\n\" +\n \"**Usage modes:**\\n\" +\n \"- With `networkId` only: lists ALL members of that index — returns userId, name, avatar, permissions (owner/member), intentCount, and joinedAt. \" +\n \"Use this to see who's in a community before browsing their intents or creating introductions.\\n\" +\n \"- With `userId` only (or omit for self): lists all indexes that user belongs to — returns networkId, networkTitle, permissions, joinedAt.\\n\" +\n \"- With both `networkId` and `userId`: checks whether that specific user is a member of that specific index (returns isMember boolean).\\n\\n\" +\n \"**When to use:** Before creating introductions (need to verify shared index membership), to explore community members, \" +\n \"or to check if a user belongs to a specific index.\\n\\n\" +\n \"**Returns:** Member list with user details, or membership list with index details, or a membership check result.\\n\\n\" +\n \"**Personal index semantics.** The personal index (`isPersonal: true` on the membership) is the user's \" +\n \"contact list — members of that index are the user's contacts. For another user, this tool only reveals the \" +\n \"indexes you already share with them.\\n\\n\" +\n \"**Shared-context pattern.** To find overlap with another user: (1) omit `userId` to read your own \" +\n \"memberships, (2) call this tool with the other person's actual `userId` to get the shared indexes, \" +\n \"(3) call read_intents for each shared network to see what each is looking for there, (4) call \" +\n \"read_user_contexts for the other party. That sequence gives you enough to decide whether to propose a \" +\n \"direct connection or an introduction.\",\n querySchema: z.object({\n networkId: z.string().optional().describe(\"Index UUID — lists all members of this index. Get from read_networks. In index-scoped chats, only the scoped index can be queried.\"),\n userId: z.string().optional().describe(\"User ID — lists that user's index memberships. Omit to get the current user's memberships. When combined with networkId, checks if this user is in that specific index.\"),\n }),\n handler: async ({ context, query }) => {\n const networkId = query.networkId?.trim() || undefined;\n const userId = query.userId?.trim() || undefined;\n\n if (networkId && !UUID_REGEX.test(networkId)) {\n return error(\"Invalid index ID format. Use the exact UUID from read_networks.\");\n }\n\n // Mode 1: list members of an index\n if (networkId && !userId) {\n // Enforce strict scope: when chat is index-scoped, only allow querying that index\n if (context.networkId && networkId !== context.networkId) {\n return error(\n `This chat is scoped to ${context.indexName ?? 'this index'}. You can only query members of this index.`\n );\n }\n\n const _readMembersGraphStart = Date.now();\n const _readMembersTraceEmitter = requestContext.getStore()?.traceEmitter;\n _readMembersTraceEmitter?.({ type: \"graph_start\", name: \"network_membership\" });\n const result = await graphs.networkMembership.invoke({\n userId: context.userId,\n networkId,\n operationMode: 'read' as const,\n });\n const _readMembersGraphMs = Date.now() - _readMembersGraphStart;\n _readMembersTraceEmitter?.({ type: \"graph_end\", name: \"network_membership\", durationMs: _readMembersGraphMs });\n\n if (result.error) {\n return error(result.error);\n }\n if (result.readResult) {\n return success({ ...result.readResult, _graphTimings: [{ name: 'network_membership', durationMs: _readMembersGraphMs, agents: result.agentTimings ?? [] }] });\n }\n return error(\"Failed to fetch index members.\");\n }\n\n // Mode 2: list a user's memberships (indexes they belong to)\n const targetUserId = userId || context.userId;\n\n // Use userDb for own memberships, but systemDb access is implicit through shared index scope\n let memberships: Awaited<ReturnType<typeof userDb.getNetworkMemberships>>;\n if (targetUserId !== context.userId) {\n // Cross-user access: systemDb will validate shared index membership\n const callerMemberships = await userDb.getNetworkMemberships();\n if (networkId) {\n // Strict scope enforcement: when chat is index-scoped, only allow querying that index\n if (context.networkId && networkId !== context.networkId) {\n return error(\n `This chat is scoped to ${context.indexName ?? 'this index'}. You can only query membership in this community.`\n );\n }\n\n const callerInIndex = callerMemberships.some((m) => m.networkId === networkId);\n if (!callerInIndex) {\n return error(\n \"Unauthorized: you can only view another user's membership in an index you belong to. Provide your own userId or omit userId for your memberships.\",\n );\n }\n // Check if target user is in the index (systemDb validates scope)\n const isMember = await systemDb.isNetworkMember(networkId, targetUserId);\n if (isMember) {\n return success({ isMember: true, userId: targetUserId, networkId });\n }\n return success({ isMember: false, userId: targetUserId, networkId, message: \"User is not a member of this index.\" });\n } else {\n // Strict scope enforcement: when chat is index-scoped, only check the scoped index\n if (context.networkId) {\n const isMember = await systemDb.isNetworkMember(context.networkId, targetUserId);\n if (isMember) {\n return success({\n isMember: true,\n userId: targetUserId,\n networkId: context.networkId,\n scopeRestriction: {\n isScoped: true,\n scopedToIndex: context.indexName ?? context.networkId,\n message: `This chat is scoped to \"${context.indexName ?? 'this index'}\". Only membership in this community is shown.`,\n },\n });\n }\n return success({\n isMember: false,\n userId: targetUserId,\n networkId: context.networkId,\n message: \"User is not a member of this community.\",\n scopeRestriction: {\n isScoped: true,\n scopedToIndex: context.indexName ?? context.networkId,\n message: `This chat is scoped to \"${context.indexName ?? 'this index'}\". Only membership in this community was checked.`,\n },\n });\n }\n\n // Unscoped chat: show overlap with shared indexes (intersection of caller and target memberships)\n const sharedIndexes: typeof callerMemberships = [];\n for (const m of callerMemberships) {\n if (await systemDb.isNetworkMember(m.networkId, targetUserId)) {\n sharedIndexes.push(m);\n }\n }\n if (sharedIndexes.length === 0) {\n return error(\n \"Unauthorized: you can only view another user's memberships if you share at least one index, or request your own memberships.\",\n );\n }\n // Return only the indexes that are shared\n return success({\n userId: targetUserId,\n count: sharedIndexes.length,\n memberships: sharedIndexes.map((m) => ({\n networkId: m.networkId,\n networkTitle: m.networkTitle,\n })),\n note: \"Only showing shared indexes.\",\n });\n }\n } else {\n // Own memberships - use userDb\n memberships = await userDb.getNetworkMemberships();\n\n // NOTE: context.networkId here is the *focus* of the scoped chat — it filters\n // what we show, not what we can reach. indexScope is the reach; the bound\n // network is one element of it. See IND-306 for the equivalent in read_intents.\n // Strict scope enforcement: when chat is index-scoped, only return the scoped index membership\n if (context.networkId && !networkId) {\n memberships = memberships.filter((m) => m.networkId === context.networkId);\n }\n }\n\n // If both networkId and userId: filter to that specific membership\n if (networkId) {\n // Strict scope enforcement: when chat is index-scoped, only allow querying that index\n if (context.networkId && networkId !== context.networkId) {\n return error(\n `This chat is scoped to ${context.indexName ?? 'this index'}. You can only query membership in this community.`\n );\n }\n\n const callerMemberships = await userDb.getNetworkMemberships();\n const callerInIndex =\n targetUserId === context.userId ||\n callerMemberships.some((m) => m.networkId === networkId);\n if (!callerInIndex) {\n return error(\n \"Unauthorized: you can only view membership in an index you belong to.\",\n );\n }\n const match = memberships.find((m) => m.networkId === networkId);\n if (!match) {\n return success({ isMember: false, userId: targetUserId, networkId, message: \"User is not a member of this index.\" });\n }\n return success({\n isMember: true,\n userId: targetUserId,\n networkId,\n networkTitle: match.networkTitle,\n permissions: match.permissions,\n joinedAt: match.joinedAt,\n });\n }\n\n // When scoped, add clear metadata so model knows results are limited\n if (context.networkId && targetUserId === context.userId) {\n return success({\n userId: targetUserId,\n count: memberships.length,\n memberships: memberships.map((m) => ({\n networkId: m.networkId,\n networkTitle: m.networkTitle,\n permissions: m.permissions,\n joinedAt: m.joinedAt,\n })),\n scopeRestriction: {\n isScoped: true,\n scopedToIndex: context.indexName ?? context.networkId,\n message: `Results are limited to \"${context.indexName ?? 'this index'}\" because this chat is scoped to that community. The user may belong to other communities not shown here.`,\n },\n });\n }\n\n return success({\n userId: targetUserId,\n count: memberships.length,\n memberships: memberships.map((m) => ({\n networkId: m.networkId,\n networkTitle: m.networkTitle,\n permissions: m.permissions,\n joinedAt: m.joinedAt,\n })),\n });\n },\n });\n\n const updateNetworkSettingsSchema = z.object({\n title: z.string().optional(),\n prompt: z.string().nullable().optional(),\n imageUrl: z.string().url().nullable().optional(),\n joinPolicy: z.enum(['anyone', 'invite_only']).optional(),\n allowGuestVibeCheck: z.boolean().optional(),\n }).strict();\n\n const updateNetwork = defineTool({\n name: \"update_network\",\n description:\n \"Updates settings of an existing index (community). Only the index owner can perform updates.\\n\\n\" +\n \"**Updatable fields:** title (display name), prompt (purpose description used for intent auto-assignment), \" +\n \"imageUrl (community avatar), joinPolicy ('anyone' for open or 'invite_only'), allowGuestVibeCheck (allow non-members to preview).\\n\\n\" +\n \"**When to use:** When an index owner wants to change their community's settings — e.g. update the purpose description, \" +\n \"change from invite-only to open, or update the community image.\\n\\n\" +\n \"**Important:** Changing the prompt affects how future intents are evaluated for auto-assignment to this index. \" +\n \"Existing intent-index links are not re-evaluated automatically.\\n\\n\" +\n \"**Returns:** Confirmation with the list of settings that were updated.\",\n querySchema: z.object({\n networkId: z.string().optional().describe(\"Index UUID to update. Get from read_networks. Defaults to the scoped index in index-scoped chats.\"),\n settings: updateNetworkSettingsSchema.describe(\"Object with fields to update. All fields are optional — only include the ones to change. title: display name. prompt: purpose description (used for intent auto-assignment). imageUrl: community image URL (null to remove). joinPolicy: 'anyone' or 'invite_only'. allowGuestVibeCheck: boolean.\"),\n }),\n handler: async ({ context, query }) => {\n const effectiveIndexId = (query.networkId?.trim() || context.networkId) ?? null;\n if (!effectiveIndexId || !UUID_REGEX.test(effectiveIndexId)) {\n return error(\"Valid networkId required.\");\n }\n\n // Strict scope enforcement: when chat is index-scoped, only allow updating that index\n if (context.networkId && effectiveIndexId !== context.networkId) {\n return error(\n `This chat is scoped to ${context.indexName ?? 'this index'}. You can only update this community's settings.`\n );\n }\n\n const _updateNetworkGraphStart = Date.now();\n const _updateNetworkTraceEmitter = requestContext.getStore()?.traceEmitter;\n _updateNetworkTraceEmitter?.({ type: \"graph_start\", name: \"index\" });\n const result = await graphs.index.invoke({\n userId: context.userId,\n networkId: effectiveIndexId,\n operationMode: 'update' as const,\n updateInput: query.settings,\n });\n const _updateNetworkGraphMs = Date.now() - _updateNetworkGraphStart;\n _updateNetworkTraceEmitter?.({ type: \"graph_end\", name: \"index\", durationMs: _updateNetworkGraphMs });\n\n if (result.mutationResult && !result.mutationResult.success) {\n return error(result.mutationResult.error || \"Failed to update index.\");\n }\n return success({ message: \"Index updated.\", settings: Object.keys(query.settings), _graphTimings: [{ name: 'index', durationMs: _updateNetworkGraphMs, agents: result.agentTimings ?? [] }] });\n },\n });\n\n const createNetwork = defineTool({\n name: \"create_network\",\n description:\n \"Creates a new index (community/group). The authenticated user becomes the owner with full control over settings and membership.\\n\\n\" +\n \"**What is an index?** A shared space where members post intents (what they're looking for) and the system discovers opportunities \" +\n \"(complementary matches) between members. The index's prompt guides what kinds of intents belong.\\n\\n\" +\n \"**When to use:** When the user wants to create a new community — e.g. a professional network, interest group, or project team.\\n\\n\" +\n \"**Returns:** The new index's networkId (UUID) and title. Use the networkId to add members (create_network_membership), \" +\n \"link intents (create_intent_index), or run discovery (discover_opportunities with networkId).\",\n querySchema: z.object({\n title: z.string().describe(\"Display name of the index (e.g. 'AI Founders Berlin', 'Design Co-op'). Required.\"),\n prompt: z.string().optional().describe(\"Description of what this community is about (e.g. 'Early-stage AI/ML founders in Berlin looking for co-founders, advisors, and investors'). Used by the system to evaluate which intents belong in this index. Highly recommended for better auto-assignment.\"),\n imageUrl: z.string().url().optional().describe(\"URL for the community's avatar/image. Optional.\"),\n joinPolicy: z.enum(['anyone', 'invite_only']).optional().describe(\"'anyone' = open (any user can self-join), 'invite_only' = only the owner can add members. Defaults to 'invite_only'.\"),\n }),\n handler: async ({ context, query }) => {\n if (!query.title?.trim()) {\n return error(\"Title is required.\");\n }\n\n const _createNetworkGraphStart = Date.now();\n const _createNetworkTraceEmitter = requestContext.getStore()?.traceEmitter;\n _createNetworkTraceEmitter?.({ type: \"graph_start\", name: \"index\" });\n const result = await graphs.index.invoke({\n userId: context.userId,\n operationMode: 'create' as const,\n createInput: {\n title: query.title.trim(),\n prompt: query.prompt?.trim() || undefined,\n imageUrl: query.imageUrl || undefined,\n joinPolicy: query.joinPolicy,\n },\n });\n const _createNetworkGraphMs = Date.now() - _createNetworkGraphStart;\n _createNetworkTraceEmitter?.({ type: \"graph_end\", name: \"index\", durationMs: _createNetworkGraphMs });\n\n if (result.mutationResult) {\n if (result.mutationResult.success) {\n return success({\n created: true,\n networkId: result.mutationResult.networkId,\n title: result.mutationResult.title,\n message: result.mutationResult.message,\n _graphTimings: [{ name: 'index', durationMs: _createNetworkGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n return error(result.mutationResult.error || \"Failed to create index.\");\n }\n return error(\"Failed to create index.\");\n },\n });\n\n const deleteNetwork = defineTool({\n name: \"delete_network\",\n description:\n \"Permanently deletes an index (community). Only the owner can delete, and the index must have no other members \" +\n \"(remove all members first with delete_network_membership). Personal indexes cannot be deleted.\\n\\n\" +\n \"**When to use:** When the owner wants to disband a community. This is irreversible — all intent-index links to this index are removed.\\n\\n\" +\n \"**Prerequisites:** Must be the owner. Must be the sole remaining member (remove others first).\\n\\n\" +\n \"**Returns:** Confirmation that the index was deleted.\",\n querySchema: z.object({\n networkId: z.string().optional().describe(\"Index UUID to delete. Get from read_networks. Defaults to the scoped index in index-scoped chats. Cannot be a personal index.\"),\n }),\n handler: async ({ context, query }) => {\n const networkId = query.networkId?.trim() || context.networkId;\n if (!networkId || !UUID_REGEX.test(networkId)) {\n return error(\"Valid networkId required.\");\n }\n\n // Strict scope enforcement: when chat is index-scoped, only allow deleting that index\n if (context.networkId && networkId !== context.networkId) {\n return error(\n `This chat is scoped to ${context.indexName ?? 'this index'}. You can only delete this community.`\n );\n }\n\n const _deleteNetworkGraphStart = Date.now();\n const _deleteNetworkTraceEmitter = requestContext.getStore()?.traceEmitter;\n _deleteNetworkTraceEmitter?.({ type: \"graph_start\", name: \"index\" });\n const result = await graphs.index.invoke({\n userId: context.userId,\n networkId,\n operationMode: 'delete' as const,\n });\n const _deleteNetworkGraphMs = Date.now() - _deleteNetworkGraphStart;\n _deleteNetworkTraceEmitter?.({ type: \"graph_end\", name: \"index\", durationMs: _deleteNetworkGraphMs });\n\n if (result.mutationResult && !result.mutationResult.success) {\n return error(result.mutationResult.error || \"Failed to delete index.\");\n }\n return success({ message: \"Network deleted.\", _graphTimings: [{ name: 'index', durationMs: _deleteNetworkGraphMs, agents: result.agentTimings ?? [] }] });\n },\n });\n\n const createNetworkMembership = defineTool({\n name: \"create_network_membership\",\n description:\n \"Adds a user as a member of an index (community). Membership enables the user to post intents in the index and be discovered \" +\n \"by other members through opportunity matching.\\n\\n\" +\n \"**Usage modes:**\\n\" +\n \"- Omit userId: self-join (only works for indexes with joinPolicy 'anyone').\\n\" +\n \"- With userId: add another user (only the index owner can do this for 'invite_only' indexes).\\n\\n\" +\n \"**When to use:** When the user wants to join an open community, or when an index owner wants to invite someone.\\n\\n\" +\n \"**Returns:** Confirmation that the member was added (or a note that they were already a member). \" +\n \"After joining, the user's existing intents with autoAssign=true may be evaluated against the new index.\",\n querySchema: z.object({\n userId: z.string().optional().describe(\"User ID to add as a member. Omit to join the index yourself. Get user IDs from read_user_contexts(query=name) or read_network_memberships.\"),\n networkId: z.string().optional().describe(\"Index UUID to add the member to. Get from read_networks. Defaults to the scoped index in index-scoped chats.\"),\n }),\n handler: async ({ context, query }) => {\n const networkId = query.networkId?.trim() || context.networkId;\n const targetUserId = query.userId?.trim() || context.userId;\n if (!networkId || !UUID_REGEX.test(networkId)) {\n return error(\"Invalid index ID format. Use the exact UUID from read_networks.\");\n }\n\n // Strict scope enforcement: when chat is index-scoped, only allow adding to that index\n if (context.networkId && networkId !== context.networkId) {\n return error(\n `This chat is scoped to ${context.indexName ?? 'this index'}. You can only add members to this community.`\n );\n }\n\n const _createMembershipGraphStart = Date.now();\n const _createMembershipTraceEmitter = requestContext.getStore()?.traceEmitter;\n _createMembershipTraceEmitter?.({ type: \"graph_start\", name: \"network_membership\" });\n const result = await graphs.networkMembership.invoke({\n userId: context.userId,\n networkId,\n targetUserId,\n operationMode: 'create' as const,\n });\n const _createMembershipGraphMs = Date.now() - _createMembershipGraphStart;\n _createMembershipTraceEmitter?.({ type: \"graph_end\", name: \"network_membership\", durationMs: _createMembershipGraphMs });\n\n if (result.mutationResult) {\n if (result.mutationResult.success) {\n const alreadyMember = result.mutationResult.message?.includes(\"already\");\n return success({\n created: !alreadyMember,\n message: result.mutationResult.message,\n _graphTimings: [{ name: 'network_membership', durationMs: _createMembershipGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n return error(result.mutationResult.error || \"Failed to add member.\");\n }\n return error(\"Failed to add member.\");\n },\n });\n\n const deleteNetworkMembership = defineTool({\n name: \"delete_network_membership\",\n description:\n \"Removes a user from an index (community). After removal, the user's intents are unlinked from this index \" +\n \"and they can no longer participate in opportunity discovery within it.\\n\\n\" +\n \"**Permissions:** Only the index owner can remove members. The owner themselves cannot be removed (delete the index instead).\\n\\n\" +\n \"**When to use:** When an index owner wants to remove a member from the community. \" +\n \"Use read_network_memberships(networkId) first to get the userId of the member to remove.\\n\\n\" +\n \"**Returns:** Confirmation that the member was removed.\",\n querySchema: z.object({\n userId: z.string().describe(\"User ID of the member to remove. Get from read_network_memberships(networkId). Cannot be the index owner.\"),\n networkId: z.string().optional().describe(\"Index UUID to remove the member from. Get from read_networks. Defaults to the scoped index in index-scoped chats.\"),\n }),\n handler: async ({ context, query }) => {\n const networkId = query.networkId?.trim() || context.networkId;\n const targetUserId = query.userId?.trim();\n\n if (!networkId || !UUID_REGEX.test(networkId)) {\n return error(\"Valid networkId required. Use the exact UUID from read_networks.\");\n }\n if (!targetUserId) {\n return error(\"userId is required.\");\n }\n\n // Strict scope enforcement: when chat is index-scoped, only allow that index\n if (context.networkId && networkId !== context.networkId) {\n return error(\n `This chat is scoped to ${context.indexName ?? 'this index'}. You can only manage members of this community.`\n );\n }\n\n const _deleteMembershipGraphStart = Date.now();\n const _deleteMembershipTraceEmitter = requestContext.getStore()?.traceEmitter;\n _deleteMembershipTraceEmitter?.({ type: \"graph_start\", name: \"network_membership\" });\n const result = await graphs.networkMembership.invoke({\n userId: context.userId,\n networkId,\n targetUserId,\n operationMode: 'delete' as const,\n });\n const _deleteMembershipGraphMs = Date.now() - _deleteMembershipGraphStart;\n _deleteMembershipTraceEmitter?.({ type: \"graph_end\", name: \"network_membership\", durationMs: _deleteMembershipGraphMs });\n\n if (result.mutationResult) {\n if (result.mutationResult.success) {\n return success({\n removed: true,\n message: result.mutationResult.message,\n _graphTimings: [{ name: 'network_membership', durationMs: _deleteMembershipGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n return error(result.mutationResult.error || \"Failed to remove member.\");\n }\n return error(\"Failed to remove member.\");\n },\n });\n\n return [readIndexes, readIndexMemberships, updateNetwork, createNetwork, deleteNetwork, createNetworkMembership, deleteNetworkMembership] as const;\n}\n"]}
1
+ {"version":3,"file":"network.tools.js","sourceRoot":"/","sources":["network/network.tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,oBAAoB,EAAE,MAAM,wCAAwC,CAAC;AAG9E,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAC7E,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AACtF,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAE9D,8EAA8E;AAC9E,0EAA0E;AAC1E,IAAI,WAA2C,CAAC;AAEhD,MAAM,UAAU,kBAAkB,CAAC,UAAsB,EAAE,IAAc;IACvE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,IAAI,CA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AAG,2BAA2B,CAAC;YAC1E,6BAA6B,EAAE,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,oBAAoB,EAAE,UAAU,EAAE,wBAAwB,EAAE,CAAC,CAAC;YAEzH,IAAI,MAAM,CAAC,cAAc,EAAE,CAAC;gBAC1B,IAAI,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,CAAC;oBAClC,OAAO,OAAO,CAAC;wBACb,OAAO,EAAE,IAAI;wBACb,OAAO,EAAE,MAAM,CAAC,cAAc,CAAC,OAAO;wBACtC,aAAa,EAAE,CAAC,EAAE,IAAI,EAAE,oBAAoB,EAAE,UAAU,EAAE,wBAAwB,EAAE,MAAM,EAAE,MAAM,CAAC,YAAY,IAAI,EAAE,EAAE,CAAC;qBACzH,CAAC,CAAC;gBACL,CAAC;gBACD,OAAO,KAAK,CAAC,MAAM,CAAC,cAAc,CAAC,KAAK,IAAI,0BAA0B,CAAC,CAAC;YAC1E,CAAC;YACD,OAAO,KAAK,CAAC,0BAA0B,CAAC,CAAC;QAC3C,CAAC;KACF,CAAC,CAAC;IAEH,OAAO,CAAC,WAAW,EAAE,oBAAoB,EAAE,aAAa,EAAE,aAAa,EAAE,aAAa,EAAE,uBAAuB,EAAE,uBAAuB,CAAU,CAAC;AACrJ,CAAC","sourcesContent":["import { z } from \"zod\";\n\nimport { requestContext } from \"../shared/observability/request-context.js\";\nimport { renderNetworkContext } from '../shared/network/metadata.renderer.js';\n\nimport type { DefineTool, ToolDeps } from \"../shared/agent/tool.helpers.js\";\nimport { success, error, UUID_REGEX } from \"../shared/agent/tool.helpers.js\";\nimport { focusedNetworkId, focusedNetworkLabel } from \"../shared/agent/tool.scope.js\";\nimport { NetworkRecommender } from \"./network.recommender.js\";\n\n// Lazy singleton — only instantiated on first onboarding ranking call so that\n// importing this module does not require OPENROUTER_API_KEY at load time.\nlet recommender: NetworkRecommender | undefined;\n\nexport function createNetworkTools(defineTool: DefineTool, deps: ToolDeps) {\n const { graphs, userDb, systemDb } = deps;\n\n const enrichWithContext = (networks: Array<Record<string, unknown>>) =>\n networks.map((n) => ({\n ...n,\n renderedContext: renderNetworkContext({\n type: (n.type as string) ?? 'community',\n title: (n.title as string) ?? '',\n prompt: n.prompt as string | undefined,\n metadata: (n.metadata as Record<string, unknown>) ?? {},\n }),\n }));\n\n const readIndexes = defineTool({\n name: \"read_networks\",\n description:\n \"Lists the authenticated user's networks (communities), including ones they own and public communities they can join.\\n\\n\" +\n \"**When to use:** To find network IDs for scoping other operations (read_intents, discover_opportunities, read_network_memberships), \" +\n \"or to show the user which communities they belong to.\\n\\n\" +\n \"**Returns:** Up to three lists — `memberOf` (networks the user joined), `owns` (networks the user created), and `publicNetworks` \" +\n \"(publicly joinable communities the user is not yet a member of). Entries in `memberOf` include `isPersonal` set to `true` for the user's \" +\n \"personal network.\\n\\n\" +\n \"**Note:** In index-scoped chats, only the scoped network is returned. During onboarding, `orderedNetworkIds` \" +\n \"may be returned alongside `publicNetworks` \\u2014 a ranked array of network IDs ordered by relevance to the user's profile (omitted when ranking is unavailable or fails).\",\n querySchema: z.object({\n userId: z.string().optional().describe(\"Must be the current user's ID or omitted. Cannot list another user's indexes.\"),\n }),\n handler: async ({ context, query }) => {\n if (query.userId && query.userId.trim() !== context.userId) {\n return error(\"You can only list your own indexes. Omit userId to see the current user's indexes.\");\n }\n\n const scopedNetworkId = focusedNetworkId(context);\n const scopedIndexLabel = focusedNetworkLabel(context);\n\n const _readIndexGraphStart = Date.now();\n const _readIndexTraceEmitter = requestContext.getStore()?.traceEmitter;\n _readIndexTraceEmitter?.({ type: \"graph_start\", name: \"index\" });\n const result = await graphs.index.invoke({\n userId: context.userId,\n networkId: scopedNetworkId,\n operationMode: 'read' as const,\n showAll: false, // Never allow bypass - strict scope enforcement\n });\n const _readIndexGraphMs = Date.now() - _readIndexGraphStart;\n _readIndexTraceEmitter?.({ type: \"graph_end\", name: \"index\", durationMs: _readIndexGraphMs });\n\n if (result.error) {\n return error(result.error);\n }\n if (result.readResult) {\n const rr = result.readResult as Record<string, unknown>;\n const enriched = {\n ...rr,\n ...(Array.isArray(rr.memberOf) ? { memberOf: enrichWithContext(rr.memberOf as Array<Record<string, unknown>>) } : {}),\n ...(Array.isArray(rr.owns) ? { owns: enrichWithContext(rr.owns as Array<Record<string, unknown>>) } : {}),\n ...(Array.isArray(rr.publicNetworks) ? { publicNetworks: enrichWithContext(rr.publicNetworks as Array<Record<string, unknown>>) } : {}),\n };\n\n // When scoped, add clear metadata so model knows results are limited\n if (scopedNetworkId) {\n return success({\n ...enriched,\n scopeRestriction: {\n isScoped: true,\n scopedToIndex: scopedIndexLabel,\n message: `Results are limited to \"${scopedIndexLabel}\" because this chat is scoped to that community. The user may belong to other communities not shown here.`,\n },\n _graphTimings: [{ name: 'index', durationMs: _readIndexGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n // Onboarding-only: rank public networks by relevance to the user's global\n // user_context paragraph (the profile-replacing identity text). Guard: only\n // when isOnboarding, not scoped, there are public networks to rank, and a\n // user_context is resolvable (generated on demand by the injected resolver).\n let orderedNetworkIds: string[] | undefined;\n const userContext = deps.getUserContextText ? await deps.getUserContextText(context.userId) : \"\";\n if (\n context.isOnboarding &&\n userContext &&\n Array.isArray(enriched.publicNetworks) &&\n (enriched.publicNetworks as Array<Record<string, unknown>>).length > 0\n ) {\n // Cap at 50 to bound LLM context window usage (matches the UI's discoverPublicIndexes(1, 50)).\n const publicNetworksForRanking = (enriched.publicNetworks as Array<Record<string, unknown>>)\n .slice(0, 50)\n .map((n) => ({\n networkId: n.networkId as string,\n renderedContext: (n.renderedContext as string) ?? `## ${n.title as string}`,\n }));\n const rankFn = deps.networkRanker ?? (async (input) => {\n try {\n recommender ??= new NetworkRecommender();\n return await recommender.invoke(input);\n } catch (err) {\n // e.g. missing OPENROUTER_API_KEY — degrade gracefully, omit orderedNetworkIds\n console.warn(\"[read_networks] NetworkRecommender unavailable, skipping ranking:\", err);\n return null;\n }\n });\n const rankingResult = await rankFn({\n userContext,\n networks: publicNetworksForRanking,\n }).catch((err: unknown) => {\n // Catches errors from a custom deps.networkRanker (the default fallback\n // handles its own errors internally). Degrade gracefully: omit orderedNetworkIds.\n console.warn(\"[read_networks] networkRanker threw, skipping ranking:\", err);\n deps.reportToolError?.(err, { operation: \"network-ranking\", toolName: \"read_networks\", userId: context.userId });\n return null;\n });\n if (rankingResult) {\n // Normalize LLM output against the ranked slice (top 50):\n // keep only IDs from the input set, de-dupe preserving order, then\n // append any slice IDs the model omitted. Networks beyond the top-50\n // slice are not in orderedNetworkIds and will sort to the tail in the\n // frontend (consistent with the UI's own 50-item page size).\n const inputIds = publicNetworksForRanking.map((n) => n.networkId);\n const inputIdSet = new Set(inputIds);\n const seen = new Set<string>();\n const normalized: string[] = [];\n for (const id of rankingResult.rankedNetworkIds) {\n if (inputIdSet.has(id) && !seen.has(id)) {\n normalized.push(id);\n seen.add(id);\n }\n }\n for (const id of inputIds) {\n if (!seen.has(id)) normalized.push(id);\n }\n orderedNetworkIds = normalized;\n }\n }\n\n return success({\n ...enriched,\n ...(orderedNetworkIds !== undefined ? { orderedNetworkIds } : {}),\n _graphTimings: [{ name: 'index', durationMs: _readIndexGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n return error(\"Failed to fetch index information.\");\n },\n });\n\n const readIndexMemberships = defineTool({\n name: \"read_network_memberships\",\n description:\n \"Reads index membership information — who is in which community. Essential for understanding the social graph before \" +\n \"creating introductions or exploring intents.\\n\\n\" +\n \"**Usage modes:**\\n\" +\n \"- With `networkId` only: lists ALL members of that index — returns userId, name, avatar, permissions (owner/member), intentCount, and joinedAt. \" +\n \"Use this to see who's in a community before browsing their intents or creating introductions.\\n\" +\n \"- With `userId` only (or omit for self): lists all indexes that user belongs to — returns networkId, networkTitle, permissions, joinedAt.\\n\" +\n \"- With both `networkId` and `userId`: checks whether that specific user is a member of that specific index (returns isMember boolean).\\n\\n\" +\n \"**When to use:** Before creating introductions (need to verify shared index membership), to explore community members, \" +\n \"or to check if a user belongs to a specific index.\\n\\n\" +\n \"**Returns:** Member list with user details, or membership list with index details, or a membership check result.\\n\\n\" +\n \"**Personal index semantics.** The personal index (`isPersonal: true` on the membership) is the user's \" +\n \"contact list — members of that index are the user's contacts. For another user, this tool only reveals the \" +\n \"indexes you already share with them.\\n\\n\" +\n \"**Shared-context pattern.** To find overlap with another user: (1) omit `userId` to read your own \" +\n \"memberships, (2) call this tool with the other person's actual `userId` to get the shared indexes, \" +\n \"(3) call read_intents for each shared network to see what each is looking for there, (4) call \" +\n \"read_user_contexts for the other party. That sequence gives you enough to decide whether to propose a \" +\n \"direct connection or an introduction.\",\n querySchema: z.object({\n networkId: z.string().optional().describe(\"Index UUID — lists all members of this index. Get from read_networks. In index-scoped chats, only the scoped index can be queried.\"),\n userId: z.string().optional().describe(\"User ID — lists that user's index memberships. Omit to get the current user's memberships. When combined with networkId, checks if this user is in that specific index.\"),\n }),\n handler: async ({ context, query }) => {\n const scopedNetworkId = focusedNetworkId(context);\n const scopedIndexLabel = focusedNetworkLabel(context);\n const networkId = query.networkId?.trim() || undefined;\n const userId = query.userId?.trim() || undefined;\n\n if (networkId && !UUID_REGEX.test(networkId)) {\n return error(\"Invalid index ID format. Use the exact UUID from read_networks.\");\n }\n\n // Mode 1: list members of an index\n if (networkId && !userId) {\n // Enforce strict scope: when chat is index-scoped, only allow querying that index\n if (scopedNetworkId && networkId !== scopedNetworkId) {\n return error(\n `This chat is scoped to ${scopedIndexLabel}. You can only query members of this index.`\n );\n }\n\n const _readMembersGraphStart = Date.now();\n const _readMembersTraceEmitter = requestContext.getStore()?.traceEmitter;\n _readMembersTraceEmitter?.({ type: \"graph_start\", name: \"network_membership\" });\n const result = await graphs.networkMembership.invoke({\n userId: context.userId,\n networkId,\n operationMode: 'read' as const,\n });\n const _readMembersGraphMs = Date.now() - _readMembersGraphStart;\n _readMembersTraceEmitter?.({ type: \"graph_end\", name: \"network_membership\", durationMs: _readMembersGraphMs });\n\n if (result.error) {\n return error(result.error);\n }\n if (result.readResult) {\n return success({ ...result.readResult, _graphTimings: [{ name: 'network_membership', durationMs: _readMembersGraphMs, agents: result.agentTimings ?? [] }] });\n }\n return error(\"Failed to fetch index members.\");\n }\n\n // Mode 2: list a user's memberships (indexes they belong to)\n const targetUserId = userId || context.userId;\n\n // Use userDb for own memberships, but systemDb access is implicit through shared index scope\n let memberships: Awaited<ReturnType<typeof userDb.getNetworkMemberships>>;\n if (targetUserId !== context.userId) {\n // Cross-user access: systemDb will validate shared index membership\n const callerMemberships = await userDb.getNetworkMemberships();\n if (networkId) {\n // Strict scope enforcement: when chat is index-scoped, only allow querying that index\n if (scopedNetworkId && networkId !== scopedNetworkId) {\n return error(\n `This chat is scoped to ${scopedIndexLabel}. You can only query membership in this community.`\n );\n }\n\n const callerInIndex = callerMemberships.some((m) => m.networkId === networkId);\n if (!callerInIndex) {\n return error(\n \"Unauthorized: you can only view another user's membership in an index you belong to. Provide your own userId or omit userId for your memberships.\",\n );\n }\n // Check if target user is in the index (systemDb validates scope)\n const isMember = await systemDb.isNetworkMember(networkId, targetUserId);\n if (isMember) {\n return success({ isMember: true, userId: targetUserId, networkId });\n }\n return success({ isMember: false, userId: targetUserId, networkId, message: \"User is not a member of this index.\" });\n } else {\n // Strict scope enforcement: when chat is index-scoped, only check the scoped index\n if (scopedNetworkId) {\n const isMember = await systemDb.isNetworkMember(scopedNetworkId, targetUserId);\n if (isMember) {\n return success({\n isMember: true,\n userId: targetUserId,\n networkId: scopedNetworkId,\n scopeRestriction: {\n isScoped: true,\n scopedToIndex: scopedIndexLabel,\n message: `This chat is scoped to \"${scopedIndexLabel}\". Only membership in this community is shown.`,\n },\n });\n }\n return success({\n isMember: false,\n userId: targetUserId,\n networkId: scopedNetworkId,\n message: \"User is not a member of this community.\",\n scopeRestriction: {\n isScoped: true,\n scopedToIndex: scopedIndexLabel,\n message: `This chat is scoped to \"${scopedIndexLabel}\". Only membership in this community was checked.`,\n },\n });\n }\n\n // Unscoped chat: show overlap with shared indexes (intersection of caller and target memberships)\n const sharedIndexes: typeof callerMemberships = [];\n for (const m of callerMemberships) {\n if (await systemDb.isNetworkMember(m.networkId, targetUserId)) {\n sharedIndexes.push(m);\n }\n }\n if (sharedIndexes.length === 0) {\n return error(\n \"Unauthorized: you can only view another user's memberships if you share at least one index, or request your own memberships.\",\n );\n }\n // Return only the indexes that are shared\n return success({\n userId: targetUserId,\n count: sharedIndexes.length,\n memberships: sharedIndexes.map((m) => ({\n networkId: m.networkId,\n networkTitle: m.networkTitle,\n })),\n note: \"Only showing shared indexes.\",\n });\n }\n } else {\n // Own memberships - use userDb\n memberships = await userDb.getNetworkMemberships();\n\n // The scope envelope's network id is the focus of the scoped chat — it filters\n // what we show, not what we can reach. Concrete reach is derived separately.\n // Strict scope enforcement: when chat is index-scoped, only return the scoped index membership\n if (scopedNetworkId && !networkId) {\n memberships = memberships.filter((m) => m.networkId === scopedNetworkId);\n }\n }\n\n // If both networkId and userId: filter to that specific membership\n if (networkId) {\n // Strict scope enforcement: when chat is index-scoped, only allow querying that index\n if (scopedNetworkId && networkId !== scopedNetworkId) {\n return error(\n `This chat is scoped to ${scopedIndexLabel}. You can only query membership in this community.`\n );\n }\n\n const callerMemberships = await userDb.getNetworkMemberships();\n const callerInIndex =\n targetUserId === context.userId ||\n callerMemberships.some((m) => m.networkId === networkId);\n if (!callerInIndex) {\n return error(\n \"Unauthorized: you can only view membership in an index you belong to.\",\n );\n }\n const match = memberships.find((m) => m.networkId === networkId);\n if (!match) {\n return success({ isMember: false, userId: targetUserId, networkId, message: \"User is not a member of this index.\" });\n }\n return success({\n isMember: true,\n userId: targetUserId,\n networkId,\n networkTitle: match.networkTitle,\n permissions: match.permissions,\n joinedAt: match.joinedAt,\n });\n }\n\n // When scoped, add clear metadata so model knows results are limited\n if (scopedNetworkId && targetUserId === context.userId) {\n return success({\n userId: targetUserId,\n count: memberships.length,\n memberships: memberships.map((m) => ({\n networkId: m.networkId,\n networkTitle: m.networkTitle,\n permissions: m.permissions,\n joinedAt: m.joinedAt,\n })),\n scopeRestriction: {\n isScoped: true,\n scopedToIndex: scopedIndexLabel,\n message: `Results are limited to \"${scopedIndexLabel}\" because this chat is scoped to that community. The user may belong to other communities not shown here.`,\n },\n });\n }\n\n return success({\n userId: targetUserId,\n count: memberships.length,\n memberships: memberships.map((m) => ({\n networkId: m.networkId,\n networkTitle: m.networkTitle,\n permissions: m.permissions,\n joinedAt: m.joinedAt,\n })),\n });\n },\n });\n\n const updateNetworkSettingsSchema = z.object({\n title: z.string().optional(),\n prompt: z.string().nullable().optional(),\n imageUrl: z.string().url().nullable().optional(),\n joinPolicy: z.enum(['anyone', 'invite_only']).optional(),\n allowGuestVibeCheck: z.boolean().optional(),\n }).strict();\n\n const updateNetwork = defineTool({\n name: \"update_network\",\n description:\n \"Updates settings of an existing index (community). Only the index owner can perform updates.\\n\\n\" +\n \"**Updatable fields:** title (display name), prompt (purpose description used for intent auto-assignment), \" +\n \"imageUrl (community avatar), joinPolicy ('anyone' for open or 'invite_only'), allowGuestVibeCheck (allow non-members to preview).\\n\\n\" +\n \"**When to use:** When an index owner wants to change their community's settings — e.g. update the purpose description, \" +\n \"change from invite-only to open, or update the community image.\\n\\n\" +\n \"**Important:** Changing the prompt affects how future intents are evaluated for auto-assignment to this index. \" +\n \"Existing intent-index links are not re-evaluated automatically.\\n\\n\" +\n \"**Returns:** Confirmation with the list of settings that were updated.\",\n querySchema: z.object({\n networkId: z.string().optional().describe(\"Index UUID to update. Get from read_networks. Defaults to the scoped index in index-scoped chats.\"),\n settings: updateNetworkSettingsSchema.describe(\"Object with fields to update. All fields are optional — only include the ones to change. title: display name. prompt: purpose description (used for intent auto-assignment). imageUrl: community image URL (null to remove). joinPolicy: 'anyone' or 'invite_only'. allowGuestVibeCheck: boolean.\"),\n }),\n handler: async ({ context, query }) => {\n const scopedNetworkId = focusedNetworkId(context);\n const scopedIndexLabel = focusedNetworkLabel(context);\n const effectiveIndexId = (query.networkId?.trim() || scopedNetworkId) ?? null;\n if (!effectiveIndexId || !UUID_REGEX.test(effectiveIndexId)) {\n return error(\"Valid networkId required.\");\n }\n\n // Strict scope enforcement: when chat is index-scoped, only allow updating that index\n if (scopedNetworkId && effectiveIndexId !== scopedNetworkId) {\n return error(\n `This chat is scoped to ${scopedIndexLabel}. You can only update this community's settings.`\n );\n }\n\n const _updateNetworkGraphStart = Date.now();\n const _updateNetworkTraceEmitter = requestContext.getStore()?.traceEmitter;\n _updateNetworkTraceEmitter?.({ type: \"graph_start\", name: \"index\" });\n const result = await graphs.index.invoke({\n userId: context.userId,\n networkId: effectiveIndexId,\n operationMode: 'update' as const,\n updateInput: query.settings,\n });\n const _updateNetworkGraphMs = Date.now() - _updateNetworkGraphStart;\n _updateNetworkTraceEmitter?.({ type: \"graph_end\", name: \"index\", durationMs: _updateNetworkGraphMs });\n\n if (result.mutationResult && !result.mutationResult.success) {\n return error(result.mutationResult.error || \"Failed to update index.\");\n }\n return success({ message: \"Index updated.\", settings: Object.keys(query.settings), _graphTimings: [{ name: 'index', durationMs: _updateNetworkGraphMs, agents: result.agentTimings ?? [] }] });\n },\n });\n\n const createNetwork = defineTool({\n name: \"create_network\",\n description:\n \"Creates a new index (community/group). The authenticated user becomes the owner with full control over settings and membership.\\n\\n\" +\n \"**What is an index?** A shared space where members post intents (what they're looking for) and the system discovers opportunities \" +\n \"(complementary matches) between members. The index's prompt guides what kinds of intents belong.\\n\\n\" +\n \"**When to use:** When the user wants to create a new community — e.g. a professional network, interest group, or project team.\\n\\n\" +\n \"**Returns:** The new index's networkId (UUID) and title. Use the networkId to add members (create_network_membership), \" +\n \"link intents (create_intent_index), or run discovery (discover_opportunities with networkId).\",\n querySchema: z.object({\n title: z.string().describe(\"Display name of the index (e.g. 'AI Founders Berlin', 'Design Co-op'). Required.\"),\n prompt: z.string().optional().describe(\"Description of what this community is about (e.g. 'Early-stage AI/ML founders in Berlin looking for co-founders, advisors, and investors'). Used by the system to evaluate which intents belong in this index. Highly recommended for better auto-assignment.\"),\n imageUrl: z.string().url().optional().describe(\"URL for the community's avatar/image. Optional.\"),\n joinPolicy: z.enum(['anyone', 'invite_only']).optional().describe(\"'anyone' = open (any user can self-join), 'invite_only' = only the owner can add members. Defaults to 'invite_only'.\"),\n }),\n handler: async ({ context, query }) => {\n if (!query.title?.trim()) {\n return error(\"Title is required.\");\n }\n\n const _createNetworkGraphStart = Date.now();\n const _createNetworkTraceEmitter = requestContext.getStore()?.traceEmitter;\n _createNetworkTraceEmitter?.({ type: \"graph_start\", name: \"index\" });\n const result = await graphs.index.invoke({\n userId: context.userId,\n operationMode: 'create' as const,\n createInput: {\n title: query.title.trim(),\n prompt: query.prompt?.trim() || undefined,\n imageUrl: query.imageUrl || undefined,\n joinPolicy: query.joinPolicy,\n },\n });\n const _createNetworkGraphMs = Date.now() - _createNetworkGraphStart;\n _createNetworkTraceEmitter?.({ type: \"graph_end\", name: \"index\", durationMs: _createNetworkGraphMs });\n\n if (result.mutationResult) {\n if (result.mutationResult.success) {\n return success({\n created: true,\n networkId: result.mutationResult.networkId,\n title: result.mutationResult.title,\n message: result.mutationResult.message,\n _graphTimings: [{ name: 'index', durationMs: _createNetworkGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n return error(result.mutationResult.error || \"Failed to create index.\");\n }\n return error(\"Failed to create index.\");\n },\n });\n\n const deleteNetwork = defineTool({\n name: \"delete_network\",\n description:\n \"Permanently deletes an index (community). Only the owner can delete, and the index must have no other members \" +\n \"(remove all members first with delete_network_membership). Personal indexes cannot be deleted.\\n\\n\" +\n \"**When to use:** When the owner wants to disband a community. This is irreversible — all intent-index links to this index are removed.\\n\\n\" +\n \"**Prerequisites:** Must be the owner. Must be the sole remaining member (remove others first).\\n\\n\" +\n \"**Returns:** Confirmation that the index was deleted.\",\n querySchema: z.object({\n networkId: z.string().optional().describe(\"Index UUID to delete. Get from read_networks. Defaults to the scoped index in index-scoped chats. Cannot be a personal index.\"),\n }),\n handler: async ({ context, query }) => {\n const scopedNetworkId = focusedNetworkId(context);\n const scopedIndexLabel = focusedNetworkLabel(context);\n const networkId = query.networkId?.trim() || scopedNetworkId;\n if (!networkId || !UUID_REGEX.test(networkId)) {\n return error(\"Valid networkId required.\");\n }\n\n // Strict scope enforcement: when chat is index-scoped, only allow deleting that index\n if (scopedNetworkId && networkId !== scopedNetworkId) {\n return error(\n `This chat is scoped to ${scopedIndexLabel}. You can only delete this community.`\n );\n }\n\n const _deleteNetworkGraphStart = Date.now();\n const _deleteNetworkTraceEmitter = requestContext.getStore()?.traceEmitter;\n _deleteNetworkTraceEmitter?.({ type: \"graph_start\", name: \"index\" });\n const result = await graphs.index.invoke({\n userId: context.userId,\n networkId,\n operationMode: 'delete' as const,\n });\n const _deleteNetworkGraphMs = Date.now() - _deleteNetworkGraphStart;\n _deleteNetworkTraceEmitter?.({ type: \"graph_end\", name: \"index\", durationMs: _deleteNetworkGraphMs });\n\n if (result.mutationResult && !result.mutationResult.success) {\n return error(result.mutationResult.error || \"Failed to delete index.\");\n }\n return success({ message: \"Network deleted.\", _graphTimings: [{ name: 'index', durationMs: _deleteNetworkGraphMs, agents: result.agentTimings ?? [] }] });\n },\n });\n\n const createNetworkMembership = defineTool({\n name: \"create_network_membership\",\n description:\n \"Adds a user as a member of an index (community). Membership enables the user to post intents in the index and be discovered \" +\n \"by other members through opportunity matching.\\n\\n\" +\n \"**Usage modes:**\\n\" +\n \"- Omit userId: self-join (only works for indexes with joinPolicy 'anyone').\\n\" +\n \"- With userId: add another user (only the index owner can do this for 'invite_only' indexes).\\n\\n\" +\n \"**When to use:** When the user wants to join an open community, or when an index owner wants to invite someone.\\n\\n\" +\n \"**Returns:** Confirmation that the member was added (or a note that they were already a member). \" +\n \"After joining, the user's existing intents with autoAssign=true may be evaluated against the new index.\",\n querySchema: z.object({\n userId: z.string().optional().describe(\"User ID to add as a member. Omit to join the index yourself. Get user IDs from read_user_contexts(query=name) or read_network_memberships.\"),\n networkId: z.string().optional().describe(\"Index UUID to add the member to. Get from read_networks. Defaults to the scoped index in index-scoped chats.\"),\n }),\n handler: async ({ context, query }) => {\n const scopedNetworkId = focusedNetworkId(context);\n const scopedIndexLabel = focusedNetworkLabel(context);\n const networkId = query.networkId?.trim() || scopedNetworkId;\n const targetUserId = query.userId?.trim() || context.userId;\n if (!networkId || !UUID_REGEX.test(networkId)) {\n return error(\"Invalid index ID format. Use the exact UUID from read_networks.\");\n }\n\n // Strict scope enforcement: when chat is index-scoped, only allow adding to that index\n if (scopedNetworkId && networkId !== scopedNetworkId) {\n return error(\n `This chat is scoped to ${scopedIndexLabel}. You can only add members to this community.`\n );\n }\n\n const _createMembershipGraphStart = Date.now();\n const _createMembershipTraceEmitter = requestContext.getStore()?.traceEmitter;\n _createMembershipTraceEmitter?.({ type: \"graph_start\", name: \"network_membership\" });\n const result = await graphs.networkMembership.invoke({\n userId: context.userId,\n networkId,\n targetUserId,\n operationMode: 'create' as const,\n });\n const _createMembershipGraphMs = Date.now() - _createMembershipGraphStart;\n _createMembershipTraceEmitter?.({ type: \"graph_end\", name: \"network_membership\", durationMs: _createMembershipGraphMs });\n\n if (result.mutationResult) {\n if (result.mutationResult.success) {\n const alreadyMember = result.mutationResult.message?.includes(\"already\");\n return success({\n created: !alreadyMember,\n message: result.mutationResult.message,\n _graphTimings: [{ name: 'network_membership', durationMs: _createMembershipGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n return error(result.mutationResult.error || \"Failed to add member.\");\n }\n return error(\"Failed to add member.\");\n },\n });\n\n const deleteNetworkMembership = defineTool({\n name: \"delete_network_membership\",\n description:\n \"Removes a user from an index (community). After removal, the user's intents are unlinked from this index \" +\n \"and they can no longer participate in opportunity discovery within it.\\n\\n\" +\n \"**Permissions:** Only the index owner can remove members. The owner themselves cannot be removed (delete the index instead).\\n\\n\" +\n \"**When to use:** When an index owner wants to remove a member from the community. \" +\n \"Use read_network_memberships(networkId) first to get the userId of the member to remove.\\n\\n\" +\n \"**Returns:** Confirmation that the member was removed.\",\n querySchema: z.object({\n userId: z.string().describe(\"User ID of the member to remove. Get from read_network_memberships(networkId). Cannot be the index owner.\"),\n networkId: z.string().optional().describe(\"Index UUID to remove the member from. Get from read_networks. Defaults to the scoped index in index-scoped chats.\"),\n }),\n handler: async ({ context, query }) => {\n const scopedNetworkId = focusedNetworkId(context);\n const scopedIndexLabel = focusedNetworkLabel(context);\n const networkId = query.networkId?.trim() || scopedNetworkId;\n const targetUserId = query.userId?.trim();\n\n if (!networkId || !UUID_REGEX.test(networkId)) {\n return error(\"Valid networkId required. Use the exact UUID from read_networks.\");\n }\n if (!targetUserId) {\n return error(\"userId is required.\");\n }\n\n // Strict scope enforcement: when chat is index-scoped, only allow that index\n if (scopedNetworkId && networkId !== scopedNetworkId) {\n return error(\n `This chat is scoped to ${scopedIndexLabel}. You can only manage members of this community.`\n );\n }\n\n const _deleteMembershipGraphStart = Date.now();\n const _deleteMembershipTraceEmitter = requestContext.getStore()?.traceEmitter;\n _deleteMembershipTraceEmitter?.({ type: \"graph_start\", name: \"network_membership\" });\n const result = await graphs.networkMembership.invoke({\n userId: context.userId,\n networkId,\n targetUserId,\n operationMode: 'delete' as const,\n });\n const _deleteMembershipGraphMs = Date.now() - _deleteMembershipGraphStart;\n _deleteMembershipTraceEmitter?.({ type: \"graph_end\", name: \"network_membership\", durationMs: _deleteMembershipGraphMs });\n\n if (result.mutationResult) {\n if (result.mutationResult.success) {\n return success({\n removed: true,\n message: result.mutationResult.message,\n _graphTimings: [{ name: 'network_membership', durationMs: _deleteMembershipGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n return error(result.mutationResult.error || \"Failed to remove member.\");\n }\n return error(\"Failed to remove member.\");\n },\n });\n\n return [readIndexes, readIndexMemberships, updateNetwork, createNetwork, deleteNetwork, createNetworkMembership, deleteNetworkMembership] as const;\n}\n"]}
@@ -11,6 +11,7 @@
11
11
  import type { ChatGraphCompositeDatabase, UserRecord } from "../shared/interfaces/database.interface.js";
12
12
  import type { Cache } from "../shared/interfaces/cache.interface.js";
13
13
  import type { QuestionerEnqueueFn } from "../questioner/questioner.types.js";
14
+ import type { ToolScopeType } from "../shared/agent/tool.scope.js";
14
15
  import { OpportunityPresenter, type OpportunityPresentationResult, type HomeCardPresentationResult } from "./opportunity.presenter.js";
15
16
  import type { ChatSummaryReader } from "../shared/interfaces/chat-summary.interface.js";
16
17
  import type { QuestionGeneratorReader } from "../shared/interfaces/question-generator.interface.js";
@@ -89,6 +90,10 @@ export interface DiscoverInput {
89
90
  * completes).
90
91
  */
91
92
  questionerEnqueue?: QuestionerEnqueueFn;
93
+ /** Focused request scope type for generated discovery questions. */
94
+ scopeType?: ToolScopeType;
95
+ /** Focused request scope id. When `scopeType === 'network'`, persisted as actor networkId. */
96
+ scopeId?: string;
92
97
  }
93
98
  /** One formatted opportunity for chat (candidate-facing). */
94
99
  export interface FormattedDiscoveryCandidate {
@@ -1 +1 @@
1
- {"version":3,"file":"opportunity.discover.d.ts","sourceRoot":"/","sources":["opportunity/opportunity.discover.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAe,0BAA0B,EAAE,UAAU,EAAE,MAAM,4CAA4C,CAAC;AACtH,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,yCAAyC,CAAC;AAGrE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AAC7E,OAAO,EAAE,oBAAoB,EAA0B,KAAK,6BAA6B,EAAE,KAAK,0BAA0B,EAAuD,MAAM,4BAA4B,CAAC;AAIpN,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,gDAAgD,CAAC;AAExF,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,sDAAsD,CAAC;AACpG,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,uDAAuD,CAAC;AAGtG,OAAO,KAAK,EAAE,QAAQ,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AAqDvF,+EAA+E;AAC/E,MAAM,MAAM,wBAAwB,GAAG,UAAU,CAC/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EAAE,wBAAwB,CAAC;IAC3C,QAAQ,EAAE,0BAA0B,CAAC;IACrC,KAAK,EAAE,KAAK,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;IACpB,kFAAkF;IAClF,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,SAAS,CAAC,EAAE,oBAAoB,CAAC;IACjC,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC7B,GAAG,OAAO,CAAC,cAAc,CAAC,CAgI1B"}
@@ -463,6 +463,8 @@ export async function runDiscoverFromQuery(input) {
463
463
  query: queryOrEmpty,
464
464
  questionerEnqueue: input.questionerEnqueue,
465
465
  userId: input.userId,
466
+ scopeType: input.scopeType,
467
+ scopeId: input.scopeId,
466
468
  userContext: input.userId
467
469
  ? ((await input.database.getUserContext(input.userId, null))?.text ?? '')
468
470
  : '',
@@ -713,6 +715,7 @@ async function maybeBuildQuestions(args) {
713
715
  sourceType: 'discovery',
714
716
  sourceId: args.chatSessionId ?? crypto.randomUUID(),
715
717
  context: enqueueInput,
718
+ ...(args.scopeType && args.scopeId ? { scopeType: args.scopeType, scopeId: args.scopeId } : {}),
716
719
  conversationId: args.chatSessionId,
717
720
  });
718
721
  logger.info("Question generation enqueued to QuestionerQueue", {