@indexnetwork/protocol 3.4.0-rc.254.1 → 3.6.0-rc.256.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.
@@ -1 +1 @@
1
- {"version":3,"file":"profile.tools.d.ts","sourceRoot":"/","sources":["profile/profile.tools.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,UAAU,EAAuB,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AAgCjG,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,0DA2tCxE"}
1
+ {"version":3,"file":"profile.tools.d.ts","sourceRoot":"/","sources":["profile/profile.tools.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,UAAU,EAAuB,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AAgCjG,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,0DA8sCxE"}
@@ -21,7 +21,7 @@ const approvedProfileDraftSchema = z.object({
21
21
  attributes: z.object({ interests: z.array(z.string()), skills: z.array(z.string()) }),
22
22
  });
23
23
  export function createProfileTools(defineTool, deps) {
24
- const { userDb, systemDb, database, graphs, enricher, grantDefaultSystemPermissions, reportToolError } = deps;
24
+ const { userDb, systemDb, graphs, enricher, grantDefaultSystemPermissions, reportToolError } = deps;
25
25
  function trimToUndefined(value) {
26
26
  const trimmed = value?.trim();
27
27
  return trimmed && trimmed.length > 0 ? trimmed : undefined;
@@ -1130,8 +1130,7 @@ export function createProfileTools(defineTool, deps) {
1130
1130
  description: "Marks the user's onboarding as complete, unlocking full platform access. This is the final step in the new-user setup flow.\n\n" +
1131
1131
  "**Prerequisites:** The user must have a profile (created via create_user_profile) AND must have explicitly confirmed it " +
1132
1132
  "(said 'yes', 'looks good', 'that's right', or similar). Do NOT call this until the user confirms.\n\n" +
1133
- "**What happens:** Sets completedAt timestamp on the user's onboarding record. May also auto-join the user to preconfigured indexes " +
1134
- "(communities) based on server configuration.\n\n" +
1133
+ "**What happens:** Sets completedAt timestamp on the user's onboarding record.\n\n" +
1135
1134
  "**Workflow:** create_user_profile() -> user confirms preview -> create_user_profile(confirm=true) -> user confirms saved profile -> complete_onboarding()\n\n" +
1136
1135
  "**Returns:** Confirmation that onboarding is complete. No parameters needed.",
1137
1136
  querySchema: z.object({}),
@@ -1158,19 +1157,7 @@ export function createProfileTools(defineTool, deps) {
1158
1157
  });
1159
1158
  }
1160
1159
  }
1161
- const autoJoinIds = (process.env.AUTO_JOIN_INDEX_IDS ?? '')
1162
- .split(',')
1163
- .map(id => id.trim())
1164
- .filter(Boolean);
1165
- for (const networkId of autoJoinIds) {
1166
- try {
1167
- await database.addMemberToNetwork(networkId, context.userId, 'member');
1168
- }
1169
- catch (err) {
1170
- logger.warn('Auto-join network failed (non-fatal)', { networkId, userId: context.userId, error: err instanceof Error ? err.message : String(err) });
1171
- }
1172
- }
1173
- logger.info("Onboarding completed", { userId: context.userId, autoJoinedNetworks: autoJoinIds.length });
1160
+ logger.info("Onboarding completed", { userId: context.userId });
1174
1161
  return success({ message: "Onboarding complete." });
1175
1162
  },
1176
1163
  });
@@ -1 +1 @@
1
- {"version":3,"file":"profile.tools.js","sourceRoot":"/","sources":["profile/profile.tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAG5E,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,kBAAkB,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AACjG,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAI5E,OAAO,EAAE,0BAA0B,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AAChG,OAAO,EAAE,uBAAuB,EAAE,MAAM,oCAAoC,CAAC;AAC7E,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;A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,CAAC;gBACpC,IAAI,CAAC;oBACH,MAAM,QAAQ,CAAC,kBAAkB,CAAC,SAAS,EAAE,OAAO,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;gBACzE,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,MAAM,CAAC,IAAI,CAAC,sCAAsC,EAAE,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,KAAK,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;gBACtJ,CAAC;YACH,CAAC;YAED,MAAM,CAAC,IAAI,CAAC,sBAAsB,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,kBAAkB,EAAE,WAAW,CAAC,MAAM,EAAE,CAAC,CAAC;YACxG,OAAO,OAAO,CAAC,EAAE,OAAO,EAAE,sBAAsB,EAAE,CAAC,CAAC;QACtD,CAAC;KACF,CAAC,CAAC;IAEH,OAAO,CAAC,gBAAgB,EAAE,8BAA8B,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,aAAa,EAAE,gBAAgB,EAAE,kBAAkB,CAAU,CAAC;AACxM,CAAC","sourcesContent":["import { z } from \"zod\";\n\nimport { requestContext } from \"../shared/observability/request-context.js\";\n\nimport type { DefineTool, ResolvedToolContext, ToolDeps } from \"../shared/agent/tool.helpers.js\";\nimport { success, error, needsClarification, UUID_REGEX } from \"../shared/agent/tool.helpers.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport type { EnrichmentResult } from \"../shared/interfaces/enrichment.interface.js\";\nimport type { OnboardingPrivacyState, OnboardingProfileSeed, OnboardingState, PrivacyConsentSource, UserRecord } from \"../shared/interfaces/database.interface.js\";\nimport type { ProfileRunInput, ProfileRunOperation } from \"../shared/interfaces/profile-run.interface.js\";\nimport { socialsToEnrichmentRequest, detectSocialLabel } from \"../shared/utils/social-label.js\";\nimport { normalizeTelegramHandle } from \"../shared/utils/telegram-handle.js\";\nimport { ProfileGenerator } from \"./profile.generator.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\n\nconst logger = protocolLogger(\"ChatTools:Profile\");\n\nfunction isMeaningfulEnrichment(enrichment: EnrichmentResult | null): enrichment is EnrichmentResult {\n return !!enrichment &&\n enrichment.confidentMatch &&\n (\n enrichment.identity.bio.trim().length > 0 ||\n enrichment.narrative.context.trim().length > 0 ||\n enrichment.attributes.skills.length > 0 ||\n enrichment.attributes.interests.length > 0\n );\n}\n\nconst approvedProfileDraftSchema = z.object({\n identity: z.object({ name: z.string(), bio: z.string(), location: z.string() }),\n narrative: z.object({ context: z.string() }),\n attributes: z.object({ interests: z.array(z.string()), skills: z.array(z.string()) }),\n});\n\ntype ApprovedProfileDraft = z.infer<typeof approvedProfileDraftSchema>;\n\nexport function createProfileTools(defineTool: DefineTool, deps: ToolDeps) {\n const { userDb, systemDb, database, graphs, enricher, grantDefaultSystemPermissions, reportToolError } = deps;\n\n function trimToUndefined(value: string | null | undefined): string | undefined {\n const trimmed = value?.trim();\n return trimmed && trimmed.length > 0 ? trimmed : undefined;\n }\n\n function isPlaceholderName(value: string): boolean {\n const normalized = value.trim().toLowerCase();\n return normalized === 'unknown' || normalized === 'user';\n }\n\n function resolveAuthenticatedLookupIdentity(user: UserRecord, context: { userName?: string; userEmail?: string }) {\n const userName = trimToUndefined(user.name);\n const contextName = trimToUndefined(context.userName);\n const name = [userName, contextName].find((candidate) => candidate !== undefined && !isPlaceholderName(candidate));\n const email = trimToUndefined(user.email) ?? trimToUndefined(context.userEmail);\n return { name, email };\n }\n\n async function enrichFromUserRecord(user: { name?: string | null; email?: string | null; socials: Array<{ id: string; userId: string; label: string; value: string }> }) {\n const enrichmentSocials = socialsToEnrichmentRequest(user.socials);\n return enricher.enrichUserProfile({\n name: trimToUndefined(user.name),\n email: trimToUndefined(user.email),\n linkedin: enrichmentSocials.linkedin || undefined,\n twitter: enrichmentSocials.twitter || undefined,\n github: enrichmentSocials.github || undefined,\n telegram: enrichmentSocials.telegram || undefined,\n websites: enrichmentSocials.websites?.length ? enrichmentSocials.websites : undefined,\n });\n }\n\n function hasPublicProfileLookupConsent(onboarding: OnboardingState | null | undefined): boolean {\n return onboarding?.privacy?.publicProfileLookup?.granted === true;\n }\n\n function hasEdgeosImportConsent(onboarding: OnboardingState | null | undefined): boolean {\n return onboarding?.privacy?.edgeosImport?.granted === true;\n }\n\n function normalizeConsentSource(source: unknown): PrivacyConsentSource {\n return source === 'agentvillage_onboarding' || source === 'hermes_setup' || source === 'web_onboarding' || source === 'api'\n ? source\n : 'api';\n }\n\n function consentDecision(granted: boolean, source: PrivacyConsentSource) {\n return { granted, decidedAt: new Date().toISOString(), source };\n }\n\n function selectProfileSeed(onboarding: OnboardingState | null | undefined, networkId?: string): OnboardingProfileSeed | undefined {\n const seeds = onboarding?.profileSeeds ?? [];\n if (seeds.length === 0) return undefined;\n const scoped = networkId ? seeds.filter((seed) => seed.networkId === networkId) : seeds;\n return scoped[scoped.length - 1] ?? seeds[seeds.length - 1];\n }\n\n function normalizeSocialUpdate(label: string, value: string): { label: string; value: string } | null {\n const normalizedLabel = label.trim().toLowerCase();\n if (!normalizedLabel) return null;\n const trimmedValue = value.trim();\n if (!trimmedValue) return null;\n if (normalizedLabel === 'telegram') {\n const handle = normalizeTelegramHandle(trimmedValue);\n return handle ? { label: normalizedLabel, value: handle } : null;\n }\n return { label: normalizedLabel, value: trimmedValue };\n }\n\n async function mergeUserSocials(incoming: { label: string; value: string }[]): Promise<void> {\n const normalizedIncoming = incoming\n .map((social) => normalizeSocialUpdate(social.label, social.value))\n .filter((social): social is { label: string; value: string } => social !== null);\n if (normalizedIncoming.length === 0) return;\n\n const existingSocials = await userDb.getUserSocials();\n const incomingLabels = new Set(normalizedIncoming.map((social) => social.label));\n const kept = existingSocials\n .filter((social) => !incomingLabels.has(social.label) || social.label === 'custom')\n .map((social) => ({ label: social.label, value: social.value }));\n const merged = incomingLabels.has('custom')\n ? [...kept.filter((social) => social.label !== 'custom'), ...normalizedIncoming]\n : [...kept, ...normalizedIncoming];\n await userDb.setUserSocials(merged);\n }\n\n function socialsRecordToRows(socials: Record<string, string> | undefined): { label: string; value: string }[] {\n if (!socials) return [];\n return Object.entries(socials).map(([label, value]) => ({ label, value }));\n }\n\n async function enqueueProfileRun(\n context: ResolvedToolContext,\n operation: ProfileRunOperation,\n input: ProfileRunInput,\n ): Promise<string | null> {\n if (!context.isMcp || !deps.profileRuns || !deps.profileRunQueue) return null;\n const run = await deps.profileRuns.create({\n userId: context.userId,\n agentId: context.agentId ?? null,\n operation,\n input,\n context: {\n userId: context.userId,\n userName: context.userName,\n userEmail: context.userEmail,\n ...(context.networkId ? { networkId: context.networkId } : {}),\n ...(context.indexName ? { indexName: context.indexName } : {}),\n indexScope: context.indexScope,\n ...(context.sessionId ? { sessionId: context.sessionId } : {}),\n ...(context.agentId ? { agentId: context.agentId } : {}),\n ...(context.clientSurface ? { clientSurface: context.clientSurface } : {}),\n },\n });\n try {\n await deps.profileRunQueue.enqueue(run.id);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n await deps.profileRuns.markFailed(run.id, message);\n if (err instanceof Error) throw err;\n const wrapped = new Error(`Failed to enqueue profile run: ${message}`) as Error & { cause?: unknown };\n wrapped.cause = err;\n throw wrapped;\n }\n return run.id;\n }\n\n async function persistApprovedProfileContext(profile: { identity: { name: string; bio: string; location: string } }, user: UserRecord | null, networkId?: string): Promise<void> {\n await userDb.updateUser({\n name: profile.identity.name,\n intro: profile.identity.bio,\n location: profile.identity.location,\n });\n\n const onboarding = user?.onboarding ?? undefined;\n if (!hasEdgeosImportConsent(onboarding)) return;\n const seed = selectProfileSeed(onboarding, networkId);\n if (!seed?.socials?.length) return;\n\n await mergeUserSocials(seed.socials);\n }\n\n function buildProfileInput(parts: {\n name?: string;\n location?: string;\n bioOrDescription?: string;\n edgeosProfileText?: string;\n enrichment?: EnrichmentResult | null;\n socials?: Array<{ label: string; value: string }>;\n }): string {\n const lines: string[] = [];\n if (parts.name) lines.push(`Name: ${parts.name}`);\n if (parts.location) lines.push(`Location: ${parts.location}`);\n if (parts.bioOrDescription) lines.push(parts.bioOrDescription);\n if (parts.edgeosProfileText) lines.push(`Event-provided profile information:\\n${parts.edgeosProfileText}`);\n if (parts.socials?.length) {\n lines.push(`User-provided public links:\\n${parts.socials.map((s) => `${s.label}: ${s.value}`).join('\\n')}`);\n }\n const enrichment = parts.enrichment ?? null;\n if (isMeaningfulEnrichment(enrichment)) {\n lines.push([\n enrichment.identity.name ? `Enriched name: ${enrichment.identity.name}` : '',\n enrichment.identity.location ? `Enriched location: ${enrichment.identity.location}` : '',\n enrichment.identity.bio ? `Enriched bio: ${enrichment.identity.bio}` : '',\n enrichment.narrative.context ? `Enriched context: ${enrichment.narrative.context}` : '',\n enrichment.attributes.skills.length ? `Skills: ${enrichment.attributes.skills.join(', ')}` : '',\n enrichment.attributes.interests.length ? `Interests: ${enrichment.attributes.interests.join(', ')}` : '',\n ].filter(Boolean).join('\\n'));\n }\n return lines.filter((line) => line.trim().length > 0).join('\\n\\n');\n }\n\n function toProfileSummary(profile: { identity: { name: string; bio: string; location: string }; attributes: { skills: string[]; interests: string[] } }) {\n return {\n name: profile.identity.name,\n bio: profile.identity.bio,\n location: profile.identity.location,\n skills: profile.attributes.skills,\n interests: profile.attributes.interests,\n };\n }\n\n function buildApprovedDraftProfileInput(draft: ApprovedProfileDraft): string {\n return [\n draft.identity.name ? `My name is ${draft.identity.name}.` : '',\n draft.identity.location ? `I am based in ${draft.identity.location}.` : '',\n draft.identity.bio || '',\n draft.narrative.context || '',\n draft.attributes.skills.length ? `My skills include ${draft.attributes.skills.join(', ')}.` : '',\n draft.attributes.interests.length ? `My interests include ${draft.attributes.interests.join(', ')}.` : '',\n ].filter((part) => part.trim().length > 0).join('\\n');\n }\n\n async function decomposeApprovedDraftProfile(\n profile: ApprovedProfileDraft & { userId: string },\n ): Promise<void> {\n const input = buildApprovedDraftProfileInput(profile);\n if (!input.trim()) return;\n\n const traceEmitter = requestContext.getStore()?.traceEmitter;\n const graphStart = Date.now();\n traceEmitter?.({ type: \"graph_start\", name: \"profile\" });\n try {\n const graphInput = {\n userId: profile.userId,\n operationMode: 'write' as const,\n input,\n forceUpdate: true,\n };\n // Always invoked as a background fire-and-forget task (see confirm_user_profile\n // call sites), so decomposition must outlive the originating request — invoke\n // the graph directly and never bind the request abort signal, which would\n // cancel it as soon as the web request completes.\n const result = await graphs.profile.invoke(graphInput);\n\n if (result.error) {\n const err = new Error(result.error);\n logger.error('Approved draft premise decomposition failed', {\n userId: profile.userId,\n error: result.error,\n });\n reportToolError?.(err, {\n subsystem: 'profile',\n operation: 'profile.confirm_draft_decompose',\n toolName: 'confirm_user_profile',\n userId: profile.userId,\n tags: { toolName: 'confirm_user_profile', execution: 'background' },\n });\n return;\n }\n\n // The write graph's decompose → aggregate → generate → save_profile\n // pipeline persists the aggregate profile. The approved draft was already\n // saved before decomposition started, so the DB is consistent regardless\n // of graph outcome. Do not re-save here — the graph's save_profile is\n // authoritative, and a concurrent user-driven profile update could race.\n } catch (err) {\n logger.error('Approved draft premise decomposition failed', {\n userId: profile.userId,\n error: err instanceof Error ? err.message : String(err),\n });\n reportToolError?.(err, {\n subsystem: 'profile',\n operation: 'profile.confirm_draft_decompose',\n toolName: 'confirm_user_profile',\n userId: profile.userId,\n tags: { toolName: 'confirm_user_profile', execution: 'background' },\n });\n } finally {\n traceEmitter?.({ type: \"graph_end\", name: \"profile\", durationMs: Date.now() - graphStart });\n }\n }\n\n const readUserProfiles = defineTool({\n name: \"read_user_profiles\",\n description:\n \"Retrieves user profiles containing identity info (name, bio, location), skills, and interests. Profiles are used for semantic matching \" +\n \"in opportunity discovery — richer profiles produce better matches.\\n\\n\" +\n \"**Usage modes:**\\n\" +\n \"- With `query` (name search): finds members by name (case-insensitive substring) across the user's indexes. \" +\n \"This is the primary way to look up a person by name. Add `networkId` to restrict search to one index.\\n\" +\n \"- With `userId`: returns that specific user's full profile (name, bio, skills, interests, location).\\n\" +\n \"- With `networkId` alone: returns profiles of ALL members in that index.\\n\" +\n \"- No parameters: returns the current user's own profile.\\n\\n\" +\n \"**When to use:** Before creating introductions (need profiles of both parties), when the user asks about a person, \" +\n \"or to check if a profile exists before suggesting create_user_profile. \" +\n \"MCP agents should call this with no arguments at session start to fetch the caller's profile AND onboarding status.\\n\\n\" +\n \"**Returns:** Profile objects with name, bio, location, skills[], interests[]. Use userId from results with other tools like read_intents(userId, networkId). \" +\n \"When called for the current user (no args, or userId=self), the response also includes `onboardingComplete: boolean` and `onboardingCompletedAt?: string` — \" +\n \"use these as the source of truth for whether the user still needs onboarding (do not rely on local file state).\",\n querySchema: z.object({\n userId: z.string().optional().describe(\"Fetch a specific user's profile by their user ID. Get user IDs from read_network_memberships or list_contacts.\"),\n networkId: z.string().optional().describe(\"Index UUID — fetch profiles of all members in this index, or narrow a name search to this index. Get from read_networks.\"),\n query: z.string().optional().describe(\"Name to search for (case-insensitive substring match). Searches across all the user's indexes unless networkId is also provided. Use this when the user asks to 'find' or 'look up' someone.\"),\n }),\n handler: async ({ context, query }) => {\n const effectiveIndexId = query.networkId?.trim() || undefined;\n const targetUserId = query.userId?.trim() || undefined;\n const nameQuery = query.query?.trim() || undefined;\n\n if (effectiveIndexId && !UUID_REGEX.test(effectiveIndexId)) {\n return error(\"Invalid network ID format. Use the exact UUID from read_networks.\");\n }\n\n // --- Name search mode: query provided → find members by name ---\n if (nameQuery) {\n const pattern = nameQuery.toLowerCase();\n const MAX_RESULTS = 20;\n // When chat is index-scoped, restrict name search to that index\n const searchIndexId = effectiveIndexId || context.networkId || undefined;\n\n let candidates: Array<{ userId: string; name: string; avatar: string | null }>;\n\n if (searchIndexId) {\n // Scoped to a specific index\n if (context.networkId && searchIndexId !== context.networkId) {\n return error(\n context.indexName\n ? `This chat is scoped to ${context.indexName}. You can only look up people in this community.`\n : `This chat is scoped to this index. You can only look up people in this community.`\n );\n }\n const callerIsMember = await systemDb.isNetworkMember(searchIndexId, context.userId);\n if (!callerIsMember) {\n return error(\"You can only look up people in indexes you are a member of.\");\n }\n const members = await systemDb.getNetworkMembers(searchIndexId);\n candidates = members.map((m) => ({ userId: m.userId, name: m.name, avatar: m.avatar ?? null }));\n } else {\n // Search across all user's indexes\n candidates = await systemDb.getMembersFromScope();\n }\n\n logger.verbose(\"Name search candidates\", {\n query: nameQuery,\n pattern,\n candidateCount: candidates.length,\n userId: context.userId,\n });\n\n // Filter by name (case-insensitive substring), exclude self\n const matched = candidates\n .filter((c) => c.userId !== context.userId && c.name.toLowerCase().includes(pattern))\n .slice(0, MAX_RESULTS);\n\n if (matched.length === 0) {\n return success({ query: nameQuery, matchCount: 0, profiles: [], message: \"No members found matching that name.\" });\n }\n\n // Fetch full profiles for matches\n const profiles = await Promise.all(\n matched.map(async (m) => {\n try {\n const profile = await systemDb.getProfile(m.userId);\n return {\n userId: m.userId,\n name: m.name,\n hasProfile: !!profile,\n profile: profile\n ? {\n name: profile.identity.name,\n bio: profile.identity.bio,\n location: profile.identity.location,\n skills: profile.attributes.skills,\n interests: profile.attributes.interests,\n }\n : undefined,\n };\n } catch (err) {\n logger.warn(\"read_user_profiles: getProfile failed; degrading to hasProfile=false\", {\n userId: m.userId,\n error: err instanceof Error ? err.message : String(err),\n });\n return { userId: m.userId, name: m.name, hasProfile: false };\n }\n })\n );\n\n return success({ query: nameQuery, matchCount: profiles.length, profiles });\n }\n\n // When no userId / networkId / query is provided, fall through to Mode 1 (self lookup).\n\n // --- Mode 3: networkId provided → fetch all member profiles ---\n if (effectiveIndexId) {\n // Strict scope enforcement: when chat is index-scoped, only allow querying that index\n if (context.networkId && effectiveIndexId !== context.networkId) {\n return error(\n context.indexName\n ? `This chat is scoped to ${context.indexName}. You can only read profiles from this community.`\n : `This chat is scoped to this index. You can only read profiles from this community.`\n );\n }\n\n // Verify the caller is a member of the index they're querying\n const callerIsMember = await systemDb.isNetworkMember(effectiveIndexId, context.userId);\n if (!callerIsMember) {\n return error(\n \"You can only read profiles from indexes you are a member of.\"\n );\n }\n\n // Use systemDb for cross-user access within shared indexes\n const members = await systemDb.getNetworkMembers(effectiveIndexId);\n const profiles = await Promise.all(\n members.map(async (member) => {\n const profile = await systemDb.getProfile(member.userId);\n return {\n userId: member.userId,\n name: member.name,\n hasProfile: !!profile,\n profile: profile\n ? {\n name: profile.identity.name,\n bio: profile.identity.bio,\n location: profile.identity.location,\n skills: profile.attributes.skills,\n interests: profile.attributes.interests,\n }\n : undefined,\n };\n })\n );\n return success({ networkId: effectiveIndexId, memberCount: members.length, profiles });\n }\n\n // --- Mode 2: userId provided (different user) → fetch single profile directly ---\n if (targetUserId && targetUserId !== context.userId) {\n // Strict scope enforcement: when chat is index-scoped, verify user is in that index\n if (context.networkId) {\n const isInScopedIndex = await systemDb.isNetworkMember(context.networkId, targetUserId);\n if (!isInScopedIndex) {\n return error(\n context.indexName\n ? `This chat is scoped to ${context.indexName}. You can only read profiles of members in this community.`\n : `This chat is scoped to this index. You can only read profiles of members in this community.`\n );\n }\n }\n\n // Use systemDb for cross-user profile access (requires shared index)\n const profile = await systemDb.getProfile(targetUserId);\n if (profile) {\n return success({\n hasProfile: true,\n profile: {\n name: profile.identity.name,\n bio: profile.identity.bio,\n location: profile.identity.location,\n skills: profile.attributes.skills,\n interests: profile.attributes.interests,\n },\n });\n }\n return success({ hasProfile: false, message: \"This user does not have a profile yet.\" });\n }\n\n // --- Mode 1: No args / self → use profileGraph query (returns id for updates) ---\n const _readProfileGraphStart = Date.now();\n const _readProfileTraceEmitter = requestContext.getStore()?.traceEmitter;\n _readProfileTraceEmitter?.({ type: \"graph_start\", name: \"profile\" });\n const result = await invokeWithAbortSignal(graphs.profile, {\n userId: context.userId,\n operationMode: 'query' as const,\n });\n const _readProfileGraphMs = Date.now() - _readProfileGraphStart;\n _readProfileTraceEmitter?.({ type: \"graph_end\", name: \"profile\", durationMs: _readProfileGraphMs });\n\n // Self-lookup includes onboarding status so MCP agents (e.g. Edge Claw)\n // can decide whether to run the onboarding flow without depending on\n // local-only state like a workspace BOOTSTRAP.md file.\n const onboardingCompletedAt = context.user.onboarding?.completedAt ?? null;\n const onboardingFields = {\n onboardingComplete: !!onboardingCompletedAt,\n ...(onboardingCompletedAt ? { onboardingCompletedAt } : {}),\n };\n\n if (result.readResult) {\n return success({ ...result.readResult, ...onboardingFields, _graphTimings: [{ name: 'profile', durationMs: _readProfileGraphMs, agents: result.agentTimings ?? [] }] });\n }\n if (result.profile) {\n return success({\n hasProfile: true,\n profile: {\n name: result.profile.identity.name,\n bio: result.profile.identity.bio,\n location: result.profile.identity.location,\n skills: result.profile.attributes.skills,\n interests: result.profile.attributes.interests,\n },\n ...onboardingFields,\n _graphTimings: [{ name: 'profile', durationMs: _readProfileGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n return success({\n hasProfile: false,\n ...onboardingFields,\n message: \"You don't have a profile yet. Would you like to create one? You can share your LinkedIn, GitHub, or X/Twitter profile, or just tell me about yourself.\",\n _graphTimings: [{ name: 'profile', durationMs: _readProfileGraphMs, agents: result.agentTimings ?? [] }],\n });\n },\n });\n\n const recordOnboardingPrivacyConsent = defineTool({\n name: \"record_onboarding_privacy_consent\",\n description:\n \"Records exactly one authenticated-user onboarding privacy choice. Use this during AgentVillage/Hermes onboarding only after the user explicitly answers the matching consent question in a prior message. \" +\n \"Do not call this in the same assistant turn as the consent question, and do not combine EdgeOS import and public lookup decisions in one call. \" +\n \"This only records consent; it does not mark onboarding complete and does not create or update a profile.\",\n querySchema: z.object({\n edgeosImportGranted: z.boolean().optional().describe(\"Whether the user grants permission to use EdgeOS/event-provided profile data for onboarding.\"),\n publicProfileLookupGranted: z.boolean().optional().describe(\"Whether the user grants permission for public internet/profile lookup during onboarding.\"),\n source: z.enum(['agentvillage_onboarding', 'hermes_setup', 'web_onboarding', 'api']).optional().default('api').describe(\"Where this consent decision was collected.\"),\n }),\n handler: async ({ context, query }) => {\n const user = await userDb.getUser();\n if (user?.isGhost) {\n return error(\"Ghost users cannot record onboarding consent. The user must authenticate as a real account first.\");\n }\n const hasEdgeosDecision = query.edgeosImportGranted !== undefined;\n const hasPublicLookupDecision = query.publicProfileLookupGranted !== undefined;\n if (!hasEdgeosDecision && !hasPublicLookupDecision) {\n return error(\"Provide exactly one consent decision to record.\");\n }\n if (hasEdgeosDecision && hasPublicLookupDecision) {\n return error(\"Record EdgeOS import consent and public-profile lookup consent separately, after each explicit user answer. Do not combine them in one call.\");\n }\n\n const currentOnboarding = user?.onboarding ?? context.user.onboarding ?? {};\n const currentPrivacy: OnboardingPrivacyState = currentOnboarding.privacy ?? {};\n const source = normalizeConsentSource(query.source);\n const privacy: OnboardingPrivacyState = {\n ...currentPrivacy,\n ...(query.edgeosImportGranted !== undefined && { edgeosImport: consentDecision(query.edgeosImportGranted, source) }),\n ...(query.publicProfileLookupGranted !== undefined && { publicProfileLookup: consentDecision(query.publicProfileLookupGranted, source) }),\n };\n\n await userDb.updateUser({\n onboarding: {\n ...currentOnboarding,\n privacy,\n },\n });\n\n return success({\n message: \"Privacy choices recorded.\",\n privacy,\n });\n },\n });\n\n const previewUserProfile = defineTool({\n name: \"preview_user_profile\",\n description:\n \"Builds a structured profile draft for onboarding without saving anything. Use this after recording privacy consent and before asking the user to approve the profile. \" +\n \"If allowPublicLookup is false, this tool uses only explicit text, EdgeOS/event data the user allowed, and user-provided social URLs. If allowPublicLookup is true, persisted public lookup consent is required. \" +\n \"In MCP contexts, starts an async profile run and returns `profileRunId`; poll get_profile_run until status is `succeeded`, then present its `result`.\" +\n \" When public lookup runs, the result includes a `publicLookup` block reporting whether a candidate identity was found (`used`, `confidentMatch`) and what it was (`identity` of name/role/location, plus `socials`), so the caller can confirm identity before saving. A candidate can be returned (`used: true`) without being confident enough to enter the draft; when no lookup runs the block is `{ used: false }`.\",\n querySchema: z.object({\n name: z.string().optional().describe(\"Name explicitly provided by the user. For authenticated public lookup, the account identity is used first and this is only a fallback.\"),\n location: z.string().optional().describe(\"Location explicitly provided by the user or allowed event data.\"),\n bioOrDescription: z.string().optional().describe(\"Explicit self-description provided by the user.\"),\n edgeosProfileText: z.string().optional().describe(\"EdgeOS/event profile text, only if the user granted EdgeOS import consent.\"),\n allowPublicLookup: z.boolean().optional().default(false).describe(\"Whether to include public profile lookup. Requires previously recorded publicProfileLookup consent.\"),\n linkedinUrl: z.string().optional().describe(\"LinkedIn URL explicitly provided by the user.\"),\n githubUrl: z.string().optional().describe(\"GitHub URL explicitly provided by the user.\"),\n twitterUrl: z.string().optional().describe(\"X/Twitter URL explicitly provided by the user.\"),\n websites: z.array(z.string()).optional().describe(\"Personal/portfolio URLs explicitly provided by the user.\"),\n }),\n handler: async ({ context, query }) => {\n const user = await userDb.getUser();\n if (!user) return error(\"User not found.\");\n\n const profileRunId = await enqueueProfileRun(context, \"preview_user_profile\", query);\n if (profileRunId) {\n return success({\n status: \"queued\" as const,\n profileRunId,\n message: `Profile preview started. Call get_profile_run with profileRunId=\"${profileRunId}\" until it succeeds, fails, or is cancelled.`,\n });\n }\n\n const onboarding = user.onboarding ?? context.user.onboarding;\n const hasEdgeosConsent = hasEdgeosImportConsent(onboarding);\n const seed = hasEdgeosConsent ? selectProfileSeed(onboarding, context.networkId) : undefined;\n const authenticatedIdentity = resolveAuthenticatedLookupIdentity(user, context);\n const name = seed?.name || authenticatedIdentity.name || query.name?.trim() || undefined;\n const location = query.location?.trim() || seed?.location || user.location || undefined;\n const bioOrDescription = query.bioOrDescription?.trim() || seed?.bio || user.intro || undefined;\n const edgeosProfileText = query.edgeosProfileText?.trim() || undefined;\n const linkedinUrl = query.linkedinUrl?.trim();\n const githubUrl = query.githubUrl?.trim();\n const twitterUrl = query.twitterUrl?.trim();\n const websites = query.websites?.map((url) => url.trim()).filter(Boolean) ?? [];\n const socials = [\n ...(seed?.socials ?? []),\n ...(linkedinUrl ? [{ label: 'linkedin', value: linkedinUrl }] : []),\n ...(githubUrl ? [{ label: 'github', value: githubUrl }] : []),\n ...(twitterUrl ? [{ label: 'twitter', value: twitterUrl }] : []),\n ...websites.map((value) => ({ label: detectSocialLabel(value), value })),\n ];\n\n if (edgeosProfileText && !hasEdgeosConsent) {\n return error(\"EdgeOS import consent has not been recorded. Ask the user first, then call record_onboarding_privacy_consent(edgeosImportGranted=true) before using event-provided profile data.\");\n }\n\n let enrichment: EnrichmentResult | null = null;\n if (query.allowPublicLookup) {\n if (!hasPublicProfileLookupConsent(user.onboarding ?? context.user.onboarding)) {\n return error(\"Public profile lookup consent has not been recorded. Ask the user first, then call record_onboarding_privacy_consent(publicProfileLookupGranted=true).\");\n }\n const hasAuthenticatedIdentity = authenticatedIdentity.name !== undefined || authenticatedIdentity.email !== undefined;\n enrichment = await enrichFromUserRecord({\n name: authenticatedIdentity.name ?? (hasAuthenticatedIdentity ? undefined : name),\n email: authenticatedIdentity.email,\n socials: socials.map((social, index) => ({ id: `preview-${index}`, userId: context.userId, ...social })),\n });\n }\n\n const input = buildProfileInput({ name, location, bioOrDescription, edgeosProfileText, enrichment, socials });\n if (!input.trim()) {\n return needsClarification({\n missingFields: ['profile_description'],\n message: \"Please share a short description, allowed EdgeOS profile text, or user-provided profile links so I can draft your profile.\",\n });\n }\n\n const generated = await new ProfileGenerator().invoke(input);\n const profile = { ...generated.output, userId: context.userId };\n return success({\n preview: true,\n persisted: false,\n message: \"Profile draft generated. Show this to the user and ask whether it looks right before calling confirm_user_profile.\",\n profile: toProfileSummary(profile),\n draft: profile,\n publicLookup: enrichment\n ? {\n used: true,\n confidentMatch: enrichment.confidentMatch,\n // identity.bio is the role/headline string returned by the lookup\n identity: {\n name: enrichment.identity.name,\n role: enrichment.identity.bio,\n location: enrichment.identity.location,\n },\n socials: enrichment.socials,\n }\n : { used: false },\n });\n },\n });\n\n const confirmUserProfile = defineTool({\n name: \"confirm_user_profile\",\n description:\n \"Saves an explicitly approved onboarding profile draft. Call this only after the user has seen the draft from preview_user_profile and approved it or provided corrections. \" +\n \"This path uses only the approved draft/explicit correction text and does not scrape or run public lookup.\",\n querySchema: z.object({\n draft: approvedProfileDraftSchema.optional().describe(\"The structured profile draft returned by preview_user_profile after user approval.\"),\n bioOrDescription: z.string().optional().describe(\"Approved correction or explicit profile text if not passing a structured draft.\"),\n name: z.string().optional().describe(\"Approved name correction.\"),\n location: z.string().optional().describe(\"Approved location correction.\"),\n }),\n handler: async ({ context, query }) => {\n const user = await userDb.getUser();\n if (query.draft) {\n const profile = { ...query.draft, userId: context.userId };\n await userDb.saveProfile(profile);\n await persistApprovedProfileContext(profile, user, context.networkId);\n\n const decomposeLogLabel = context.isMcp\n ? 'Approved draft premise decomposition failed'\n : 'Approved draft premise decomposition failed (web)';\n decomposeApprovedDraftProfile(profile).catch((err: unknown) => {\n logger.error(decomposeLogLabel, {\n userId: profile.userId,\n error: err instanceof Error ? err.message : String(err),\n });\n });\n\n return success({\n created: true,\n message: context.isMcp\n ? \"Profile saved from approved draft. Premise extraction is running in the background.\"\n : \"Profile saved from approved draft.\",\n profile: toProfileSummary(profile),\n });\n }\n\n const description = query.bioOrDescription?.trim();\n if (!description) {\n return error(\"Pass the approved structured draft or explicit approved profile text.\");\n }\n const approvedName = query.name?.trim();\n const approvedLocation = query.location?.trim();\n const input = buildProfileInput({\n name: approvedName,\n location: approvedLocation,\n bioOrDescription: description,\n });\n const rawProfile = {\n identity: {\n name: approvedName && approvedName.length > 0 ? approvedName : user?.name ?? '',\n bio: description,\n location: approvedLocation && approvedLocation.length > 0 ? approvedLocation : user?.location ?? '',\n },\n };\n await persistApprovedProfileContext(rawProfile, user, context.networkId);\n\n const _confirmTraceEmitter = requestContext.getStore()?.traceEmitter;\n const _confirmGraphStart = Date.now();\n _confirmTraceEmitter?.({ type: \"graph_start\", name: \"profile\" });\n graphs.profile.invoke({\n userId: context.userId,\n operationMode: 'write' as const,\n input,\n forceUpdate: true,\n }).then((result) => {\n if (result.error || !result.profile) {\n logger.error('Background profile generation failed', {\n userId: context.userId,\n error: result.error ?? 'No profile returned',\n });\n }\n }).catch((err: unknown) =>\n logger.error('Background profile generation failed', {\n userId: context.userId,\n error: err instanceof Error ? err.message : String(err),\n })\n ).finally(() => {\n const _confirmGraphMs = Date.now() - _confirmGraphStart;\n _confirmTraceEmitter?.({ type: \"graph_end\", name: \"profile\", durationMs: _confirmGraphMs });\n });\n\n return success({\n created: true,\n message: \"Profile text accepted. Your profile is being structured in the background.\",\n profile: toProfileSummary({\n identity: rawProfile.identity,\n attributes: { skills: [], interests: [] },\n }),\n });\n },\n });\n\n const createUserProfile = defineTool({\n name: \"create_user_profile\",\n description:\n \"Legacy/backward-compatible tool that creates or regenerates the authenticated user's profile. AgentVillage/Hermes onboarding must use \" +\n \"record_onboarding_privacy_consent → preview_user_profile → confirm_user_profile instead, so consent is recorded and the draft is shown before saving. \" +\n \"Profiles are essential for discovery — they provide the semantic context used to match users with complementary intents.\\n\\n\" +\n \"**How it works:** For generic clients, the system can enrich profile data from public web sources (LinkedIn, GitHub, Twitter) and/or explicit user input, \" +\n \"then generates a structured profile with bio, skills, interests, location, and narrative context. Do not call with no arguments in consent-required onboarding flows.\\n\\n\" +\n \"**Usage patterns:**\\n\" +\n \"- No args: attempts auto-generation from account data. If insufficient info, returns `missingFields` — ask the user for name/social URLs and retry.\\n\" +\n \"- With social URLs (linkedinUrl, githubUrl, etc.): enriches from those specific URLs.\\n\" +\n \"- With bioOrDescription: creates profile from explicit text only (no web scraping).\\n\" +\n \"- Legacy onboarding clients: first call returns a preview. AgentVillage/Hermes clients should not use this preview path; use preview_user_profile instead because it does not persist enrichment side effects.\\n\\n\" +\n \"**Returns:** The generated profile (name, bio, location, skills, interests) or a `needsClarification` response listing missing fields.\\n\\n\" +\n \"**Next steps:** After profile creation, the user can create intents (create_intent) and join indexes (create_network_membership) to start discovering opportunities.\",\n querySchema: z.object({\n name: z.string().optional().describe(\"User's full name (first and last). Pass when the user explicitly provides their name.\"),\n linkedinUrl: z.string().optional().describe(\"LinkedIn profile URL (e.g. 'https://linkedin.com/in/username'). Pass when user shares a LinkedIn link.\"),\n githubUrl: z.string().optional().describe(\"GitHub profile URL (e.g. 'https://github.com/username'). Pass when user shares a GitHub link.\"),\n twitterUrl: z.string().optional().describe(\"X/Twitter profile URL (e.g. 'https://x.com/username'). Pass when user shares a Twitter/X link.\"),\n websites: z.array(z.string()).optional().describe(\"Personal or portfolio website URLs. Pass when user shares website links.\"),\n location: z.string().optional().describe(\"User's location (e.g. 'Berlin, Germany' or 'SF Bay Area'). Pass when the user mentions where they are based.\"),\n bioOrDescription: z.string().optional().describe(\"Explicit profile text from the user (e.g. 'software engineer focused on AI/ML, based in SF'). When provided, creates/updates profile from this text only — no web scraping. Use when user describes themselves in chat.\"),\n confirm: z.boolean().optional().describe(\"Set to true to save a previously previewed profile. Only used during onboarding flow after the user approves the preview.\"),\n }),\n handler: async ({ context, query }) => {\n // Persist user-info fields (name, location, socials) to users table before any branching.\n // This ensures users.name is always updated regardless of which code path runs.\n // Trim all string fields to avoid persisting whitespace-only values.\n const name = query.name?.trim();\n const location = query.location?.trim();\n const linkedinUrl = query.linkedinUrl?.trim();\n const githubUrl = query.githubUrl?.trim();\n const twitterUrl = query.twitterUrl?.trim();\n const websites = query.websites?.map((url) => url.trim()).filter(Boolean);\n const hasSocialsFromQuery = Boolean(linkedinUrl || githubUrl || twitterUrl || websites?.length);\n if (name || location) {\n await userDb.updateUser({\n ...(name ? { name } : {}),\n ...(location ? { location } : {}),\n });\n }\n if (hasSocialsFromQuery) {\n const newSocials: { label: string; value: string }[] = [];\n if (linkedinUrl) newSocials.push({ label: 'linkedin', value: linkedinUrl });\n if (githubUrl) newSocials.push({ label: 'github', value: githubUrl });\n if (twitterUrl) newSocials.push({ label: 'twitter', value: twitterUrl });\n if (websites?.length) {\n for (const w of websites) newSocials.push({ label: detectSocialLabel(w) === 'custom' ? 'custom' : detectSocialLabel(w), value: w });\n }\n await mergeUserSocials(newSocials);\n }\n logger.verbose(\"Persisted user-info fields to user record\", { userId: context.userId });\n\n const isOnboarding = !(context.user.onboarding?.completedAt);\n if (isOnboarding) {\n const existingProfile = await userDb.getProfile();\n if (existingProfile) {\n return success({\n alreadyExists: true,\n message: \"Profile already exists. If the user confirmed it, call complete_onboarding() to finish setup. If they want changes, use create_user_profile(bioOrDescription=\\\"...\\\", confirm=true).\",\n profile: {\n name: existingProfile.identity.name,\n bio: existingProfile.identity.bio,\n location: existingProfile.identity.location,\n skills: existingProfile.attributes.skills,\n interests: existingProfile.attributes.interests,\n },\n });\n }\n\n // Preview mode: enrich and persist enrichment results, but don't generate full profile\n if (!query.confirm) {\n try {\n const user = await userDb.getUser();\n const enrichment = user ? await enrichFromUserRecord(user) : null;\n\n if (isMeaningfulEnrichment(enrichment)) {\n // Persist enrichment data to user record so confirm path has it\n const updatePayload: {\n name?: string;\n intro?: string;\n location?: string;\n } = {};\n if (enrichment.identity.name?.trim()) {\n updatePayload.name = enrichment.identity.name.trim();\n }\n if (enrichment.identity.bio?.trim()) updatePayload.intro = enrichment.identity.bio.trim();\n if (enrichment.identity.location?.trim()) updatePayload.location = enrichment.identity.location.trim();\n if (Object.keys(updatePayload).length > 0) await userDb.updateUser(updatePayload);\n const enrichedSocials: { label: string; value: string }[] = [];\n if (enrichment.socials.twitter) enrichedSocials.push({ label: 'twitter', value: enrichment.socials.twitter });\n if (enrichment.socials.linkedin) enrichedSocials.push({ label: 'linkedin', value: enrichment.socials.linkedin });\n if (enrichment.socials.github) enrichedSocials.push({ label: 'github', value: enrichment.socials.github });\n if (enrichment.socials.telegram) enrichedSocials.push({ label: 'telegram', value: enrichment.socials.telegram });\n if (enrichment.socials.websites?.length) {\n for (const w of enrichment.socials.websites) enrichedSocials.push({ label: 'custom', value: w });\n }\n if (enrichedSocials.length > 0) {\n await mergeUserSocials(enrichedSocials);\n }\n\n return success({\n preview: true,\n message: \"Profile preview generated. Call create_user_profile(confirm=true) to save.\",\n profile: {\n name: enrichment.identity.name,\n bio: enrichment.identity.bio,\n location: enrichment.identity.location,\n skills: enrichment.attributes.skills,\n interests: enrichment.attributes.interests,\n },\n // Always present when isMeaningfulEnrichment passes — may be {} if the\n // enrichment found no social handles. LLM should ask the user to provide\n // links when empty (see buildOnboarding step 3 in chat.prompt.ts).\n detectedSocials: enrichment.socials,\n });\n }\n } catch (err) {\n logger.warn(\"Enrichment preview failed\", {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n\n return needsClarification({\n missingFields: ['bio_or_social_urls'],\n message: \"I couldn't find enough public info. Could you share a short description of yourself, or a LinkedIn/GitHub/X profile link?\",\n });\n }\n\n // Confirm mode: invoke graph in generate mode (enrichment data already persisted during preview)\n // Do NOT re-run enrichFromUserRecord — the graph's autoGenerateNode handles enrichment\n // from the (now well-populated) user record, avoiding non-deterministic drift.\n try {\n const _confirmGraphStart = Date.now();\n const _confirmTraceEmitter = requestContext.getStore()?.traceEmitter;\n _confirmTraceEmitter?.({ type: \"graph_start\", name: \"profile\" });\n const result = await invokeWithAbortSignal(graphs.profile, {\n userId: context.userId,\n operationMode: 'generate' as const,\n });\n const _confirmGraphMs = Date.now() - _confirmGraphStart;\n _confirmTraceEmitter?.({ type: \"graph_end\", name: \"profile\", durationMs: _confirmGraphMs });\n\n if (result.error) return error(result.error);\n if (result.profile) {\n return success({\n created: true,\n message: \"Profile saved.\",\n profile: {\n name: result.profile.identity.name,\n bio: result.profile.identity.bio,\n location: result.profile.identity.location,\n skills: result.profile.attributes.skills,\n interests: result.profile.attributes.interests,\n },\n _graphTimings: [{ name: 'profile', durationMs: _confirmGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n } catch (err) {\n logger.warn(\"Profile generation on confirm failed, falling back to full graph\", {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n // Fallback: graph invocation failed on confirm, fall through to full graph invocation\n }\n\n const hasBioOrDescription = !!query.bioOrDescription?.trim();\n\n if (hasBioOrDescription) {\n // Create/update profile from user's explicit text only; do not persist to user record\n // Include name and location in the input if provided so the ProfileGenerator can use them\n const inputParts: string[] = [];\n if (name) inputParts.push(`Name: ${name}`);\n if (location) inputParts.push(`Location: ${location}`);\n inputParts.push(query.bioOrDescription!.trim());\n const profileInput = inputParts.join('\\n');\n \n const _bioProfileGraphStart = Date.now();\n const _bioProfileTraceEmitter = requestContext.getStore()?.traceEmitter;\n _bioProfileTraceEmitter?.({ type: \"graph_start\", name: \"profile\" });\n const result = await invokeWithAbortSignal(graphs.profile, {\n userId: context.userId,\n operationMode: 'write' as const,\n input: profileInput,\n forceUpdate: true,\n });\n const _bioProfileGraphMs = Date.now() - _bioProfileGraphStart;\n _bioProfileTraceEmitter?.({ type: \"graph_end\", name: \"profile\", durationMs: _bioProfileGraphMs });\n if (result.error) {\n return error(result.error);\n }\n if (result.profile) {\n return success({\n created: true,\n message: \"Profile created/updated with the information you provided.\",\n profile: {\n name: result.profile.identity.name,\n bio: result.profile.identity.bio,\n location: result.profile.identity.location,\n skills: result.profile.attributes.skills,\n interests: result.profile.attributes.interests,\n },\n _graphTimings: [{ name: 'profile', durationMs: _bioProfileGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n return success({\n created: true,\n message: \"Profile created/updated with the information you provided.\",\n _graphTimings: [{ name: 'profile', durationMs: _bioProfileGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n\n // Invoke profile graph in generate mode (uses enrichUserProfile Chat API)\n const _generateProfileGraphStart = Date.now();\n const _generateProfileTraceEmitter = requestContext.getStore()?.traceEmitter;\n _generateProfileTraceEmitter?.({ type: \"graph_start\", name: \"profile\" });\n const result = await invokeWithAbortSignal(graphs.profile, {\n userId: context.userId,\n operationMode: 'generate' as const,\n forceUpdate: true,\n });\n const _generateProfileGraphMs = Date.now() - _generateProfileGraphStart;\n _generateProfileTraceEmitter?.({ type: \"graph_end\", name: \"profile\", durationMs: _generateProfileGraphMs });\n\n // If user info is insufficient, ask conversationally\n if (result.needsUserInfo) {\n return needsClarification({\n missingFields: result.missingUserInfo || ['social_urls', 'full_name'],\n message: \"I need a bit more information to create your profile. Could you share your full name and any social links (LinkedIn, GitHub, or X/Twitter)?\",\n });\n }\n\n if (result.error) {\n return error(result.error);\n }\n\n if (result.profile) {\n return success({\n created: true,\n message: \"Profile generated from your account data.\",\n profile: {\n name: result.profile.identity.name,\n bio: result.profile.identity.bio,\n location: result.profile.identity.location,\n skills: result.profile.attributes.skills,\n interests: result.profile.attributes.interests,\n },\n _graphTimings: [{ name: 'profile', durationMs: _generateProfileGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n\n return error(\"Failed to create profile. Please try again.\");\n },\n });\n\n const updateUserProfile = defineTool({\n name: \"update_user_profile\",\n description:\n \"Updates the authenticated user's existing profile using a verb-style instruction interface.\\n\\n\" +\n \"**How to use it:**\\n\" +\n \"- `action`: a natural-language instruction describing what to change (e.g. \\\"add interests\\\", \\\"update bio\\\", \\\"remove skill\\\", \\\"set location\\\").\\n\" +\n \"- `details`: the content to apply (e.g. \\\"procedural generation, roguelikes, narrative games\\\").\\n\" +\n \"- `socials`: optional social handles to merge into the user's reachable profile (e.g. `{ telegram: \\\"@alice\\\" }`).\\n\\n\" +\n \"**Examples:**\\n\" +\n \"- `action=\\\"add interests\\\"`, `details=\\\"procedural generation, roguelikes\\\"`\\n\" +\n \"- `action=\\\"update bio\\\"`, `details=\\\"Product designer focused on desktop CRPG interfaces\\\"`\\n\" +\n \"- `action=\\\"set location\\\"`, `details=\\\"Berlin\\\"`\\n\" +\n \"- `socials={ telegram: \\\"@alice\\\" }` to silently add a reachable chat handle without regenerating the profile.\\n\\n\" +\n \"**When to use:** When the user wants to make specific changes without regenerating the whole profile. For full profile regeneration from social URLs, use create_user_profile instead.\\n\\n\" +\n \"**Important:** If the user provides a URL to update from, call scrape_url first, then pass the scraped content in `details`.\\n\\n\" +\n \"**MCP behavior:** For MCP clients, text/profile graph updates are accepted immediately and completed in the background to avoid transport timeouts. Social-only updates still complete synchronously.\\n\\n\" +\n \"**Returns:** Confirmation that the profile was updated or accepted for background update.\",\n querySchema: z.object({\n profileId: z.string().optional().describe(\"Profile UUID from read_user_profiles. Omit to update the current user's own profile (most common usage).\"),\n action: z.string().optional().describe(\"Natural language description of ALL changes to make in a single call. Examples: 'update bio to focus on AI research', 'add Python and Rust to skills', 'change location to Berlin and add machine learning to interests'. Optional when only updating socials.\"),\n details: z.string().optional().describe(\"Additional context or content to incorporate. Use this to pass scraped URL content (from scrape_url) or longer text the user provided.\"),\n socials: z.record(z.string()).optional().describe(\"Social handles or URLs to merge into the user profile, keyed by label. Example: { telegram: '@alice', github: 'alice' }. Existing socials with other labels are preserved.\"),\n }),\n handler: async ({ context, query }) => {\n const socialUpdates = socialsRecordToRows(query.socials);\n const inputForProfile = [query.action, query.details].filter(Boolean).join(\"\\n\");\n if (!inputForProfile.trim()) {\n if (socialUpdates.length > 0) {\n await mergeUserSocials(socialUpdates);\n return success({ message: \"Profile socials updated.\" });\n }\n return error(\"Please specify what to update (e.g. action: 'update bio to X') or provide socials.\");\n }\n\n const profileRunId = await enqueueProfileRun(context, \"update_user_profile\", query);\n if (profileRunId) {\n return success({\n status: \"queued\" as const,\n profileRunId,\n message: `Profile update started. Call get_profile_run with profileRunId=\"${profileRunId}\" until it succeeds, fails, or is cancelled.`,\n });\n }\n\n // Use profileGraph query mode to validate profile existence and get id\n const _updateQueryProfileGraphStart = Date.now();\n const _updateQueryProfileTraceEmitter = requestContext.getStore()?.traceEmitter;\n _updateQueryProfileTraceEmitter?.({ type: \"graph_start\", name: \"profile\" });\n const queryResult = await invokeWithAbortSignal(graphs.profile, { userId: context.userId, operationMode: 'query' as const });\n const _updateQueryProfileGraphMs = Date.now() - _updateQueryProfileGraphStart;\n _updateQueryProfileTraceEmitter?.({ type: \"graph_end\", name: \"profile\", durationMs: _updateQueryProfileGraphMs });\n if (!queryResult.readResult?.hasProfile && !queryResult.profile) {\n return error(\"You don't have a profile yet. Use create_user_profile first.\");\n }\n const existingProfileId = queryResult.readResult?.profile?.id;\n const providedProfileId = query.profileId?.trim();\n if (providedProfileId && existingProfileId && providedProfileId !== existingProfileId) {\n return error(\"Invalid profileId. Use the profile id from read_user_profiles.\");\n }\n\n if (socialUpdates.length > 0) {\n await mergeUserSocials(socialUpdates);\n }\n\n if (context.isMcp) {\n const _backgroundWriteProfileGraphStart = Date.now();\n const _backgroundWriteProfileTraceEmitter = requestContext.getStore()?.traceEmitter;\n _backgroundWriteProfileTraceEmitter?.({ type: \"graph_start\", name: \"profile\" });\n graphs.profile.invoke({\n userId: context.userId,\n operationMode: \"write\",\n input: inputForProfile,\n forceUpdate: true,\n }).then((writeResult) => {\n if (writeResult.error) {\n logger.error(\"Background profile update failed\", {\n userId: context.userId,\n error: writeResult.error,\n });\n reportToolError?.(new Error(writeResult.error), {\n subsystem: \"profile\",\n operation: \"profile.update_background\",\n toolName: \"update_user_profile\",\n userId: context.userId,\n tags: { toolName: \"update_user_profile\", execution: \"background\" },\n context: { profileId: existingProfileId ?? providedProfileId },\n });\n }\n }).catch((err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n logger.error(\"Background profile update failed\", {\n userId: context.userId,\n error: message,\n });\n reportToolError?.(err, {\n subsystem: \"profile\",\n operation: \"profile.update_background\",\n toolName: \"update_user_profile\",\n userId: context.userId,\n tags: { toolName: \"update_user_profile\", execution: \"background\" },\n context: { profileId: existingProfileId ?? providedProfileId },\n });\n }).finally(() => {\n const _backgroundWriteProfileGraphMs = Date.now() - _backgroundWriteProfileGraphStart;\n _backgroundWriteProfileTraceEmitter?.({ type: \"graph_end\", name: \"profile\", durationMs: _backgroundWriteProfileGraphMs });\n });\n\n return success({\n accepted: true,\n message: \"Profile update accepted. The structured profile will refresh in the background.\",\n _graphTimings: [\n { name: 'profile', durationMs: _updateQueryProfileGraphMs, agents: queryResult.agentTimings ?? [] },\n ],\n });\n }\n\n // Execute update directly\n const _updateWriteProfileGraphStart = Date.now();\n const _updateWriteProfileTraceEmitter = requestContext.getStore()?.traceEmitter;\n _updateWriteProfileTraceEmitter?.({ type: \"graph_start\", name: \"profile\" });\n const _writeResult = await invokeWithAbortSignal(graphs.profile, {\n userId: context.userId,\n operationMode: \"write\",\n input: inputForProfile,\n forceUpdate: true,\n });\n const _updateWriteProfileGraphMs = Date.now() - _updateWriteProfileGraphStart;\n _updateWriteProfileTraceEmitter?.({ type: \"graph_end\", name: \"profile\", durationMs: _updateWriteProfileGraphMs });\n if (_writeResult.error) {\n return error(_writeResult.error);\n }\n return success({\n message: \"Profile updated.\",\n _graphTimings: [\n { name: 'profile', durationMs: _updateQueryProfileGraphMs, agents: queryResult.agentTimings ?? [] },\n { name: 'profile', durationMs: _updateWriteProfileGraphMs, agents: _writeResult.agentTimings ?? [] },\n ],\n });\n },\n });\n\n const getProfileRun = defineTool({\n name: \"get_profile_run\",\n description:\n \"Checks the status of an async profile preview/update run started by preview_user_profile or update_user_profile in MCP contexts. \" +\n \"Poll this tool with the profileRunId until status is succeeded, failed, or cancelled. When succeeded, present the result to the user.\",\n querySchema: z.object({\n profileRunId: z.string().describe(\"Profile run ID returned by preview_user_profile or update_user_profile.\"),\n }),\n handler: async ({ context, query }) => {\n if (!deps.profileRuns) {\n return error(\"Profile run polling is not available in this environment.\");\n }\n const run = await deps.profileRuns.get(query.profileRunId, context.userId);\n if (!run) return error(\"Profile run not found.\");\n return success({\n profileRunId: run.id,\n operation: run.operation,\n status: run.status,\n progress: run.progress ?? null,\n result: run.result ?? null,\n error: run.error ?? null,\n createdAt: run.createdAt.toISOString?.() ?? null,\n startedAt: run.startedAt?.toISOString?.() ?? null,\n completedAt: run.completedAt?.toISOString?.() ?? null,\n });\n },\n });\n\n const cancelProfileRun = defineTool({\n name: \"cancel_profile_run\",\n description:\n \"Requests cancellation for an async profile run. If the queued job has not started, it is removed and marked cancelled. \" +\n \"If already running, the worker observes the cancellation request and aborts where supported.\",\n querySchema: z.object({\n profileRunId: z.string().describe(\"Profile run ID returned by preview_user_profile or update_user_profile.\"),\n }),\n handler: async ({ context, query }) => {\n if (!deps.profileRuns || !deps.profileRunQueue) {\n return error(\"Profile run cancellation is not available in this environment.\");\n }\n const existing = await deps.profileRuns.get(query.profileRunId, context.userId);\n if (!existing) return error(\"Profile run not found.\");\n if (![\"queued\", \"running\"].includes(existing.status)) {\n return success({\n profileRunId: existing.id,\n status: existing.status,\n message: `Profile run is already ${existing.status}.`,\n });\n }\n const run = await deps.profileRuns.requestCancel(query.profileRunId, context.userId);\n if (!run) return error(\"Profile run not found or cannot be cancelled.\");\n const removed = await deps.profileRunQueue.cancel(run.id);\n if (removed) {\n await deps.profileRuns.markCancelled(run.id, \"cancelled before worker start\");\n }\n const updated = await deps.profileRuns.get(run.id, context.userId);\n return success({\n profileRunId: run.id,\n status: updated?.status ?? run.status,\n cancelled: true,\n message: removed\n ? \"Profile run cancelled before it started.\"\n : \"Cancellation requested while the profile run is running or queued.\",\n });\n },\n });\n\n const completeOnboarding = defineTool({\n name: \"complete_onboarding\",\n description:\n \"Marks the user's onboarding as complete, unlocking full platform access. This is the final step in the new-user setup flow.\\n\\n\" +\n \"**Prerequisites:** The user must have a profile (created via create_user_profile) AND must have explicitly confirmed it \" +\n \"(said 'yes', 'looks good', 'that's right', or similar). Do NOT call this until the user confirms.\\n\\n\" +\n \"**What happens:** Sets completedAt timestamp on the user's onboarding record. May also auto-join the user to preconfigured indexes \" +\n \"(communities) based on server configuration.\\n\\n\" +\n \"**Workflow:** create_user_profile() -> user confirms preview -> create_user_profile(confirm=true) -> user confirms saved profile -> complete_onboarding()\\n\\n\" +\n \"**Returns:** Confirmation that onboarding is complete. No parameters needed.\",\n querySchema: z.object({}),\n handler: async ({ context }) => {\n const currentOnboarding = context.user.onboarding ?? {};\n if (currentOnboarding.completedAt) {\n logger.verbose(\"Onboarding already completed, skipping\", { userId: context.userId });\n return success({ message: \"Onboarding already completed.\" });\n }\n await userDb.updateUser({\n onboarding: {\n ...currentOnboarding,\n completedAt: new Date().toISOString(),\n },\n });\n\n if (grantDefaultSystemPermissions) {\n try {\n await grantDefaultSystemPermissions(context.userId);\n } catch (err) {\n logger.warn('Default system agent permission grant failed (non-fatal)', {\n userId: context.userId,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n const autoJoinIds = (process.env.AUTO_JOIN_INDEX_IDS ?? '')\n .split(',')\n .map(id => id.trim())\n .filter(Boolean);\n for (const networkId of autoJoinIds) {\n try {\n await database.addMemberToNetwork(networkId, context.userId, 'member');\n } catch (err) {\n logger.warn('Auto-join network failed (non-fatal)', { networkId, userId: context.userId, error: err instanceof Error ? err.message : String(err) });\n }\n }\n\n logger.info(\"Onboarding completed\", { userId: context.userId, autoJoinedNetworks: autoJoinIds.length });\n return success({ message: \"Onboarding complete.\" });\n },\n });\n\n return [readUserProfiles, recordOnboardingPrivacyConsent, previewUserProfile, confirmUserProfile, createUserProfile, updateUserProfile, getProfileRun, cancelProfileRun, completeOnboarding] as const;\n}\n"]}
1
+ {"version":3,"file":"profile.tools.js","sourceRoot":"/","sources":["profile/profile.tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAG5E,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,kBAAkB,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AACjG,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAI5E,OAAO,EAAE,0BAA0B,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AAChG,OAAO,EAAE,uBAAuB,EAAE,MAAM,oCAAoC,CAAC;AAC7E,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAExE,MAAM,MAAM,GAAG,cAAc,CAAC,mBAAmB,CAAC,CAAC;AAEnD,SAAS,sBAAsB,CAAC,UAAmC;IACjE,OAAO,CAAC,CAAC,UAAU;QACjB,UAAU,CAAC,cAAc;QACzB,CACE,UAAU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gBAClC,MAAM,CAAC,OAAO,CAAC,wCAAwC,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;gBACrF,OAAO,OAAO,CAAC,EAAE,OAAO,EAAE,+BAA+B,EAAE,CAAC,CAAC;YAC/D,CAAC;YACD,MAAM,MAAM,CAAC,UAAU,CAAC;gBACtB,UAAU,EAAE;oBACV,GAAG,iBAAiB;oBACpB,WAAW,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;iBACtC;aACF,CAAC,CAAC;YAEH,IAAI,6BAA6B,EAAE,CAAC;gBAClC,IAAI,CAAC;oBACH,MAAM,6BAA6B,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;gBACtD,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,MAAM,CAAC,IAAI,CAAC,0DAA0D,EAAE;wBACtE,MAAM,EAAE,OAAO,CAAC,MAAM;wBACtB,KAAK,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC;qBACxD,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;YAED,MAAM,CAAC,IAAI,CAAC,sBAAsB,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;YAChE,OAAO,OAAO,CAAC,EAAE,OAAO,EAAE,sBAAsB,EAAE,CAAC,CAAC;QACtD,CAAC;KACF,CAAC,CAAC;IAEH,OAAO,CAAC,gBAAgB,EAAE,8BAA8B,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,aAAa,EAAE,gBAAgB,EAAE,kBAAkB,CAAU,CAAC;AACxM,CAAC","sourcesContent":["import { z } from \"zod\";\n\nimport { requestContext } from \"../shared/observability/request-context.js\";\n\nimport type { DefineTool, ResolvedToolContext, ToolDeps } from \"../shared/agent/tool.helpers.js\";\nimport { success, error, needsClarification, UUID_REGEX } from \"../shared/agent/tool.helpers.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport type { EnrichmentResult } from \"../shared/interfaces/enrichment.interface.js\";\nimport type { OnboardingPrivacyState, OnboardingProfileSeed, OnboardingState, PrivacyConsentSource, UserRecord } from \"../shared/interfaces/database.interface.js\";\nimport type { ProfileRunInput, ProfileRunOperation } from \"../shared/interfaces/profile-run.interface.js\";\nimport { socialsToEnrichmentRequest, detectSocialLabel } from \"../shared/utils/social-label.js\";\nimport { normalizeTelegramHandle } from \"../shared/utils/telegram-handle.js\";\nimport { ProfileGenerator } from \"./profile.generator.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\n\nconst logger = protocolLogger(\"ChatTools:Profile\");\n\nfunction isMeaningfulEnrichment(enrichment: EnrichmentResult | null): enrichment is EnrichmentResult {\n return !!enrichment &&\n enrichment.confidentMatch &&\n (\n enrichment.identity.bio.trim().length > 0 ||\n enrichment.narrative.context.trim().length > 0 ||\n enrichment.attributes.skills.length > 0 ||\n enrichment.attributes.interests.length > 0\n );\n}\n\nconst approvedProfileDraftSchema = z.object({\n identity: z.object({ name: z.string(), bio: z.string(), location: z.string() }),\n narrative: z.object({ context: z.string() }),\n attributes: z.object({ interests: z.array(z.string()), skills: z.array(z.string()) }),\n});\n\ntype ApprovedProfileDraft = z.infer<typeof approvedProfileDraftSchema>;\n\nexport function createProfileTools(defineTool: DefineTool, deps: ToolDeps) {\n const { userDb, systemDb, graphs, enricher, grantDefaultSystemPermissions, reportToolError } = deps;\n\n function trimToUndefined(value: string | null | undefined): string | undefined {\n const trimmed = value?.trim();\n return trimmed && trimmed.length > 0 ? trimmed : undefined;\n }\n\n function isPlaceholderName(value: string): boolean {\n const normalized = value.trim().toLowerCase();\n return normalized === 'unknown' || normalized === 'user';\n }\n\n function resolveAuthenticatedLookupIdentity(user: UserRecord, context: { userName?: string; userEmail?: string }) {\n const userName = trimToUndefined(user.name);\n const contextName = trimToUndefined(context.userName);\n const name = [userName, contextName].find((candidate) => candidate !== undefined && !isPlaceholderName(candidate));\n const email = trimToUndefined(user.email) ?? trimToUndefined(context.userEmail);\n return { name, email };\n }\n\n async function enrichFromUserRecord(user: { name?: string | null; email?: string | null; socials: Array<{ id: string; userId: string; label: string; value: string }> }) {\n const enrichmentSocials = socialsToEnrichmentRequest(user.socials);\n return enricher.enrichUserProfile({\n name: trimToUndefined(user.name),\n email: trimToUndefined(user.email),\n linkedin: enrichmentSocials.linkedin || undefined,\n twitter: enrichmentSocials.twitter || undefined,\n github: enrichmentSocials.github || undefined,\n telegram: enrichmentSocials.telegram || undefined,\n websites: enrichmentSocials.websites?.length ? enrichmentSocials.websites : undefined,\n });\n }\n\n function hasPublicProfileLookupConsent(onboarding: OnboardingState | null | undefined): boolean {\n return onboarding?.privacy?.publicProfileLookup?.granted === true;\n }\n\n function hasEdgeosImportConsent(onboarding: OnboardingState | null | undefined): boolean {\n return onboarding?.privacy?.edgeosImport?.granted === true;\n }\n\n function normalizeConsentSource(source: unknown): PrivacyConsentSource {\n return source === 'agentvillage_onboarding' || source === 'hermes_setup' || source === 'web_onboarding' || source === 'api'\n ? source\n : 'api';\n }\n\n function consentDecision(granted: boolean, source: PrivacyConsentSource) {\n return { granted, decidedAt: new Date().toISOString(), source };\n }\n\n function selectProfileSeed(onboarding: OnboardingState | null | undefined, networkId?: string): OnboardingProfileSeed | undefined {\n const seeds = onboarding?.profileSeeds ?? [];\n if (seeds.length === 0) return undefined;\n const scoped = networkId ? seeds.filter((seed) => seed.networkId === networkId) : seeds;\n return scoped[scoped.length - 1] ?? seeds[seeds.length - 1];\n }\n\n function normalizeSocialUpdate(label: string, value: string): { label: string; value: string } | null {\n const normalizedLabel = label.trim().toLowerCase();\n if (!normalizedLabel) return null;\n const trimmedValue = value.trim();\n if (!trimmedValue) return null;\n if (normalizedLabel === 'telegram') {\n const handle = normalizeTelegramHandle(trimmedValue);\n return handle ? { label: normalizedLabel, value: handle } : null;\n }\n return { label: normalizedLabel, value: trimmedValue };\n }\n\n async function mergeUserSocials(incoming: { label: string; value: string }[]): Promise<void> {\n const normalizedIncoming = incoming\n .map((social) => normalizeSocialUpdate(social.label, social.value))\n .filter((social): social is { label: string; value: string } => social !== null);\n if (normalizedIncoming.length === 0) return;\n\n const existingSocials = await userDb.getUserSocials();\n const incomingLabels = new Set(normalizedIncoming.map((social) => social.label));\n const kept = existingSocials\n .filter((social) => !incomingLabels.has(social.label) || social.label === 'custom')\n .map((social) => ({ label: social.label, value: social.value }));\n const merged = incomingLabels.has('custom')\n ? [...kept.filter((social) => social.label !== 'custom'), ...normalizedIncoming]\n : [...kept, ...normalizedIncoming];\n await userDb.setUserSocials(merged);\n }\n\n function socialsRecordToRows(socials: Record<string, string> | undefined): { label: string; value: string }[] {\n if (!socials) return [];\n return Object.entries(socials).map(([label, value]) => ({ label, value }));\n }\n\n async function enqueueProfileRun(\n context: ResolvedToolContext,\n operation: ProfileRunOperation,\n input: ProfileRunInput,\n ): Promise<string | null> {\n if (!context.isMcp || !deps.profileRuns || !deps.profileRunQueue) return null;\n const run = await deps.profileRuns.create({\n userId: context.userId,\n agentId: context.agentId ?? null,\n operation,\n input,\n context: {\n userId: context.userId,\n userName: context.userName,\n userEmail: context.userEmail,\n ...(context.networkId ? { networkId: context.networkId } : {}),\n ...(context.indexName ? { indexName: context.indexName } : {}),\n indexScope: context.indexScope,\n ...(context.sessionId ? { sessionId: context.sessionId } : {}),\n ...(context.agentId ? { agentId: context.agentId } : {}),\n ...(context.clientSurface ? { clientSurface: context.clientSurface } : {}),\n },\n });\n try {\n await deps.profileRunQueue.enqueue(run.id);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n await deps.profileRuns.markFailed(run.id, message);\n if (err instanceof Error) throw err;\n const wrapped = new Error(`Failed to enqueue profile run: ${message}`) as Error & { cause?: unknown };\n wrapped.cause = err;\n throw wrapped;\n }\n return run.id;\n }\n\n async function persistApprovedProfileContext(profile: { identity: { name: string; bio: string; location: string } }, user: UserRecord | null, networkId?: string): Promise<void> {\n await userDb.updateUser({\n name: profile.identity.name,\n intro: profile.identity.bio,\n location: profile.identity.location,\n });\n\n const onboarding = user?.onboarding ?? undefined;\n if (!hasEdgeosImportConsent(onboarding)) return;\n const seed = selectProfileSeed(onboarding, networkId);\n if (!seed?.socials?.length) return;\n\n await mergeUserSocials(seed.socials);\n }\n\n function buildProfileInput(parts: {\n name?: string;\n location?: string;\n bioOrDescription?: string;\n edgeosProfileText?: string;\n enrichment?: EnrichmentResult | null;\n socials?: Array<{ label: string; value: string }>;\n }): string {\n const lines: string[] = [];\n if (parts.name) lines.push(`Name: ${parts.name}`);\n if (parts.location) lines.push(`Location: ${parts.location}`);\n if (parts.bioOrDescription) lines.push(parts.bioOrDescription);\n if (parts.edgeosProfileText) lines.push(`Event-provided profile information:\\n${parts.edgeosProfileText}`);\n if (parts.socials?.length) {\n lines.push(`User-provided public links:\\n${parts.socials.map((s) => `${s.label}: ${s.value}`).join('\\n')}`);\n }\n const enrichment = parts.enrichment ?? null;\n if (isMeaningfulEnrichment(enrichment)) {\n lines.push([\n enrichment.identity.name ? `Enriched name: ${enrichment.identity.name}` : '',\n enrichment.identity.location ? `Enriched location: ${enrichment.identity.location}` : '',\n enrichment.identity.bio ? `Enriched bio: ${enrichment.identity.bio}` : '',\n enrichment.narrative.context ? `Enriched context: ${enrichment.narrative.context}` : '',\n enrichment.attributes.skills.length ? `Skills: ${enrichment.attributes.skills.join(', ')}` : '',\n enrichment.attributes.interests.length ? `Interests: ${enrichment.attributes.interests.join(', ')}` : '',\n ].filter(Boolean).join('\\n'));\n }\n return lines.filter((line) => line.trim().length > 0).join('\\n\\n');\n }\n\n function toProfileSummary(profile: { identity: { name: string; bio: string; location: string }; attributes: { skills: string[]; interests: string[] } }) {\n return {\n name: profile.identity.name,\n bio: profile.identity.bio,\n location: profile.identity.location,\n skills: profile.attributes.skills,\n interests: profile.attributes.interests,\n };\n }\n\n function buildApprovedDraftProfileInput(draft: ApprovedProfileDraft): string {\n return [\n draft.identity.name ? `My name is ${draft.identity.name}.` : '',\n draft.identity.location ? `I am based in ${draft.identity.location}.` : '',\n draft.identity.bio || '',\n draft.narrative.context || '',\n draft.attributes.skills.length ? `My skills include ${draft.attributes.skills.join(', ')}.` : '',\n draft.attributes.interests.length ? `My interests include ${draft.attributes.interests.join(', ')}.` : '',\n ].filter((part) => part.trim().length > 0).join('\\n');\n }\n\n async function decomposeApprovedDraftProfile(\n profile: ApprovedProfileDraft & { userId: string },\n ): Promise<void> {\n const input = buildApprovedDraftProfileInput(profile);\n if (!input.trim()) return;\n\n const traceEmitter = requestContext.getStore()?.traceEmitter;\n const graphStart = Date.now();\n traceEmitter?.({ type: \"graph_start\", name: \"profile\" });\n try {\n const graphInput = {\n userId: profile.userId,\n operationMode: 'write' as const,\n input,\n forceUpdate: true,\n };\n // Always invoked as a background fire-and-forget task (see confirm_user_profile\n // call sites), so decomposition must outlive the originating request — invoke\n // the graph directly and never bind the request abort signal, which would\n // cancel it as soon as the web request completes.\n const result = await graphs.profile.invoke(graphInput);\n\n if (result.error) {\n const err = new Error(result.error);\n logger.error('Approved draft premise decomposition failed', {\n userId: profile.userId,\n error: result.error,\n });\n reportToolError?.(err, {\n subsystem: 'profile',\n operation: 'profile.confirm_draft_decompose',\n toolName: 'confirm_user_profile',\n userId: profile.userId,\n tags: { toolName: 'confirm_user_profile', execution: 'background' },\n });\n return;\n }\n\n // The write graph's decompose → aggregate → generate → save_profile\n // pipeline persists the aggregate profile. The approved draft was already\n // saved before decomposition started, so the DB is consistent regardless\n // of graph outcome. Do not re-save here — the graph's save_profile is\n // authoritative, and a concurrent user-driven profile update could race.\n } catch (err) {\n logger.error('Approved draft premise decomposition failed', {\n userId: profile.userId,\n error: err instanceof Error ? err.message : String(err),\n });\n reportToolError?.(err, {\n subsystem: 'profile',\n operation: 'profile.confirm_draft_decompose',\n toolName: 'confirm_user_profile',\n userId: profile.userId,\n tags: { toolName: 'confirm_user_profile', execution: 'background' },\n });\n } finally {\n traceEmitter?.({ type: \"graph_end\", name: \"profile\", durationMs: Date.now() - graphStart });\n }\n }\n\n const readUserProfiles = defineTool({\n name: \"read_user_profiles\",\n description:\n \"Retrieves user profiles containing identity info (name, bio, location), skills, and interests. Profiles are used for semantic matching \" +\n \"in opportunity discovery — richer profiles produce better matches.\\n\\n\" +\n \"**Usage modes:**\\n\" +\n \"- With `query` (name search): finds members by name (case-insensitive substring) across the user's indexes. \" +\n \"This is the primary way to look up a person by name. Add `networkId` to restrict search to one index.\\n\" +\n \"- With `userId`: returns that specific user's full profile (name, bio, skills, interests, location).\\n\" +\n \"- With `networkId` alone: returns profiles of ALL members in that index.\\n\" +\n \"- No parameters: returns the current user's own profile.\\n\\n\" +\n \"**When to use:** Before creating introductions (need profiles of both parties), when the user asks about a person, \" +\n \"or to check if a profile exists before suggesting create_user_profile. \" +\n \"MCP agents should call this with no arguments at session start to fetch the caller's profile AND onboarding status.\\n\\n\" +\n \"**Returns:** Profile objects with name, bio, location, skills[], interests[]. Use userId from results with other tools like read_intents(userId, networkId). \" +\n \"When called for the current user (no args, or userId=self), the response also includes `onboardingComplete: boolean` and `onboardingCompletedAt?: string` — \" +\n \"use these as the source of truth for whether the user still needs onboarding (do not rely on local file state).\",\n querySchema: z.object({\n userId: z.string().optional().describe(\"Fetch a specific user's profile by their user ID. Get user IDs from read_network_memberships or list_contacts.\"),\n networkId: z.string().optional().describe(\"Index UUID — fetch profiles of all members in this index, or narrow a name search to this index. Get from read_networks.\"),\n query: z.string().optional().describe(\"Name to search for (case-insensitive substring match). Searches across all the user's indexes unless networkId is also provided. Use this when the user asks to 'find' or 'look up' someone.\"),\n }),\n handler: async ({ context, query }) => {\n const effectiveIndexId = query.networkId?.trim() || undefined;\n const targetUserId = query.userId?.trim() || undefined;\n const nameQuery = query.query?.trim() || undefined;\n\n if (effectiveIndexId && !UUID_REGEX.test(effectiveIndexId)) {\n return error(\"Invalid network ID format. Use the exact UUID from read_networks.\");\n }\n\n // --- Name search mode: query provided → find members by name ---\n if (nameQuery) {\n const pattern = nameQuery.toLowerCase();\n const MAX_RESULTS = 20;\n // When chat is index-scoped, restrict name search to that index\n const searchIndexId = effectiveIndexId || context.networkId || undefined;\n\n let candidates: Array<{ userId: string; name: string; avatar: string | null }>;\n\n if (searchIndexId) {\n // Scoped to a specific index\n if (context.networkId && searchIndexId !== context.networkId) {\n return error(\n context.indexName\n ? `This chat is scoped to ${context.indexName}. You can only look up people in this community.`\n : `This chat is scoped to this index. You can only look up people in this community.`\n );\n }\n const callerIsMember = await systemDb.isNetworkMember(searchIndexId, context.userId);\n if (!callerIsMember) {\n return error(\"You can only look up people in indexes you are a member of.\");\n }\n const members = await systemDb.getNetworkMembers(searchIndexId);\n candidates = members.map((m) => ({ userId: m.userId, name: m.name, avatar: m.avatar ?? null }));\n } else {\n // Search across all user's indexes\n candidates = await systemDb.getMembersFromScope();\n }\n\n logger.verbose(\"Name search candidates\", {\n query: nameQuery,\n pattern,\n candidateCount: candidates.length,\n userId: context.userId,\n });\n\n // Filter by name (case-insensitive substring), exclude self\n const matched = candidates\n .filter((c) => c.userId !== context.userId && c.name.toLowerCase().includes(pattern))\n .slice(0, MAX_RESULTS);\n\n if (matched.length === 0) {\n return success({ query: nameQuery, matchCount: 0, profiles: [], message: \"No members found matching that name.\" });\n }\n\n // Fetch full profiles for matches\n const profiles = await Promise.all(\n matched.map(async (m) => {\n try {\n const profile = await systemDb.getProfile(m.userId);\n return {\n userId: m.userId,\n name: m.name,\n hasProfile: !!profile,\n profile: profile\n ? {\n name: profile.identity.name,\n bio: profile.identity.bio,\n location: profile.identity.location,\n skills: profile.attributes.skills,\n interests: profile.attributes.interests,\n }\n : undefined,\n };\n } catch (err) {\n logger.warn(\"read_user_profiles: getProfile failed; degrading to hasProfile=false\", {\n userId: m.userId,\n error: err instanceof Error ? err.message : String(err),\n });\n return { userId: m.userId, name: m.name, hasProfile: false };\n }\n })\n );\n\n return success({ query: nameQuery, matchCount: profiles.length, profiles });\n }\n\n // When no userId / networkId / query is provided, fall through to Mode 1 (self lookup).\n\n // --- Mode 3: networkId provided → fetch all member profiles ---\n if (effectiveIndexId) {\n // Strict scope enforcement: when chat is index-scoped, only allow querying that index\n if (context.networkId && effectiveIndexId !== context.networkId) {\n return error(\n context.indexName\n ? `This chat is scoped to ${context.indexName}. You can only read profiles from this community.`\n : `This chat is scoped to this index. You can only read profiles from this community.`\n );\n }\n\n // Verify the caller is a member of the index they're querying\n const callerIsMember = await systemDb.isNetworkMember(effectiveIndexId, context.userId);\n if (!callerIsMember) {\n return error(\n \"You can only read profiles from indexes you are a member of.\"\n );\n }\n\n // Use systemDb for cross-user access within shared indexes\n const members = await systemDb.getNetworkMembers(effectiveIndexId);\n const profiles = await Promise.all(\n members.map(async (member) => {\n const profile = await systemDb.getProfile(member.userId);\n return {\n userId: member.userId,\n name: member.name,\n hasProfile: !!profile,\n profile: profile\n ? {\n name: profile.identity.name,\n bio: profile.identity.bio,\n location: profile.identity.location,\n skills: profile.attributes.skills,\n interests: profile.attributes.interests,\n }\n : undefined,\n };\n })\n );\n return success({ networkId: effectiveIndexId, memberCount: members.length, profiles });\n }\n\n // --- Mode 2: userId provided (different user) → fetch single profile directly ---\n if (targetUserId && targetUserId !== context.userId) {\n // Strict scope enforcement: when chat is index-scoped, verify user is in that index\n if (context.networkId) {\n const isInScopedIndex = await systemDb.isNetworkMember(context.networkId, targetUserId);\n if (!isInScopedIndex) {\n return error(\n context.indexName\n ? `This chat is scoped to ${context.indexName}. You can only read profiles of members in this community.`\n : `This chat is scoped to this index. You can only read profiles of members in this community.`\n );\n }\n }\n\n // Use systemDb for cross-user profile access (requires shared index)\n const profile = await systemDb.getProfile(targetUserId);\n if (profile) {\n return success({\n hasProfile: true,\n profile: {\n name: profile.identity.name,\n bio: profile.identity.bio,\n location: profile.identity.location,\n skills: profile.attributes.skills,\n interests: profile.attributes.interests,\n },\n });\n }\n return success({ hasProfile: false, message: \"This user does not have a profile yet.\" });\n }\n\n // --- Mode 1: No args / self → use profileGraph query (returns id for updates) ---\n const _readProfileGraphStart = Date.now();\n const _readProfileTraceEmitter = requestContext.getStore()?.traceEmitter;\n _readProfileTraceEmitter?.({ type: \"graph_start\", name: \"profile\" });\n const result = await invokeWithAbortSignal(graphs.profile, {\n userId: context.userId,\n operationMode: 'query' as const,\n });\n const _readProfileGraphMs = Date.now() - _readProfileGraphStart;\n _readProfileTraceEmitter?.({ type: \"graph_end\", name: \"profile\", durationMs: _readProfileGraphMs });\n\n // Self-lookup includes onboarding status so MCP agents (e.g. Edge Claw)\n // can decide whether to run the onboarding flow without depending on\n // local-only state like a workspace BOOTSTRAP.md file.\n const onboardingCompletedAt = context.user.onboarding?.completedAt ?? null;\n const onboardingFields = {\n onboardingComplete: !!onboardingCompletedAt,\n ...(onboardingCompletedAt ? { onboardingCompletedAt } : {}),\n };\n\n if (result.readResult) {\n return success({ ...result.readResult, ...onboardingFields, _graphTimings: [{ name: 'profile', durationMs: _readProfileGraphMs, agents: result.agentTimings ?? [] }] });\n }\n if (result.profile) {\n return success({\n hasProfile: true,\n profile: {\n name: result.profile.identity.name,\n bio: result.profile.identity.bio,\n location: result.profile.identity.location,\n skills: result.profile.attributes.skills,\n interests: result.profile.attributes.interests,\n },\n ...onboardingFields,\n _graphTimings: [{ name: 'profile', durationMs: _readProfileGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n return success({\n hasProfile: false,\n ...onboardingFields,\n message: \"You don't have a profile yet. Would you like to create one? You can share your LinkedIn, GitHub, or X/Twitter profile, or just tell me about yourself.\",\n _graphTimings: [{ name: 'profile', durationMs: _readProfileGraphMs, agents: result.agentTimings ?? [] }],\n });\n },\n });\n\n const recordOnboardingPrivacyConsent = defineTool({\n name: \"record_onboarding_privacy_consent\",\n description:\n \"Records exactly one authenticated-user onboarding privacy choice. Use this during AgentVillage/Hermes onboarding only after the user explicitly answers the matching consent question in a prior message. \" +\n \"Do not call this in the same assistant turn as the consent question, and do not combine EdgeOS import and public lookup decisions in one call. \" +\n \"This only records consent; it does not mark onboarding complete and does not create or update a profile.\",\n querySchema: z.object({\n edgeosImportGranted: z.boolean().optional().describe(\"Whether the user grants permission to use EdgeOS/event-provided profile data for onboarding.\"),\n publicProfileLookupGranted: z.boolean().optional().describe(\"Whether the user grants permission for public internet/profile lookup during onboarding.\"),\n source: z.enum(['agentvillage_onboarding', 'hermes_setup', 'web_onboarding', 'api']).optional().default('api').describe(\"Where this consent decision was collected.\"),\n }),\n handler: async ({ context, query }) => {\n const user = await userDb.getUser();\n if (user?.isGhost) {\n return error(\"Ghost users cannot record onboarding consent. The user must authenticate as a real account first.\");\n }\n const hasEdgeosDecision = query.edgeosImportGranted !== undefined;\n const hasPublicLookupDecision = query.publicProfileLookupGranted !== undefined;\n if (!hasEdgeosDecision && !hasPublicLookupDecision) {\n return error(\"Provide exactly one consent decision to record.\");\n }\n if (hasEdgeosDecision && hasPublicLookupDecision) {\n return error(\"Record EdgeOS import consent and public-profile lookup consent separately, after each explicit user answer. Do not combine them in one call.\");\n }\n\n const currentOnboarding = user?.onboarding ?? context.user.onboarding ?? {};\n const currentPrivacy: OnboardingPrivacyState = currentOnboarding.privacy ?? {};\n const source = normalizeConsentSource(query.source);\n const privacy: OnboardingPrivacyState = {\n ...currentPrivacy,\n ...(query.edgeosImportGranted !== undefined && { edgeosImport: consentDecision(query.edgeosImportGranted, source) }),\n ...(query.publicProfileLookupGranted !== undefined && { publicProfileLookup: consentDecision(query.publicProfileLookupGranted, source) }),\n };\n\n await userDb.updateUser({\n onboarding: {\n ...currentOnboarding,\n privacy,\n },\n });\n\n return success({\n message: \"Privacy choices recorded.\",\n privacy,\n });\n },\n });\n\n const previewUserProfile = defineTool({\n name: \"preview_user_profile\",\n description:\n \"Builds a structured profile draft for onboarding without saving anything. Use this after recording privacy consent and before asking the user to approve the profile. \" +\n \"If allowPublicLookup is false, this tool uses only explicit text, EdgeOS/event data the user allowed, and user-provided social URLs. If allowPublicLookup is true, persisted public lookup consent is required. \" +\n \"In MCP contexts, starts an async profile run and returns `profileRunId`; poll get_profile_run until status is `succeeded`, then present its `result`.\" +\n \" When public lookup runs, the result includes a `publicLookup` block reporting whether a candidate identity was found (`used`, `confidentMatch`) and what it was (`identity` of name/role/location, plus `socials`), so the caller can confirm identity before saving. A candidate can be returned (`used: true`) without being confident enough to enter the draft; when no lookup runs the block is `{ used: false }`.\",\n querySchema: z.object({\n name: z.string().optional().describe(\"Name explicitly provided by the user. For authenticated public lookup, the account identity is used first and this is only a fallback.\"),\n location: z.string().optional().describe(\"Location explicitly provided by the user or allowed event data.\"),\n bioOrDescription: z.string().optional().describe(\"Explicit self-description provided by the user.\"),\n edgeosProfileText: z.string().optional().describe(\"EdgeOS/event profile text, only if the user granted EdgeOS import consent.\"),\n allowPublicLookup: z.boolean().optional().default(false).describe(\"Whether to include public profile lookup. Requires previously recorded publicProfileLookup consent.\"),\n linkedinUrl: z.string().optional().describe(\"LinkedIn URL explicitly provided by the user.\"),\n githubUrl: z.string().optional().describe(\"GitHub URL explicitly provided by the user.\"),\n twitterUrl: z.string().optional().describe(\"X/Twitter URL explicitly provided by the user.\"),\n websites: z.array(z.string()).optional().describe(\"Personal/portfolio URLs explicitly provided by the user.\"),\n }),\n handler: async ({ context, query }) => {\n const user = await userDb.getUser();\n if (!user) return error(\"User not found.\");\n\n const profileRunId = await enqueueProfileRun(context, \"preview_user_profile\", query);\n if (profileRunId) {\n return success({\n status: \"queued\" as const,\n profileRunId,\n message: `Profile preview started. Call get_profile_run with profileRunId=\"${profileRunId}\" until it succeeds, fails, or is cancelled.`,\n });\n }\n\n const onboarding = user.onboarding ?? context.user.onboarding;\n const hasEdgeosConsent = hasEdgeosImportConsent(onboarding);\n const seed = hasEdgeosConsent ? selectProfileSeed(onboarding, context.networkId) : undefined;\n const authenticatedIdentity = resolveAuthenticatedLookupIdentity(user, context);\n const name = seed?.name || authenticatedIdentity.name || query.name?.trim() || undefined;\n const location = query.location?.trim() || seed?.location || user.location || undefined;\n const bioOrDescription = query.bioOrDescription?.trim() || seed?.bio || user.intro || undefined;\n const edgeosProfileText = query.edgeosProfileText?.trim() || undefined;\n const linkedinUrl = query.linkedinUrl?.trim();\n const githubUrl = query.githubUrl?.trim();\n const twitterUrl = query.twitterUrl?.trim();\n const websites = query.websites?.map((url) => url.trim()).filter(Boolean) ?? [];\n const socials = [\n ...(seed?.socials ?? []),\n ...(linkedinUrl ? [{ label: 'linkedin', value: linkedinUrl }] : []),\n ...(githubUrl ? [{ label: 'github', value: githubUrl }] : []),\n ...(twitterUrl ? [{ label: 'twitter', value: twitterUrl }] : []),\n ...websites.map((value) => ({ label: detectSocialLabel(value), value })),\n ];\n\n if (edgeosProfileText && !hasEdgeosConsent) {\n return error(\"EdgeOS import consent has not been recorded. Ask the user first, then call record_onboarding_privacy_consent(edgeosImportGranted=true) before using event-provided profile data.\");\n }\n\n let enrichment: EnrichmentResult | null = null;\n if (query.allowPublicLookup) {\n if (!hasPublicProfileLookupConsent(user.onboarding ?? context.user.onboarding)) {\n return error(\"Public profile lookup consent has not been recorded. Ask the user first, then call record_onboarding_privacy_consent(publicProfileLookupGranted=true).\");\n }\n const hasAuthenticatedIdentity = authenticatedIdentity.name !== undefined || authenticatedIdentity.email !== undefined;\n enrichment = await enrichFromUserRecord({\n name: authenticatedIdentity.name ?? (hasAuthenticatedIdentity ? undefined : name),\n email: authenticatedIdentity.email,\n socials: socials.map((social, index) => ({ id: `preview-${index}`, userId: context.userId, ...social })),\n });\n }\n\n const input = buildProfileInput({ name, location, bioOrDescription, edgeosProfileText, enrichment, socials });\n if (!input.trim()) {\n return needsClarification({\n missingFields: ['profile_description'],\n message: \"Please share a short description, allowed EdgeOS profile text, or user-provided profile links so I can draft your profile.\",\n });\n }\n\n const generated = await new ProfileGenerator().invoke(input);\n const profile = { ...generated.output, userId: context.userId };\n return success({\n preview: true,\n persisted: false,\n message: \"Profile draft generated. Show this to the user and ask whether it looks right before calling confirm_user_profile.\",\n profile: toProfileSummary(profile),\n draft: profile,\n publicLookup: enrichment\n ? {\n used: true,\n confidentMatch: enrichment.confidentMatch,\n // identity.bio is the role/headline string returned by the lookup\n identity: {\n name: enrichment.identity.name,\n role: enrichment.identity.bio,\n location: enrichment.identity.location,\n },\n socials: enrichment.socials,\n }\n : { used: false },\n });\n },\n });\n\n const confirmUserProfile = defineTool({\n name: \"confirm_user_profile\",\n description:\n \"Saves an explicitly approved onboarding profile draft. Call this only after the user has seen the draft from preview_user_profile and approved it or provided corrections. \" +\n \"This path uses only the approved draft/explicit correction text and does not scrape or run public lookup.\",\n querySchema: z.object({\n draft: approvedProfileDraftSchema.optional().describe(\"The structured profile draft returned by preview_user_profile after user approval.\"),\n bioOrDescription: z.string().optional().describe(\"Approved correction or explicit profile text if not passing a structured draft.\"),\n name: z.string().optional().describe(\"Approved name correction.\"),\n location: z.string().optional().describe(\"Approved location correction.\"),\n }),\n handler: async ({ context, query }) => {\n const user = await userDb.getUser();\n if (query.draft) {\n const profile = { ...query.draft, userId: context.userId };\n await userDb.saveProfile(profile);\n await persistApprovedProfileContext(profile, user, context.networkId);\n\n const decomposeLogLabel = context.isMcp\n ? 'Approved draft premise decomposition failed'\n : 'Approved draft premise decomposition failed (web)';\n decomposeApprovedDraftProfile(profile).catch((err: unknown) => {\n logger.error(decomposeLogLabel, {\n userId: profile.userId,\n error: err instanceof Error ? err.message : String(err),\n });\n });\n\n return success({\n created: true,\n message: context.isMcp\n ? \"Profile saved from approved draft. Premise extraction is running in the background.\"\n : \"Profile saved from approved draft.\",\n profile: toProfileSummary(profile),\n });\n }\n\n const description = query.bioOrDescription?.trim();\n if (!description) {\n return error(\"Pass the approved structured draft or explicit approved profile text.\");\n }\n const approvedName = query.name?.trim();\n const approvedLocation = query.location?.trim();\n const input = buildProfileInput({\n name: approvedName,\n location: approvedLocation,\n bioOrDescription: description,\n });\n const rawProfile = {\n identity: {\n name: approvedName && approvedName.length > 0 ? approvedName : user?.name ?? '',\n bio: description,\n location: approvedLocation && approvedLocation.length > 0 ? approvedLocation : user?.location ?? '',\n },\n };\n await persistApprovedProfileContext(rawProfile, user, context.networkId);\n\n const _confirmTraceEmitter = requestContext.getStore()?.traceEmitter;\n const _confirmGraphStart = Date.now();\n _confirmTraceEmitter?.({ type: \"graph_start\", name: \"profile\" });\n graphs.profile.invoke({\n userId: context.userId,\n operationMode: 'write' as const,\n input,\n forceUpdate: true,\n }).then((result) => {\n if (result.error || !result.profile) {\n logger.error('Background profile generation failed', {\n userId: context.userId,\n error: result.error ?? 'No profile returned',\n });\n }\n }).catch((err: unknown) =>\n logger.error('Background profile generation failed', {\n userId: context.userId,\n error: err instanceof Error ? err.message : String(err),\n })\n ).finally(() => {\n const _confirmGraphMs = Date.now() - _confirmGraphStart;\n _confirmTraceEmitter?.({ type: \"graph_end\", name: \"profile\", durationMs: _confirmGraphMs });\n });\n\n return success({\n created: true,\n message: \"Profile text accepted. Your profile is being structured in the background.\",\n profile: toProfileSummary({\n identity: rawProfile.identity,\n attributes: { skills: [], interests: [] },\n }),\n });\n },\n });\n\n const createUserProfile = defineTool({\n name: \"create_user_profile\",\n description:\n \"Legacy/backward-compatible tool that creates or regenerates the authenticated user's profile. AgentVillage/Hermes onboarding must use \" +\n \"record_onboarding_privacy_consent → preview_user_profile → confirm_user_profile instead, so consent is recorded and the draft is shown before saving. \" +\n \"Profiles are essential for discovery — they provide the semantic context used to match users with complementary intents.\\n\\n\" +\n \"**How it works:** For generic clients, the system can enrich profile data from public web sources (LinkedIn, GitHub, Twitter) and/or explicit user input, \" +\n \"then generates a structured profile with bio, skills, interests, location, and narrative context. Do not call with no arguments in consent-required onboarding flows.\\n\\n\" +\n \"**Usage patterns:**\\n\" +\n \"- No args: attempts auto-generation from account data. If insufficient info, returns `missingFields` — ask the user for name/social URLs and retry.\\n\" +\n \"- With social URLs (linkedinUrl, githubUrl, etc.): enriches from those specific URLs.\\n\" +\n \"- With bioOrDescription: creates profile from explicit text only (no web scraping).\\n\" +\n \"- Legacy onboarding clients: first call returns a preview. AgentVillage/Hermes clients should not use this preview path; use preview_user_profile instead because it does not persist enrichment side effects.\\n\\n\" +\n \"**Returns:** The generated profile (name, bio, location, skills, interests) or a `needsClarification` response listing missing fields.\\n\\n\" +\n \"**Next steps:** After profile creation, the user can create intents (create_intent) and join indexes (create_network_membership) to start discovering opportunities.\",\n querySchema: z.object({\n name: z.string().optional().describe(\"User's full name (first and last). Pass when the user explicitly provides their name.\"),\n linkedinUrl: z.string().optional().describe(\"LinkedIn profile URL (e.g. 'https://linkedin.com/in/username'). Pass when user shares a LinkedIn link.\"),\n githubUrl: z.string().optional().describe(\"GitHub profile URL (e.g. 'https://github.com/username'). Pass when user shares a GitHub link.\"),\n twitterUrl: z.string().optional().describe(\"X/Twitter profile URL (e.g. 'https://x.com/username'). Pass when user shares a Twitter/X link.\"),\n websites: z.array(z.string()).optional().describe(\"Personal or portfolio website URLs. Pass when user shares website links.\"),\n location: z.string().optional().describe(\"User's location (e.g. 'Berlin, Germany' or 'SF Bay Area'). Pass when the user mentions where they are based.\"),\n bioOrDescription: z.string().optional().describe(\"Explicit profile text from the user (e.g. 'software engineer focused on AI/ML, based in SF'). When provided, creates/updates profile from this text only — no web scraping. Use when user describes themselves in chat.\"),\n confirm: z.boolean().optional().describe(\"Set to true to save a previously previewed profile. Only used during onboarding flow after the user approves the preview.\"),\n }),\n handler: async ({ context, query }) => {\n // Persist user-info fields (name, location, socials) to users table before any branching.\n // This ensures users.name is always updated regardless of which code path runs.\n // Trim all string fields to avoid persisting whitespace-only values.\n const name = query.name?.trim();\n const location = query.location?.trim();\n const linkedinUrl = query.linkedinUrl?.trim();\n const githubUrl = query.githubUrl?.trim();\n const twitterUrl = query.twitterUrl?.trim();\n const websites = query.websites?.map((url) => url.trim()).filter(Boolean);\n const hasSocialsFromQuery = Boolean(linkedinUrl || githubUrl || twitterUrl || websites?.length);\n if (name || location) {\n await userDb.updateUser({\n ...(name ? { name } : {}),\n ...(location ? { location } : {}),\n });\n }\n if (hasSocialsFromQuery) {\n const newSocials: { label: string; value: string }[] = [];\n if (linkedinUrl) newSocials.push({ label: 'linkedin', value: linkedinUrl });\n if (githubUrl) newSocials.push({ label: 'github', value: githubUrl });\n if (twitterUrl) newSocials.push({ label: 'twitter', value: twitterUrl });\n if (websites?.length) {\n for (const w of websites) newSocials.push({ label: detectSocialLabel(w) === 'custom' ? 'custom' : detectSocialLabel(w), value: w });\n }\n await mergeUserSocials(newSocials);\n }\n logger.verbose(\"Persisted user-info fields to user record\", { userId: context.userId });\n\n const isOnboarding = !(context.user.onboarding?.completedAt);\n if (isOnboarding) {\n const existingProfile = await userDb.getProfile();\n if (existingProfile) {\n return success({\n alreadyExists: true,\n message: \"Profile already exists. If the user confirmed it, call complete_onboarding() to finish setup. If they want changes, use create_user_profile(bioOrDescription=\\\"...\\\", confirm=true).\",\n profile: {\n name: existingProfile.identity.name,\n bio: existingProfile.identity.bio,\n location: existingProfile.identity.location,\n skills: existingProfile.attributes.skills,\n interests: existingProfile.attributes.interests,\n },\n });\n }\n\n // Preview mode: enrich and persist enrichment results, but don't generate full profile\n if (!query.confirm) {\n try {\n const user = await userDb.getUser();\n const enrichment = user ? await enrichFromUserRecord(user) : null;\n\n if (isMeaningfulEnrichment(enrichment)) {\n // Persist enrichment data to user record so confirm path has it\n const updatePayload: {\n name?: string;\n intro?: string;\n location?: string;\n } = {};\n if (enrichment.identity.name?.trim()) {\n updatePayload.name = enrichment.identity.name.trim();\n }\n if (enrichment.identity.bio?.trim()) updatePayload.intro = enrichment.identity.bio.trim();\n if (enrichment.identity.location?.trim()) updatePayload.location = enrichment.identity.location.trim();\n if (Object.keys(updatePayload).length > 0) await userDb.updateUser(updatePayload);\n const enrichedSocials: { label: string; value: string }[] = [];\n if (enrichment.socials.twitter) enrichedSocials.push({ label: 'twitter', value: enrichment.socials.twitter });\n if (enrichment.socials.linkedin) enrichedSocials.push({ label: 'linkedin', value: enrichment.socials.linkedin });\n if (enrichment.socials.github) enrichedSocials.push({ label: 'github', value: enrichment.socials.github });\n if (enrichment.socials.telegram) enrichedSocials.push({ label: 'telegram', value: enrichment.socials.telegram });\n if (enrichment.socials.websites?.length) {\n for (const w of enrichment.socials.websites) enrichedSocials.push({ label: 'custom', value: w });\n }\n if (enrichedSocials.length > 0) {\n await mergeUserSocials(enrichedSocials);\n }\n\n return success({\n preview: true,\n message: \"Profile preview generated. Call create_user_profile(confirm=true) to save.\",\n profile: {\n name: enrichment.identity.name,\n bio: enrichment.identity.bio,\n location: enrichment.identity.location,\n skills: enrichment.attributes.skills,\n interests: enrichment.attributes.interests,\n },\n // Always present when isMeaningfulEnrichment passes — may be {} if the\n // enrichment found no social handles. LLM should ask the user to provide\n // links when empty (see buildOnboarding step 3 in chat.prompt.ts).\n detectedSocials: enrichment.socials,\n });\n }\n } catch (err) {\n logger.warn(\"Enrichment preview failed\", {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n\n return needsClarification({\n missingFields: ['bio_or_social_urls'],\n message: \"I couldn't find enough public info. Could you share a short description of yourself, or a LinkedIn/GitHub/X profile link?\",\n });\n }\n\n // Confirm mode: invoke graph in generate mode (enrichment data already persisted during preview)\n // Do NOT re-run enrichFromUserRecord — the graph's autoGenerateNode handles enrichment\n // from the (now well-populated) user record, avoiding non-deterministic drift.\n try {\n const _confirmGraphStart = Date.now();\n const _confirmTraceEmitter = requestContext.getStore()?.traceEmitter;\n _confirmTraceEmitter?.({ type: \"graph_start\", name: \"profile\" });\n const result = await invokeWithAbortSignal(graphs.profile, {\n userId: context.userId,\n operationMode: 'generate' as const,\n });\n const _confirmGraphMs = Date.now() - _confirmGraphStart;\n _confirmTraceEmitter?.({ type: \"graph_end\", name: \"profile\", durationMs: _confirmGraphMs });\n\n if (result.error) return error(result.error);\n if (result.profile) {\n return success({\n created: true,\n message: \"Profile saved.\",\n profile: {\n name: result.profile.identity.name,\n bio: result.profile.identity.bio,\n location: result.profile.identity.location,\n skills: result.profile.attributes.skills,\n interests: result.profile.attributes.interests,\n },\n _graphTimings: [{ name: 'profile', durationMs: _confirmGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n } catch (err) {\n logger.warn(\"Profile generation on confirm failed, falling back to full graph\", {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n // Fallback: graph invocation failed on confirm, fall through to full graph invocation\n }\n\n const hasBioOrDescription = !!query.bioOrDescription?.trim();\n\n if (hasBioOrDescription) {\n // Create/update profile from user's explicit text only; do not persist to user record\n // Include name and location in the input if provided so the ProfileGenerator can use them\n const inputParts: string[] = [];\n if (name) inputParts.push(`Name: ${name}`);\n if (location) inputParts.push(`Location: ${location}`);\n inputParts.push(query.bioOrDescription!.trim());\n const profileInput = inputParts.join('\\n');\n \n const _bioProfileGraphStart = Date.now();\n const _bioProfileTraceEmitter = requestContext.getStore()?.traceEmitter;\n _bioProfileTraceEmitter?.({ type: \"graph_start\", name: \"profile\" });\n const result = await invokeWithAbortSignal(graphs.profile, {\n userId: context.userId,\n operationMode: 'write' as const,\n input: profileInput,\n forceUpdate: true,\n });\n const _bioProfileGraphMs = Date.now() - _bioProfileGraphStart;\n _bioProfileTraceEmitter?.({ type: \"graph_end\", name: \"profile\", durationMs: _bioProfileGraphMs });\n if (result.error) {\n return error(result.error);\n }\n if (result.profile) {\n return success({\n created: true,\n message: \"Profile created/updated with the information you provided.\",\n profile: {\n name: result.profile.identity.name,\n bio: result.profile.identity.bio,\n location: result.profile.identity.location,\n skills: result.profile.attributes.skills,\n interests: result.profile.attributes.interests,\n },\n _graphTimings: [{ name: 'profile', durationMs: _bioProfileGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n return success({\n created: true,\n message: \"Profile created/updated with the information you provided.\",\n _graphTimings: [{ name: 'profile', durationMs: _bioProfileGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n\n // Invoke profile graph in generate mode (uses enrichUserProfile Chat API)\n const _generateProfileGraphStart = Date.now();\n const _generateProfileTraceEmitter = requestContext.getStore()?.traceEmitter;\n _generateProfileTraceEmitter?.({ type: \"graph_start\", name: \"profile\" });\n const result = await invokeWithAbortSignal(graphs.profile, {\n userId: context.userId,\n operationMode: 'generate' as const,\n forceUpdate: true,\n });\n const _generateProfileGraphMs = Date.now() - _generateProfileGraphStart;\n _generateProfileTraceEmitter?.({ type: \"graph_end\", name: \"profile\", durationMs: _generateProfileGraphMs });\n\n // If user info is insufficient, ask conversationally\n if (result.needsUserInfo) {\n return needsClarification({\n missingFields: result.missingUserInfo || ['social_urls', 'full_name'],\n message: \"I need a bit more information to create your profile. Could you share your full name and any social links (LinkedIn, GitHub, or X/Twitter)?\",\n });\n }\n\n if (result.error) {\n return error(result.error);\n }\n\n if (result.profile) {\n return success({\n created: true,\n message: \"Profile generated from your account data.\",\n profile: {\n name: result.profile.identity.name,\n bio: result.profile.identity.bio,\n location: result.profile.identity.location,\n skills: result.profile.attributes.skills,\n interests: result.profile.attributes.interests,\n },\n _graphTimings: [{ name: 'profile', durationMs: _generateProfileGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n\n return error(\"Failed to create profile. Please try again.\");\n },\n });\n\n const updateUserProfile = defineTool({\n name: \"update_user_profile\",\n description:\n \"Updates the authenticated user's existing profile using a verb-style instruction interface.\\n\\n\" +\n \"**How to use it:**\\n\" +\n \"- `action`: a natural-language instruction describing what to change (e.g. \\\"add interests\\\", \\\"update bio\\\", \\\"remove skill\\\", \\\"set location\\\").\\n\" +\n \"- `details`: the content to apply (e.g. \\\"procedural generation, roguelikes, narrative games\\\").\\n\" +\n \"- `socials`: optional social handles to merge into the user's reachable profile (e.g. `{ telegram: \\\"@alice\\\" }`).\\n\\n\" +\n \"**Examples:**\\n\" +\n \"- `action=\\\"add interests\\\"`, `details=\\\"procedural generation, roguelikes\\\"`\\n\" +\n \"- `action=\\\"update bio\\\"`, `details=\\\"Product designer focused on desktop CRPG interfaces\\\"`\\n\" +\n \"- `action=\\\"set location\\\"`, `details=\\\"Berlin\\\"`\\n\" +\n \"- `socials={ telegram: \\\"@alice\\\" }` to silently add a reachable chat handle without regenerating the profile.\\n\\n\" +\n \"**When to use:** When the user wants to make specific changes without regenerating the whole profile. For full profile regeneration from social URLs, use create_user_profile instead.\\n\\n\" +\n \"**Important:** If the user provides a URL to update from, call scrape_url first, then pass the scraped content in `details`.\\n\\n\" +\n \"**MCP behavior:** For MCP clients, text/profile graph updates are accepted immediately and completed in the background to avoid transport timeouts. Social-only updates still complete synchronously.\\n\\n\" +\n \"**Returns:** Confirmation that the profile was updated or accepted for background update.\",\n querySchema: z.object({\n profileId: z.string().optional().describe(\"Profile UUID from read_user_profiles. Omit to update the current user's own profile (most common usage).\"),\n action: z.string().optional().describe(\"Natural language description of ALL changes to make in a single call. Examples: 'update bio to focus on AI research', 'add Python and Rust to skills', 'change location to Berlin and add machine learning to interests'. Optional when only updating socials.\"),\n details: z.string().optional().describe(\"Additional context or content to incorporate. Use this to pass scraped URL content (from scrape_url) or longer text the user provided.\"),\n socials: z.record(z.string()).optional().describe(\"Social handles or URLs to merge into the user profile, keyed by label. Example: { telegram: '@alice', github: 'alice' }. Existing socials with other labels are preserved.\"),\n }),\n handler: async ({ context, query }) => {\n const socialUpdates = socialsRecordToRows(query.socials);\n const inputForProfile = [query.action, query.details].filter(Boolean).join(\"\\n\");\n if (!inputForProfile.trim()) {\n if (socialUpdates.length > 0) {\n await mergeUserSocials(socialUpdates);\n return success({ message: \"Profile socials updated.\" });\n }\n return error(\"Please specify what to update (e.g. action: 'update bio to X') or provide socials.\");\n }\n\n const profileRunId = await enqueueProfileRun(context, \"update_user_profile\", query);\n if (profileRunId) {\n return success({\n status: \"queued\" as const,\n profileRunId,\n message: `Profile update started. Call get_profile_run with profileRunId=\"${profileRunId}\" until it succeeds, fails, or is cancelled.`,\n });\n }\n\n // Use profileGraph query mode to validate profile existence and get id\n const _updateQueryProfileGraphStart = Date.now();\n const _updateQueryProfileTraceEmitter = requestContext.getStore()?.traceEmitter;\n _updateQueryProfileTraceEmitter?.({ type: \"graph_start\", name: \"profile\" });\n const queryResult = await invokeWithAbortSignal(graphs.profile, { userId: context.userId, operationMode: 'query' as const });\n const _updateQueryProfileGraphMs = Date.now() - _updateQueryProfileGraphStart;\n _updateQueryProfileTraceEmitter?.({ type: \"graph_end\", name: \"profile\", durationMs: _updateQueryProfileGraphMs });\n if (!queryResult.readResult?.hasProfile && !queryResult.profile) {\n return error(\"You don't have a profile yet. Use create_user_profile first.\");\n }\n const existingProfileId = queryResult.readResult?.profile?.id;\n const providedProfileId = query.profileId?.trim();\n if (providedProfileId && existingProfileId && providedProfileId !== existingProfileId) {\n return error(\"Invalid profileId. Use the profile id from read_user_profiles.\");\n }\n\n if (socialUpdates.length > 0) {\n await mergeUserSocials(socialUpdates);\n }\n\n if (context.isMcp) {\n const _backgroundWriteProfileGraphStart = Date.now();\n const _backgroundWriteProfileTraceEmitter = requestContext.getStore()?.traceEmitter;\n _backgroundWriteProfileTraceEmitter?.({ type: \"graph_start\", name: \"profile\" });\n graphs.profile.invoke({\n userId: context.userId,\n operationMode: \"write\",\n input: inputForProfile,\n forceUpdate: true,\n }).then((writeResult) => {\n if (writeResult.error) {\n logger.error(\"Background profile update failed\", {\n userId: context.userId,\n error: writeResult.error,\n });\n reportToolError?.(new Error(writeResult.error), {\n subsystem: \"profile\",\n operation: \"profile.update_background\",\n toolName: \"update_user_profile\",\n userId: context.userId,\n tags: { toolName: \"update_user_profile\", execution: \"background\" },\n context: { profileId: existingProfileId ?? providedProfileId },\n });\n }\n }).catch((err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n logger.error(\"Background profile update failed\", {\n userId: context.userId,\n error: message,\n });\n reportToolError?.(err, {\n subsystem: \"profile\",\n operation: \"profile.update_background\",\n toolName: \"update_user_profile\",\n userId: context.userId,\n tags: { toolName: \"update_user_profile\", execution: \"background\" },\n context: { profileId: existingProfileId ?? providedProfileId },\n });\n }).finally(() => {\n const _backgroundWriteProfileGraphMs = Date.now() - _backgroundWriteProfileGraphStart;\n _backgroundWriteProfileTraceEmitter?.({ type: \"graph_end\", name: \"profile\", durationMs: _backgroundWriteProfileGraphMs });\n });\n\n return success({\n accepted: true,\n message: \"Profile update accepted. The structured profile will refresh in the background.\",\n _graphTimings: [\n { name: 'profile', durationMs: _updateQueryProfileGraphMs, agents: queryResult.agentTimings ?? [] },\n ],\n });\n }\n\n // Execute update directly\n const _updateWriteProfileGraphStart = Date.now();\n const _updateWriteProfileTraceEmitter = requestContext.getStore()?.traceEmitter;\n _updateWriteProfileTraceEmitter?.({ type: \"graph_start\", name: \"profile\" });\n const _writeResult = await invokeWithAbortSignal(graphs.profile, {\n userId: context.userId,\n operationMode: \"write\",\n input: inputForProfile,\n forceUpdate: true,\n });\n const _updateWriteProfileGraphMs = Date.now() - _updateWriteProfileGraphStart;\n _updateWriteProfileTraceEmitter?.({ type: \"graph_end\", name: \"profile\", durationMs: _updateWriteProfileGraphMs });\n if (_writeResult.error) {\n return error(_writeResult.error);\n }\n return success({\n message: \"Profile updated.\",\n _graphTimings: [\n { name: 'profile', durationMs: _updateQueryProfileGraphMs, agents: queryResult.agentTimings ?? [] },\n { name: 'profile', durationMs: _updateWriteProfileGraphMs, agents: _writeResult.agentTimings ?? [] },\n ],\n });\n },\n });\n\n const getProfileRun = defineTool({\n name: \"get_profile_run\",\n description:\n \"Checks the status of an async profile preview/update run started by preview_user_profile or update_user_profile in MCP contexts. \" +\n \"Poll this tool with the profileRunId until status is succeeded, failed, or cancelled. When succeeded, present the result to the user.\",\n querySchema: z.object({\n profileRunId: z.string().describe(\"Profile run ID returned by preview_user_profile or update_user_profile.\"),\n }),\n handler: async ({ context, query }) => {\n if (!deps.profileRuns) {\n return error(\"Profile run polling is not available in this environment.\");\n }\n const run = await deps.profileRuns.get(query.profileRunId, context.userId);\n if (!run) return error(\"Profile run not found.\");\n return success({\n profileRunId: run.id,\n operation: run.operation,\n status: run.status,\n progress: run.progress ?? null,\n result: run.result ?? null,\n error: run.error ?? null,\n createdAt: run.createdAt.toISOString?.() ?? null,\n startedAt: run.startedAt?.toISOString?.() ?? null,\n completedAt: run.completedAt?.toISOString?.() ?? null,\n });\n },\n });\n\n const cancelProfileRun = defineTool({\n name: \"cancel_profile_run\",\n description:\n \"Requests cancellation for an async profile run. If the queued job has not started, it is removed and marked cancelled. \" +\n \"If already running, the worker observes the cancellation request and aborts where supported.\",\n querySchema: z.object({\n profileRunId: z.string().describe(\"Profile run ID returned by preview_user_profile or update_user_profile.\"),\n }),\n handler: async ({ context, query }) => {\n if (!deps.profileRuns || !deps.profileRunQueue) {\n return error(\"Profile run cancellation is not available in this environment.\");\n }\n const existing = await deps.profileRuns.get(query.profileRunId, context.userId);\n if (!existing) return error(\"Profile run not found.\");\n if (![\"queued\", \"running\"].includes(existing.status)) {\n return success({\n profileRunId: existing.id,\n status: existing.status,\n message: `Profile run is already ${existing.status}.`,\n });\n }\n const run = await deps.profileRuns.requestCancel(query.profileRunId, context.userId);\n if (!run) return error(\"Profile run not found or cannot be cancelled.\");\n const removed = await deps.profileRunQueue.cancel(run.id);\n if (removed) {\n await deps.profileRuns.markCancelled(run.id, \"cancelled before worker start\");\n }\n const updated = await deps.profileRuns.get(run.id, context.userId);\n return success({\n profileRunId: run.id,\n status: updated?.status ?? run.status,\n cancelled: true,\n message: removed\n ? \"Profile run cancelled before it started.\"\n : \"Cancellation requested while the profile run is running or queued.\",\n });\n },\n });\n\n const completeOnboarding = defineTool({\n name: \"complete_onboarding\",\n description:\n \"Marks the user's onboarding as complete, unlocking full platform access. This is the final step in the new-user setup flow.\\n\\n\" +\n \"**Prerequisites:** The user must have a profile (created via create_user_profile) AND must have explicitly confirmed it \" +\n \"(said 'yes', 'looks good', 'that's right', or similar). Do NOT call this until the user confirms.\\n\\n\" +\n \"**What happens:** Sets completedAt timestamp on the user's onboarding record.\\n\\n\" +\n \"**Workflow:** create_user_profile() -> user confirms preview -> create_user_profile(confirm=true) -> user confirms saved profile -> complete_onboarding()\\n\\n\" +\n \"**Returns:** Confirmation that onboarding is complete. No parameters needed.\",\n querySchema: z.object({}),\n handler: async ({ context }) => {\n const currentOnboarding = context.user.onboarding ?? {};\n if (currentOnboarding.completedAt) {\n logger.verbose(\"Onboarding already completed, skipping\", { userId: context.userId });\n return success({ message: \"Onboarding already completed.\" });\n }\n await userDb.updateUser({\n onboarding: {\n ...currentOnboarding,\n completedAt: new Date().toISOString(),\n },\n });\n\n if (grantDefaultSystemPermissions) {\n try {\n await grantDefaultSystemPermissions(context.userId);\n } catch (err) {\n logger.warn('Default system agent permission grant failed (non-fatal)', {\n userId: context.userId,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n logger.info(\"Onboarding completed\", { userId: context.userId });\n return success({ message: \"Onboarding complete.\" });\n },\n });\n\n return [readUserProfiles, recordOnboardingPrivacyConsent, previewUserProfile, confirmUserProfile, createUserProfile, updateUserProfile, getProfileRun, cancelProfileRun, completeOnboarding] as const;\n}\n"]}
@@ -0,0 +1,16 @@
1
+ import type { DefineTool, ToolDeps } from "../shared/agent/tool.helpers.js";
2
+ /**
3
+ * Creates MCP tool definitions for the questioner domain.
4
+ * Exposes `read_pending_questions` for retrieving the caller's pending
5
+ * questions generated by QuestionerAgent (profile, intent, negotiation, discovery modes).
6
+ *
7
+ * Network-scoped agent keys (context.networkId set via applyNetworkScopeToContext)
8
+ * are clamped to self-owned modes; the result then carries a `scopeRestriction`
9
+ * block mirroring the network-tools convention.
10
+ *
11
+ * @param defineTool - Tool factory provided by the composition root.
12
+ * @param deps - Shared tool dependencies; `findPendingQuestions` is optional
13
+ * and the tool fails gracefully when absent.
14
+ */
15
+ export declare function createQuestionerTools(defineTool: DefineTool, deps: ToolDeps): readonly [any];
16
+ //# sourceMappingURL=questioner.tools.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"questioner.tools.d.ts","sourceRoot":"/","sources":["questioner/questioner.tools.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AAa5E;;;;;;;;;;;;GAYG;AACH,wBAAgB,qBAAqB,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,kBAuE3E"}
@@ -0,0 +1,90 @@
1
+ import { z } from "zod";
2
+ import { error, success } from "../shared/agent/tool.helpers.js";
3
+ /**
4
+ * Detection modes whose questions derive solely from the caller's own data
5
+ * (profile gaps, own intents, own discovery sessions). Negotiation-mode
6
+ * questions are excluded for network-scoped agents: their prompts are seeded
7
+ * from opportunity metadata that can reference out-of-scope networks and
8
+ * other users' content (same leak class as the getOpportunitiesForUser fix).
9
+ */
10
+ const SELF_OWNED_MODES = ["profile", "intent", "discovery"];
11
+ /**
12
+ * Creates MCP tool definitions for the questioner domain.
13
+ * Exposes `read_pending_questions` for retrieving the caller's pending
14
+ * questions generated by QuestionerAgent (profile, intent, negotiation, discovery modes).
15
+ *
16
+ * Network-scoped agent keys (context.networkId set via applyNetworkScopeToContext)
17
+ * are clamped to self-owned modes; the result then carries a `scopeRestriction`
18
+ * block mirroring the network-tools convention.
19
+ *
20
+ * @param defineTool - Tool factory provided by the composition root.
21
+ * @param deps - Shared tool dependencies; `findPendingQuestions` is optional
22
+ * and the tool fails gracefully when absent.
23
+ */
24
+ export function createQuestionerTools(defineTool, deps) {
25
+ const readPendingQuestions = defineTool({
26
+ name: "read_pending_questions",
27
+ description: "Returns pending questions generated for the authenticated user across all modes " +
28
+ "(profile, intent, negotiation, discovery). These are questions generated by the " +
29
+ "system to help surface missing signals, refine intents, or capture engagement context.\n\n" +
30
+ "**Returns:** List of pending questions, each with `id`, `title`, `prompt`, `options`, " +
31
+ "`multiSelect`, `mode`, `sourceType`, `sourceId`, `createdAt`, and optional `expiresAt`. " +
32
+ "Network-scoped agents receive only profile/intent/discovery questions plus a " +
33
+ "`scopeRestriction` note.\n\n" +
34
+ "**Use:** Call with no arguments to get all pending questions, or pass `limit` to cap the " +
35
+ "count. For the daily brief the script calls with a small `limit` and renders the first " +
36
+ "question that has not been delivered yet.",
37
+ querySchema: z.object({
38
+ limit: z
39
+ .number()
40
+ .int()
41
+ .min(1)
42
+ .max(10)
43
+ .optional()
44
+ .describe("Maximum number of questions to return (1-10, default 10)."),
45
+ }),
46
+ handler: async ({ context, query }) => {
47
+ if (!deps.findPendingQuestions) {
48
+ return error("Question lookup is not available.");
49
+ }
50
+ const limit = query.limit ?? 10;
51
+ // Scoped-key discriminator: applyNetworkScopeToContext sets networkId
52
+ // only for network-scoped agent keys (mcp.server.ts:558).
53
+ const isScoped = Boolean(context.networkId);
54
+ try {
55
+ const fetched = await deps.findPendingQuestions(context.userId, {
56
+ ...(isScoped ? { modes: SELF_OWNED_MODES } : {}),
57
+ limit,
58
+ });
59
+ // Defense-in-depth: hosts apply `modes`/`limit` SQL-side; re-apply both
60
+ // here so the clamp holds even when a custom dep ignores the filters.
61
+ const visible = isScoped
62
+ ? fetched.filter((q) => SELF_OWNED_MODES.includes(q.mode))
63
+ : fetched;
64
+ const limited = visible.slice(0, limit);
65
+ if (isScoped) {
66
+ return success({
67
+ questions: limited,
68
+ scopeRestriction: {
69
+ isScoped: true,
70
+ scopedToIndex: context.indexName ?? context.networkId,
71
+ message: `Results exclude negotiation questions because this agent is scoped to ` +
72
+ `"${context.indexName ?? "this index"}".`,
73
+ },
74
+ });
75
+ }
76
+ return success({ questions: limited });
77
+ }
78
+ catch (err) {
79
+ deps.reportToolError?.(err, {
80
+ operation: "read-pending-questions",
81
+ toolName: "read_pending_questions",
82
+ userId: context.userId,
83
+ });
84
+ return error("Failed to read pending questions.");
85
+ }
86
+ },
87
+ });
88
+ return [readPendingQuestions];
89
+ }
90
+ //# sourceMappingURL=questioner.tools.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"questioner.tools.js","sourceRoot":"/","sources":["questioner/questioner.tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,iCAAiC,CAAC;AAGjE;;;;;;GAMG;AACH,MAAM,gBAAgB,GAAmB,CAAC,SAAS,EAA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CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAE,gBAA6B,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;oBACxE,CAAC,CAAC,OAAO,CAAC;gBACZ,MAAM,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;gBAExC,IAAI,QAAQ,EAAE,CAAC;oBACb,OAAO,OAAO,CAAC;wBACb,SAAS,EAAE,OAAO;wBAClB,gBAAgB,EAAE;4BAChB,QAAQ,EAAE,IAAI;4BACd,aAAa,EAAE,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,SAAS;4BACrD,OAAO,EACL,wEAAwE;gCACxE,IAAI,OAAO,CAAC,SAAS,IAAI,YAAY,IAAI;yBAC5C;qBACF,CAAC,CAAC;gBACL,CAAC;gBAED,OAAO,OAAO,CAAC,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC,CAAC;YACzC,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,IAAI,CAAC,eAAe,EAAE,CAAC,GAAG,EAAE;oBAC1B,SAAS,EAAE,wBAAwB;oBACnC,QAAQ,EAAE,wBAAwB;oBAClC,MAAM,EAAE,OAAO,CAAC,MAAM;iBACvB,CAAC,CAAC;gBACH,OAAO,KAAK,CAAC,mCAAmC,CAAC,CAAC;YACpD,CAAC;QACH,CAAC;KACF,CAAC,CAAC;IAEH,OAAO,CAAC,oBAAoB,CAAU,CAAC;AACzC,CAAC","sourcesContent":["import { z } from \"zod\";\n\nimport type { DefineTool, ToolDeps } from \"../shared/agent/tool.helpers.js\";\nimport { error, success } from \"../shared/agent/tool.helpers.js\";\nimport type { QuestionMode } from \"../shared/schemas/question.schema.js\";\n\n/**\n * Detection modes whose questions derive solely from the caller's own data\n * (profile gaps, own intents, own discovery sessions). Negotiation-mode\n * questions are excluded for network-scoped agents: their prompts are seeded\n * from opportunity metadata that can reference out-of-scope networks and\n * other users' content (same leak class as the getOpportunitiesForUser fix).\n */\nconst SELF_OWNED_MODES: QuestionMode[] = [\"profile\", \"intent\", \"discovery\"];\n\n/**\n * Creates MCP tool definitions for the questioner domain.\n * Exposes `read_pending_questions` for retrieving the caller's pending\n * questions generated by QuestionerAgent (profile, intent, negotiation, discovery modes).\n *\n * Network-scoped agent keys (context.networkId set via applyNetworkScopeToContext)\n * are clamped to self-owned modes; the result then carries a `scopeRestriction`\n * block mirroring the network-tools convention.\n *\n * @param defineTool - Tool factory provided by the composition root.\n * @param deps - Shared tool dependencies; `findPendingQuestions` is optional\n * and the tool fails gracefully when absent.\n */\nexport function createQuestionerTools(defineTool: DefineTool, deps: ToolDeps) {\n const readPendingQuestions = defineTool({\n name: \"read_pending_questions\",\n description:\n \"Returns pending questions generated for the authenticated user across all modes \" +\n \"(profile, intent, negotiation, discovery). These are questions generated by the \" +\n \"system to help surface missing signals, refine intents, or capture engagement context.\\n\\n\" +\n \"**Returns:** List of pending questions, each with `id`, `title`, `prompt`, `options`, \" +\n \"`multiSelect`, `mode`, `sourceType`, `sourceId`, `createdAt`, and optional `expiresAt`. \" +\n \"Network-scoped agents receive only profile/intent/discovery questions plus a \" +\n \"`scopeRestriction` note.\\n\\n\" +\n \"**Use:** Call with no arguments to get all pending questions, or pass `limit` to cap the \" +\n \"count. For the daily brief the script calls with a small `limit` and renders the first \" +\n \"question that has not been delivered yet.\",\n querySchema: z.object({\n limit: z\n .number()\n .int()\n .min(1)\n .max(10)\n .optional()\n .describe(\"Maximum number of questions to return (1-10, default 10).\"),\n }),\n handler: async ({ context, query }) => {\n if (!deps.findPendingQuestions) {\n return error(\"Question lookup is not available.\");\n }\n\n const limit = query.limit ?? 10;\n // Scoped-key discriminator: applyNetworkScopeToContext sets networkId\n // only for network-scoped agent keys (mcp.server.ts:558).\n const isScoped = Boolean(context.networkId);\n\n try {\n const fetched = await deps.findPendingQuestions(context.userId, {\n ...(isScoped ? { modes: SELF_OWNED_MODES } : {}),\n limit,\n });\n // Defense-in-depth: hosts apply `modes`/`limit` SQL-side; re-apply both\n // here so the clamp holds even when a custom dep ignores the filters.\n const visible = isScoped\n ? fetched.filter((q) => (SELF_OWNED_MODES as string[]).includes(q.mode))\n : fetched;\n const limited = visible.slice(0, limit);\n\n if (isScoped) {\n return success({\n questions: limited,\n scopeRestriction: {\n isScoped: true,\n scopedToIndex: context.indexName ?? context.networkId,\n message:\n `Results exclude negotiation questions because this agent is scoped to ` +\n `\"${context.indexName ?? \"this index\"}\".`,\n },\n });\n }\n\n return success({ questions: limited });\n } catch (err) {\n deps.reportToolError?.(err, {\n operation: \"read-pending-questions\",\n toolName: \"read_pending_questions\",\n userId: context.userId,\n });\n return error(\"Failed to read pending questions.\");\n }\n },\n });\n\n return [readPendingQuestions] as const;\n}\n"]}
@@ -23,6 +23,7 @@ import type { MintConnectLink } from "../interfaces/connect-link.interface.js";
23
23
  import type { QuestionerDatabase } from "../interfaces/questioner.interface.js";
24
24
  import type { QuestionerEnqueueFn } from "../../questioner/questioner.types.js";
25
25
  import type { PendingQuestionSummary } from "../schemas/pending-question.schema.js";
26
+ import type { QuestionMode } from "../schemas/question.schema.js";
26
27
  import type { DiscoveryRunQueue, DiscoveryRunStore } from "../interfaces/discovery-run.interface.js";
27
28
  import type { ProfileRunQueue, ProfileRunStore } from "../interfaces/profile-run.interface.js";
28
29
  export type ProfileContext = ProfileDocument | null;
@@ -323,13 +324,18 @@ export interface ToolDeps {
323
324
  */
324
325
  questionerEnqueue?: QuestionerEnqueueFn;
325
326
  /**
326
- * Lookup pending questions for a user, optionally filtered by source.
327
+ * Lookup pending questions for a user, optionally filtered by source,
328
+ * detection mode, or capped by count (hosts apply `limit` SQL-side).
327
329
  * Used by tools to attach contextually relevant questions to their results.
328
330
  * Injected by the composition root — absent when question delivery is disabled.
329
331
  */
330
332
  findPendingQuestions?: (userId: string, filters?: {
331
333
  sourceType?: string;
332
334
  sourceId?: string;
335
+ /** Restrict to questions whose detection mode is in this set. */
336
+ modes?: QuestionMode[];
337
+ /** Maximum rows to return; hosts should apply this in the query. */
338
+ limit?: number;
333
339
  }) => Promise<PendingQuestionSummary[]>;
334
340
  /** Negotiation-digest summarizer. Optional; consumers fall back to deterministic digests. */
335
341
  negotiationSummary?: NegotiationSummaryReader;
@@ -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,EACV,0BAA0B,EAC1B,iBAAiB,EACjB,UAAU,EACV,YAAY,EACZ,cAAc,EACd,wBAAwB,EACzB,MAAM,qCAAqC,CAAC;AAC7C,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,MAAM,kCAAkC,CAAC;AACzE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,yCAAyC,CAAC;AACjF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,yCAAyC,CAAC;AACjF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,gDAAgD,CAAC;AACxF,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,+CAA+C,CAAC;AAC7F,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,gDAA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IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;YACd,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAChB,CAAC;IACH,CAAC;IAED,OAAO,GAAG,CAAC;AACb,CAAC;AAED,MAAM,oBAAoB,GAAG,IAAI,GAAG,CAAC;IACnC,QAAQ;IACR,eAAe;IACf,UAAU;IACV,QAAQ;IACR,OAAO;IACP,aAAa;IACb,cAAc;IACd,YAAY;IACZ,WAAW;IACX,aAAa;IACb,cAAc;CACf,CAAC,CAAC;AAEH;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,qBAAqB,CAAC,KAAc;IAClD,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAC9D,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACzB,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAC,CAAC;IAC1D,CAAC;IACD,MAAM,GAAG,GAA4B,EAAE,CAAC;IACxC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,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 {\n ChatGraphCompositeDatabase,\n NetworkMembership,\n UserRecord,\n UserDatabase,\n SystemDatabase,\n NegotiationGraphDatabase,\n} 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 { 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 /** Mints a short-lived connect token for opportunity accept links (optional — absent in non-MCP contexts). */\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 /** 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 * 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?: { sourceType?: string; sourceId?: string },\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 /** Mints a short-lived connect token for opportunity accept links (optional — absent in non-MCP contexts). */\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":"AA8PA;;;GAGG;AACH,MAAM,OAAO,sBAAuB,SAAQ,KAAK;IAC/C,YACE,OAAe,EACC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qB,CAAC,KAAc;IAClD,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAC9D,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACzB,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAC,CAAC;IAC1D,CAAC;IACD,MAAM,GAAG,GAA4B,EAAE,CAAC;IACxC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,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 {\n ChatGraphCompositeDatabase,\n NetworkMembership,\n UserRecord,\n UserDatabase,\n SystemDatabase,\n NegotiationGraphDatabase,\n} 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 /** Mints a short-lived connect token for opportunity accept links (optional — absent in non-MCP contexts). */\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 /** 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 /** Mints a short-lived connect token for opportunity accept links (optional — absent in non-MCP contexts). */\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 +1 @@
1
- {"version":3,"file":"tool.registry.d.ts","sourceRoot":"/","sources":["shared/agent/tool.registry.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAmC,QAAQ,EAAqB,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAkBpH;;;;;;;;GAQG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,QAAQ,GAAG,YAAY,CA4D/D"}
1
+ {"version":3,"file":"tool.registry.d.ts","sourceRoot":"/","sources":["shared/agent/tool.registry.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAmC,QAAQ,EAAqB,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAmBpH;;;;;;;;GAQG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,QAAQ,GAAG,YAAY,CA6D/D"}
@@ -10,6 +10,7 @@ import { createAgentTools } from '../../agent/agent.tools.js';
10
10
  import { createNegotiationTools } from '../../negotiation/negotiation.tools.js';
11
11
  import { createChatTools } from '../../chat/chat.tools.js';
12
12
  import { createPremiseTools } from '../../premise/premise.tools.js';
13
+ import { createQuestionerTools } from '../../questioner/questioner.tools.js';
13
14
  import { protocolLogger } from '../observability/protocol.logger.js';
14
15
  import { requestContext } from '../observability/request-context.js';
15
16
  const logger = protocolLogger('ToolRegistry');
@@ -68,6 +69,7 @@ export function createToolRegistry(deps) {
68
69
  createAgentTools(dt, deps);
69
70
  createNegotiationTools(dt, deps);
70
71
  createPremiseTools(dt, deps);
72
+ createQuestionerTools(dt, deps);
71
73
  if (deps.chatSession) {
72
74
  createChatTools(dt, deps);
73
75
  }
@@ -1 +1 @@
1
- {"version":3,"file":"tool.registry.js","sourceRoot":"/","sources":["shared/agent/tool.registry.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AACjE,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACpE,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACpE,OAAO,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AAChF,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AAChF,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACpE,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,EAAE,sBAAsB,EAAE,MA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AC;IAED,MAAM,CAAC,OAAO,CAAC,8BAA8B,QAAQ,CAAC,IAAI,QAAQ,CAAC,CAAC;IACpE,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import { z } from 'zod';\n\nimport type { DefineTool, ResolvedToolContext, ToolDeps, RawToolDefinition, ToolRegistry } from './tool.helpers.js';\nimport { error, redactSensitiveFields } from './tool.helpers.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 { createChatTools } from '../../chat/chat.tools.js';\nimport { createPremiseTools } from '../../premise/premise.tools.js';\nimport { protocolLogger } from '../observability/protocol.logger.js';\nimport { requestContext } from '../observability/request-context.js';\n\nconst logger = protocolLogger('ToolRegistry');\n\n/**\n * Creates a tool registry containing all tool handlers indexed by name.\n * Handlers are raw async functions (not LangChain tool() wrappers) that\n * accept { context, query } and return a JSON string.\n *\n * @param deps - Shared tool dependencies (graphs, database, embedder, etc.)\n * @param context - Resolved user context for this request.\n * @returns Map of tool name to raw tool definition.\n */\nexport function createToolRegistry(deps: ToolDeps): ToolRegistry {\n const registry: ToolRegistry = new Map();\n\n // defineTool that captures raw handlers into the registry\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 const entry: RawToolDefinition = {\n name: opts.name,\n description: opts.description,\n schema: opts.querySchema,\n handler: async (input: { context: ResolvedToolContext; query: unknown }) => {\n logger.verbose(`Tool: ${opts.name}`, {\n context: { userId: input.context.userId, networkId: input.context.networkId },\n query: redactSensitiveFields(input.query),\n });\n try {\n return await opts.handler({ context: input.context, query: input.query as z.infer<T> });\n } catch (err) {\n const abortSignal = requestContext.getStore()?.abortSignal;\n if (abortSignal?.aborted) {\n throw err;\n }\n logger.error(`${opts.name} failed`, {\n error: err instanceof Error ? err.message : String(err),\n });\n return error(`Failed to execute ${opts.name}: ${err instanceof Error ? err.message : String(err)}`);\n }\n },\n };\n\n registry.set(opts.name, entry);\n\n // Return a dummy — create*Tools functions collect return values into arrays,\n // but for the registry path we only need the side-effect on the Map.\n return null as unknown;\n }\n\n // Create all tool domains -- each one calls defineTool() which populates the registry.\n // The local defineTool is compatible with DefineTool (which returns any).\n const dt = defineTool as DefineTool;\n createProfileTools(dt, deps);\n createIntentTools(dt, deps);\n createNetworkTools(dt, deps);\n createOpportunityTools(dt, deps);\n createUtilityTools(dt, deps);\n createIntegrationTools(dt, deps);\n createContactTools(dt, deps);\n createAgentTools(dt, deps);\n createNegotiationTools(dt, deps);\n createPremiseTools(dt, deps);\n if (deps.chatSession) {\n createChatTools(dt, deps);\n }\n\n logger.verbose(`Tool registry created with ${registry.size} tools`);\n return registry;\n}\n"]}
1
+ {"version":3,"file":"tool.registry.js","sourceRoot":"/","sources":["shared/agent/tool.registry.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AACjE,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACpE,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACpE,OAAO,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AAChF,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AAChF,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACpE,OAAO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,EAAE,EAAE,IAAI,CAAC,CAAC;IAC7B,qBAAqB,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;IAChC,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC;QACrB,eAAe,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;IAC5B,CAAC;IAED,MAAM,CAAC,OAAO,CAAC,8BAA8B,QAAQ,CAAC,IAAI,QAAQ,CAAC,CAAC;IACpE,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import { z } from 'zod';\n\nimport type { DefineTool, ResolvedToolContext, ToolDeps, RawToolDefinition, ToolRegistry } from './tool.helpers.js';\nimport { error, redactSensitiveFields } from './tool.helpers.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 { createChatTools } from '../../chat/chat.tools.js';\nimport { createPremiseTools } from '../../premise/premise.tools.js';\nimport { createQuestionerTools } from '../../questioner/questioner.tools.js';\nimport { protocolLogger } from '../observability/protocol.logger.js';\nimport { requestContext } from '../observability/request-context.js';\n\nconst logger = protocolLogger('ToolRegistry');\n\n/**\n * Creates a tool registry containing all tool handlers indexed by name.\n * Handlers are raw async functions (not LangChain tool() wrappers) that\n * accept { context, query } and return a JSON string.\n *\n * @param deps - Shared tool dependencies (graphs, database, embedder, etc.)\n * @param context - Resolved user context for this request.\n * @returns Map of tool name to raw tool definition.\n */\nexport function createToolRegistry(deps: ToolDeps): ToolRegistry {\n const registry: ToolRegistry = new Map();\n\n // defineTool that captures raw handlers into the registry\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 const entry: RawToolDefinition = {\n name: opts.name,\n description: opts.description,\n schema: opts.querySchema,\n handler: async (input: { context: ResolvedToolContext; query: unknown }) => {\n logger.verbose(`Tool: ${opts.name}`, {\n context: { userId: input.context.userId, networkId: input.context.networkId },\n query: redactSensitiveFields(input.query),\n });\n try {\n return await opts.handler({ context: input.context, query: input.query as z.infer<T> });\n } catch (err) {\n const abortSignal = requestContext.getStore()?.abortSignal;\n if (abortSignal?.aborted) {\n throw err;\n }\n logger.error(`${opts.name} failed`, {\n error: err instanceof Error ? err.message : String(err),\n });\n return error(`Failed to execute ${opts.name}: ${err instanceof Error ? err.message : String(err)}`);\n }\n },\n };\n\n registry.set(opts.name, entry);\n\n // Return a dummy — create*Tools functions collect return values into arrays,\n // but for the registry path we only need the side-effect on the Map.\n return null as unknown;\n }\n\n // Create all tool domains -- each one calls defineTool() which populates the registry.\n // The local defineTool is compatible with DefineTool (which returns any).\n const dt = defineTool as DefineTool;\n createProfileTools(dt, deps);\n createIntentTools(dt, deps);\n createNetworkTools(dt, deps);\n createOpportunityTools(dt, deps);\n createUtilityTools(dt, deps);\n createIntegrationTools(dt, deps);\n createContactTools(dt, deps);\n createAgentTools(dt, deps);\n createNegotiationTools(dt, deps);\n createPremiseTools(dt, deps);\n createQuestionerTools(dt, deps);\n if (deps.chatSession) {\n createChatTools(dt, deps);\n }\n\n logger.verbose(`Tool registry created with ${registry.size} tools`);\n return registry;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@indexnetwork/protocol",
3
- "version": "3.4.0-rc.254.1",
3
+ "version": "3.6.0-rc.256.1",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",