@indexnetwork/protocol 3.7.0-rc.276.1 → 3.7.0-rc.277.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/contact/contact.tools.d.ts.map +1 -1
- package/dist/contact/contact.tools.js +17 -5
- package/dist/contact/contact.tools.js.map +1 -1
- package/dist/integration/integration.tools.d.ts.map +1 -1
- package/dist/integration/integration.tools.js +6 -0
- package/dist/integration/integration.tools.js.map +1 -1
- package/dist/shared/agent/tool.factory.d.ts.map +1 -1
- package/dist/shared/agent/tool.factory.js +1 -0
- package/dist/shared/agent/tool.factory.js.map +1 -1
- package/dist/shared/agent/tool.helpers.d.ts +14 -0
- package/dist/shared/agent/tool.helpers.d.ts.map +1 -1
- package/dist/shared/agent/tool.helpers.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"contact.tools.d.ts","sourceRoot":"/","sources":["contact/contact.tools.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AAM5E;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,
|
|
1
|
+
{"version":3,"file":"contact.tools.d.ts","sourceRoot":"/","sources":["contact/contact.tools.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AAM5E;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,SAqLxE"}
|
|
@@ -8,7 +8,13 @@ const logger = protocolLogger('ContactTools');
|
|
|
8
8
|
*/
|
|
9
9
|
export function createContactTools(defineTool, deps) {
|
|
10
10
|
const { contactService } = deps;
|
|
11
|
-
|
|
11
|
+
// Contact import / manual-add create ghost users. These are gated behind the
|
|
12
|
+
// CONTACTS_ENABLED flag (injected as deps.contactsEnabled). Read/remove/search
|
|
13
|
+
// tools below are always available so existing contacts stay manageable.
|
|
14
|
+
const contactsEnabled = deps.contactsEnabled === true;
|
|
15
|
+
// Only register when enabled: in the registry path defineTool registers as a
|
|
16
|
+
// side effect, so the call itself must be gated, not just the returned array.
|
|
17
|
+
const import_contacts = contactsEnabled ? defineTool({
|
|
12
18
|
name: 'import_contacts',
|
|
13
19
|
description: "Bulk-imports contacts into the authenticated user's personal network (personal index). Contacts become members of the user's " +
|
|
14
20
|
"personal index with 'contact' permission, making them available for opportunity discovery.\n\n" +
|
|
@@ -41,7 +47,7 @@ export function createContactTools(defineTool, deps) {
|
|
|
41
47
|
return error('Failed to import contacts. Please try again.');
|
|
42
48
|
}
|
|
43
49
|
},
|
|
44
|
-
});
|
|
50
|
+
}) : null;
|
|
45
51
|
const list_contacts = defineTool({
|
|
46
52
|
name: 'list_contacts',
|
|
47
53
|
description: "Lists all contacts in the authenticated user's personal network. Contacts are people the user has added " +
|
|
@@ -77,7 +83,7 @@ export function createContactTools(defineTool, deps) {
|
|
|
77
83
|
}
|
|
78
84
|
},
|
|
79
85
|
});
|
|
80
|
-
const add_contact = defineTool({
|
|
86
|
+
const add_contact = contactsEnabled ? defineTool({
|
|
81
87
|
name: 'add_contact',
|
|
82
88
|
description: "Adds a single contact to the authenticated user's personal network by email address. " +
|
|
83
89
|
"For bulk imports, use import_contacts instead.\n\n" +
|
|
@@ -108,7 +114,7 @@ export function createContactTools(defineTool, deps) {
|
|
|
108
114
|
return error('Failed to add contact. Please try again.');
|
|
109
115
|
}
|
|
110
116
|
},
|
|
111
|
-
});
|
|
117
|
+
}) : null;
|
|
112
118
|
const remove_contact = defineTool({
|
|
113
119
|
name: 'remove_contact',
|
|
114
120
|
description: "Removes a contact from the authenticated user's personal network. The contact relationship is deleted — " +
|
|
@@ -162,6 +168,12 @@ export function createContactTools(defineTool, deps) {
|
|
|
162
168
|
}
|
|
163
169
|
},
|
|
164
170
|
});
|
|
165
|
-
return [
|
|
171
|
+
return [
|
|
172
|
+
...(import_contacts ? [import_contacts] : []),
|
|
173
|
+
...(add_contact ? [add_contact] : []),
|
|
174
|
+
list_contacts,
|
|
175
|
+
remove_contact,
|
|
176
|
+
search_contacts,
|
|
177
|
+
];
|
|
166
178
|
}
|
|
167
179
|
//# sourceMappingURL=contact.tools.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"contact.tools.js","sourceRoot":"/","sources":["contact/contact.tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAE5E,MAAM,MAAM,GAAG,cAAc,CAAC,cAAc,CAAC,CAAC;AAE9C;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CAAC,UAAsB,EAAE,IAAc;IACvE,MAAM,EAAE,cAAc,EAAE,GAAG,IAAI,CAAC;IAEhC,MAAM,eAAe,GAAG,UAAU,CAAC;QACjC,IAAI,EAAE,iBAAiB;QACvB,WAAW,EACT,+HAA+H;YAC/H,gGAAgG;YAChG,yHAAyH;YACzH,4HAA4H;YAC5H,0FAA0F;YAC1F,8HAA8H;YAC9H,gEAAgE;YAChE,oHAAoH;YACpH,4FAA4F;QAC9F,WAAW,EAAE,CAAC,CAAC,MAAM,CAAC;YACpB,QAAQ,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC;gBACzB,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,8CAA8C,CAAC;gBACzE,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,2EAA2E,CAAC;aACxG,CAAC,CAAC,CAAC,QAAQ,CAAC,uGAAuG,CAAC;SACtH,CAAC;QACF,OAAO,EAAE,KAAK,EAAE,EAAE,OA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AAE,CAAC,CAAC,OAAO;qBACnB,CAAC,CAAC;iBACJ,CAAC,CAAC;YACL,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,MAAM,CAAC,KAAK,CAAC,2BAA2B,EAAE,EAAE,GAAG,EAAE,CAAC,CAAC;gBACnD,OAAO,KAAK,CAAC,8CAA8C,CAAC,CAAC;YAC/D,CAAC;QACH,CAAC;KACF,CAAC,CAAC;IAEH,OAAO,CAAC,eAAe,EAAE,aAAa,EAAE,WAAW,EAAE,cAAc,EAAE,eAAe,CAAC,CAAC;AACxF,CAAC","sourcesContent":["import { z } from 'zod';\nimport type { DefineTool, ToolDeps } from '../shared/agent/tool.helpers.js';\nimport { success, error } from '../shared/agent/tool.helpers.js';\nimport { protocolLogger } from '../shared/observability/protocol.logger.js';\n\nconst logger = protocolLogger('ContactTools');\n\n/**\n * Creates contact management tools for the chat agent.\n * Enables importing, listing, and managing the user's network.\n */\nexport function createContactTools(defineTool: DefineTool, deps: ToolDeps) {\n const { contactService } = deps;\n\n const import_contacts = defineTool({\n name: 'import_contacts',\n description:\n \"Bulk-imports contacts into the authenticated user's personal network (personal index). Contacts become members of the user's \" +\n \"personal index with 'contact' permission, making them available for opportunity discovery.\\n\\n\" +\n \"**What happens:** Each contact is matched by email. If the email belongs to an existing user, they're linked directly. \" +\n \"If not, a 'ghost user' is created — a placeholder account enriched with public profile data (from LinkedIn, GitHub, etc.) \" +\n \"that participates in opportunity matching even before the person joins the platform.\\n\\n\" +\n \"**When to use:** When the user provides a list of contacts to add (from CSV, manual input, or any source other than Gmail). \" +\n \"For Gmail specifically, use import_gmail_contacts instead.\\n\\n\" +\n \"**Returns:** Import statistics: imported (total processed), skipped (invalid), newContacts (ghost users created), \" +\n \"existingContacts (already in network). Use list_contacts to see all contacts after import.\",\n querySchema: z.object({\n contacts: z.array(z.object({\n name: z.string().describe('Full name of the contact (e.g. \"Jane Smith\")'),\n email: z.string().describe('Email address — used as the unique identifier for matching existing users'),\n })).describe('Array of contact objects to import. Each must have name and email. Duplicates (by email) are skipped.'),\n }),\n handler: async ({ context, query }) => {\n try {\n const result = await contactService.importContacts(\n context.userId,\n query.contacts\n );\n return success({\n message: `Imported ${result.imported} contacts to your network.`,\n imported: result.imported,\n skipped: result.skipped,\n newContacts: result.newContacts,\n existingContacts: result.existingContacts,\n });\n } catch (err) {\n logger.error('Failed to import contacts', { err });\n return error('Failed to import contacts. Please try again.');\n }\n },\n });\n\n const list_contacts = defineTool({\n name: 'list_contacts',\n description:\n \"Lists all contacts in the authenticated user's personal network. Contacts are people the user has added \" +\n \"(via import_contacts, add_contact, or import_gmail_contacts) stored as members of their personal index.\\n\\n\" +\n \"**When to use:** To see who's in the user's network, find a contact's userId for other operations, \" +\n \"or check if a specific person is already a contact.\\n\\n\" +\n \"**Returns:** Array of contacts, each with: userId (use with read_user_profiles or discover_opportunities), \" +\n \"name, email, avatar URL, and isGhost (true = no account yet, profile enriched from public data). \" +\n \"Use the userId with read_user_profiles(userId) to get the full profile, or with discover_opportunities(targetUserId) to connect.\",\n querySchema: z.object({\n limit: z.number().optional().describe('Maximum number of contacts to return. Omit to return all contacts. Use for large networks to paginate results.'),\n }),\n handler: async ({ context, query }) => {\n try {\n let contacts = await contactService.listContacts(context.userId);\n\n if (query.limit && query.limit > 0) {\n contacts = contacts.slice(0, query.limit);\n }\n\n return success({\n count: contacts.length,\n contacts: contacts.map(c => ({\n userId: c.userId,\n name: c.user.name,\n email: c.user.email,\n avatar: c.user.avatar,\n isGhost: c.user.isGhost,\n })),\n });\n } catch (err) {\n logger.error('Failed to list contacts', { err });\n return error('Failed to list contacts. Please try again.');\n }\n },\n });\n\n const add_contact = defineTool({\n name: 'add_contact',\n description:\n \"Adds a single contact to the authenticated user's personal network by email address. \" +\n \"For bulk imports, use import_contacts instead.\\n\\n\" +\n \"**What happens:** Looks up the email. If an account exists, links that user as a contact. \" +\n \"If not, creates a ghost user (placeholder enriched with public profile data) and adds them. \" +\n \"The contact can then appear in opportunity discovery within the user's personal index.\\n\\n\" +\n \"**When to use:** When the user wants to add a specific person (e.g. 'add john@example.com to my network').\\n\\n\" +\n \"**Returns:** Confirmation with the contact's userId and whether a new ghost user was created (isNewGhost). \" +\n \"Use the userId with discover_opportunities(targetUserId) to find connection opportunities.\",\n querySchema: z.object({\n email: z.string().describe('Email address of the person to add. Used as unique identifier — if already a contact, the operation is idempotent.'),\n name: z.string().optional().describe('Full name of the contact. Optional — if omitted, the email prefix is used as name. Provide when known for better profile enrichment.'),\n }),\n handler: async ({ context, query }) => {\n try {\n const result = await contactService.addContact(context.userId, query.email, { name: query.name, restore: true });\n\n return success({\n added: true,\n message: result.isNew\n ? `Added ${query.name || query.email} to your network. Their profile is being enriched.`\n : `Added ${query.name || query.email} to your network.`,\n userId: result.userId,\n isNewGhost: result.isNew,\n });\n } catch (err) {\n logger.error('Failed to add contact', { err });\n return error('Failed to add contact. Please try again.');\n }\n },\n });\n\n const remove_contact = defineTool({\n name: 'remove_contact',\n description:\n \"Removes a contact from the authenticated user's personal network. The contact relationship is deleted — \" +\n \"the person is no longer a member of the user's personal index and won't appear in personal-index-scoped discovery.\\n\\n\" +\n \"**When to use:** When the user wants to remove someone from their network (e.g. 'remove John from my contacts').\\n\\n\" +\n \"**Note:** This only removes the contact relationship. If the contact is a real user (not a ghost), \" +\n \"they still exist on the platform and may appear in shared index discovery.\\n\\n\" +\n \"**Returns:** Confirmation that the contact was removed.\",\n querySchema: z.object({\n contactUserId: z.string().describe('The userId of the contact to remove. Get this from list_contacts results.'),\n }),\n handler: async ({ context, query }) => {\n try {\n await contactService.removeContact(context.userId, query.contactUserId);\n return success({ removed: true, message: 'Contact removed from your network.' });\n } catch (err) {\n logger.error('Failed to remove contact', { err });\n return error('Failed to remove contact. Please try again.');\n }\n },\n });\n\n const search_contacts = defineTool({\n name: 'search_contacts',\n description:\n \"Searches the authenticated user's personal network by name or email (case-insensitive substring). \" +\n \"Use when the user refers to a contact by partial name or email and you need their userId for another tool \" +\n \"(e.g. read_user_profiles, discover_opportunities).\\n\\n\" +\n \"**When to use:** Before list_contacts when the network is large — returns only matching contacts, bounded by limit.\\n\\n\" +\n \"**Returns:** Array of matching contacts: userId, name, email, avatar, isGhost.\",\n querySchema: z.object({\n query: z.string().trim().min(1).describe('Free-text query matched against contact name and email (case-insensitive, substring).'),\n limit: z.number().int().positive().max(100).optional().describe('Maximum rows to return. Defaults to 25.'),\n }),\n handler: async ({ context, query }) => {\n try {\n const rows = await contactService.searchContacts(context.userId, query.query, query.limit ?? 25);\n return success({\n count: rows.length,\n contacts: rows.map(r => ({\n userId: r.contactId,\n name: r.name,\n email: r.email,\n avatar: r.avatar,\n isGhost: r.isGhost,\n })),\n });\n } catch (err) {\n logger.error('Failed to search contacts', { err });\n return error('Failed to search contacts. Please try again.');\n }\n },\n });\n\n return [import_contacts, list_contacts, add_contact, remove_contact, search_contacts];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"contact.tools.js","sourceRoot":"/","sources":["contact/contact.tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAE5E,MAAM,MAAM,GAAG,cAAc,CAAC,cAAc,CAAC,CAAC;AAE9C;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CAAC,UAAsB,EAAE,IAAc;IACvE,MAAM,EAAE,cAAc,EAAE,GAAG,IAAI,CAAC;IAChC,6EAA6E;IAC7E,+EAA+E;IAC/E,yEAAyE;IACzE,MAAM,eAAe,GAAG,IAAI,CAAC,eAAe,KAAK,IAAI,CAAC;IAEtD,6EAA6E;IAC7E,8EAA8E;IAC9E,MAAM,eAAe,GAAG,eAAe,CAAC,CAAC,CAAC,UAAU,CAAC;QACnD,IAAI,EAAE,iBAAiB;QACvB,WAAW,EACT,+HAA+H;YAC/H,gGAAgG;YAChG,y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AC;QACF,OAAO,EAAE,KAAK,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE;YACpC,IAAI,CAAC;gBACH,MAAM,IAAI,GAAG,MAAM,cAAc,CAAC,cAAc,CAAC,OAAO,CAAC,MAAM,EAAE,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC;gBACjG,OAAO,OAAO,CAAC;oBACb,KAAK,EAAE,IAAI,CAAC,MAAM;oBAClB,QAAQ,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;wBACvB,MAAM,EAAE,CAAC,CAAC,SAAS;wBACnB,IAAI,EAAE,CAAC,CAAC,IAAI;wBACZ,KAAK,EAAE,CAAC,CAAC,KAAK;wBACd,MAAM,EAAE,CAAC,CAAC,MAAM;wBAChB,OAAO,EAAE,CAAC,CAAC,OAAO;qBACnB,CAAC,CAAC;iBACJ,CAAC,CAAC;YACL,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,MAAM,CAAC,KAAK,CAAC,2BAA2B,EAAE,EAAE,GAAG,EAAE,CAAC,CAAC;gBACnD,OAAO,KAAK,CAAC,8CAA8C,CAAC,CAAC;YAC/D,CAAC;QACH,CAAC;KACF,CAAC,CAAC;IAEH,OAAO;QACL,GAAG,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QAC7C,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QACrC,aAAa;QACb,cAAc;QACd,eAAe;KAChB,CAAC;AACJ,CAAC","sourcesContent":["import { z } from 'zod';\nimport type { DefineTool, ToolDeps } from '../shared/agent/tool.helpers.js';\nimport { success, error } from '../shared/agent/tool.helpers.js';\nimport { protocolLogger } from '../shared/observability/protocol.logger.js';\n\nconst logger = protocolLogger('ContactTools');\n\n/**\n * Creates contact management tools for the chat agent.\n * Enables importing, listing, and managing the user's network.\n */\nexport function createContactTools(defineTool: DefineTool, deps: ToolDeps) {\n const { contactService } = deps;\n // Contact import / manual-add create ghost users. These are gated behind the\n // CONTACTS_ENABLED flag (injected as deps.contactsEnabled). Read/remove/search\n // tools below are always available so existing contacts stay manageable.\n const contactsEnabled = deps.contactsEnabled === true;\n\n // Only register when enabled: in the registry path defineTool registers as a\n // side effect, so the call itself must be gated, not just the returned array.\n const import_contacts = contactsEnabled ? defineTool({\n name: 'import_contacts',\n description:\n \"Bulk-imports contacts into the authenticated user's personal network (personal index). Contacts become members of the user's \" +\n \"personal index with 'contact' permission, making them available for opportunity discovery.\\n\\n\" +\n \"**What happens:** Each contact is matched by email. If the email belongs to an existing user, they're linked directly. \" +\n \"If not, a 'ghost user' is created — a placeholder account enriched with public profile data (from LinkedIn, GitHub, etc.) \" +\n \"that participates in opportunity matching even before the person joins the platform.\\n\\n\" +\n \"**When to use:** When the user provides a list of contacts to add (from CSV, manual input, or any source other than Gmail). \" +\n \"For Gmail specifically, use import_gmail_contacts instead.\\n\\n\" +\n \"**Returns:** Import statistics: imported (total processed), skipped (invalid), newContacts (ghost users created), \" +\n \"existingContacts (already in network). Use list_contacts to see all contacts after import.\",\n querySchema: z.object({\n contacts: z.array(z.object({\n name: z.string().describe('Full name of the contact (e.g. \"Jane Smith\")'),\n email: z.string().describe('Email address — used as the unique identifier for matching existing users'),\n })).describe('Array of contact objects to import. Each must have name and email. Duplicates (by email) are skipped.'),\n }),\n handler: async ({ context, query }) => {\n try {\n const result = await contactService.importContacts(\n context.userId,\n query.contacts\n );\n return success({\n message: `Imported ${result.imported} contacts to your network.`,\n imported: result.imported,\n skipped: result.skipped,\n newContacts: result.newContacts,\n existingContacts: result.existingContacts,\n });\n } catch (err) {\n logger.error('Failed to import contacts', { err });\n return error('Failed to import contacts. Please try again.');\n }\n },\n }) : null;\n\n const list_contacts = defineTool({\n name: 'list_contacts',\n description:\n \"Lists all contacts in the authenticated user's personal network. Contacts are people the user has added \" +\n \"(via import_contacts, add_contact, or import_gmail_contacts) stored as members of their personal index.\\n\\n\" +\n \"**When to use:** To see who's in the user's network, find a contact's userId for other operations, \" +\n \"or check if a specific person is already a contact.\\n\\n\" +\n \"**Returns:** Array of contacts, each with: userId (use with read_user_profiles or discover_opportunities), \" +\n \"name, email, avatar URL, and isGhost (true = no account yet, profile enriched from public data). \" +\n \"Use the userId with read_user_profiles(userId) to get the full profile, or with discover_opportunities(targetUserId) to connect.\",\n querySchema: z.object({\n limit: z.number().optional().describe('Maximum number of contacts to return. Omit to return all contacts. Use for large networks to paginate results.'),\n }),\n handler: async ({ context, query }) => {\n try {\n let contacts = await contactService.listContacts(context.userId);\n\n if (query.limit && query.limit > 0) {\n contacts = contacts.slice(0, query.limit);\n }\n\n return success({\n count: contacts.length,\n contacts: contacts.map(c => ({\n userId: c.userId,\n name: c.user.name,\n email: c.user.email,\n avatar: c.user.avatar,\n isGhost: c.user.isGhost,\n })),\n });\n } catch (err) {\n logger.error('Failed to list contacts', { err });\n return error('Failed to list contacts. Please try again.');\n }\n },\n });\n\n const add_contact = contactsEnabled ? defineTool({\n name: 'add_contact',\n description:\n \"Adds a single contact to the authenticated user's personal network by email address. \" +\n \"For bulk imports, use import_contacts instead.\\n\\n\" +\n \"**What happens:** Looks up the email. If an account exists, links that user as a contact. \" +\n \"If not, creates a ghost user (placeholder enriched with public profile data) and adds them. \" +\n \"The contact can then appear in opportunity discovery within the user's personal index.\\n\\n\" +\n \"**When to use:** When the user wants to add a specific person (e.g. 'add john@example.com to my network').\\n\\n\" +\n \"**Returns:** Confirmation with the contact's userId and whether a new ghost user was created (isNewGhost). \" +\n \"Use the userId with discover_opportunities(targetUserId) to find connection opportunities.\",\n querySchema: z.object({\n email: z.string().describe('Email address of the person to add. Used as unique identifier — if already a contact, the operation is idempotent.'),\n name: z.string().optional().describe('Full name of the contact. Optional — if omitted, the email prefix is used as name. Provide when known for better profile enrichment.'),\n }),\n handler: async ({ context, query }) => {\n try {\n const result = await contactService.addContact(context.userId, query.email, { name: query.name, restore: true });\n\n return success({\n added: true,\n message: result.isNew\n ? `Added ${query.name || query.email} to your network. Their profile is being enriched.`\n : `Added ${query.name || query.email} to your network.`,\n userId: result.userId,\n isNewGhost: result.isNew,\n });\n } catch (err) {\n logger.error('Failed to add contact', { err });\n return error('Failed to add contact. Please try again.');\n }\n },\n }) : null;\n\n const remove_contact = defineTool({\n name: 'remove_contact',\n description:\n \"Removes a contact from the authenticated user's personal network. The contact relationship is deleted — \" +\n \"the person is no longer a member of the user's personal index and won't appear in personal-index-scoped discovery.\\n\\n\" +\n \"**When to use:** When the user wants to remove someone from their network (e.g. 'remove John from my contacts').\\n\\n\" +\n \"**Note:** This only removes the contact relationship. If the contact is a real user (not a ghost), \" +\n \"they still exist on the platform and may appear in shared index discovery.\\n\\n\" +\n \"**Returns:** Confirmation that the contact was removed.\",\n querySchema: z.object({\n contactUserId: z.string().describe('The userId of the contact to remove. Get this from list_contacts results.'),\n }),\n handler: async ({ context, query }) => {\n try {\n await contactService.removeContact(context.userId, query.contactUserId);\n return success({ removed: true, message: 'Contact removed from your network.' });\n } catch (err) {\n logger.error('Failed to remove contact', { err });\n return error('Failed to remove contact. Please try again.');\n }\n },\n });\n\n const search_contacts = defineTool({\n name: 'search_contacts',\n description:\n \"Searches the authenticated user's personal network by name or email (case-insensitive substring). \" +\n \"Use when the user refers to a contact by partial name or email and you need their userId for another tool \" +\n \"(e.g. read_user_profiles, discover_opportunities).\\n\\n\" +\n \"**When to use:** Before list_contacts when the network is large — returns only matching contacts, bounded by limit.\\n\\n\" +\n \"**Returns:** Array of matching contacts: userId, name, email, avatar, isGhost.\",\n querySchema: z.object({\n query: z.string().trim().min(1).describe('Free-text query matched against contact name and email (case-insensitive, substring).'),\n limit: z.number().int().positive().max(100).optional().describe('Maximum rows to return. Defaults to 25.'),\n }),\n handler: async ({ context, query }) => {\n try {\n const rows = await contactService.searchContacts(context.userId, query.query, query.limit ?? 25);\n return success({\n count: rows.length,\n contacts: rows.map(r => ({\n userId: r.contactId,\n name: r.name,\n email: r.email,\n avatar: r.avatar,\n isGhost: r.isGhost,\n })),\n });\n } catch (err) {\n logger.error('Failed to search contacts', { err });\n return error('Failed to search contacts. Please try again.');\n }\n },\n });\n\n return [\n ...(import_contacts ? [import_contacts] : []),\n ...(add_contact ? [add_contact] : []),\n list_contacts,\n remove_contact,\n search_contacts,\n ];\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integration.tools.d.ts","sourceRoot":"/","sources":["integration/integration.tools.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AAO5E;;;;;;;;;GASG;AACH,wBAAgB,sBAAsB,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,
|
|
1
|
+
{"version":3,"file":"integration.tools.d.ts","sourceRoot":"/","sources":["integration/integration.tools.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AAO5E;;;;;;;;;GASG;AACH,wBAAgB,sBAAsB,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,SA6E5E"}
|
|
@@ -15,6 +15,12 @@ const logger = protocolLogger('IntegrationTools');
|
|
|
15
15
|
*/
|
|
16
16
|
export function createIntegrationTools(defineTool, deps) {
|
|
17
17
|
const { integration, integrationImporter } = deps;
|
|
18
|
+
// import_gmail_contacts creates ghost users, so it is gated behind the
|
|
19
|
+
// CONTACTS_ENABLED flag (injected as deps.contactsEnabled). When disabled the
|
|
20
|
+
// tool is not registered at all (defineTool registers as a side effect).
|
|
21
|
+
if (deps.contactsEnabled !== true) {
|
|
22
|
+
return [];
|
|
23
|
+
}
|
|
18
24
|
const import_gmail_contacts = defineTool({
|
|
19
25
|
name: 'import_gmail_contacts',
|
|
20
26
|
description: "Imports contacts from the user's connected Gmail/Google account into their personal network. " +
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integration.tools.js","sourceRoot":"/","sources":["integration/integration.tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAE5E,MAAM,MAAM,GAAG,cAAc,CAAC,kBAAkB,CAAC,CAAC;AAElD;;;;;;;;;GASG;AACH,MAAM,UAAU,sBAAsB,CAAC,UAAsB,EAAE,IAAc;IAC3E,MAAM,EAAE,WAAW,EAAE,mBAAmB,EAAE,GAAG,IAAI,CAAC;IAElD,MAAM,qBAAqB,GAAG,UAAU,CAAC;QACvC,IAAI,EAAE,uBAAuB;QAC7B,WAAW,EACT,+FAA+F;YAC/F,6IAA6I;YAC7I,oHAAoH;YACpH,mFAAmF;YACnF,qFAAqF;YACrF,kIAAkI;YAClI,6FAA6F;YAC7F,8GAA8G;YAC9G,2GAA2G;YAC3G,wHAAwH;QAC1H,WAAW,EAAE,CAAC,CAAC,MAAM,CAAC,EAAE,CAAC;QACzB,OAAO,EAAE,KAAK,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE;YAC7B,IAAI,CAAC;gBACH,MAAM,OAAO,GAAG,MAAM,WAAW,CAAC,aAAa,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;gBAChE,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,QAAQ,EAAE,CAAC;gBAE1C,MAAM,YAAY,GAAG,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,OAAO,CAAC,CAAC;gBAClE,MAAM,WAAW,GAAG,CAAC,CAAC,YAAY,EAAE,UAAU,EAAE,gBAAg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OAAO,YAAY,CAAC,QAAQ,2EAA2E;4BACzG,CAAC,CAAC,oEAAoE;oBAC1E,QAAQ,EAAE,YAAY,CAAC,QAAQ;oBAC/B,WAAW,EAAE,YAAY,CAAC,WAAW;oBACrC,gBAAgB,EAAE,YAAY,CAAC,gBAAgB;oBAC/C,OAAO,EAAE,YAAY,CAAC,OAAO;iBAC9B,CAAC,CAAC;YACL,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,MAAM,CAAC,KAAK,CAAC,8BAA8B,EAAE;oBAC3C,MAAM,EAAE,OAAO,CAAC,MAAM;oBACtB,GAAG;iBACJ,CAAC,CAAC;gBACH,OAAO,KAAK,CAAC,oDAAoD,CAAC,CAAC;YACrE,CAAC;QACH,CAAC;KACF,CAAC,CAAC;IAEH,OAAO,CAAC,qBAAqB,CAAC,CAAC;AACjC,CAAC","sourcesContent":["import { z } from 'zod';\nimport type { DefineTool, ToolDeps } from '../shared/agent/tool.helpers.js';\nimport { success, error } from '../shared/agent/tool.helpers.js';\nimport { requestContext } from \"../shared/observability/request-context.js\";\nimport { protocolLogger } from '../shared/observability/protocol.logger.js';\n\nconst logger = protocolLogger('IntegrationTools');\n\n/**\n * Creates integration tools for the chat agent.\n *\n * Exposes `import_gmail_contacts` which authenticates via the integration adapter,\n * fetches all Gmail contacts (paginated), and imports them as ghost users into the network.\n *\n * @param defineTool - Tool definition helper injected by the tool registry.\n * @param deps - Shared tool dependencies including the integration adapter.\n * @returns An array of tool definitions to register with the chat agent.\n */\nexport function createIntegrationTools(defineTool: DefineTool, deps: ToolDeps) {\n const { integration, integrationImporter } = deps;\n\n const import_gmail_contacts = defineTool({\n name: 'import_gmail_contacts',\n description:\n \"Imports contacts from the user's connected Gmail/Google account into their personal network. \" +\n \"This is the preferred method for importing Google Contacts — handles OAuth authentication, pagination, and deduplication automatically.\\n\\n\" +\n \"**Authentication flow:** If Gmail is not yet connected, returns an `authUrl` the user must visit to grant access. \" +\n \"After they complete OAuth, call this tool again to perform the actual import.\\n\\n\" +\n \"**What happens on import:** All Gmail contacts with valid name+email are imported. \" +\n \"Contacts without existing platform accounts become ghost users (enriched with public profile data from LinkedIn, GitHub, etc.). \" +\n \"All imported contacts are added to the user's personal index for opportunity discovery.\\n\\n\" +\n \"**When to use:** When the user asks to import or sync their Gmail/Google contacts. No parameters needed.\\n\\n\" +\n \"**Returns:** Either `{ requiresAuth: true, authUrl }` (user needs to authenticate) or import statistics: \" +\n \"imported (total), newContacts (ghost users created), existingContacts (already in network), skipped (invalid entries).\",\n querySchema: z.object({}),\n handler: async ({ context }) => {\n try {\n const session = await integration.createSession(context.userId);\n const toolkits = await session.toolkits();\n\n const gmailToolkit = toolkits.items.find(t => t.slug === 'gmail');\n const isConnected = !!gmailToolkit?.connection?.connectedAccount?.id;\n\n if (!isConnected) {\n logger.info('Gmail not connected, returning auth URL', { userId: context.userId });\n const originUrl = requestContext.getStore()?.originUrl;\n const callbackUrl = originUrl ? `${originUrl}/oauth/callback` : undefined;\n type AuthorizeFn = (toolkit: string, options?: { callbackUrl?: string }) => Promise<{ redirectUrl: string }>;\n const authRequest = await (session.authorize as unknown as AuthorizeFn)('gmail', callbackUrl ? { callbackUrl } : undefined);\n return success({\n requiresAuth: true,\n message: 'Please connect your Gmail account to import contacts.',\n authUrl: authRequest.redirectUrl,\n });\n }\n\n const importResult = await integrationImporter.importContacts(context.userId, 'gmail');\n\n logger.info('Gmail contacts imported', {\n userId: context.userId,\n imported: importResult.imported,\n skipped: importResult.skipped,\n newContacts: importResult.newContacts,\n existingContacts: importResult.existingContacts,\n });\n\n return success({\n message: importResult.newContacts > 0\n ? `Imported ${importResult.imported} contacts from Gmail. ${importResult.newContacts} new, ${importResult.existingContacts} already in your network.`\n : importResult.imported > 0\n ? `All ${importResult.imported} contacts from Gmail were already in your network. No new contacts added.`\n : 'No contacts with valid name and email found in your Gmail account.',\n imported: importResult.imported,\n newContacts: importResult.newContacts,\n existingContacts: importResult.existingContacts,\n skipped: importResult.skipped,\n });\n } catch (err) {\n logger.error('import_gmail_contacts failed', {\n userId: context.userId,\n err,\n });\n return error('Failed to import Gmail contacts. Please try again.');\n }\n },\n });\n\n return [import_gmail_contacts];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"integration.tools.js","sourceRoot":"/","sources":["integration/integration.tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAE5E,MAAM,MAAM,GAAG,cAAc,CAAC,kBAAkB,CAAC,CAAC;AAElD;;;;;;;;;GASG;AACH,MAAM,UAAU,sBAAsB,CAAC,UAAsB,EAAE,IAAc;IAC3E,MAAM,EAAE,WAAW,EAAE,mBAAmB,EAAE,GAAG,IAAI,CAAC;IAElD,uEAAuE;IACvE,8EAA8E;IAC9E,yEAAyE;IACzE,IAAI,IAAI,CAAC,eAAe,KAAK,IAAI,EAAE,CAAC;QAClC,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,MAAM,qBAAqB,GAAG,UAAU,CAAC;QACvC,IAAI,EAAE,uBAAuB;QAC7B,WAAW,EACT,+FAA+F;YAC/F,6IAA6I;YAC7I,oHAAoH;YACpH,mFAAmF;YACnF,qFAAqF;YACrF,kIAAkI;YAClI,6FAA6F;YAC7F,8GAA8G;YAC9G,2GAA2G;YAC3G,wHAAwH;QAC1H,WAAW,EAAE,CAAC,CAAC,MAAM,CAAC,EAAE,CAAC;QACzB,OAAO,EAAE,KAAK,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE;YAC7B,IAAI,CAAC;gBACH,MAAM,OAAO,GAAG,MAAM,WAAW,CAAC,aAAa,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;gBAChE,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC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AAO,EAAE,YAAY,CAAC,WAAW,GAAG,CAAC;wBACnC,CAAC,CAAC,YAAY,YAAY,CAAC,QAAQ,yBAAyB,YAAY,CAAC,WAAW,SAAS,YAAY,CAAC,gBAAgB,2BAA2B;wBACrJ,CAAC,CAAC,YAAY,CAAC,QAAQ,GAAG,CAAC;4BACzB,CAAC,CAAC,OAAO,YAAY,CAAC,QAAQ,2EAA2E;4BACzG,CAAC,CAAC,oEAAoE;oBAC1E,QAAQ,EAAE,YAAY,CAAC,QAAQ;oBAC/B,WAAW,EAAE,YAAY,CAAC,WAAW;oBACrC,gBAAgB,EAAE,YAAY,CAAC,gBAAgB;oBAC/C,OAAO,EAAE,YAAY,CAAC,OAAO;iBAC9B,CAAC,CAAC;YACL,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,MAAM,CAAC,KAAK,CAAC,8BAA8B,EAAE;oBAC3C,MAAM,EAAE,OAAO,CAAC,MAAM;oBACtB,GAAG;iBACJ,CAAC,CAAC;gBACH,OAAO,KAAK,CAAC,oDAAoD,CAAC,CAAC;YACrE,CAAC;QACH,CAAC;KACF,CAAC,CAAC;IAEH,OAAO,CAAC,qBAAqB,CAAC,CAAC;AACjC,CAAC","sourcesContent":["import { z } from 'zod';\nimport type { DefineTool, ToolDeps } from '../shared/agent/tool.helpers.js';\nimport { success, error } from '../shared/agent/tool.helpers.js';\nimport { requestContext } from \"../shared/observability/request-context.js\";\nimport { protocolLogger } from '../shared/observability/protocol.logger.js';\n\nconst logger = protocolLogger('IntegrationTools');\n\n/**\n * Creates integration tools for the chat agent.\n *\n * Exposes `import_gmail_contacts` which authenticates via the integration adapter,\n * fetches all Gmail contacts (paginated), and imports them as ghost users into the network.\n *\n * @param defineTool - Tool definition helper injected by the tool registry.\n * @param deps - Shared tool dependencies including the integration adapter.\n * @returns An array of tool definitions to register with the chat agent.\n */\nexport function createIntegrationTools(defineTool: DefineTool, deps: ToolDeps) {\n const { integration, integrationImporter } = deps;\n\n // import_gmail_contacts creates ghost users, so it is gated behind the\n // CONTACTS_ENABLED flag (injected as deps.contactsEnabled). When disabled the\n // tool is not registered at all (defineTool registers as a side effect).\n if (deps.contactsEnabled !== true) {\n return [];\n }\n\n const import_gmail_contacts = defineTool({\n name: 'import_gmail_contacts',\n description:\n \"Imports contacts from the user's connected Gmail/Google account into their personal network. \" +\n \"This is the preferred method for importing Google Contacts — handles OAuth authentication, pagination, and deduplication automatically.\\n\\n\" +\n \"**Authentication flow:** If Gmail is not yet connected, returns an `authUrl` the user must visit to grant access. \" +\n \"After they complete OAuth, call this tool again to perform the actual import.\\n\\n\" +\n \"**What happens on import:** All Gmail contacts with valid name+email are imported. \" +\n \"Contacts without existing platform accounts become ghost users (enriched with public profile data from LinkedIn, GitHub, etc.). \" +\n \"All imported contacts are added to the user's personal index for opportunity discovery.\\n\\n\" +\n \"**When to use:** When the user asks to import or sync their Gmail/Google contacts. No parameters needed.\\n\\n\" +\n \"**Returns:** Either `{ requiresAuth: true, authUrl }` (user needs to authenticate) or import statistics: \" +\n \"imported (total), newContacts (ghost users created), existingContacts (already in network), skipped (invalid entries).\",\n querySchema: z.object({}),\n handler: async ({ context }) => {\n try {\n const session = await integration.createSession(context.userId);\n const toolkits = await session.toolkits();\n\n const gmailToolkit = toolkits.items.find(t => t.slug === 'gmail');\n const isConnected = !!gmailToolkit?.connection?.connectedAccount?.id;\n\n if (!isConnected) {\n logger.info('Gmail not connected, returning auth URL', { userId: context.userId });\n const originUrl = requestContext.getStore()?.originUrl;\n const callbackUrl = originUrl ? `${originUrl}/oauth/callback` : undefined;\n type AuthorizeFn = (toolkit: string, options?: { callbackUrl?: string }) => Promise<{ redirectUrl: string }>;\n const authRequest = await (session.authorize as unknown as AuthorizeFn)('gmail', callbackUrl ? { callbackUrl } : undefined);\n return success({\n requiresAuth: true,\n message: 'Please connect your Gmail account to import contacts.',\n authUrl: authRequest.redirectUrl,\n });\n }\n\n const importResult = await integrationImporter.importContacts(context.userId, 'gmail');\n\n logger.info('Gmail contacts imported', {\n userId: context.userId,\n imported: importResult.imported,\n skipped: importResult.skipped,\n newContacts: importResult.newContacts,\n existingContacts: importResult.existingContacts,\n });\n\n return success({\n message: importResult.newContacts > 0\n ? `Imported ${importResult.imported} contacts from Gmail. ${importResult.newContacts} new, ${importResult.existingContacts} already in your network.`\n : importResult.imported > 0\n ? `All ${importResult.imported} contacts from Gmail were already in your network. No new contacts added.`\n : 'No contacts with valid name and email found in your Gmail account.',\n imported: importResult.imported,\n newContacts: importResult.newContacts,\n existingContacts: importResult.existingContacts,\n skipped: importResult.skipped,\n });\n } catch (err) {\n logger.error('import_gmail_contacts failed', {\n userId: context.userId,\n err,\n });\n return error('Failed to import Gmail contacts. Please try again.');\n }\n },\n });\n\n return [import_gmail_contacts];\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool.factory.d.ts","sourceRoot":"/","sources":["shared/agent/tool.factory.ts"],"names":[],"mappings":"AAmBA,OAAO,EAAE,KAAK,WAAW,EAAE,KAAK,mBAAmB,EAAqC,MAAM,mBAAmB,CAAC;AAelH,YAAY,EAAE,WAAW,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACxF,YAAY,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAQlD;;;;;;;GAOG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,WAAW,EACjB,kBAAkB,CAAC,EAAE,mBAAmB,
|
|
1
|
+
{"version":3,"file":"tool.factory.d.ts","sourceRoot":"/","sources":["shared/agent/tool.factory.ts"],"names":[],"mappings":"AAmBA,OAAO,EAAE,KAAK,WAAW,EAAE,KAAK,mBAAmB,EAAqC,MAAM,mBAAmB,CAAC;AAelH,YAAY,EAAE,WAAW,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACxF,YAAY,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAQlD;;;;;;;GAOG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,WAAW,EACjB,kBAAkB,CAAC,EAAE,mBAAmB,kBAuMzC;AAED;;GAEG;AACH,MAAM,MAAM,SAAS,GAAG,OAAO,CAAC,UAAU,CAAC,OAAO,eAAe,CAAC,CAAC,CAAC"}
|
|
@@ -134,6 +134,7 @@ export async function createChatTools(deps, preResolvedContext) {
|
|
|
134
134
|
cache,
|
|
135
135
|
integration,
|
|
136
136
|
contactService: deps.contactService,
|
|
137
|
+
contactsEnabled: deps.contactsEnabled,
|
|
137
138
|
integrationImporter: deps.integrationImporter,
|
|
138
139
|
enricher: deps.enricher,
|
|
139
140
|
negotiationDatabase: deps.negotiationDatabase,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool.factory.js","sourceRoot":"/","sources":["shared/agent/tool.factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAG7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AACjF,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,6BAA6B,EAAE,MAAM,8CAA8C,CAAC;AAC7F,OAAO,EAAE,yBAAyB,EAAE,MAAM,wCAAwC,CAAC;AACnF,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAC/D,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AACjF,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,cAAc,EAAE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;QAC5C,8BAA8B;KAC/B,CAAC,CAAC;IACH,MAAM,uBAAuB,GAAG,gBAAgB,CAAC,MAAM,CACrD,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,6BAA6B,CAAC,GAAG,CAAE,CAAsB,CAAC,IAAI,CAAC,CACxE,CAAC;IAEF,OAAO;QACL,GAAG,YAAY;QACf,GAAG,WAAW;QACd,GAAG,YAAY;QACf,GAAG,uBAAuB;QAC1B,GAAG,YAAY;QACf,GAAG,gBAAgB;QACnB,GAAG,YAAY;QACf,GAAG,UAAU;QACb,GAAG,gBAAgB;QACnB,GAAG,YAAY;KAChB,CAAC;AACJ,CAAC","sourcesContent":["import { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport type { HydeGraphDatabase } from \"../interfaces/database.interface.js\";\nimport { IntentGraphFactory } from \"../../intent/intent.graph.js\";\nimport { ProfileGraphFactory } from \"../../profile/profile.graph.js\";\nimport { OpportunityGraphFactory } from \"../../opportunity/opportunity.graph.js\";\nimport { HydeGraphFactory } from \"../hyde/hyde.graph.js\";\nimport { HydeGenerator } from \"../hyde/hyde.generator.js\";\nimport { LensInferrer } from \"../hyde/lens.inferrer.js\";\nimport { NetworkGraphFactory } from \"../../network/network.graph.js\";\nimport { NetworkMembershipGraphFactory } from \"../../network/membership/membership.graph.js\";\nimport { IntentNetworkGraphFactory } from \"../../network/indexer/indexer.graph.js\";\nimport { IntentIndexer } from \"../../intent/intent.indexer.js\";\nimport { NegotiationGraphFactory } from \"../../negotiation/negotiation.graph.js\";\nimport { PremiseGraphFactory } from \"../../premise/premise.graph.js\";\nimport { protocolLogger } from \"../observability/protocol.logger.js\";\n\nimport type { QuestionerEnqueueFn } from \"../../questioner/questioner.types.js\";\n\nimport { type ToolContext, type ResolvedToolContext, type ToolDeps, resolveChatContext } from \"./tool.helpers.js\";\nimport { error, redactSensitiveFields } from \"./tool.helpers.js\";\nimport { invokeToolRuntime, toolRuntimeErrorToResult } from \"./tool.runtime.js\";\nimport { createProfileTools } from \"../../profile/profile.tools.js\";\nimport { createIntentTools } from \"../../intent/intent.tools.js\";\nimport { createNetworkTools } from \"../../network/network.tools.js\";\nimport { createOpportunityTools } from \"../../opportunity/opportunity.tools.js\";\nimport { createUtilityTools } from \"./utility.tools.js\";\nimport { createIntegrationTools } from \"../../integration/integration.tools.js\";\nimport { createContactTools } from \"../../contact/contact.tools.js\";\nimport { createAgentTools } from \"../../agent/agent.tools.js\";\nimport { createNegotiationTools } from \"../../negotiation/negotiation.tools.js\";\nimport { createPremiseTools } from \"../../premise/premise.tools.js\";\n\n// Re-export types for consumers\nexport type { ToolContext, ResolvedToolContext, ProtocolDeps } from \"./tool.helpers.js\";\nexport type { ToolDeps } from \"./tool.helpers.js\";\n\nconst logger = protocolLogger(\"ChatTools\");\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TOOL FACTORY\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Creates all chat tools bound to a specific user context.\n * Resolves user/index identity from DB at init time.\n * Tools are created fresh for each user session to ensure proper isolation.\n *\n * All external dependencies (cache, integration, queue, etc.) are provided\n * via the `deps` parameter — the protocol lib never imports concrete adapters.\n */\nexport async function createChatTools(\n deps: ToolContext,\n preResolvedContext?: ResolvedToolContext\n) {\n const { database, embedder, scraper } = deps;\n\n // ─── Resolve context from DB ───────────────────────────────────────────────\n const resolvedContext =\n preResolvedContext ??\n (await resolveChatContext({\n database,\n userId: deps.userId,\n networkId: deps.networkId,\n sessionId: deps.sessionId,\n }));\n\n // Allow callers (e.g. MCP server, tests) to override the computed indexScope\n // without going through a full re-resolve. The MCP path sets this via\n // applyNetworkScopeToContext; ToolContext.indexScope provides the same override\n // when no preResolvedContext is given.\n if (!preResolvedContext && deps.indexScope !== undefined) {\n resolvedContext.indexScope = deps.indexScope;\n }\n\n // ─── Tool wrapper ──────────────────────────────────────────────────────────\n /**\n * Standardized tool factory. Auto-injects resolved context and\n * provides uniform logging / error handling for every tool.\n */\n function defineTool<T extends z.ZodType>(opts: {\n name: string;\n description: string;\n querySchema: T;\n handler: (input: { context: ResolvedToolContext; query: z.infer<T> }) => Promise<string>;\n }) {\n return tool(\n async (query: z.infer<T>) => {\n logger.info(`Tool: ${opts.name}`, {\n context: { userId: resolvedContext.userId, networkId: resolvedContext.networkId },\n query: redactSensitiveFields(query),\n });\n try {\n return await invokeToolRuntime({\n toolName: opts.name,\n tool: { handler: async ({ context, query }) => opts.handler({ context, query: query as z.infer<T> }) },\n context: resolvedContext,\n query,\n });\n } catch (err) {\n logger.error(`${opts.name} failed`, {\n error: err instanceof Error ? err.message : String(err),\n });\n const runtimeResult = toolRuntimeErrorToResult(err);\n if (runtimeResult) return runtimeResult;\n const reason = err instanceof Error ? err.message : String(err);\n return error(`Failed to execute ${opts.name}: ${reason}`);\n }\n },\n { name: opts.name, description: opts.description, schema: opts.querySchema }\n );\n }\n\n // ─── Compile subgraphs ─────────────────────────────────────────────────────\n\n // Wrap questionerEnqueue to include session context when available\n const sessionAwareEnqueue: QuestionerEnqueueFn | undefined = deps.questionerEnqueue\n ? (input) => deps.questionerEnqueue!({\n ...input,\n ...(resolvedContext.sessionId && !input.conversationId ? { conversationId: resolvedContext.sessionId } : {}),\n })\n : undefined;\n\n const intentGraph = new IntentGraphFactory(database, embedder, deps.intentQueue, sessionAwareEnqueue).createGraph();\n const premiseGraph = new PremiseGraphFactory(database, embedder).createGraph();\n const profileGraph = new ProfileGraphFactory(database, scraper, deps.enricher, sessionAwareEnqueue, premiseGraph).createGraph();\n const hydeCache = deps.hydeCache;\n const lensInferrer = new LensInferrer();\n const hydeGenerator = new HydeGenerator();\n const compiledHydeGraph = new HydeGraphFactory(\n database as unknown as HydeGraphDatabase,\n embedder,\n hydeCache,\n lensInferrer,\n hydeGenerator\n ).createGraph();\n const negotiationGraph = deps.agentDispatcher\n ? new NegotiationGraphFactory(\n deps.negotiationDatabase,\n deps.agentDispatcher,\n deps.negotiationTimeoutQueue,\n sessionAwareEnqueue,\n ).createGraph()\n : undefined;\n const opportunityGraph = new OpportunityGraphFactory(\n database,\n embedder,\n compiledHydeGraph,\n undefined, // evaluator (default)\n undefined, // queueNotification\n negotiationGraph,\n deps.agentDispatcher,\n deps.queueNegotiateExisting,\n ).createGraph();\n const networkGraph = new NetworkGraphFactory(database).createGraph();\n const networkMembershipGraph = new NetworkMembershipGraphFactory(database).createGraph();\n const intentNetworkGraph = new IntentNetworkGraphFactory(database, new IntentIndexer()).createGraph();\n\n // ─── Create context-bound databases ────────────────────────────────────────\n // Use injected instances when provided (e.g. tests). Otherwise create from the same\n // database used for graphs so that scope checks (e.g. ensureScopedMembership, opportunity\n // update) use the same adapter as the rest of the tool pipeline.\n //\n // The systemDb's DB-level clamp uses `resolvedContext.indexScope` — the same\n // set tools see — so the JSDoc claim that indexScope is \"the same set used\n // to clamp the DB-level systemDb\" holds for both the MCP path (where the\n // MCP server already populated indexScope via applyNetworkScopeToContext)\n // and the web-chat path (where resolveChatContext clamps to [bound, personal]\n // when networkId is set).\n const userDb = deps.userDb ?? deps.createUserDatabase(database, resolvedContext.userId);\n const systemDb = deps.systemDb ?? deps.createSystemDatabase(database, resolvedContext.userId, resolvedContext.indexScope, embedder);\n\n // ─── Assemble dependencies ─────────────────────────────────────────────────\n const cache = deps.cache;\n const integration = deps.integration;\n const toolDeps: ToolDeps = {\n database,\n userDb,\n systemDb,\n scraper,\n embedder,\n cache,\n integration,\n contactService: deps.contactService,\n integrationImporter: deps.integrationImporter,\n enricher: deps.enricher,\n negotiationDatabase: deps.negotiationDatabase,\n negotiationTimeoutQueue: deps.negotiationTimeoutQueue,\n agentDatabase: deps.agentDatabase,\n grantDefaultSystemPermissions: deps.grantDefaultSystemPermissions,\n agentDispatcher: deps.agentDispatcher,\n deliveryLedger: deps.deliveryLedger,\n discoveryRuns: deps.discoveryRuns,\n discoveryRunQueue: deps.discoveryRunQueue,\n profileRuns: deps.profileRuns,\n profileRunQueue: deps.profileRunQueue,\n mintConnectToken: deps.mintConnectToken,\n mintConnectLink: deps.mintConnectLink,\n frontendUrl: deps.frontendUrl,\n apiBaseUrl: deps.apiBaseUrl,\n ...(deps.premiseEvents && { premiseEvents: deps.premiseEvents }),\n ...(deps.chatSummary && { chatSummary: deps.chatSummary }),\n ...(deps.questionGenerator && { questionGenerator: deps.questionGenerator }),\n ...(sessionAwareEnqueue && { questionerEnqueue: sessionAwareEnqueue }),\n ...(deps.negotiationSummary && { negotiationSummary: deps.negotiationSummary }),\n graphs: {\n profile: profileGraph,\n intent: intentGraph,\n index: networkGraph,\n networkMembership: networkMembershipGraph,\n intentIndex: intentNetworkGraph,\n opportunity: opportunityGraph,\n premise: premiseGraph,\n },\n };\n\n // ─── Create domain tools ──────────────────────────────────────────────────\n const profileTools = createProfileTools(defineTool, toolDeps);\n const intentTools = createIntentTools(defineTool, toolDeps);\n const networkTools = createNetworkTools(defineTool, toolDeps);\n const opportunityTools = createOpportunityTools(defineTool, toolDeps);\n const utilityTools = createUtilityTools(defineTool, toolDeps);\n const contactTools = createContactTools(defineTool, toolDeps);\n const agentTools = createAgentTools(defineTool, toolDeps);\n const integrationTools = createIntegrationTools(defineTool, toolDeps);\n const negotiationTools = deps.agentDispatcher\n ? createNegotiationTools(defineTool, toolDeps)\n : [];\n const premiseTools = createPremiseTools(defineTool, toolDeps);\n\n // confirm_opportunity_delivery is an OpenClaw-delivery ledger write and must not be\n // callable from regular chat sessions.\n const chatOpportunityToolExclusions = new Set([\n \"confirm_opportunity_delivery\",\n ]);\n const opportunityToolsForChat = opportunityTools.filter(\n (t) => !chatOpportunityToolExclusions.has((t as { name: string }).name)\n );\n\n return [\n ...profileTools,\n ...intentTools,\n ...networkTools,\n ...opportunityToolsForChat,\n ...utilityTools,\n ...integrationTools,\n ...contactTools,\n ...agentTools,\n ...negotiationTools,\n ...premiseTools,\n ];\n}\n\n/**\n * Type for the tools array returned by createChatTools.\n */\nexport type ChatTools = Awaited<ReturnType<typeof createChatTools>>;\n"]}
|
|
1
|
+
{"version":3,"file":"tool.factory.js","source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nimport { z } from \"zod\";\nimport type { HydeGraphDatabase } from \"../interfaces/database.interface.js\";\nimport { IntentGraphFactory } from \"../../intent/intent.graph.js\";\nimport { ProfileGraphFactory } from \"../../profile/profile.graph.js\";\nimport { OpportunityGraphFactory } from \"../../opportunity/opportunity.graph.js\";\nimport { HydeGraphFactory } from \"../hyde/hyde.graph.js\";\nimport { HydeGenerator } from \"../hyde/hyde.generator.js\";\nimport { LensInferrer } from \"../hyde/lens.inferrer.js\";\nimport { NetworkGraphFactory } from \"../../network/network.graph.js\";\nimport { NetworkMembershipGraphFactory } from \"../../network/membership/membership.graph.js\";\nimport { IntentNetworkGraphFactory } from \"../../network/indexer/indexer.graph.js\";\nimport { IntentIndexer } from \"../../intent/intent.indexer.js\";\nimport { NegotiationGraphFactory } from \"../../negotiation/negotiation.graph.js\";\nimport { PremiseGraphFactory } from \"../../premise/premise.graph.js\";\nimport { protocolLogger } from \"../observability/protocol.logger.js\";\n\nimport type { QuestionerEnqueueFn } from \"../../questioner/questioner.types.js\";\n\nimport { type ToolContext, type ResolvedToolContext, type ToolDeps, resolveChatContext } from \"./tool.helpers.js\";\nimport { error, redactSensitiveFields } from \"./tool.helpers.js\";\nimport { invokeToolRuntime, toolRuntimeErrorToResult } from \"./tool.runtime.js\";\nimport { createProfileTools } from \"../../profile/profile.tools.js\";\nimport { createIntentTools } from \"../../intent/intent.tools.js\";\nimport { createNetworkTools } from \"../../network/network.tools.js\";\nimport { createOpportunityTools } from \"../../opportunity/opportunity.tools.js\";\nimport { createUtilityTools } from \"./utility.tools.js\";\nimport { createIntegrationTools } from \"../../integration/integration.tools.js\";\nimport { createContactTools } from \"../../contact/contact.tools.js\";\nimport { createAgentTools } from \"../../agent/agent.tools.js\";\nimport { createNegotiationTools } from \"../../negotiation/negotiation.tools.js\";\nimport { createPremiseTools } from \"../../premise/premise.tools.js\";\n\n// Re-export types for consumers\nexport type { ToolContext, ResolvedToolContext, ProtocolDeps } from \"./tool.helpers.js\";\nexport type { ToolDeps } from \"./tool.helpers.js\";\n\nconst logger = protocolLogger(\"ChatTools\");\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TOOL FACTORY\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Creates all chat tools bound to a specific user context.\n * Resolves user/index identity from DB at init time.\n * Tools are created fresh for each user session to ensure proper isolation.\n *\n * All external dependencies (cache, integration, queue, etc.) are provided\n * via the `deps` parameter — the protocol lib never imports concrete adapters.\n */\nexport async function createChatTools(\n deps: ToolContext,\n preResolvedContext?: ResolvedToolContext\n) {\n const { database, embedder, scraper } = deps;\n\n // ─── Resolve context from DB ───────────────────────────────────────────────\n const resolvedContext =\n preResolvedContext ??\n (await resolveChatContext({\n database,\n userId: deps.userId,\n networkId: deps.networkId,\n sessionId: deps.sessionId,\n }));\n\n // Allow callers (e.g. MCP server, tests) to override the computed indexScope\n // without going through a full re-resolve. The MCP path sets this via\n // applyNetworkScopeToContext; ToolContext.indexScope provides the same override\n // when no preResolvedContext is given.\n if (!preResolvedContext && deps.indexScope !== undefined) {\n resolvedContext.indexScope = deps.indexScope;\n }\n\n // ─── Tool wrapper ──────────────────────────────────────────────────────────\n /**\n * Standardized tool factory. Auto-injects resolved context and\n * provides uniform logging / error handling for every tool.\n */\n function defineTool<T extends z.ZodType>(opts: {\n name: string;\n description: string;\n querySchema: T;\n handler: (input: { context: ResolvedToolContext; query: z.infer<T> }) => Promise<string>;\n }) {\n return tool(\n async (query: z.infer<T>) => {\n logger.info(`Tool: ${opts.name}`, {\n context: { userId: resolvedContext.userId, networkId: resolvedContext.networkId },\n query: redactSensitiveFields(query),\n });\n try {\n return await invokeToolRuntime({\n toolName: opts.name,\n tool: { handler: async ({ context, query }) => opts.handler({ context, query: query as z.infer<T> }) },\n context: resolvedContext,\n query,\n });\n } catch (err) {\n logger.error(`${opts.name} failed`, {\n error: err instanceof Error ? err.message : String(err),\n });\n const runtimeResult = toolRuntimeErrorToResult(err);\n if (runtimeResult) return runtimeResult;\n const reason = err instanceof Error ? err.message : String(err);\n return error(`Failed to execute ${opts.name}: ${reason}`);\n }\n },\n { name: opts.name, description: opts.description, schema: opts.querySchema }\n );\n }\n\n // ─── Compile subgraphs ─────────────────────────────────────────────────────\n\n // Wrap questionerEnqueue to include session context when available\n const sessionAwareEnqueue: QuestionerEnqueueFn | undefined = deps.questionerEnqueue\n ? (input) => deps.questionerEnqueue!({\n ...input,\n ...(resolvedContext.sessionId && !input.conversationId ? { conversationId: resolvedContext.sessionId } : {}),\n })\n : undefined;\n\n const intentGraph = new IntentGraphFactory(database, embedder, deps.intentQueue, sessionAwareEnqueue).createGraph();\n const premiseGraph = new PremiseGraphFactory(database, embedder).createGraph();\n const profileGraph = new ProfileGraphFactory(database, scraper, deps.enricher, sessionAwareEnqueue, premiseGraph).createGraph();\n const hydeCache = deps.hydeCache;\n const lensInferrer = new LensInferrer();\n const hydeGenerator = new HydeGenerator();\n const compiledHydeGraph = new HydeGraphFactory(\n database as unknown as HydeGraphDatabase,\n embedder,\n hydeCache,\n lensInferrer,\n hydeGenerator\n ).createGraph();\n const negotiationGraph = deps.agentDispatcher\n ? new NegotiationGraphFactory(\n deps.negotiationDatabase,\n deps.agentDispatcher,\n deps.negotiationTimeoutQueue,\n sessionAwareEnqueue,\n ).createGraph()\n : undefined;\n const opportunityGraph = new OpportunityGraphFactory(\n database,\n embedder,\n compiledHydeGraph,\n undefined, // evaluator (default)\n undefined, // queueNotification\n negotiationGraph,\n deps.agentDispatcher,\n deps.queueNegotiateExisting,\n ).createGraph();\n const networkGraph = new NetworkGraphFactory(database).createGraph();\n const networkMembershipGraph = new NetworkMembershipGraphFactory(database).createGraph();\n const intentNetworkGraph = new IntentNetworkGraphFactory(database, new IntentIndexer()).createGraph();\n\n // ─── Create context-bound databases ────────────────────────────────────────\n // Use injected instances when provided (e.g. tests). Otherwise create from the same\n // database used for graphs so that scope checks (e.g. ensureScopedMembership, opportunity\n // update) use the same adapter as the rest of the tool pipeline.\n //\n // The systemDb's DB-level clamp uses `resolvedContext.indexScope` — the same\n // set tools see — so the JSDoc claim that indexScope is \"the same set used\n // to clamp the DB-level systemDb\" holds for both the MCP path (where the\n // MCP server already populated indexScope via applyNetworkScopeToContext)\n // and the web-chat path (where resolveChatContext clamps to [bound, personal]\n // when networkId is set).\n const userDb = deps.userDb ?? deps.createUserDatabase(database, resolvedContext.userId);\n const systemDb = deps.systemDb ?? deps.createSystemDatabase(database, resolvedContext.userId, resolvedContext.indexScope, embedder);\n\n // ─── Assemble dependencies ─────────────────────────────────────────────────\n const cache = deps.cache;\n const integration = deps.integration;\n const toolDeps: ToolDeps = {\n database,\n userDb,\n systemDb,\n scraper,\n embedder,\n cache,\n integration,\n contactService: deps.contactService,\n contactsEnabled: deps.contactsEnabled,\n integrationImporter: deps.integrationImporter,\n enricher: deps.enricher,\n negotiationDatabase: deps.negotiationDatabase,\n negotiationTimeoutQueue: deps.negotiationTimeoutQueue,\n agentDatabase: deps.agentDatabase,\n grantDefaultSystemPermissions: deps.grantDefaultSystemPermissions,\n agentDispatcher: deps.agentDispatcher,\n deliveryLedger: deps.deliveryLedger,\n discoveryRuns: deps.discoveryRuns,\n discoveryRunQueue: deps.discoveryRunQueue,\n profileRuns: deps.profileRuns,\n profileRunQueue: deps.profileRunQueue,\n mintConnectToken: deps.mintConnectToken,\n mintConnectLink: deps.mintConnectLink,\n frontendUrl: deps.frontendUrl,\n apiBaseUrl: deps.apiBaseUrl,\n ...(deps.premiseEvents && { premiseEvents: deps.premiseEvents }),\n ...(deps.chatSummary && { chatSummary: deps.chatSummary }),\n ...(deps.questionGenerator && { questionGenerator: deps.questionGenerator }),\n ...(sessionAwareEnqueue && { questionerEnqueue: sessionAwareEnqueue }),\n ...(deps.negotiationSummary && { negotiationSummary: deps.negotiationSummary }),\n graphs: {\n profile: profileGraph,\n intent: intentGraph,\n index: networkGraph,\n networkMembership: networkMembershipGraph,\n intentIndex: intentNetworkGraph,\n opportunity: opportunityGraph,\n premise: premiseGraph,\n },\n };\n\n // ─── Create domain tools ──────────────────────────────────────────────────\n const profileTools = createProfileTools(defineTool, toolDeps);\n const intentTools = createIntentTools(defineTool, toolDeps);\n const networkTools = createNetworkTools(defineTool, toolDeps);\n const opportunityTools = createOpportunityTools(defineTool, toolDeps);\n const utilityTools = createUtilityTools(defineTool, toolDeps);\n const contactTools = createContactTools(defineTool, toolDeps);\n const agentTools = createAgentTools(defineTool, toolDeps);\n const integrationTools = createIntegrationTools(defineTool, toolDeps);\n const negotiationTools = deps.agentDispatcher\n ? createNegotiationTools(defineTool, toolDeps)\n : [];\n const premiseTools = createPremiseTools(defineTool, toolDeps);\n\n // confirm_opportunity_delivery is an OpenClaw-delivery ledger write and must not be\n // callable from regular chat sessions.\n const chatOpportunityToolExclusions = new Set([\n \"confirm_opportunity_delivery\",\n ]);\n const opportunityToolsForChat = opportunityTools.filter(\n (t) => !chatOpportunityToolExclusions.has((t as { name: string }).name)\n );\n\n return [\n ...profileTools,\n ...intentTools,\n ...networkTools,\n ...opportunityToolsForChat,\n ...utilityTools,\n ...integrationTools,\n ...contactTools,\n ...agentTools,\n ...negotiationTools,\n ...premiseTools,\n ];\n}\n\n/**\n * Type for the tools array returned by createChatTools.\n */\nexport type ChatTools = Awaited<ReturnType<typeof createChatTools>>;\n"]}
|
|
@@ -135,6 +135,13 @@ export interface ToolContext {
|
|
|
135
135
|
intentQueue: IntentGraphQueue;
|
|
136
136
|
/** Contact management operations. */
|
|
137
137
|
contactService: ContactServiceAdapter;
|
|
138
|
+
/**
|
|
139
|
+
* When false (or unset), the contact import / manual-add tools
|
|
140
|
+
* (import_contacts, add_contact, import_gmail_contacts) are not registered.
|
|
141
|
+
* Injected by the composition root from CONTACTS_ENABLED. Read/remove/search
|
|
142
|
+
* contact tools are always registered.
|
|
143
|
+
*/
|
|
144
|
+
contactsEnabled?: boolean;
|
|
138
145
|
/** Chat session reader for loading conversation history. */
|
|
139
146
|
chatSession: ChatSessionReader;
|
|
140
147
|
/** Read-through chat-session digest. Optional; consumers fall back to undefined `chatContext`. */
|
|
@@ -300,6 +307,13 @@ export interface ToolDeps {
|
|
|
300
307
|
cache: Cache;
|
|
301
308
|
integration: IntegrationAdapter;
|
|
302
309
|
contactService: ContactServiceAdapter;
|
|
310
|
+
/**
|
|
311
|
+
* When false (or unset), the contact import / manual-add tools
|
|
312
|
+
* (import_contacts, add_contact, import_gmail_contacts) are not registered.
|
|
313
|
+
* Injected by the composition root from CONTACTS_ENABLED. Read/remove/search
|
|
314
|
+
* contact tools are always registered.
|
|
315
|
+
*/
|
|
316
|
+
contactsEnabled?: boolean;
|
|
303
317
|
integrationImporter: {
|
|
304
318
|
importContacts(userId: string, toolkit: string): Promise<{
|
|
305
319
|
imported: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool.helpers.d.ts","sourceRoot":"/","sources":["shared/agent/tool.helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AACpE,OAAO,KAAK,EAAE,0BAA0B,EAAE,iBAAiB,EAAE,UAAU,EAAE,YAAY,EAAE,cAAc,EAAE,wBAAwB,EAAE,MAAM,qCAAqC,CAAC;AAC7K,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,oCAAoC,CAAC;AAClE,OAAO,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,kCAAkC,CAAC;AACzE,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,2CAA2C,CAAC;AAC1F,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,wCAAwC,CAAC;AACjF,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,oCAAoC,CAAC;AAChF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uCAAuC,CAAC;AAC7E,OAAO,KAAK,EAAE,gBAAgB,EAAE,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C;QACvD,IAAI,oBAAoB,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,CAAC;YACzC,GAAG,CAAC,GAAG,CAAC,GAAG,YAAY,CAAC;QAC1B,CAAC;aAAM,CAAC;YACN,GAAG,CAAC,GAAG,CAAC,GAAG,qBAAqB,CAAC,KAAK,CAAC,CAAC;QAC1C,CAAC;IACH,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import { z } from \"zod\";\nimport type { ModelConfig } from \"./model.config.js\";\nimport type { ProfileDocument } from \"../schemas/profile.schema.js\";\nimport type { ChatGraphCompositeDatabase, NetworkMembership, UserRecord, UserDatabase, SystemDatabase, NegotiationGraphDatabase } from \"../interfaces/database.interface.js\";\nimport type { Scraper } from \"../interfaces/scraper.interface.js\";\nimport type { Cache, HydeCache } from \"../interfaces/cache.interface.js\";\nimport type { CompiledOpportunityGraph } from \"../../opportunity/opportunity.discover.js\";\nimport type { IntegrationAdapter } from \"../interfaces/integration.interface.js\";\nimport type { ContactServiceAdapter } from \"../interfaces/contact.interface.js\";\nimport type { ProfileEnricher } from \"../interfaces/enrichment.interface.js\";\nimport type { IntentGraphQueue } from \"../interfaces/queue.interface.js\";\nimport type { ChatSessionReader } from \"../interfaces/chat-session.interface.js\";\nimport type { ChatSummaryReader } from \"../interfaces/chat-summary.interface.js\";\nimport type { ChatMessageWriter } from \"../interfaces/chat-message-writer.interface.js\";\nimport type { QuestionGeneratorReader } from \"../interfaces/question-generator.interface.js\";\nimport type { NegotiationSummaryReader } from \"../interfaces/negotiation-summary.interface.js\";\nimport type { Embedder } from \"../interfaces/embedder.interface.js\";\nimport type { AgentDatabase } from \"../interfaces/agent.interface.js\";\nimport type { NegotiationTimeoutQueue } from \"../interfaces/negotiation-events.interface.js\";\nimport type { AgentDispatcher } from \"../interfaces/agent-dispatcher.interface.js\";\nimport type { DeliveryLedger } from \"../interfaces/delivery-ledger.interface.js\";\nimport type { MintConnectLink } from \"../interfaces/connect-link.interface.js\";\nimport type { QuestionerDatabase } from \"../interfaces/questioner.interface.js\";\nimport type { QuestionerEnqueueFn } from \"../../questioner/questioner.types.js\";\nimport type { PendingQuestionSummary } from \"../schemas/pending-question.schema.js\";\nimport type { QuestionMode } from \"../schemas/question.schema.js\";\nimport type { DiscoveryRunQueue, DiscoveryRunStore } from \"../interfaces/discovery-run.interface.js\";\nimport type { ProfileRunQueue, ProfileRunStore } from \"../interfaces/profile-run.interface.js\";\n\nexport type ProfileContext = ProfileDocument | null;\n\nexport interface ToolErrorReport {\n operation: string;\n subsystem?: string;\n toolName?: string;\n userId?: string;\n tags?: Record<string, string | number | boolean | null | undefined>;\n context?: Record<string, unknown>;\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// COMPILED GRAPH TYPE\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/** Minimal interface for an invokable compiled LangGraph. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type CompiledGraph = { invoke: (input: any) => Promise<any> };\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TOOL CONTEXT TYPES\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Resolved context available to every tool handler.\n * Contains the current user and optional index identity, resolved from DB at init.\n * The LLM can see this context (via system prompt) but cannot change it.\n */\nexport interface ResolvedToolContext {\n // Legacy flat fields (kept for backwards compatibility in tools/prompts).\n userId: string;\n userName: string;\n userEmail: string;\n networkId?: string;\n indexName?: string;\n /** True when chat is index-scoped and the user owns the index. */\n isOwner?: boolean;\n // Rich identity context for prompt/tool orchestration.\n user: UserRecord;\n userProfile: ProfileContext;\n userNetworks: NetworkMembership[];\n /**\n * The set of index IDs this caller can reach in the current request.\n * For unscoped chats: every index the user is a member of.\n * For network-scoped agents: `[boundNetwork, personalIndex]`.\n * This is the same set used to clamp the DB-level systemDb.\n * Tools that filter intents/profiles default to this set; `networkId` is\n * the \"primary focus\" hint, not a read filter.\n */\n indexScope: string[];\n scopedIndex?: {\n id: string;\n title: string;\n prompt: string | null;\n type?: string;\n metadata?: Record<string, unknown>;\n permissions?: Record<string, unknown>;\n };\n scopedMembershipRole?: \"owner\" | \"member\";\n /** True when user has not completed onboarding (onboarding.completedAt is null). */\n isOnboarding: boolean;\n /** True when the user has a non-empty name. */\n hasName: boolean;\n /** Chat session ID when tools are used in a chat; used for draft opportunities (context.conversationId). */\n sessionId?: string;\n /** True when the request originates from an MCP transport (no interactive UI available). */\n isMcp?: boolean;\n /** Agent ID when the request originates from an API key linked to an agent. */\n agentId?: string;\n /**\n * Receiver's rendering surface declared by the MCP client via the\n * `x-index-surface` request header. `'telegram'` means the MCP response is\n * being rendered inside a Telegram chat; anything\n * else (including `undefined`) is treated as web. Forwarded into\n * `mintConnectLink` so the click-time redirect can branch.\n */\n clientSurface?: 'telegram' | 'web';\n}\n\n/**\n * Dependencies passed when creating tools for a user session.\n * Includes DB adapters, embedder, and scraper.\n *\n * Note: userDb and systemDb are optional inputs - if not provided, createChatTools\n * will create them internally from the chatDatabaseAdapter singleton.\n */\nexport interface ToolContext {\n userId: string;\n /** @deprecated Use userDb or systemDb instead. Kept for backwards compatibility. */\n database: ChatGraphCompositeDatabase;\n /** Context-bound database for accessing the authenticated user's own resources. Created internally if not provided. */\n userDb?: UserDatabase;\n /** Context-bound database for LLM/system operations on cross-user resources within shared indexes. Created internally if not provided. */\n systemDb?: SystemDatabase;\n embedder: Embedder;\n scraper: Scraper;\n /** When set, chat is scoped to this index; tools use it as default for read_intents and create_intent. */\n networkId?: string;\n /**\n * Optional override of the resolved `indexScope`. `resolveChatContext` always\n * computes `indexScope` from the user's memberships (clamped to [bound,\n * personal] when `networkId` is set). When the caller has already computed\n * a clamped scope — notably the MCP server, which clamps via\n * `applyNetworkScopeToContext` for network-scoped agents — passing it on\n * `ToolContext.indexScope` causes `createChatTools` (in tool.factory.ts) to\n * override `resolvedContext.indexScope` with this value rather than the\n * freshly computed one. See ResolvedToolContext.indexScope for the\n * resolved-side semantics.\n */\n indexScope?: string[];\n /** Chat session ID when creating tools for a chat; enables draft opportunities with context.conversationId. */\n sessionId?: string;\n\n // ─── Protocol-level dependencies (injected by composition root) ──────────\n /** General-purpose cache (e.g. for tool results). */\n cache: Cache;\n /** Dedicated cache for HyDE graph (may be same instance as cache). */\n hydeCache: HydeCache;\n /** External integration platform adapter (OAuth, tool actions). */\n integration: IntegrationAdapter;\n /** Queue for enqueuing follow-up intent processing (HyDE generation/deletion). */\n intentQueue: IntentGraphQueue;\n /** Contact management operations. */\n contactService: ContactServiceAdapter;\n /** Chat session reader for loading conversation history. */\n chatSession: ChatSessionReader;\n /** Read-through chat-session digest. Optional; consumers fall back to undefined `chatContext`. */\n chatSummary?: ChatSummaryReader;\n /** Writes user messages into the user's most-recent chat session (Slice 5 MCP elicitation). */\n chatMessageWriter?: ChatMessageWriter;\n /** Decision-question generator. Optional; consumers fall back to no `questions`. */\n questionGenerator?: QuestionGeneratorReader;\n /**\n * Optional async question enqueue callback. When provided, question generation\n * is dispatched asynchronously to the QuestionerQueue instead of running inline.\n * Injected by the composition root when QUESTIONER_ENABLED=true.\n */\n questionerEnqueue?: QuestionerEnqueueFn;\n /** Negotiation-digest summarizer. Optional; consumers fall back to deterministic digests. */\n negotiationSummary?: NegotiationSummaryReader;\n /** Profile enrichment from external data sources. */\n enricher: ProfileEnricher;\n /** Database adapter for negotiation/conversation operations. */\n negotiationDatabase: NegotiationGraphDatabase;\n /** Integration importer for bulk contact import from toolkits. */\n integrationImporter: {\n importContacts(userId: string, toolkit: string): Promise<{\n imported: number;\n skipped: number;\n newContacts: number;\n existingContacts: number;\n }>;\n };\n /** Factory for user-scoped database access. */\n createUserDatabase: (db: ChatGraphCompositeDatabase, userId: string) => UserDatabase;\n /** Factory for system-scoped database access. */\n createSystemDatabase: (db: ChatGraphCompositeDatabase, userId: string, indexScope: string[], embedder?: Embedder) => SystemDatabase;\n /** Optional runtime LLM config. Pass to override env vars for API key, model, etc. */\n modelConfig?: ModelConfig;\n /** Manages negotiation timeout jobs (optional — enables AI fallback on external agent timeout). */\n negotiationTimeoutQueue?: NegotiationTimeoutQueue;\n /** Agent registry database adapter (optional — absent when host does not support agents). */\n agentDatabase?: AgentDatabase;\n /** Grants the default system-agent permissions after onboarding (optional). */\n grantDefaultSystemPermissions?: (userId: string) => Promise<void>;\n /** Dispatcher for routing negotiation turns to personal agents (optional — falls back to system AI). */\n agentDispatcher?: AgentDispatcher;\n /** Enqueue a negotiate_existing job after introducer approval (optional). */\n queueNegotiateExisting?: (opportunityId: string, userId: string) => Promise<void>;\n /** Delivery ledger for committing opportunity delivery rows (optional — absent in chat context). */\n deliveryLedger?: DeliveryLedger;\n /** Persistence for async MCP discovery runs (optional — absent in non-MCP/test contexts). */\n discoveryRuns?: DiscoveryRunStore;\n /** Queue for async MCP discovery run execution (optional — absent in non-MCP/test contexts). */\n discoveryRunQueue?: DiscoveryRunQueue;\n /** Persistence for async MCP profile runs (optional — absent in non-MCP/test contexts). */\n profileRuns?: ProfileRunStore;\n /** Queue for async MCP profile run execution (optional — absent in non-MCP/test contexts). */\n profileRunQueue?: ProfileRunQueue;\n /**\n * Legacy direct-token minting for opportunity accept redirects.\n * Prefer `mintConnectLink` for user-facing links.\n */\n mintConnectToken?: (userId: string, opportunityId: string) => Promise<string>;\n /** Mints (or reuses) a short connect link, snapshotting the greeting (optional — absent in non-MCP contexts). */\n mintConnectLink?: MintConnectLink;\n /** Frontend base URL for building profile links (e.g. https://index.network, optional). */\n frontendUrl?: string;\n /** API base URL for building opportunity accept links (e.g. https://protocol.index.network, optional). */\n apiBaseUrl?: string;\n /** Persistence for structured questions generated by the QuestionerAgent (optional). */\n questionerDatabase?: QuestionerDatabase;\n /** Optional host-side error reporter for swallowed protocol/tool errors. */\n reportToolError?: (error: unknown, report: ToolErrorReport) => void;\n /**\n * Optional host-side per-principal MCP call throttle. Invoked once per MCP\n * tool dispatch (after identity resolves, before any DB work). When the\n * returned decision is `allowed: false`, the dispatch short-circuits with a\n * rate-limit error carrying `retryAfterSec`. Absent in chat/test contexts.\n */\n mcpRateLimiter?: (input: { userId: string; agentId?: string; toolName: string }) => Promise<{\n allowed: boolean;\n retryAfterSec?: number;\n limit?: number;\n scope?: 'tool' | 'principal';\n }>;\n /** Optional premise lifecycle event callbacks. Fired by premise tools after successful operations. */\n premiseEvents?: {\n onCreated?: (premiseId: string, userId: string) => void;\n onUpdated?: (premiseId: string, userId: string) => void;\n onRetracted?: (premiseId: string, userId: string) => void;\n };\n}\n\n/**\n * All external dependencies needed to initialize the protocol tool engine.\n * The host application (composition root) must provide concrete implementations.\n * This is the subset of ToolContext that is NOT per-request (no userId, indexId, sessionId).\n */\nexport type ProtocolDeps = Omit<ToolContext, 'userId' | 'indexId' | 'sessionId' | 'userDb' | 'systemDb'>;\n\n/**\n * Thrown when a requested chat scope is invalid for the authenticated user.\n * Controllers can map this to an HTTP status code.\n */\nexport class ChatContextAccessError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number,\n public readonly code: \"USER_NOT_FOUND\" | \"INDEX_NOT_FOUND\" | \"INDEX_MEMBERSHIP_REQUIRED\"\n ) {\n super(message);\n this.name = \"ChatContextAccessError\";\n }\n}\n\n/**\n * Resolve the canonical context used by chat tools and system prompt.\n * This preloads user identity, profile, index memberships, and scoped index role.\n */\nexport async function resolveChatContext(params: {\n database: Pick<\n ChatGraphCompositeDatabase,\n \"getUser\" | \"getProfile\" | \"getNetworkMemberships\" | \"getNetworkMembership\" | \"getNetwork\" | \"isIndexOwner\" | \"isNetworkMember\"\n >;\n userId: string;\n networkId?: string;\n /** Chat session ID for draft opportunities (stored as context.conversationId). */\n sessionId?: string;\n}): Promise<ResolvedToolContext> {\n const { database, userId, networkId, sessionId } = params;\n\n const [user, rawProfile, userNetworks] = await Promise.all([\n database.getUser(userId),\n database.getProfile(userId),\n database.getNetworkMemberships(userId),\n ]);\n\n const userProfile: ProfileContext = rawProfile ?? null;\n\n if (!user) {\n throw new ChatContextAccessError(\n \"User not found\",\n 404,\n \"USER_NOT_FOUND\"\n );\n }\n\n let scopedIndex: ResolvedToolContext[\"scopedIndex\"] = undefined;\n let scopedMembershipRole: ResolvedToolContext[\"scopedMembershipRole\"] = undefined;\n let isOwner = false;\n let indexName: string | undefined;\n\n if (networkId) {\n const [index, isMember, owner] = await Promise.all([\n database.getNetwork(networkId),\n database.isNetworkMember(networkId, userId),\n database.isIndexOwner(networkId, userId),\n ]);\n\n if (!index) {\n throw new ChatContextAccessError(\n \"Index not found\",\n 404,\n \"INDEX_NOT_FOUND\"\n );\n }\n\n if (!isMember) {\n throw new ChatContextAccessError(\n \"You are not a member of this index\",\n 403,\n \"INDEX_MEMBERSHIP_REQUIRED\"\n );\n }\n\n let membership = userNetworks.find((m) => m.networkId === index.id);\n if (membership === undefined) {\n membership = (await database.getNetworkMembership(index.id, userId)) ?? undefined;\n }\n scopedIndex = {\n id: index.id,\n title: index.title,\n prompt: membership?.indexPrompt ?? null,\n type: index.type ?? 'community',\n metadata: index.metadata ?? {},\n permissions: index.permissions ?? {},\n };\n isOwner = owner;\n indexName = index.title;\n scopedMembershipRole = owner ? \"owner\" : \"member\";\n }\n\n const userName = user.name ?? \"Unknown\";\n const userEmail = user.email ?? \"\";\n const hasName = !!user.name?.trim();\n\n // When scoped to an index, clamp the caller's reach to [scopedIndex, personalIndex]\n // so the chat's data model matches its \"focus\" semantic: a chat scoped to a\n // community sees that community plus the user's personal index, not their\n // other unrelated memberships. Mirrors the MCP path's clamp for network-scoped\n // agents (see applyNetworkScopeToContext / computeAgentIndexScope).\n const indexScope = networkId\n ? userNetworks\n .filter((m) => m.networkId === networkId || m.isPersonal === true)\n .map((m) => m.networkId)\n : userNetworks.map((m) => m.networkId);\n\n return {\n userId,\n userName,\n userEmail,\n networkId,\n indexName,\n isOwner,\n user,\n userProfile,\n userNetworks,\n indexScope,\n scopedIndex,\n scopedMembershipRole,\n isOnboarding: !(user.onboarding?.completedAt),\n hasName,\n ...(sessionId !== undefined ? { sessionId } : {}),\n };\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// DEFINE TOOL TYPE\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Type for the `defineTool` closure created in `createChatTools`.\n * Auto-injects resolved context and provides uniform logging / error handling.\n */\nexport type DefineTool = <T extends z.ZodType>(opts: {\n name: string;\n description: string;\n querySchema: T;\n handler: (input: { context: ResolvedToolContext; query: z.infer<T> }) => Promise<string>;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n}) => any;\n\n/**\n * A raw tool definition before LangChain wrapping.\n * Used by the tool registry for direct HTTP invocation.\n */\nexport interface RawToolDefinition {\n name: string;\n description: string;\n schema: z.ZodType;\n handler: (input: { context: ResolvedToolContext; query: unknown }) => Promise<string>;\n}\n\n/**\n * Registry mapping tool names to their raw definitions.\n */\nexport type ToolRegistry = Map<string, RawToolDefinition>;\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TOOL DEPENDENCIES\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Shared dependencies available to all tool domain factories.\n * Passed by `createChatTools` after compiling all subgraphs.\n */\nexport interface ToolDeps {\n /** @deprecated Use userDb or systemDb instead. Kept for backwards compatibility. */\n database: ChatGraphCompositeDatabase;\n /** Context-bound database for accessing the authenticated user's own resources. */\n userDb: UserDatabase;\n /** Context-bound database for LLM/system operations on cross-user resources within shared indexes. */\n systemDb: SystemDatabase;\n scraper: Scraper;\n embedder: import('../interfaces/embedder.interface.js').Embedder;\n cache: Cache;\n integration: IntegrationAdapter;\n contactService: ContactServiceAdapter;\n integrationImporter: {\n importContacts(userId: string, toolkit: string): Promise<{\n imported: number;\n skipped: number;\n newContacts: number;\n existingContacts: number;\n }>;\n };\n enricher: ProfileEnricher;\n /** Database adapter for negotiation/conversation operations. */\n negotiationDatabase: NegotiationGraphDatabase;\n /** Chat session reader for exposing the caller's past conversations as MCP tools. */\n chatSession?: ChatSessionReader;\n /** Read-through chat-session digest. Optional; consumers fall back to undefined `chatContext`. */\n chatSummary?: ChatSummaryReader;\n /**\n * Test seam for opportunity discovery helpers. Production compositions leave\n * this unset so tools call the real discovery module directly.\n */\n opportunityDiscovery?: {\n runDiscoverFromQuery?: (input: unknown) => Promise<unknown>;\n continueDiscovery?: (input: unknown) => Promise<unknown>;\n };\n /**\n * Test seam for opportunity card presentation helpers. Production\n * compositions leave this unset so tools construct the real presenter.\n */\n opportunityPresentation?: {\n createPresenter?: () => { presentHomeCard(input: unknown): Promise<unknown> };\n gatherPresenterContext?: (...args: unknown[]) => Promise<unknown>;\n };\n /** Writes user messages into the user's most-recent chat session (Slice 5 MCP elicitation). */\n chatMessageWriter?: ChatMessageWriter;\n /** Decision-question generator. Optional; consumers fall back to no `questions`. */\n questionGenerator?: QuestionGeneratorReader;\n /**\n * Optional async question enqueue callback. When provided, question generation\n * is dispatched asynchronously to the QuestionerQueue instead of running inline\n * via the `questionGenerator`. Injected by the composition root when\n * QUESTIONER_ENABLED=true.\n */\n questionerEnqueue?: QuestionerEnqueueFn;\n /**\n * Lookup pending questions for a user, optionally filtered by source,\n * detection mode, or capped by count (hosts apply `limit` SQL-side).\n * Used by tools to attach contextually relevant questions to their results.\n * Injected by the composition root — absent when question delivery is disabled.\n */\n findPendingQuestions?: (\n userId: string,\n filters?: {\n sourceType?: string;\n sourceId?: string;\n /** Restrict to questions whose detection mode is in this set. */\n modes?: QuestionMode[];\n /** Maximum rows to return; hosts should apply this in the query. */\n limit?: number;\n },\n ) => Promise<PendingQuestionSummary[]>;\n /** Negotiation-digest summarizer. Optional; consumers fall back to deterministic digests. */\n negotiationSummary?: NegotiationSummaryReader;\n /** Manages negotiation timeout jobs (optional — enables AI fallback on external agent timeout). */\n negotiationTimeoutQueue?: NegotiationTimeoutQueue;\n /** Agent registry database adapter (optional — absent when host does not support agents). */\n agentDatabase?: AgentDatabase;\n /** Grants the default system-agent permissions after onboarding (optional). */\n grantDefaultSystemPermissions?: (userId: string) => Promise<void>;\n /** Dispatcher for routing negotiation turns to personal agents (optional — falls back to system AI). */\n agentDispatcher?: AgentDispatcher;\n /** Delivery ledger for committing opportunity delivery rows (optional — absent in chat context). */\n deliveryLedger?: DeliveryLedger;\n /** Persistence for async MCP discovery runs (optional — absent in non-MCP/test contexts). */\n discoveryRuns?: DiscoveryRunStore;\n /** Queue for async MCP discovery run execution (optional — absent in non-MCP/test contexts). */\n discoveryRunQueue?: DiscoveryRunQueue;\n /** Persistence for async MCP profile runs (optional — absent in non-MCP/test contexts). */\n profileRuns?: ProfileRunStore;\n /** Queue for async MCP profile run execution (optional — absent in non-MCP/test contexts). */\n profileRunQueue?: ProfileRunQueue;\n /**\n * Legacy direct-token minting for opportunity accept redirects.\n * Prefer `mintConnectLink` for user-facing links.\n */\n mintConnectToken?: (userId: string, opportunityId: string) => Promise<string>;\n /** Mints (or reuses) a short connect link, snapshotting the greeting (optional — absent in non-MCP contexts). */\n mintConnectLink?: MintConnectLink;\n /** Frontend base URL for building profile links (e.g. https://index.network, optional). */\n frontendUrl?: string;\n /** API base URL for building opportunity accept links (e.g. https://protocol.index.network, optional). */\n apiBaseUrl?: string;\n /** Optional host-side error reporter for swallowed protocol/tool errors. */\n reportToolError?: (error: unknown, report: ToolErrorReport) => void;\n /**\n * Optional host-side per-principal MCP call throttle. Invoked once per MCP\n * tool dispatch (after identity resolves, before any DB work). When the\n * returned decision is `allowed: false`, the dispatch short-circuits with a\n * rate-limit error carrying `retryAfterSec`. Absent in chat/test contexts.\n */\n mcpRateLimiter?: (input: { userId: string; agentId?: string; toolName: string }) => Promise<{\n allowed: boolean;\n retryAfterSec?: number;\n limit?: number;\n scope?: 'tool' | 'principal';\n }>;\n /** Optional premise lifecycle event callbacks. Fired by premise tools after successful operations. */\n premiseEvents?: {\n onCreated?: (premiseId: string, userId: string) => void;\n onUpdated?: (premiseId: string, userId: string) => void;\n onRetracted?: (premiseId: string, userId: string) => void;\n };\n graphs: {\n profile: CompiledGraph;\n intent: CompiledGraph;\n index: CompiledGraph;\n networkMembership: CompiledGraph;\n intentIndex: CompiledGraph;\n opportunity: CompiledOpportunityGraph;\n premise: CompiledGraph;\n };\n /**\n * Optional network ranking override for `read_networks`. Injected by tests or custom compositions.\n * When absent, defaults to `NetworkRecommender.invoke()` with a lazy module-level singleton.\n */\n networkRanker?: (input: {\n userProfile: { bio: string; location: string; interests: string[]; skills: string[] };\n networks: Array<{ networkId: string; renderedContext: string }>;\n }) => Promise<{ rankedNetworkIds: string[] } | null>;\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TOOL RESULT HELPERS\n// ═══════════════════════════════════════════════════════════════════════════════\n\nexport function success<T>(data: T): string {\n return JSON.stringify({ success: true, data });\n}\n\nexport function error(\n message: string,\n debugSteps?: Array<{ step: string; detail?: string; data?: Record<string, unknown> }>\n): string {\n return JSON.stringify({\n success: false,\n error: message,\n ...(debugSteps?.length ? { debugSteps } : {}),\n });\n}\n\n/** Return needsClarification for missing required fields. */\nexport function needsClarification(params: {\n missingFields: string[];\n message: string;\n}): string {\n return JSON.stringify({\n success: false,\n needsClarification: true,\n ...params,\n });\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// CONSTANTS & UTILITIES\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/** Matches http/https URLs in text; captures full URL. */\nconst URL_IN_TEXT_REGEX = /https?:\\/\\/[^\\s\"'<>)\\]]+/gi;\n\n/**\n * Matches bare domain URLs without protocol (e.g. github.com/foo, www.example.com).\n * Requires at least a SLD.TLD pattern followed by optional path.\n * Negative lookbehind ensures we don't double-match URLs already caught by URL_IN_TEXT_REGEX.\n */\nconst BARE_URL_REGEX = /(?<!\\w:\\/\\/)(?<![/\\w])(?:www\\.)?[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.(?:com|org|net|io|dev|co|ai|app|xyz|me|info|gg|so|sh|cc|ly|fm|tv|to|tech|design|network|world|edu|gov|mil|int|us|uk|eu|de|fr|ca|au|jp|cn|in|br|nl|se|no|fi|dk|ch|at|be|it|es|pt|pl|cz|ru|kr|tw|hk|sg|nz|za|mx|ar|cl|id|ph|th|vn|my|ie)(?:\\/[^\\s\"'<>)\\]]*)?/gi;\n\n/** UUID v4 format: 8-4-4-4-12 hex chars (e.g. c2505011-2e45-426e-81dd-b9abb9b72023) */\nexport const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/**\n * Resolves an array of network IDs to their display titles.\n * Skips any IDs that don't resolve (deleted or invalid networks).\n */\nexport async function resolveIndexNames(\n database: { getNetwork(id: string): Promise<{ id: string; title: string } | null> },\n networkIds: string[]\n): Promise<string[]> {\n if (networkIds.length === 0) return [];\n const results = await Promise.all(\n networkIds.map(id => database.getNetwork(id))\n );\n return results.filter(Boolean).map(idx => idx!.title);\n}\n\n/**\n * Normalize a URL string: if it lacks a protocol, prepend \"https://\".\n * Returns the normalized URL or null if the result is not a valid URL.\n */\nexport function normalizeUrl(raw: string): string | null {\n let url = raw.replace(/[.,;:!?)]+$/, \"\").trim();\n if (!/^https?:\\/\\//i.test(url)) {\n url = `https://${url}`;\n }\n try {\n new URL(url);\n return url;\n } catch {\n return null;\n }\n}\n\n/**\n * Extract unique, valid URLs from a string (e.g. user message or details).\n * Handles both full URLs (https://...) and bare domains (github.com/...).\n */\nexport function extractUrls(text: string): string[] {\n if (!text || typeof text !== \"string\") return [];\n\n const seen = new Set<string>();\n const out: string[] = [];\n\n // Pass 1: full protocol URLs\n const fullMatches = text.match(URL_IN_TEXT_REGEX) ?? [];\n for (const raw of fullMatches) {\n const url = normalizeUrl(raw);\n if (url && !seen.has(url)) {\n seen.add(url);\n out.push(url);\n }\n }\n\n // Pass 2: bare domain URLs (e.g. github.com/foo)\n const bareMatches = text.match(BARE_URL_REGEX) ?? [];\n for (const raw of bareMatches) {\n const url = normalizeUrl(raw);\n if (url && !seen.has(url)) {\n seen.add(url);\n out.push(url);\n }\n }\n\n return out;\n}\n\nconst SENSITIVE_FIELD_KEYS = new Set([\n \"secret\",\n \"webhooksecret\",\n \"password\",\n \"apikey\",\n \"token\",\n \"accesstoken\",\n \"refreshtoken\",\n \"privatekey\",\n \"authtoken\",\n \"bearertoken\",\n \"clientsecret\",\n]);\n\n/**\n * Recursively redacts sensitive field values from an arbitrary payload before\n * it is passed to a structured logger. Matches field names case-insensitively\n * and ignoring underscores, so `api_key`, `apiKey`, and `API_KEY` all match.\n * Non-sensitive fields are passed through unchanged. Never mutates the input —\n * returns a new value.\n *\n * Intended for structured-log redaction only. Do NOT use as a security\n * boundary for data in motion.\n *\n * @param value - Arbitrary JSON-like payload (query object, config blob, etc.)\n * @returns A new value with sensitive fields replaced by `\"[redacted]\"`.\n */\nexport function redactSensitiveFields(value: unknown): unknown {\n if (value === null || typeof value !== \"object\") return value;\n if (Array.isArray(value)) {\n return value.map((item) => redactSensitiveFields(item));\n }\n const out: Record<string, unknown> = {};\n for (const [key, inner] of Object.entries(value as Record<string, unknown>)) {\n const normalized = key.toLowerCase().replace(/_/g, \"\");\n if (SENSITIVE_FIELD_KEYS.has(normalized)) {\n out[key] = \"[redacted]\";\n } else {\n out[key] = redactSensitiveFields(inner);\n }\n }\n return out;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"tool.helpers.js","sourceRoot":"/","sources":["shared/agent/tool.helpers.ts"],"names":[],"mappings":"AAiQA;;;GAGG;AACH,MAAM,OAAO,sBAAuB,SAAQ,KAAK;IAC/C,YACE,OAAe,EACC,UAAkB,EAClB,IAAwE;QAExF,KAAK,CAAC,OAAO,CAAC,CAAC;QAHC,eAAU,GAAV,UAAU,CAAQ;QAClB,SAAI,GAAJ,IAAI,CAAoE;QAGxF,IAAI,CAAC,IAAI,GAAG,wBAAwB,CAAC;IACvC,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,kBAAkB,CAAC,MASxC;IACC,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,GAAG,MAAM,CAAC;IAE1D,MAAM,CAAC,IAAI,EAAE,UAAU,EAAE,YAAY,CAAC,GA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CAAC,KAAgC,CAAC,EAAE,CAAC;QAC5E,MAAM,UAAU,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;QACvD,IAAI,oBAAoB,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,CAAC;YACzC,GAAG,CAAC,GAAG,CAAC,GAAG,YAAY,CAAC;QAC1B,CAAC;aAAM,CAAC;YACN,GAAG,CAAC,GAAG,CAAC,GAAG,qBAAqB,CAAC,KAAK,CAAC,CAAC;QAC1C,CAAC;IACH,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import { z } from \"zod\";\nimport type { ModelConfig } from \"./model.config.js\";\nimport type { ProfileDocument } from \"../schemas/profile.schema.js\";\nimport type { ChatGraphCompositeDatabase, NetworkMembership, UserRecord, UserDatabase, SystemDatabase, NegotiationGraphDatabase } from \"../interfaces/database.interface.js\";\nimport type { Scraper } from \"../interfaces/scraper.interface.js\";\nimport type { Cache, HydeCache } from \"../interfaces/cache.interface.js\";\nimport type { CompiledOpportunityGraph } from \"../../opportunity/opportunity.discover.js\";\nimport type { IntegrationAdapter } from \"../interfaces/integration.interface.js\";\nimport type { ContactServiceAdapter } from \"../interfaces/contact.interface.js\";\nimport type { ProfileEnricher } from \"../interfaces/enrichment.interface.js\";\nimport type { IntentGraphQueue } from \"../interfaces/queue.interface.js\";\nimport type { ChatSessionReader } from \"../interfaces/chat-session.interface.js\";\nimport type { ChatSummaryReader } from \"../interfaces/chat-summary.interface.js\";\nimport type { ChatMessageWriter } from \"../interfaces/chat-message-writer.interface.js\";\nimport type { QuestionGeneratorReader } from \"../interfaces/question-generator.interface.js\";\nimport type { NegotiationSummaryReader } from \"../interfaces/negotiation-summary.interface.js\";\nimport type { Embedder } from \"../interfaces/embedder.interface.js\";\nimport type { AgentDatabase } from \"../interfaces/agent.interface.js\";\nimport type { NegotiationTimeoutQueue } from \"../interfaces/negotiation-events.interface.js\";\nimport type { AgentDispatcher } from \"../interfaces/agent-dispatcher.interface.js\";\nimport type { DeliveryLedger } from \"../interfaces/delivery-ledger.interface.js\";\nimport type { MintConnectLink } from \"../interfaces/connect-link.interface.js\";\nimport type { QuestionerDatabase } from \"../interfaces/questioner.interface.js\";\nimport type { QuestionerEnqueueFn } from \"../../questioner/questioner.types.js\";\nimport type { PendingQuestionSummary } from \"../schemas/pending-question.schema.js\";\nimport type { QuestionMode } from \"../schemas/question.schema.js\";\nimport type { DiscoveryRunQueue, DiscoveryRunStore } from \"../interfaces/discovery-run.interface.js\";\nimport type { ProfileRunQueue, ProfileRunStore } from \"../interfaces/profile-run.interface.js\";\n\nexport type ProfileContext = ProfileDocument | null;\n\nexport interface ToolErrorReport {\n operation: string;\n subsystem?: string;\n toolName?: string;\n userId?: string;\n tags?: Record<string, string | number | boolean | null | undefined>;\n context?: Record<string, unknown>;\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// COMPILED GRAPH TYPE\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/** Minimal interface for an invokable compiled LangGraph. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type CompiledGraph = { invoke: (input: any) => Promise<any> };\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TOOL CONTEXT TYPES\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Resolved context available to every tool handler.\n * Contains the current user and optional index identity, resolved from DB at init.\n * The LLM can see this context (via system prompt) but cannot change it.\n */\nexport interface ResolvedToolContext {\n // Legacy flat fields (kept for backwards compatibility in tools/prompts).\n userId: string;\n userName: string;\n userEmail: string;\n networkId?: string;\n indexName?: string;\n /** True when chat is index-scoped and the user owns the index. */\n isOwner?: boolean;\n // Rich identity context for prompt/tool orchestration.\n user: UserRecord;\n userProfile: ProfileContext;\n userNetworks: NetworkMembership[];\n /**\n * The set of index IDs this caller can reach in the current request.\n * For unscoped chats: every index the user is a member of.\n * For network-scoped agents: `[boundNetwork, personalIndex]`.\n * This is the same set used to clamp the DB-level systemDb.\n * Tools that filter intents/profiles default to this set; `networkId` is\n * the \"primary focus\" hint, not a read filter.\n */\n indexScope: string[];\n scopedIndex?: {\n id: string;\n title: string;\n prompt: string | null;\n type?: string;\n metadata?: Record<string, unknown>;\n permissions?: Record<string, unknown>;\n };\n scopedMembershipRole?: \"owner\" | \"member\";\n /** True when user has not completed onboarding (onboarding.completedAt is null). */\n isOnboarding: boolean;\n /** True when the user has a non-empty name. */\n hasName: boolean;\n /** Chat session ID when tools are used in a chat; used for draft opportunities (context.conversationId). */\n sessionId?: string;\n /** True when the request originates from an MCP transport (no interactive UI available). */\n isMcp?: boolean;\n /** Agent ID when the request originates from an API key linked to an agent. */\n agentId?: string;\n /**\n * Receiver's rendering surface declared by the MCP client via the\n * `x-index-surface` request header. `'telegram'` means the MCP response is\n * being rendered inside a Telegram chat; anything\n * else (including `undefined`) is treated as web. Forwarded into\n * `mintConnectLink` so the click-time redirect can branch.\n */\n clientSurface?: 'telegram' | 'web';\n}\n\n/**\n * Dependencies passed when creating tools for a user session.\n * Includes DB adapters, embedder, and scraper.\n *\n * Note: userDb and systemDb are optional inputs - if not provided, createChatTools\n * will create them internally from the chatDatabaseAdapter singleton.\n */\nexport interface ToolContext {\n userId: string;\n /** @deprecated Use userDb or systemDb instead. Kept for backwards compatibility. */\n database: ChatGraphCompositeDatabase;\n /** Context-bound database for accessing the authenticated user's own resources. Created internally if not provided. */\n userDb?: UserDatabase;\n /** Context-bound database for LLM/system operations on cross-user resources within shared indexes. Created internally if not provided. */\n systemDb?: SystemDatabase;\n embedder: Embedder;\n scraper: Scraper;\n /** When set, chat is scoped to this index; tools use it as default for read_intents and create_intent. */\n networkId?: string;\n /**\n * Optional override of the resolved `indexScope`. `resolveChatContext` always\n * computes `indexScope` from the user's memberships (clamped to [bound,\n * personal] when `networkId` is set). When the caller has already computed\n * a clamped scope — notably the MCP server, which clamps via\n * `applyNetworkScopeToContext` for network-scoped agents — passing it on\n * `ToolContext.indexScope` causes `createChatTools` (in tool.factory.ts) to\n * override `resolvedContext.indexScope` with this value rather than the\n * freshly computed one. See ResolvedToolContext.indexScope for the\n * resolved-side semantics.\n */\n indexScope?: string[];\n /** Chat session ID when creating tools for a chat; enables draft opportunities with context.conversationId. */\n sessionId?: string;\n\n // ─── Protocol-level dependencies (injected by composition root) ──────────\n /** General-purpose cache (e.g. for tool results). */\n cache: Cache;\n /** Dedicated cache for HyDE graph (may be same instance as cache). */\n hydeCache: HydeCache;\n /** External integration platform adapter (OAuth, tool actions). */\n integration: IntegrationAdapter;\n /** Queue for enqueuing follow-up intent processing (HyDE generation/deletion). */\n intentQueue: IntentGraphQueue;\n /** Contact management operations. */\n contactService: ContactServiceAdapter;\n /**\n * When false (or unset), the contact import / manual-add tools\n * (import_contacts, add_contact, import_gmail_contacts) are not registered.\n * Injected by the composition root from CONTACTS_ENABLED. Read/remove/search\n * contact tools are always registered.\n */\n contactsEnabled?: boolean;\n /** Chat session reader for loading conversation history. */\n chatSession: ChatSessionReader;\n /** Read-through chat-session digest. Optional; consumers fall back to undefined `chatContext`. */\n chatSummary?: ChatSummaryReader;\n /** Writes user messages into the user's most-recent chat session (Slice 5 MCP elicitation). */\n chatMessageWriter?: ChatMessageWriter;\n /** Decision-question generator. Optional; consumers fall back to no `questions`. */\n questionGenerator?: QuestionGeneratorReader;\n /**\n * Optional async question enqueue callback. When provided, question generation\n * is dispatched asynchronously to the QuestionerQueue instead of running inline.\n * Injected by the composition root when QUESTIONER_ENABLED=true.\n */\n questionerEnqueue?: QuestionerEnqueueFn;\n /** Negotiation-digest summarizer. Optional; consumers fall back to deterministic digests. */\n negotiationSummary?: NegotiationSummaryReader;\n /** Profile enrichment from external data sources. */\n enricher: ProfileEnricher;\n /** Database adapter for negotiation/conversation operations. */\n negotiationDatabase: NegotiationGraphDatabase;\n /** Integration importer for bulk contact import from toolkits. */\n integrationImporter: {\n importContacts(userId: string, toolkit: string): Promise<{\n imported: number;\n skipped: number;\n newContacts: number;\n existingContacts: number;\n }>;\n };\n /** Factory for user-scoped database access. */\n createUserDatabase: (db: ChatGraphCompositeDatabase, userId: string) => UserDatabase;\n /** Factory for system-scoped database access. */\n createSystemDatabase: (db: ChatGraphCompositeDatabase, userId: string, indexScope: string[], embedder?: Embedder) => SystemDatabase;\n /** Optional runtime LLM config. Pass to override env vars for API key, model, etc. */\n modelConfig?: ModelConfig;\n /** Manages negotiation timeout jobs (optional — enables AI fallback on external agent timeout). */\n negotiationTimeoutQueue?: NegotiationTimeoutQueue;\n /** Agent registry database adapter (optional — absent when host does not support agents). */\n agentDatabase?: AgentDatabase;\n /** Grants the default system-agent permissions after onboarding (optional). */\n grantDefaultSystemPermissions?: (userId: string) => Promise<void>;\n /** Dispatcher for routing negotiation turns to personal agents (optional — falls back to system AI). */\n agentDispatcher?: AgentDispatcher;\n /** Enqueue a negotiate_existing job after introducer approval (optional). */\n queueNegotiateExisting?: (opportunityId: string, userId: string) => Promise<void>;\n /** Delivery ledger for committing opportunity delivery rows (optional — absent in chat context). */\n deliveryLedger?: DeliveryLedger;\n /** Persistence for async MCP discovery runs (optional — absent in non-MCP/test contexts). */\n discoveryRuns?: DiscoveryRunStore;\n /** Queue for async MCP discovery run execution (optional — absent in non-MCP/test contexts). */\n discoveryRunQueue?: DiscoveryRunQueue;\n /** Persistence for async MCP profile runs (optional — absent in non-MCP/test contexts). */\n profileRuns?: ProfileRunStore;\n /** Queue for async MCP profile run execution (optional — absent in non-MCP/test contexts). */\n profileRunQueue?: ProfileRunQueue;\n /**\n * Legacy direct-token minting for opportunity accept redirects.\n * Prefer `mintConnectLink` for user-facing links.\n */\n mintConnectToken?: (userId: string, opportunityId: string) => Promise<string>;\n /** Mints (or reuses) a short connect link, snapshotting the greeting (optional — absent in non-MCP contexts). */\n mintConnectLink?: MintConnectLink;\n /** Frontend base URL for building profile links (e.g. https://index.network, optional). */\n frontendUrl?: string;\n /** API base URL for building opportunity accept links (e.g. https://protocol.index.network, optional). */\n apiBaseUrl?: string;\n /** Persistence for structured questions generated by the QuestionerAgent (optional). */\n questionerDatabase?: QuestionerDatabase;\n /** Optional host-side error reporter for swallowed protocol/tool errors. */\n reportToolError?: (error: unknown, report: ToolErrorReport) => void;\n /**\n * Optional host-side per-principal MCP call throttle. Invoked once per MCP\n * tool dispatch (after identity resolves, before any DB work). When the\n * returned decision is `allowed: false`, the dispatch short-circuits with a\n * rate-limit error carrying `retryAfterSec`. Absent in chat/test contexts.\n */\n mcpRateLimiter?: (input: { userId: string; agentId?: string; toolName: string }) => Promise<{\n allowed: boolean;\n retryAfterSec?: number;\n limit?: number;\n scope?: 'tool' | 'principal';\n }>;\n /** Optional premise lifecycle event callbacks. Fired by premise tools after successful operations. */\n premiseEvents?: {\n onCreated?: (premiseId: string, userId: string) => void;\n onUpdated?: (premiseId: string, userId: string) => void;\n onRetracted?: (premiseId: string, userId: string) => void;\n };\n}\n\n/**\n * All external dependencies needed to initialize the protocol tool engine.\n * The host application (composition root) must provide concrete implementations.\n * This is the subset of ToolContext that is NOT per-request (no userId, indexId, sessionId).\n */\nexport type ProtocolDeps = Omit<ToolContext, 'userId' | 'indexId' | 'sessionId' | 'userDb' | 'systemDb'>;\n\n/**\n * Thrown when a requested chat scope is invalid for the authenticated user.\n * Controllers can map this to an HTTP status code.\n */\nexport class ChatContextAccessError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number,\n public readonly code: \"USER_NOT_FOUND\" | \"INDEX_NOT_FOUND\" | \"INDEX_MEMBERSHIP_REQUIRED\"\n ) {\n super(message);\n this.name = \"ChatContextAccessError\";\n }\n}\n\n/**\n * Resolve the canonical context used by chat tools and system prompt.\n * This preloads user identity, profile, index memberships, and scoped index role.\n */\nexport async function resolveChatContext(params: {\n database: Pick<\n ChatGraphCompositeDatabase,\n \"getUser\" | \"getProfile\" | \"getNetworkMemberships\" | \"getNetworkMembership\" | \"getNetwork\" | \"isIndexOwner\" | \"isNetworkMember\"\n >;\n userId: string;\n networkId?: string;\n /** Chat session ID for draft opportunities (stored as context.conversationId). */\n sessionId?: string;\n}): Promise<ResolvedToolContext> {\n const { database, userId, networkId, sessionId } = params;\n\n const [user, rawProfile, userNetworks] = await Promise.all([\n database.getUser(userId),\n database.getProfile(userId),\n database.getNetworkMemberships(userId),\n ]);\n\n const userProfile: ProfileContext = rawProfile ?? null;\n\n if (!user) {\n throw new ChatContextAccessError(\n \"User not found\",\n 404,\n \"USER_NOT_FOUND\"\n );\n }\n\n let scopedIndex: ResolvedToolContext[\"scopedIndex\"] = undefined;\n let scopedMembershipRole: ResolvedToolContext[\"scopedMembershipRole\"] = undefined;\n let isOwner = false;\n let indexName: string | undefined;\n\n if (networkId) {\n const [index, isMember, owner] = await Promise.all([\n database.getNetwork(networkId),\n database.isNetworkMember(networkId, userId),\n database.isIndexOwner(networkId, userId),\n ]);\n\n if (!index) {\n throw new ChatContextAccessError(\n \"Index not found\",\n 404,\n \"INDEX_NOT_FOUND\"\n );\n }\n\n if (!isMember) {\n throw new ChatContextAccessError(\n \"You are not a member of this index\",\n 403,\n \"INDEX_MEMBERSHIP_REQUIRED\"\n );\n }\n\n let membership = userNetworks.find((m) => m.networkId === index.id);\n if (membership === undefined) {\n membership = (await database.getNetworkMembership(index.id, userId)) ?? undefined;\n }\n scopedIndex = {\n id: index.id,\n title: index.title,\n prompt: membership?.indexPrompt ?? null,\n type: index.type ?? 'community',\n metadata: index.metadata ?? {},\n permissions: index.permissions ?? {},\n };\n isOwner = owner;\n indexName = index.title;\n scopedMembershipRole = owner ? \"owner\" : \"member\";\n }\n\n const userName = user.name ?? \"Unknown\";\n const userEmail = user.email ?? \"\";\n const hasName = !!user.name?.trim();\n\n // When scoped to an index, clamp the caller's reach to [scopedIndex, personalIndex]\n // so the chat's data model matches its \"focus\" semantic: a chat scoped to a\n // community sees that community plus the user's personal index, not their\n // other unrelated memberships. Mirrors the MCP path's clamp for network-scoped\n // agents (see applyNetworkScopeToContext / computeAgentIndexScope).\n const indexScope = networkId\n ? userNetworks\n .filter((m) => m.networkId === networkId || m.isPersonal === true)\n .map((m) => m.networkId)\n : userNetworks.map((m) => m.networkId);\n\n return {\n userId,\n userName,\n userEmail,\n networkId,\n indexName,\n isOwner,\n user,\n userProfile,\n userNetworks,\n indexScope,\n scopedIndex,\n scopedMembershipRole,\n isOnboarding: !(user.onboarding?.completedAt),\n hasName,\n ...(sessionId !== undefined ? { sessionId } : {}),\n };\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// DEFINE TOOL TYPE\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Type for the `defineTool` closure created in `createChatTools`.\n * Auto-injects resolved context and provides uniform logging / error handling.\n */\nexport type DefineTool = <T extends z.ZodType>(opts: {\n name: string;\n description: string;\n querySchema: T;\n handler: (input: { context: ResolvedToolContext; query: z.infer<T> }) => Promise<string>;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n}) => any;\n\n/**\n * A raw tool definition before LangChain wrapping.\n * Used by the tool registry for direct HTTP invocation.\n */\nexport interface RawToolDefinition {\n name: string;\n description: string;\n schema: z.ZodType;\n handler: (input: { context: ResolvedToolContext; query: unknown }) => Promise<string>;\n}\n\n/**\n * Registry mapping tool names to their raw definitions.\n */\nexport type ToolRegistry = Map<string, RawToolDefinition>;\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TOOL DEPENDENCIES\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Shared dependencies available to all tool domain factories.\n * Passed by `createChatTools` after compiling all subgraphs.\n */\nexport interface ToolDeps {\n /** @deprecated Use userDb or systemDb instead. Kept for backwards compatibility. */\n database: ChatGraphCompositeDatabase;\n /** Context-bound database for accessing the authenticated user's own resources. */\n userDb: UserDatabase;\n /** Context-bound database for LLM/system operations on cross-user resources within shared indexes. */\n systemDb: SystemDatabase;\n scraper: Scraper;\n embedder: import('../interfaces/embedder.interface.js').Embedder;\n cache: Cache;\n integration: IntegrationAdapter;\n contactService: ContactServiceAdapter;\n /**\n * When false (or unset), the contact import / manual-add tools\n * (import_contacts, add_contact, import_gmail_contacts) are not registered.\n * Injected by the composition root from CONTACTS_ENABLED. Read/remove/search\n * contact tools are always registered.\n */\n contactsEnabled?: boolean;\n integrationImporter: {\n importContacts(userId: string, toolkit: string): Promise<{\n imported: number;\n skipped: number;\n newContacts: number;\n existingContacts: number;\n }>;\n };\n enricher: ProfileEnricher;\n /** Database adapter for negotiation/conversation operations. */\n negotiationDatabase: NegotiationGraphDatabase;\n /** Chat session reader for exposing the caller's past conversations as MCP tools. */\n chatSession?: ChatSessionReader;\n /** Read-through chat-session digest. Optional; consumers fall back to undefined `chatContext`. */\n chatSummary?: ChatSummaryReader;\n /**\n * Test seam for opportunity discovery helpers. Production compositions leave\n * this unset so tools call the real discovery module directly.\n */\n opportunityDiscovery?: {\n runDiscoverFromQuery?: (input: unknown) => Promise<unknown>;\n continueDiscovery?: (input: unknown) => Promise<unknown>;\n };\n /**\n * Test seam for opportunity card presentation helpers. Production\n * compositions leave this unset so tools construct the real presenter.\n */\n opportunityPresentation?: {\n createPresenter?: () => { presentHomeCard(input: unknown): Promise<unknown> };\n gatherPresenterContext?: (...args: unknown[]) => Promise<unknown>;\n };\n /** Writes user messages into the user's most-recent chat session (Slice 5 MCP elicitation). */\n chatMessageWriter?: ChatMessageWriter;\n /** Decision-question generator. Optional; consumers fall back to no `questions`. */\n questionGenerator?: QuestionGeneratorReader;\n /**\n * Optional async question enqueue callback. When provided, question generation\n * is dispatched asynchronously to the QuestionerQueue instead of running inline\n * via the `questionGenerator`. Injected by the composition root when\n * QUESTIONER_ENABLED=true.\n */\n questionerEnqueue?: QuestionerEnqueueFn;\n /**\n * Lookup pending questions for a user, optionally filtered by source,\n * detection mode, or capped by count (hosts apply `limit` SQL-side).\n * Used by tools to attach contextually relevant questions to their results.\n * Injected by the composition root — absent when question delivery is disabled.\n */\n findPendingQuestions?: (\n userId: string,\n filters?: {\n sourceType?: string;\n sourceId?: string;\n /** Restrict to questions whose detection mode is in this set. */\n modes?: QuestionMode[];\n /** Maximum rows to return; hosts should apply this in the query. */\n limit?: number;\n },\n ) => Promise<PendingQuestionSummary[]>;\n /** Negotiation-digest summarizer. Optional; consumers fall back to deterministic digests. */\n negotiationSummary?: NegotiationSummaryReader;\n /** Manages negotiation timeout jobs (optional — enables AI fallback on external agent timeout). */\n negotiationTimeoutQueue?: NegotiationTimeoutQueue;\n /** Agent registry database adapter (optional — absent when host does not support agents). */\n agentDatabase?: AgentDatabase;\n /** Grants the default system-agent permissions after onboarding (optional). */\n grantDefaultSystemPermissions?: (userId: string) => Promise<void>;\n /** Dispatcher for routing negotiation turns to personal agents (optional — falls back to system AI). */\n agentDispatcher?: AgentDispatcher;\n /** Delivery ledger for committing opportunity delivery rows (optional — absent in chat context). */\n deliveryLedger?: DeliveryLedger;\n /** Persistence for async MCP discovery runs (optional — absent in non-MCP/test contexts). */\n discoveryRuns?: DiscoveryRunStore;\n /** Queue for async MCP discovery run execution (optional — absent in non-MCP/test contexts). */\n discoveryRunQueue?: DiscoveryRunQueue;\n /** Persistence for async MCP profile runs (optional — absent in non-MCP/test contexts). */\n profileRuns?: ProfileRunStore;\n /** Queue for async MCP profile run execution (optional — absent in non-MCP/test contexts). */\n profileRunQueue?: ProfileRunQueue;\n /**\n * Legacy direct-token minting for opportunity accept redirects.\n * Prefer `mintConnectLink` for user-facing links.\n */\n mintConnectToken?: (userId: string, opportunityId: string) => Promise<string>;\n /** Mints (or reuses) a short connect link, snapshotting the greeting (optional — absent in non-MCP contexts). */\n mintConnectLink?: MintConnectLink;\n /** Frontend base URL for building profile links (e.g. https://index.network, optional). */\n frontendUrl?: string;\n /** API base URL for building opportunity accept links (e.g. https://protocol.index.network, optional). */\n apiBaseUrl?: string;\n /** Optional host-side error reporter for swallowed protocol/tool errors. */\n reportToolError?: (error: unknown, report: ToolErrorReport) => void;\n /**\n * Optional host-side per-principal MCP call throttle. Invoked once per MCP\n * tool dispatch (after identity resolves, before any DB work). When the\n * returned decision is `allowed: false`, the dispatch short-circuits with a\n * rate-limit error carrying `retryAfterSec`. Absent in chat/test contexts.\n */\n mcpRateLimiter?: (input: { userId: string; agentId?: string; toolName: string }) => Promise<{\n allowed: boolean;\n retryAfterSec?: number;\n limit?: number;\n scope?: 'tool' | 'principal';\n }>;\n /** Optional premise lifecycle event callbacks. Fired by premise tools after successful operations. */\n premiseEvents?: {\n onCreated?: (premiseId: string, userId: string) => void;\n onUpdated?: (premiseId: string, userId: string) => void;\n onRetracted?: (premiseId: string, userId: string) => void;\n };\n graphs: {\n profile: CompiledGraph;\n intent: CompiledGraph;\n index: CompiledGraph;\n networkMembership: CompiledGraph;\n intentIndex: CompiledGraph;\n opportunity: CompiledOpportunityGraph;\n premise: CompiledGraph;\n };\n /**\n * Optional network ranking override for `read_networks`. Injected by tests or custom compositions.\n * When absent, defaults to `NetworkRecommender.invoke()` with a lazy module-level singleton.\n */\n networkRanker?: (input: {\n userProfile: { bio: string; location: string; interests: string[]; skills: string[] };\n networks: Array<{ networkId: string; renderedContext: string }>;\n }) => Promise<{ rankedNetworkIds: string[] } | null>;\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TOOL RESULT HELPERS\n// ═══════════════════════════════════════════════════════════════════════════════\n\nexport function success<T>(data: T): string {\n return JSON.stringify({ success: true, data });\n}\n\nexport function error(\n message: string,\n debugSteps?: Array<{ step: string; detail?: string; data?: Record<string, unknown> }>\n): string {\n return JSON.stringify({\n success: false,\n error: message,\n ...(debugSteps?.length ? { debugSteps } : {}),\n });\n}\n\n/** Return needsClarification for missing required fields. */\nexport function needsClarification(params: {\n missingFields: string[];\n message: string;\n}): string {\n return JSON.stringify({\n success: false,\n needsClarification: true,\n ...params,\n });\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// CONSTANTS & UTILITIES\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/** Matches http/https URLs in text; captures full URL. */\nconst URL_IN_TEXT_REGEX = /https?:\\/\\/[^\\s\"'<>)\\]]+/gi;\n\n/**\n * Matches bare domain URLs without protocol (e.g. github.com/foo, www.example.com).\n * Requires at least a SLD.TLD pattern followed by optional path.\n * Negative lookbehind ensures we don't double-match URLs already caught by URL_IN_TEXT_REGEX.\n */\nconst BARE_URL_REGEX = /(?<!\\w:\\/\\/)(?<![/\\w])(?:www\\.)?[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.(?:com|org|net|io|dev|co|ai|app|xyz|me|info|gg|so|sh|cc|ly|fm|tv|to|tech|design|network|world|edu|gov|mil|int|us|uk|eu|de|fr|ca|au|jp|cn|in|br|nl|se|no|fi|dk|ch|at|be|it|es|pt|pl|cz|ru|kr|tw|hk|sg|nz|za|mx|ar|cl|id|ph|th|vn|my|ie)(?:\\/[^\\s\"'<>)\\]]*)?/gi;\n\n/** UUID v4 format: 8-4-4-4-12 hex chars (e.g. c2505011-2e45-426e-81dd-b9abb9b72023) */\nexport const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/**\n * Resolves an array of network IDs to their display titles.\n * Skips any IDs that don't resolve (deleted or invalid networks).\n */\nexport async function resolveIndexNames(\n database: { getNetwork(id: string): Promise<{ id: string; title: string } | null> },\n networkIds: string[]\n): Promise<string[]> {\n if (networkIds.length === 0) return [];\n const results = await Promise.all(\n networkIds.map(id => database.getNetwork(id))\n );\n return results.filter(Boolean).map(idx => idx!.title);\n}\n\n/**\n * Normalize a URL string: if it lacks a protocol, prepend \"https://\".\n * Returns the normalized URL or null if the result is not a valid URL.\n */\nexport function normalizeUrl(raw: string): string | null {\n let url = raw.replace(/[.,;:!?)]+$/, \"\").trim();\n if (!/^https?:\\/\\//i.test(url)) {\n url = `https://${url}`;\n }\n try {\n new URL(url);\n return url;\n } catch {\n return null;\n }\n}\n\n/**\n * Extract unique, valid URLs from a string (e.g. user message or details).\n * Handles both full URLs (https://...) and bare domains (github.com/...).\n */\nexport function extractUrls(text: string): string[] {\n if (!text || typeof text !== \"string\") return [];\n\n const seen = new Set<string>();\n const out: string[] = [];\n\n // Pass 1: full protocol URLs\n const fullMatches = text.match(URL_IN_TEXT_REGEX) ?? [];\n for (const raw of fullMatches) {\n const url = normalizeUrl(raw);\n if (url && !seen.has(url)) {\n seen.add(url);\n out.push(url);\n }\n }\n\n // Pass 2: bare domain URLs (e.g. github.com/foo)\n const bareMatches = text.match(BARE_URL_REGEX) ?? [];\n for (const raw of bareMatches) {\n const url = normalizeUrl(raw);\n if (url && !seen.has(url)) {\n seen.add(url);\n out.push(url);\n }\n }\n\n return out;\n}\n\nconst SENSITIVE_FIELD_KEYS = new Set([\n \"secret\",\n \"webhooksecret\",\n \"password\",\n \"apikey\",\n \"token\",\n \"accesstoken\",\n \"refreshtoken\",\n \"privatekey\",\n \"authtoken\",\n \"bearertoken\",\n \"clientsecret\",\n]);\n\n/**\n * Recursively redacts sensitive field values from an arbitrary payload before\n * it is passed to a structured logger. Matches field names case-insensitively\n * and ignoring underscores, so `api_key`, `apiKey`, and `API_KEY` all match.\n * Non-sensitive fields are passed through unchanged. Never mutates the input —\n * returns a new value.\n *\n * Intended for structured-log redaction only. Do NOT use as a security\n * boundary for data in motion.\n *\n * @param value - Arbitrary JSON-like payload (query object, config blob, etc.)\n * @returns A new value with sensitive fields replaced by `\"[redacted]\"`.\n */\nexport function redactSensitiveFields(value: unknown): unknown {\n if (value === null || typeof value !== \"object\") return value;\n if (Array.isArray(value)) {\n return value.map((item) => redactSensitiveFields(item));\n }\n const out: Record<string, unknown> = {};\n for (const [key, inner] of Object.entries(value as Record<string, unknown>)) {\n const normalized = key.toLowerCase().replace(/_/g, \"\");\n if (SENSITIVE_FIELD_KEYS.has(normalized)) {\n out[key] = \"[redacted]\";\n } else {\n out[key] = redactSensitiveFields(inner);\n }\n }\n return out;\n}\n"]}
|