@indexnetwork/protocol 4.1.1 → 4.1.2-rc.293.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":"enrichment.tools.d.ts","sourceRoot":"/","sources":["enrichment/enrichment.tools.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,UAAU,EAAuB,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AAgCjG,wBAAgB,qBAAqB,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,0DAmtC3E"}
1
+ {"version":3,"file":"enrichment.tools.d.ts","sourceRoot":"/","sources":["enrichment/enrichment.tools.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,UAAU,EAAuB,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AAgCjG,wBAAgB,qBAAqB,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,0DA+tC3E"}
@@ -729,16 +729,28 @@ export function createEnrichmentTools(defineTool, deps) {
729
729
  logger.verbose("Persisted user-info fields to user record", { userId: context.userId });
730
730
  const isOnboarding = !(context.user.onboarding?.completedAt);
731
731
  if (isOnboarding) {
732
- const existingProfile = await userDb.getProfile();
733
- if (existingProfile) {
732
+ // "Already enriched?" must key on a real enrichment signal, not getProfile():
733
+ // post-WS11 getProfile() returns a presentation row for EVERY existing user, so
734
+ // it would always short-circuit onboarding and refuse to enrich. The global
735
+ // user_context is the canonical signal (non-empty <=> the user has premises /
736
+ // has been enriched), mirroring findWithGraph's `hasProfile`.
737
+ const existingContext = getUserContextText
738
+ ? (await getUserContextText(context.userId)).trim()
739
+ : '';
740
+ if (existingContext) {
741
+ const existingProfile = await userDb.getProfile();
734
742
  return success({
735
743
  alreadyExists: true,
736
744
  message: "Profile already exists. If the user confirmed it, call complete_onboarding() to finish setup. If they want changes, use create_user_context(bioOrDescription=\"...\", confirm=true).",
737
- profile: {
738
- name: existingProfile.identity.name,
739
- bio: existingProfile.identity.bio,
740
- location: existingProfile.identity.location,
741
- },
745
+ ...(existingProfile
746
+ ? {
747
+ profile: {
748
+ name: existingProfile.identity.name,
749
+ bio: existingProfile.identity.bio,
750
+ location: existingProfile.identity.location,
751
+ },
752
+ }
753
+ : {}),
742
754
  });
743
755
  }
744
756
  // Preview mode: enrich and persist enrichment results, but don't generate full profile
@@ -1 +1 @@
1
- {"version":3,"file":"enrichment.tools.js","sourceRoot":"/","sources":["enrichment/enrichment.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,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAExE,MAAM,MAAM,GAAG,cAAc,CAAC,sBAAsB,CAAC,CAAC;AAEtD,SAAS,sBAAsB,CAAC,UAAmC;IACjE,OAAO,CAAC,CAAC,UAAU;QACjB,UAAU,CAAC,cAAc;QACzB,CACE,UAAU,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC;YACzC,UAAU,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC;YAC9C,UAAU,CAAC,UAAU,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC;YACvC,UAAU,CAAC,UAAU,CAAC,SAAS,CAAC,MAAM,GAAG,CAA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iBAAiB,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,kBAAkB,CAAU,CAAC;AAC9M,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 { EnrichmentRunInput, EnrichmentRunOperation } from \"../shared/interfaces/enrichment-run.interface.js\";\nimport { socialsToEnrichmentRequest, detectSocialLabel } from \"../shared/utils/social-label.js\";\nimport { normalizeTelegramHandle } from \"../shared/utils/telegram-handle.js\";\nimport { EnrichmentGenerator } from \"./enrichment.generator.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\n\nconst logger = protocolLogger(\"ChatTools:Enrichment\");\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 createEnrichmentTools(defineTool: DefineTool, deps: ToolDeps) {\n const { userDb, systemDb, graphs, enricher, grantDefaultSystemPermissions, reportToolError, getUserContextText } = 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 enqueueEnrichmentRun(\n context: ResolvedToolContext,\n operation: EnrichmentRunOperation,\n input: EnrichmentRunInput,\n ): Promise<string | null> {\n if (!context.isMcp || !deps.enrichmentRuns || !deps.enrichmentRunQueue) return null;\n const run = await deps.enrichmentRuns.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.enrichmentRunQueue.enqueue(run.id);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n await deps.enrichmentRuns.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: \"enrichment\" });\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_context\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: 'enrichment',\n operation: 'profile.confirm_draft_decompose',\n toolName: 'confirm_user_context',\n userId: profile.userId,\n tags: { toolName: 'confirm_user_context', 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: 'enrichment',\n operation: 'profile.confirm_draft_decompose',\n toolName: 'confirm_user_context',\n userId: profile.userId,\n tags: { toolName: 'confirm_user_context', execution: 'background' },\n });\n } finally {\n traceEmitter?.({ type: \"graph_end\", name: \"enrichment\", durationMs: Date.now() - graphStart });\n }\n }\n\n const readUserContexts = defineTool({\n name: \"read_user_contexts\",\n description:\n \"Retrieves user profiles containing identity info (name, bio, location) plus a rich `context` paragraph (the user's synthesized identity text). \" +\n \"Profiles are used for semantic matching in opportunity discovery — the richer the user's context, the better the 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. (List results return thin identity only — no `context`.)\\n\" +\n \"- With `userId`: returns that specific user's profile — name, bio, location, and their `context` paragraph.\\n\" +\n \"- With `networkId` alone: returns thin-identity profiles of ALL members in that index (no `context`).\\n\" +\n \"- No parameters: returns the current user's own profile, including their `context`.\\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_context. \" +\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, and (for single-user reads) a `context` paragraph. 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 // Flat thin identity for list results. skills/interests are retired; the\n // rich identity text (global user_context) is fetched per-user via a userId read.\n return {\n userId: m.userId,\n name: m.name,\n hasProfile: !!profile,\n ...(profile\n ? { bio: profile.identity.bio, location: profile.identity.location }\n : {}),\n };\n } catch (err) {\n logger.warn(\"read_user_contexts: 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 // Flat thin identity for roster results. skills/interests are retired; fetch a\n // member's global user_context text via a single-user (userId) read.\n return {\n userId: member.userId,\n name: member.name,\n hasProfile: !!profile,\n ...(profile\n ? { bio: profile.identity.bio, location: profile.identity.location }\n : {}),\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 // Thin identity + the user's global user_context text (profile-replacing\n // identity paragraph). skills/interests/narrative are retired (WS6).\n const context = getUserContextText ? await getUserContextText(targetUserId) : '';\n return success({\n hasProfile: true,\n name: profile.identity.name,\n bio: profile.identity.bio,\n location: profile.identity.location,\n context,\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: \"enrichment\" });\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: \"enrichment\", 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 // Augment the graph's thin-identity readResult with the caller's global\n // user_context text (the rich, profile-replacing identity paragraph).\n const readResult = result.readResult as { hasProfile?: boolean; profile?: Record<string, unknown>; message?: string };\n // Flatten identity fields up; drop the nested `profile` object (WS11).\n const flat = readResult.hasProfile && readResult.profile\n ? { hasProfile: true, ...readResult.profile, context: getUserContextText ? await getUserContextText(context.userId) : '' }\n : { ...readResult };\n return success({ ...flat, ...onboardingFields, _graphTimings: [{ name: 'enrichment', durationMs: _readProfileGraphMs, agents: result.agentTimings ?? [] }] });\n }\n if (result.profile) {\n return success({\n hasProfile: true,\n name: result.profile.identity.name,\n bio: result.profile.identity.bio,\n location: result.profile.identity.location,\n context: getUserContextText ? await getUserContextText(context.userId) : '',\n ...onboardingFields,\n _graphTimings: [{ name: 'enrichment', 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: 'enrichment', 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 previewUserContext = defineTool({\n name: \"preview_user_context\",\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_enrichment_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 enqueueEnrichmentRun(context, \"preview_user_context\", query);\n if (profileRunId) {\n return success({\n status: \"queued\" as const,\n profileRunId,\n message: `Profile preview started. Call get_enrichment_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 EnrichmentGenerator().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_context.\",\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 confirmUserContext = defineTool({\n name: \"confirm_user_context\",\n description:\n \"Saves an explicitly approved onboarding profile draft. Call this only after the user has seen the draft from preview_user_context 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_context 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({ userId: context.userId, identity: profile.identity, context: profile.narrative?.context ?? '' });\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: \"enrichment\" });\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: \"enrichment\", 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 createUserContext = defineTool({\n name: \"create_user_context\",\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_context → confirm_user_context 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_context 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), 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_context(bioOrDescription=\\\"...\\\", confirm=true).\",\n profile: {\n name: existingProfile.identity.name,\n bio: existingProfile.identity.bio,\n location: existingProfile.identity.location,\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_context(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: \"enrichment\" });\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: \"enrichment\", 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: 'enrichment', 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 EnrichmentGenerator 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: \"enrichment\" });\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: \"enrichment\", 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: 'enrichment', 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: 'enrichment', 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: \"enrichment\" });\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: \"enrichment\", 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: 'enrichment', durationMs: _generateProfileGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n\n return error(\"Failed to create profile. Please try again.\");\n },\n });\n\n const updateUserContext = defineTool({\n name: \"update_user_context\",\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_context 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_contexts. 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 enqueueEnrichmentRun(context, \"update_user_context\", query);\n if (profileRunId) {\n return success({\n status: \"queued\" as const,\n profileRunId,\n message: `Profile update started. Call get_enrichment_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: \"enrichment\" });\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: \"enrichment\", durationMs: _updateQueryProfileGraphMs });\n if (!queryResult.readResult?.hasProfile && !queryResult.profile) {\n return error(\"You don't have a profile yet. Use create_user_context 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_contexts.\");\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: \"enrichment\" });\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: \"enrichment\",\n operation: \"profile.update_background\",\n toolName: \"update_user_context\",\n userId: context.userId,\n tags: { toolName: \"update_user_context\", 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: \"enrichment\",\n operation: \"profile.update_background\",\n toolName: \"update_user_context\",\n userId: context.userId,\n tags: { toolName: \"update_user_context\", execution: \"background\" },\n context: { profileId: existingProfileId ?? providedProfileId },\n });\n }).finally(() => {\n const _backgroundWriteProfileGraphMs = Date.now() - _backgroundWriteProfileGraphStart;\n _backgroundWriteProfileTraceEmitter?.({ type: \"graph_end\", name: \"enrichment\", 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: 'enrichment', 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: \"enrichment\" });\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: \"enrichment\", durationMs: _updateWriteProfileGraphMs });\n if (_writeResult.error) {\n return error(_writeResult.error);\n }\n return success({\n message: \"Profile updated.\",\n _graphTimings: [\n { name: 'enrichment', durationMs: _updateQueryProfileGraphMs, agents: queryResult.agentTimings ?? [] },\n { name: 'enrichment', durationMs: _updateWriteProfileGraphMs, agents: _writeResult.agentTimings ?? [] },\n ],\n });\n },\n });\n\n const getEnrichmentRun = defineTool({\n name: \"get_enrichment_run\",\n description:\n \"Checks the status of an async profile preview/update run started by preview_user_context or update_user_context 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_context or update_user_context.\"),\n }),\n handler: async ({ context, query }) => {\n if (!deps.enrichmentRuns) {\n return error(\"Profile run polling is not available in this environment.\");\n }\n const run = await deps.enrichmentRuns.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 cancelEnrichmentRun = defineTool({\n name: \"cancel_enrichment_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_context or update_user_context.\"),\n }),\n handler: async ({ context, query }) => {\n if (!deps.enrichmentRuns || !deps.enrichmentRunQueue) {\n return error(\"Profile run cancellation is not available in this environment.\");\n }\n const existing = await deps.enrichmentRuns.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.enrichmentRuns.requestCancel(query.profileRunId, context.userId);\n if (!run) return error(\"Profile run not found or cannot be cancelled.\");\n const removed = await deps.enrichmentRunQueue.cancel(run.id);\n if (removed) {\n await deps.enrichmentRuns.markCancelled(run.id, \"cancelled before worker start\");\n }\n const updated = await deps.enrichmentRuns.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 confirmed profile AND at least one active intent/signal. The profile must be shown to the user and explicitly approved \" +\n \"(said 'yes', 'looks good', 'that's right', or similar). The first signal must be persisted before this tool is called; MCP/onboarding agents should call create_intent(..., autoApprove=true).\\n\\n\" +\n \"**What happens:** Validates that the confirmed profile and first active intent exist, then sets completedAt timestamp on the user's onboarding record.\\n\\n\" +\n \"**Workflow:** create_user_context() -> user confirms preview -> create_user_context(confirm=true) -> create_intent(..., autoApprove=true) -> 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\n const confirmedProfile = await userDb.getProfile();\n if (!confirmedProfile) {\n return error(\"Onboarding cannot be completed until the user has a confirmed profile. Show the profile draft, get explicit approval, then save it before finishing onboarding.\");\n }\n\n const activeIntents = await userDb.getActiveIntents();\n if (activeIntents.length === 0) {\n return error(\"Onboarding cannot be completed until the user has at least one active intent. Ask what they are open to right now and create the first signal before finishing onboarding.\");\n }\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 [readUserContexts, recordOnboardingPrivacyConsent, previewUserContext, confirmUserContext, createUserContext, updateUserContext, getEnrichmentRun, cancelEnrichmentRun, completeOnboarding] as const;\n}\n"]}
1
+ {"version":3,"file":"enrichment.tools.js","sourceRoot":"/","sources":["enrichment/enrichment.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,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAExE,MAAM,MAAM,GAAG,cAAc,CAAC,sBAAsB,CAAC,CAAC;AAEtD,SAAS,sBAAsB,CAAC,UAAmC;IACjE,OAAO,CAAC,CAAC,UAAU;QACjB,UAAU,CAAC,cAAc;QACzB,CACE,UAAU,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC;YACzC,UAAU,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC;YAC9C,UAAU,CAAC,UAAU,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC;YACvC,UAAU,CAAC,UAAU,CAAC,SAAS,CA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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,gBAAgB,EAAE,mBAAmB,EAAE,kBAAkB,CAAU,CAAC;AAC9M,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 { EnrichmentRunInput, EnrichmentRunOperation } from \"../shared/interfaces/enrichment-run.interface.js\";\nimport { socialsToEnrichmentRequest, detectSocialLabel } from \"../shared/utils/social-label.js\";\nimport { normalizeTelegramHandle } from \"../shared/utils/telegram-handle.js\";\nimport { EnrichmentGenerator } from \"./enrichment.generator.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\n\nconst logger = protocolLogger(\"ChatTools:Enrichment\");\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 createEnrichmentTools(defineTool: DefineTool, deps: ToolDeps) {\n const { userDb, systemDb, graphs, enricher, grantDefaultSystemPermissions, reportToolError, getUserContextText } = 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 enqueueEnrichmentRun(\n context: ResolvedToolContext,\n operation: EnrichmentRunOperation,\n input: EnrichmentRunInput,\n ): Promise<string | null> {\n if (!context.isMcp || !deps.enrichmentRuns || !deps.enrichmentRunQueue) return null;\n const run = await deps.enrichmentRuns.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.enrichmentRunQueue.enqueue(run.id);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n await deps.enrichmentRuns.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: \"enrichment\" });\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_context\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: 'enrichment',\n operation: 'profile.confirm_draft_decompose',\n toolName: 'confirm_user_context',\n userId: profile.userId,\n tags: { toolName: 'confirm_user_context', 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: 'enrichment',\n operation: 'profile.confirm_draft_decompose',\n toolName: 'confirm_user_context',\n userId: profile.userId,\n tags: { toolName: 'confirm_user_context', execution: 'background' },\n });\n } finally {\n traceEmitter?.({ type: \"graph_end\", name: \"enrichment\", durationMs: Date.now() - graphStart });\n }\n }\n\n const readUserContexts = defineTool({\n name: \"read_user_contexts\",\n description:\n \"Retrieves user profiles containing identity info (name, bio, location) plus a rich `context` paragraph (the user's synthesized identity text). \" +\n \"Profiles are used for semantic matching in opportunity discovery — the richer the user's context, the better the 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. (List results return thin identity only — no `context`.)\\n\" +\n \"- With `userId`: returns that specific user's profile — name, bio, location, and their `context` paragraph.\\n\" +\n \"- With `networkId` alone: returns thin-identity profiles of ALL members in that index (no `context`).\\n\" +\n \"- No parameters: returns the current user's own profile, including their `context`.\\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_context. \" +\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, and (for single-user reads) a `context` paragraph. 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 // Flat thin identity for list results. skills/interests are retired; the\n // rich identity text (global user_context) is fetched per-user via a userId read.\n return {\n userId: m.userId,\n name: m.name,\n hasProfile: !!profile,\n ...(profile\n ? { bio: profile.identity.bio, location: profile.identity.location }\n : {}),\n };\n } catch (err) {\n logger.warn(\"read_user_contexts: 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 // Flat thin identity for roster results. skills/interests are retired; fetch a\n // member's global user_context text via a single-user (userId) read.\n return {\n userId: member.userId,\n name: member.name,\n hasProfile: !!profile,\n ...(profile\n ? { bio: profile.identity.bio, location: profile.identity.location }\n : {}),\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 // Thin identity + the user's global user_context text (profile-replacing\n // identity paragraph). skills/interests/narrative are retired (WS6).\n const context = getUserContextText ? await getUserContextText(targetUserId) : '';\n return success({\n hasProfile: true,\n name: profile.identity.name,\n bio: profile.identity.bio,\n location: profile.identity.location,\n context,\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: \"enrichment\" });\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: \"enrichment\", 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 // Augment the graph's thin-identity readResult with the caller's global\n // user_context text (the rich, profile-replacing identity paragraph).\n const readResult = result.readResult as { hasProfile?: boolean; profile?: Record<string, unknown>; message?: string };\n // Flatten identity fields up; drop the nested `profile` object (WS11).\n const flat = readResult.hasProfile && readResult.profile\n ? { hasProfile: true, ...readResult.profile, context: getUserContextText ? await getUserContextText(context.userId) : '' }\n : { ...readResult };\n return success({ ...flat, ...onboardingFields, _graphTimings: [{ name: 'enrichment', durationMs: _readProfileGraphMs, agents: result.agentTimings ?? [] }] });\n }\n if (result.profile) {\n return success({\n hasProfile: true,\n name: result.profile.identity.name,\n bio: result.profile.identity.bio,\n location: result.profile.identity.location,\n context: getUserContextText ? await getUserContextText(context.userId) : '',\n ...onboardingFields,\n _graphTimings: [{ name: 'enrichment', 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: 'enrichment', 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 previewUserContext = defineTool({\n name: \"preview_user_context\",\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_enrichment_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 enqueueEnrichmentRun(context, \"preview_user_context\", query);\n if (profileRunId) {\n return success({\n status: \"queued\" as const,\n profileRunId,\n message: `Profile preview started. Call get_enrichment_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 EnrichmentGenerator().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_context.\",\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 confirmUserContext = defineTool({\n name: \"confirm_user_context\",\n description:\n \"Saves an explicitly approved onboarding profile draft. Call this only after the user has seen the draft from preview_user_context 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_context 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({ userId: context.userId, identity: profile.identity, context: profile.narrative?.context ?? '' });\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: \"enrichment\" });\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: \"enrichment\", 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 createUserContext = defineTool({\n name: \"create_user_context\",\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_context → confirm_user_context 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_context 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), 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 // \"Already enriched?\" must key on a real enrichment signal, not getProfile():\n // post-WS11 getProfile() returns a presentation row for EVERY existing user, so\n // it would always short-circuit onboarding and refuse to enrich. The global\n // user_context is the canonical signal (non-empty <=> the user has premises /\n // has been enriched), mirroring findWithGraph's `hasProfile`.\n const existingContext = getUserContextText\n ? (await getUserContextText(context.userId)).trim()\n : '';\n if (existingContext) {\n const existingProfile = await userDb.getProfile();\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_context(bioOrDescription=\\\"...\\\", confirm=true).\",\n ...(existingProfile\n ? {\n profile: {\n name: existingProfile.identity.name,\n bio: existingProfile.identity.bio,\n location: existingProfile.identity.location,\n },\n }\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_context(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: \"enrichment\" });\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: \"enrichment\", 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: 'enrichment', 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 EnrichmentGenerator 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: \"enrichment\" });\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: \"enrichment\", 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: 'enrichment', 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: 'enrichment', 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: \"enrichment\" });\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: \"enrichment\", 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: 'enrichment', durationMs: _generateProfileGraphMs, agents: result.agentTimings ?? [] }],\n });\n }\n\n return error(\"Failed to create profile. Please try again.\");\n },\n });\n\n const updateUserContext = defineTool({\n name: \"update_user_context\",\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_context 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_contexts. 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 enqueueEnrichmentRun(context, \"update_user_context\", query);\n if (profileRunId) {\n return success({\n status: \"queued\" as const,\n profileRunId,\n message: `Profile update started. Call get_enrichment_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: \"enrichment\" });\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: \"enrichment\", durationMs: _updateQueryProfileGraphMs });\n if (!queryResult.readResult?.hasProfile && !queryResult.profile) {\n return error(\"You don't have a profile yet. Use create_user_context 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_contexts.\");\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: \"enrichment\" });\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: \"enrichment\",\n operation: \"profile.update_background\",\n toolName: \"update_user_context\",\n userId: context.userId,\n tags: { toolName: \"update_user_context\", 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: \"enrichment\",\n operation: \"profile.update_background\",\n toolName: \"update_user_context\",\n userId: context.userId,\n tags: { toolName: \"update_user_context\", execution: \"background\" },\n context: { profileId: existingProfileId ?? providedProfileId },\n });\n }).finally(() => {\n const _backgroundWriteProfileGraphMs = Date.now() - _backgroundWriteProfileGraphStart;\n _backgroundWriteProfileTraceEmitter?.({ type: \"graph_end\", name: \"enrichment\", 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: 'enrichment', 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: \"enrichment\" });\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: \"enrichment\", durationMs: _updateWriteProfileGraphMs });\n if (_writeResult.error) {\n return error(_writeResult.error);\n }\n return success({\n message: \"Profile updated.\",\n _graphTimings: [\n { name: 'enrichment', durationMs: _updateQueryProfileGraphMs, agents: queryResult.agentTimings ?? [] },\n { name: 'enrichment', durationMs: _updateWriteProfileGraphMs, agents: _writeResult.agentTimings ?? [] },\n ],\n });\n },\n });\n\n const getEnrichmentRun = defineTool({\n name: \"get_enrichment_run\",\n description:\n \"Checks the status of an async profile preview/update run started by preview_user_context or update_user_context 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_context or update_user_context.\"),\n }),\n handler: async ({ context, query }) => {\n if (!deps.enrichmentRuns) {\n return error(\"Profile run polling is not available in this environment.\");\n }\n const run = await deps.enrichmentRuns.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 cancelEnrichmentRun = defineTool({\n name: \"cancel_enrichment_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_context or update_user_context.\"),\n }),\n handler: async ({ context, query }) => {\n if (!deps.enrichmentRuns || !deps.enrichmentRunQueue) {\n return error(\"Profile run cancellation is not available in this environment.\");\n }\n const existing = await deps.enrichmentRuns.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.enrichmentRuns.requestCancel(query.profileRunId, context.userId);\n if (!run) return error(\"Profile run not found or cannot be cancelled.\");\n const removed = await deps.enrichmentRunQueue.cancel(run.id);\n if (removed) {\n await deps.enrichmentRuns.markCancelled(run.id, \"cancelled before worker start\");\n }\n const updated = await deps.enrichmentRuns.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 confirmed profile AND at least one active intent/signal. The profile must be shown to the user and explicitly approved \" +\n \"(said 'yes', 'looks good', 'that's right', or similar). The first signal must be persisted before this tool is called; MCP/onboarding agents should call create_intent(..., autoApprove=true).\\n\\n\" +\n \"**What happens:** Validates that the confirmed profile and first active intent exist, then sets completedAt timestamp on the user's onboarding record.\\n\\n\" +\n \"**Workflow:** create_user_context() -> user confirms preview -> create_user_context(confirm=true) -> create_intent(..., autoApprove=true) -> 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\n const confirmedProfile = await userDb.getProfile();\n if (!confirmedProfile) {\n return error(\"Onboarding cannot be completed until the user has a confirmed profile. Show the profile draft, get explicit approval, then save it before finishing onboarding.\");\n }\n\n const activeIntents = await userDb.getActiveIntents();\n if (activeIntents.length === 0) {\n return error(\"Onboarding cannot be completed until the user has at least one active intent. Ask what they are open to right now and create the first signal before finishing onboarding.\");\n }\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 [readUserContexts, recordOnboardingPrivacyConsent, previewUserContext, confirmUserContext, createUserContext, updateUserContext, getEnrichmentRun, cancelEnrichmentRun, completeOnboarding] as const;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@indexnetwork/protocol",
3
- "version": "4.1.1",
3
+ "version": "4.1.2-rc.293.1",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",