@indexnetwork/protocol 6.6.0-rc.386.1 → 6.6.2-rc.388.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1 -0
- package/dist/chat/chat.agent.d.ts +6 -0
- package/dist/chat/chat.agent.d.ts.map +1 -1
- package/dist/chat/chat.agent.js +119 -0
- package/dist/chat/chat.agent.js.map +1 -1
- package/dist/chat/chat.persona.d.ts +5 -0
- package/dist/chat/chat.persona.d.ts.map +1 -1
- package/dist/chat/chat.persona.js.map +1 -1
- package/dist/chat/chat.prompt.modules.d.ts +2 -0
- package/dist/chat/chat.prompt.modules.d.ts.map +1 -1
- package/dist/chat/chat.prompt.modules.js.map +1 -1
- package/dist/chat/reporter.persona.d.ts.map +1 -1
- package/dist/chat/reporter.persona.js +2 -1
- package/dist/chat/reporter.persona.js.map +1 -1
- package/dist/chat/reporter.prompt.d.ts +4 -0
- package/dist/chat/reporter.prompt.d.ts.map +1 -1
- package/dist/chat/reporter.prompt.js +39 -5
- package/dist/chat/reporter.prompt.js.map +1 -1
- package/dist/opportunity/discriminator/discriminator.adjustments.js +1 -1
- package/dist/opportunity/discriminator/discriminator.adjustments.js.map +1 -1
- package/dist/opportunity/opportunity.safe-presentation.d.ts +1 -1
- package/dist/opportunity/opportunity.safe-presentation.js +1 -1
- package/dist/opportunity/opportunity.safe-presentation.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat.prompt.modules.js","sourceRoot":"/","sources":["chat/chat.prompt.modules.ts"],"names":[],"mappings":"AAsCA,kFAAkF;AAClF,aAAa;AACb,kFAAkF;AAElF;;;;;;;;;GASG;AACH,MAAM,UAAU,sBAAsB,CACpC,QAAuB;IAEvB,0CAA0C;IAC1C,IAAI,YAAY,GAAG,CAAC,CAAC,CAAC;IACtB,KAAK,IAAI,CAAC,GAAG,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,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AAI,GAAG,CAAC,QAAQ,EAAE,CAAC;YACjB,KAAK,MAAM,UAAU,IAAI,GAAG,CAAC,QAAQ,EAAE,CAAC;gBACtC,IAAI,UAAU,KAAK,GAAG,CAAC,EAAE,EAAE,CAAC;oBAC1B,UAAU,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;gBAChC,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;IAED,eAAe;IACf,MAAM,QAAQ,GAAa,EAAE,CAAC;IAC9B,KAAK,MAAM,GAAG,IAAI,UAAU,CAAC,MAAM,EAAE,EAAE,CAAC;QACtC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC;IAC1C,CAAC;IACD,OAAO,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC7B,CAAC","sourcesContent":["import type { BaseMessage, AIMessage } from \"@langchain/core/messages\";\n\nimport type { ResolvedToolContext } from \"../shared/agent/tool.factory.js\";\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TYPES\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * A conditional prompt section injected into the system prompt based on triggers.\n */\nexport interface PromptModule {\n /** Unique module identifier. */\n id: string;\n /** Tool names that activate this module. */\n triggers: string[];\n /** Module IDs to suppress when this module activates (unidirectional). */\n excludes?: string[];\n /** Optional filter applied after tool trigger match. Return false to skip despite trigger match. */\n triggerFilter?: (iterCtx: IterationContext) => boolean;\n /** User message pattern that activates this module (secondary trigger). */\n regex?: RegExp;\n /** Returns the prompt text to inject. */\n content: (ctx: ResolvedToolContext) => string;\n}\n\n/**\n * State available to module resolution at each iteration.\n */\nexport interface IterationContext {\n /** Tool calls from all iterations since the last user message. */\n recentTools: Array<{ name: string; args: Record<string, unknown> }>;\n /** Text of the latest user message (for regex matching). */\n currentMessage?: string;\n /** Resolved tool context (user, profile, indexes, etc.). */\n ctx: ResolvedToolContext;\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// EXTRACTION\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Extracts tool calls from all AI messages since the last HumanMessage.\n *\n * Scans backwards to find the last HumanMessage, then collects all tool calls\n * from AIMessages after that point. This ensures multi-iteration tool history\n * is available for module resolution within a single user turn.\n *\n * @param messages - The current conversation message array\n * @returns Flattened array of tool name + args from the current agent turn\n */\nexport function extractRecentToolCalls(\n messages: BaseMessage[],\n): Array<{ name: string; args: Record<string, unknown> }> {\n // Find the index of the last HumanMessage\n let lastHumanIdx = -1;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]._getType() === \"human\") {\n lastHumanIdx = i;\n break;\n }\n }\n\n // Collect tool calls from all AIMessages after the last HumanMessage\n const toolCalls: Array<{ name: string; args: Record<string, unknown> }> = [];\n const startIdx = lastHumanIdx + 1;\n\n for (let i = startIdx; i < messages.length; i++) {\n const msg = messages[i];\n if (msg._getType() === \"ai\") {\n const aiMsg = msg as AIMessage;\n const calls = aiMsg.tool_calls ?? [];\n for (const tc of calls) {\n toolCalls.push({\n name: tc.name,\n args: (tc.args ?? {}) as Record<string, unknown>,\n });\n }\n }\n }\n\n return toolCalls;\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// HELPERS\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Checks whether recent tool calls include discover_opportunities with\n * introduction-specific arguments (partyUserIds or introTargetUserId).\n */\nfunction hasIntroductionArgs(recentTools: IterationContext[\"recentTools\"]): boolean {\n return recentTools.some(\n (t) =>\n t.name === \"discover_opportunities\" &&\n (t.args.partyUserIds || t.args.introTargetUserId),\n );\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// MODULE DEFINITIONS\n// ═══════════════════════════════════════════════════════════════════════════════\n\nconst discoveryModule: PromptModule = {\n id: \"discovery\",\n triggers: [\"discover_opportunities\", \"update_opportunity\", \"list_opportunities\"],\n triggerFilter: (iterCtx) => !hasIntroductionArgs(iterCtx.recentTools),\n content: () => `\n### 1. User wants to find connections or discover (default for connection-seeking)\n\nFor open-ended connection-seeking (\"find me a mentor\", \"who needs a React dev\", \"I want to meet people in AI\", \"looking for investors\", \"find me X\"), run **discovery first**.\n\n**CRITICAL: DO NOT create an intent first. Discovery comes FIRST.**\n\n**Network scoping**: When the user says \"in my network\", \"from my contacts\", \"people I know\", \"among my connections\", or similar network-scoping language, pass the user's **personal network ID** as \\`networkId\\`. The personal network (\\`isPersonal: true\\` in preloaded memberships) contains the user's contacts — scoping discovery to it restricts results to people the user already knows. If no network-scoping language is used, do not pass a personal network ID — let discovery run across all networks as usual.\n\n- Call \\`discover_opportunities(searchQuery=user's request)\\` IMMEDIATELY (with networkId when scoped).\n- Do NOT call \\`create_intent\\` unless the user **explicitly** asks to \"create\", \"save\", \"add\", or \"remember\" an intent/signal.\n- Phrases like \"looking for X\", \"find me X\", \"I want to meet X\", \"I need X\" are discovery requests — NOT intent creation requests.\n- If the tool returns \\`createIntentSuggested\\` and \\`suggestedIntentDescription\\`, the system will create an intent and retry discovery automatically; use the final result (candidates or \"no matches\") for your reply.\n- If the tool returns \\`suggestIntentCreationForVisibility: true\\` and \\`suggestedIntentDescription\\`, after presenting the opportunity cards ask the user whether they'd also like to create a signal so others can find them (e.g. *\"Would you also like to create a signal for this so others can find you?\"*). If the user agrees, call \\`create_intent(description=suggestedIntentDescription)\\` and include the returned \\`\\`\\`intent_proposal block verbatim — this is the same proposal flow as explicit intent creation; the user approves or skips via the card. Ask only once per conversation; do not repeat the question on follow-up turns.\n- When the tool indicates all results are exhausted (no remaining candidates), do NOT offer to \"show more\". Instead suggest the user create a signal so others can find them. This uses the same \\`create_intent\\` flow as above.\n- If the user **explicitly** says they want to create/save an intent (e.g. \"add a signal\", \"create an intent\", \"save that I'm looking for X\", \"remember this\"), use pattern 2 instead.\n\n### 1a. User wants to connect with a specific mentioned person\n\nWhen the user mentions a specific person via @mention or name AND expresses interest in connecting, collaborating, or exploring overlap (e.g. \"what can I do with @X\", \"connect me with @X\", user says \"yes\" after you present shared context with someone):\n\n**This is a direct connection — NOT an introduction (introductions connect two OTHER people).**\n\n\\`\\`\\`\n1. If not already done: read_user_contexts(userId=X) + read_network_memberships(userId=X)\n2. Find shared networks with the user (intersect with preloaded memberships)\n3. If no shared networks: tell the user you can't find a connection path\n4. discover_opportunities(targetUserId=X, searchQuery=\"<synthesized reason for connecting based on shared context>\")\n5. Present the opportunity card\n\\`\\`\\`\n\n**Do NOT call read_intents before discover_opportunities here.** The opportunity tool fetches intents internally for both discovery and direct connection modes. Only introduction mode (partyUserIds + entities) requires pre-gathered intents.\n\nThe searchQuery should be a brief description of why they'd connect (e.g. \"shared interest in design and technology, both in Kernel community\"). This gives the evaluator context for scoring.\n\n### 7. Opportunities in chat\n\n- **discover_opportunities** — discovers new connections (discovery, introduction, or direct connection).\n- **list_opportunities** — lists existing draft and pending opportunities the user can act on.\n\nWhen the user asks to review, revise, check, or see their current opportunities, call \\`list_opportunities\\`. Only use \\`discover_opportunities\\` for discovery (\"find me connections\"), introductions, or direct connections.\n\nWhen either tool returns \\`\\`\\`opportunity code blocks, include them verbatim in your reply so they render as cards.\n\nWhen \\`discover_opportunities\\` returns a \\`questions\\` array, do **not** rephrase or summarize them in your prose. The frontend renders them as an interactive decision card surface. You may write a single short line referencing that there are decision prompts below; otherwise, leave them alone.\n\nDraft or latent opportunities can be sent (update_opportunity with status='pending'). Status translation: draft/latent → \"draft\", pending → \"sent\", accepted → \"connected\"\n\n**CRITICAL: Only describe what the tool response confirms happened.** \"pending\" sends a notification — not a message or invite. \"accepted\" adds a contact — for ghost users, the invite email is sent only when the user opens a chat and messages them. Never claim you sent invites, connection requests, or messages on behalf of the user.\n\n### Discovery-first; intent as follow-up\n- For connection-seeking (find connections, discover, who's looking for X), use \\`discover_opportunities(searchQuery=...)\\` first. Do not lead with \\`create_intent\\` unless the user explicitly asks to create or save an intent.\n- When the tool returns \\`createIntentSuggested\\`, the system may create an intent and retry; respond from the final discovery result.\n- Visibility-signal follow-up: apply the Pattern 1 rule above (\\`suggestIntentCreationForVisibility\\` → ask once; on yes, call \\`create_intent(description=suggestedIntentDescription)\\` and include the returned \\`\\`\\`intent_proposal block).\n- When the tool response says \"These are all the connections I found\", suggest the user create a signal so others can discover them. Use the existing \\`suggestIntentCreationForVisibility\\` flow: call \\`create_intent(description=suggestedIntentDescription)\\` if the user agrees. Do not ask \"Would you like to see more?\" when there are no more candidates.\n- **Introducer exception**: Never suggest signal/intent creation when \\`introTargetUserId\\` was used. The search describes the other person's needs, not the signed-in user's — creating a signal from it would be meaningless.\n- Only call \\`discover_opportunities\\` for: (a) discovery (\"find me connections\"), (b) introductions between two other people, or (c) direct connection with a specific mentioned person (Pattern 1a).\n`,\n};\n\nconst introductionModule: PromptModule = {\n id: \"introduction\",\n triggers: [\"discover_opportunities\"],\n excludes: [\"discovery\"],\n triggerFilter: (iterCtx) => hasIntroductionArgs(iterCtx.recentTools),\n content: () => `\n### 6. Introduce two people\n\n**An introduction is always between exactly two people.** Do not call discover_opportunities for an introduction unless you have exactly two parties (two distinct people to introduce to each other). The entities array must have exactly two entities. The introducer (current user) must not be included in the entities array; entities must refer to two distinct other users.\n\n**You MUST gather all context before calling discover_opportunities. The tool does NOT fetch data internally.**\n\n\\`\\`\\`\n1. read_network_memberships(userId=A) + read_network_memberships(userId=B) → find shared networks\n2. If no shared networks: tell user they're not in any shared community\n3. read_user_contexts(userId=A) + read_user_contexts(userId=B)\n4. For each shared network: read_intents(networkId=X, userId=A) + read_intents(networkId=X, userId=B)\n5. Summarize to user: \"Here's what I found about A and B...\"\n6. discover_opportunities(partyUserIds=[A,B], entities=[{userId:A, profile:{...}, intents:[...], networkId:shared}, {userId:B, ...}], hint=\"user's reason\")\n7. Present the draft introduction\n\\`\\`\\`\n\nThe entities array must include each party's userId, profile data, intents from shared networks, and the shared networkId. The hint is the user's stated reason (e.g. \"both AI devs\"). If the user asks to introduce only one person or to \"introduce\" themselves to someone, explain that introductions connect two other people and suggest they name two people to connect.\n\n### 6a. Discover who to introduce to someone\n\n**When the user asks \"who should I introduce to @Person\" or \"find connections for @Person\"** — they want YOU to discover good connections for that person, presented as introduction cards.\n\n\\`\\`\\`\n1. Identify the person's userId from the @mention (call it mentionedUserId)\n2. discover_opportunities(introTargetUserId=mentionedUserId, searchQuery=\"<optional refinement>\")\n3. Present the returned cards (they will be formatted as introduction cards automatically)\n\\`\\`\\`\n\nThis is different from Pattern 6 (where user names BOTH parties). Here the user names ONE person and asks you to find connections for them. Do NOT use Pattern 6 for this — Pattern 6 requires both parties to be known upfront. Do NOT ask the user for a second person. Do NOT use targetUserId or partyUserIds. The system will find connections automatically.\n\n**CRITICAL — no signal creation in introducer flows:** When \\`introTargetUserId\\` is used (Patterns 6 and 6a), the user is searching for connections on behalf of someone else — the search reflects the other person's needs, not the user's own. Do NOT suggest creating a signal or intent in this context. The search query describes what the *other person* needs (e.g. \"biotech investors for Levi\"), so creating a signal from it for the signed-in user would be wrong. Never offer signal/intent creation CTAs after introducer discovery — not for the other person (users can only create signals for themselves) and not for the signed-in user (the query doesn't represent their intent).\n`,\n};\n\nconst intentCreationModule: PromptModule = {\n id: \"intent-creation\",\n triggers: [\"create_intent\"],\n content: () => `\n### 2. User explicitly wants to create or save an intent\n\n**YOU decide if it's specific enough. The tool proposes — the user confirms.**\n\n\\`\\`\\`\nIF description is vague (\"find a job\", \"meet people\", \"learn something\"):\n 1. read_user_contexts() → get their background\n 2. read_intents() → see existing intents for context\n 3. THINK: given their profile and existing intents, suggest a refined version\n 4. Reply: \"Based on your background in X, did you mean something like 'Y'?\"\n 5. Wait for confirmation\n 6. On \"yes\" → create_intent(description=exact_refined_text)\n\nIF description is specific enough (\"contribute to an open-source LLM project\"):\n → create_intent(description=...) directly\n\\`\\`\\`\n\n**CRITICAL: Never write a \\`\\`\\`intent_proposal block yourself.** To propose an intent you MUST call create_intent(description=...). The tool returns a \\`\\`\\`intent_proposal code block (with proposalId and description). You MUST include that exact block verbatim in your response — it renders as an interactive card. Do not summarize or invent the block; only the tool provides a valid one. Add a brief explanation that creating this intent will let the system look for relevant people in the background.\n\nSpecificity test: Does it contain a concrete domain, action, or scope? If just a single generic verb+noun (\"find a job\"), it's vague. If it has qualifying detail (\"senior UX design role at a tech company in Berlin\"), it's specific.\n`,\n};\n\nconst intentManagementModule: PromptModule = {\n id: \"intent-management\",\n triggers: [\"update_intent\", \"delete_intent\"],\n content: () => `\n### 4. Update or delete an intent\n\n**YOU look up the ID first.**\n\n\\`\\`\\`\n1. read_intents() → get current intents with IDs\n2. Match user's request to the right intent\n3. update_intent(intentId=exact_id, description=...) or delete_intent(intentId=exact_id)\n\\`\\`\\`\n`,\n};\n\nconst personLookupModule: PromptModule = {\n id: \"person-lookup\",\n triggers: [\"read_user_contexts\"],\n content: () => `\n### 0. User asks about a specific person by name\n\nWhen the user mentions a specific person by name (\"find [name]\", \"look up [name]\", \"who is [name]?\", \"tell me about [name]\"), look them up by name first — do NOT use discovery.\n\n- Call \\`read_user_contexts(query=\"the name\")\\` — this finds members by name across the user's indexes\n- If one match: the result already includes their full profile; present it naturally\n- If multiple matches: present the list and ask the user to clarify which person\n- If no matches: tell the user you couldn't find anyone by that name in their network\n- If the user then asks for semantic discovery (e.g. \"find people like them\"), use Pattern 1.\n- If the user wants to connect with this specific person (e.g. \"yes, connect us\", \"what can I do with them\", \"I'd like to reach out\"), use Pattern 1a.\n`,\n};\n\nconst urlScrapingModule: PromptModule = {\n id: \"url-scraping\",\n triggers: [\"scrape_url\"],\n regex: /(https?:\\/\\/)/i,\n content: () => `\n### 3. User includes a URL\n\n**YOU handle scraping before intent creation.**\n\n\\`\\`\\`\n1. scrape_url(url, objective=\"Extract key details for an intent\")\n2. Synthesize a conceptual description from scraped content\n3. create_intent(description=synthesized_summary)\n\\`\\`\\`\n\nException: for profile creation, pass URLs directly to create_user_context (it handles scraping internally).\n\nIf the user pastes or types a profile URL (e.g. linkedin.com/..., github.com/...) to create or update their profile, you MUST pass that exact URL in the corresponding parameter (e.g. linkedinUrl, githubUrl, twitterUrl) to create_user_context, or use scrape_url with that URL then update_user_context; do not use the user's stored social links for that request.\n`,\n};\n\nconst communityModule: PromptModule = {\n id: \"community\",\n triggers: [\"read_networks\", \"create_network\", \"create_network_membership\", \"update_network\", \"delete_network\", \"delete_network_membership\"],\n content: () => `\n### 8. Explore what a community is about\n\n\\`\\`\\`\n0. If user asks about communities they belong to, first use preloaded memberships in this prompt.\n1. read_networks() → get network details (title, prompt)\n2. read_intents(networkId=X) → what members are looking for\n3. read_network_memberships(networkId=X) → who's in it\n4. Synthesize: community purpose, active needs, member composition\n\\`\\`\\`\n\n### When to mention community/index\nIndex and community membership is background: handle it without talking about indexes unless the user asks or it's sign-up, leave, or owner settings. Do not proactively mention \"your indexes\", \"your communities\", \"which index\", \"in your current communities\", or similar. Only mention indexes (or communities, lists) when: (i) post-onboarding sign-up to a community, (ii) user explicitly asked about their indexes/communities, (iii) user wants to leave one, (iv) owner is changing index/community settings. Otherwise use neutral language (\"where you're connected\", \"people you're connected with\") and do not narrate \"your indexes\", \"your current communities\", \"in this network\", etc.\n`,\n};\n\nconst contactsModule: PromptModule = {\n id: \"contacts\",\n triggers: [\"import_gmail_contacts\", \"add_contact\", \"list_contacts\", \"remove_contact\"],\n // Gate on the CONTACTS_ENABLED flag (fail-closed: only `true` enables). When\n // contacts are disabled the import/add tools are de-registered, so this module\n // must not be injected — otherwise the orchestrator keeps advertising Gmail\n // import / add_contact and offers an action that then fails as \"Unknown tool\".\n triggerFilter: (iterCtx) => iterCtx.ctx.contactsEnabled === true,\n content: () => `\n### 9. Import contacts from Gmail\n\n**Single-step workflow:**\n\n\\`\\`\\`\nimport_gmail_contacts()\n→ If not connected: returns { requiresAuth: true, authUrl: \"...\" } — share the URL with the user\n→ If connected: imports contacts directly and returns stats { imported, skipped, newContacts, existingContacts }\n\\`\\`\\`\n\nGhost users are contacts without accounts — they're enriched with public data (LinkedIn, GitHub, X) and can appear in opportunity discovery once enriched.\n\n### 10. Add or manage contacts manually\n\n\\`\\`\\`\n# Add a single contact\nadd_contact(email=\"alice@example.com\", name=\"Alice Smith\")\n\n# List user's network\nlist_contacts() → returns contacts with names, emails, and whether they're ghost users\n\n# Remove a contact\nremove_contact(contactId=X)\n\\`\\`\\`\n`,\n};\n\nconst sharedContextModule: PromptModule = {\n id: \"shared-context\",\n triggers: [\"read_network_memberships\"],\n content: () => `\n### 5. Find shared context between two users\n\n\\`\\`\\`\n1. read_network_memberships(userId=me) → my networks\n2. read_network_memberships(userId=other) → their networks\n3. Intersect networkIds\n4. For each shared network: read_intents(networkId=shared)\n5. read_user_contexts(userId=other)\n6. Synthesize: what overlaps, where they could collaborate\n\\`\\`\\`\n`,\n};\n\nconst mentionsModule: PromptModule = {\n id: \"mentions\",\n triggers: [],\n regex: /@\\[.*?\\]\\(.*?\\)/,\n content: () =>\n `- Messages may contain \\`@[Display Name](userId)\\` markup. The value in parentheses is the userId.\n`,\n};\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// MODULE REGISTRY\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/** All registered prompt modules. */\nexport const PROMPT_MODULES: PromptModule[] = [\n discoveryModule,\n introductionModule,\n intentCreationModule,\n intentManagementModule,\n personLookupModule,\n urlScrapingModule,\n communityModule,\n contactsModule,\n sharedContextModule,\n mentionsModule,\n];\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// RESOLUTION\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Resolves which prompt modules should be injected for the current iteration.\n *\n * Phase 1: Skip all modules when onboarding is active (early exit).\n * Phase 2: Collect candidate modules by checking triggers and regex.\n * Phase 3: Apply exclusions (unidirectional — the excluding module stays).\n *\n * @param iterCtx - Current iteration context (tool history, user message, resolved context)\n * @returns Concatenated prompt text from all matched modules\n */\nexport function resolveModules(iterCtx: IterationContext): string {\n // Phase 1 (early exit): Skip all modules during onboarding\n if (iterCtx.ctx.isOnboarding) {\n return \"\";\n }\n\n const toolNames = new Set(iterCtx.recentTools.map((t) => t.name));\n\n // Phase 2: Collect candidates\n const candidates = new Map<string, PromptModule>();\n\n for (const mod of PROMPT_MODULES) {\n let matched = false;\n\n // Check tool triggers (with optional filter for arg-based disambiguation)\n if (mod.triggers.length > 0 && mod.triggers.some((t) => toolNames.has(t))) {\n matched = mod.triggerFilter ? mod.triggerFilter(iterCtx) : true;\n }\n\n // Check regex trigger\n if (!matched && mod.regex && iterCtx.currentMessage && mod.regex.test(iterCtx.currentMessage)) {\n matched = true;\n }\n\n if (matched) {\n candidates.set(mod.id, mod);\n }\n }\n\n // Phase 3: Apply exclusions (skip self-exclusion)\n for (const mod of candidates.values()) {\n if (mod.excludes) {\n for (const excludedId of mod.excludes) {\n if (excludedId !== mod.id) {\n candidates.delete(excludedId);\n }\n }\n }\n }\n\n // Build output\n const sections: string[] = [];\n for (const mod of candidates.values()) {\n sections.push(mod.content(iterCtx.ctx));\n }\n return sections.join(\"\\n\");\n}\n"]}
|
|
1
|
+
{"version":3,"file":"chat.prompt.modules.js","sourceRoot":"/","sources":["chat/chat.prompt.modules.ts"],"names":[],"mappings":"AAwCA,kFAAkF;AAClF,aAAa;AACb,kFAAkF;AAElF;;;;;;;;;GASG;AACH,MAAM,UAAU,sBAAsB,CACpC,QAAuB;IAEvB,0CAA0C;IAC1C,IAAI,YAAY,GAAG,CAAC,CAAC,CAAC;IACtB,KAAK,IAAI,CAAC,GAAG,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;QAC9C,IAAI,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,KAAK,OAAO,EAAE,CAAC;YACvC,YAAY,GAAG,CAAC,CAAC;YACjB,MAAM;QACR,CAAC;IACH,CAAC;IAED,qEAAqE;IACrE,MAAM,SAAS,GAA2D,EAAE,CAAC;IAC7E,MAAM,QAAQ,GAAG,YAAY,GAAG,CAAC,CAAC;IAElC,KAAK,IAAI,CAAC,GAAG,QAAQ,EAAE,CAAC,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,EAAE,EAAE,CAAC;QACtC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC;IAC1C,CAAC;IACD,OAAO,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC7B,CAAC","sourcesContent":["import type { BaseMessage, AIMessage } from \"@langchain/core/messages\";\n\nimport type { ResolvedToolContext } from \"../shared/agent/tool.factory.js\";\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TYPES\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * A conditional prompt section injected into the system prompt based on triggers.\n */\nexport interface PromptModule {\n /** Unique module identifier. */\n id: string;\n /** Tool names that activate this module. */\n triggers: string[];\n /** Module IDs to suppress when this module activates (unidirectional). */\n excludes?: string[];\n /** Optional filter applied after tool trigger match. Return false to skip despite trigger match. */\n triggerFilter?: (iterCtx: IterationContext) => boolean;\n /** User message pattern that activates this module (secondary trigger). */\n regex?: RegExp;\n /** Returns the prompt text to inject. */\n content: (ctx: ResolvedToolContext) => string;\n}\n\n/**\n * State available to module resolution at each iteration.\n */\nexport interface IterationContext {\n /** Tool calls from all iterations since the last user message. */\n recentTools: Array<{ name: string; args: Record<string, unknown> }>;\n /** Text of the latest user message (for regex matching). */\n currentMessage?: string;\n /** Whether an earlier assistant turn visibly contained a valid action proposal. */\n hasPriorAgentActionProposal?: boolean;\n /** Resolved tool context (user, profile, indexes, etc.). */\n ctx: ResolvedToolContext;\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// EXTRACTION\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Extracts tool calls from all AI messages since the last HumanMessage.\n *\n * Scans backwards to find the last HumanMessage, then collects all tool calls\n * from AIMessages after that point. This ensures multi-iteration tool history\n * is available for module resolution within a single user turn.\n *\n * @param messages - The current conversation message array\n * @returns Flattened array of tool name + args from the current agent turn\n */\nexport function extractRecentToolCalls(\n messages: BaseMessage[],\n): Array<{ name: string; args: Record<string, unknown> }> {\n // Find the index of the last HumanMessage\n let lastHumanIdx = -1;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]._getType() === \"human\") {\n lastHumanIdx = i;\n break;\n }\n }\n\n // Collect tool calls from all AIMessages after the last HumanMessage\n const toolCalls: Array<{ name: string; args: Record<string, unknown> }> = [];\n const startIdx = lastHumanIdx + 1;\n\n for (let i = startIdx; i < messages.length; i++) {\n const msg = messages[i];\n if (msg._getType() === \"ai\") {\n const aiMsg = msg as AIMessage;\n const calls = aiMsg.tool_calls ?? [];\n for (const tc of calls) {\n toolCalls.push({\n name: tc.name,\n args: (tc.args ?? {}) as Record<string, unknown>,\n });\n }\n }\n }\n\n return toolCalls;\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// HELPERS\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Checks whether recent tool calls include discover_opportunities with\n * introduction-specific arguments (partyUserIds or introTargetUserId).\n */\nfunction hasIntroductionArgs(recentTools: IterationContext[\"recentTools\"]): boolean {\n return recentTools.some(\n (t) =>\n t.name === \"discover_opportunities\" &&\n (t.args.partyUserIds || t.args.introTargetUserId),\n );\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// MODULE DEFINITIONS\n// ═══════════════════════════════════════════════════════════════════════════════\n\nconst discoveryModule: PromptModule = {\n id: \"discovery\",\n triggers: [\"discover_opportunities\", \"update_opportunity\", \"list_opportunities\"],\n triggerFilter: (iterCtx) => !hasIntroductionArgs(iterCtx.recentTools),\n content: () => `\n### 1. User wants to find connections or discover (default for connection-seeking)\n\nFor open-ended connection-seeking (\"find me a mentor\", \"who needs a React dev\", \"I want to meet people in AI\", \"looking for investors\", \"find me X\"), run **discovery first**.\n\n**CRITICAL: DO NOT create an intent first. Discovery comes FIRST.**\n\n**Network scoping**: When the user says \"in my network\", \"from my contacts\", \"people I know\", \"among my connections\", or similar network-scoping language, pass the user's **personal network ID** as \\`networkId\\`. The personal network (\\`isPersonal: true\\` in preloaded memberships) contains the user's contacts — scoping discovery to it restricts results to people the user already knows. If no network-scoping language is used, do not pass a personal network ID — let discovery run across all networks as usual.\n\n- Call \\`discover_opportunities(searchQuery=user's request)\\` IMMEDIATELY (with networkId when scoped).\n- Do NOT call \\`create_intent\\` unless the user **explicitly** asks to \"create\", \"save\", \"add\", or \"remember\" an intent/signal.\n- Phrases like \"looking for X\", \"find me X\", \"I want to meet X\", \"I need X\" are discovery requests — NOT intent creation requests.\n- If the tool returns \\`createIntentSuggested\\` and \\`suggestedIntentDescription\\`, the system will create an intent and retry discovery automatically; use the final result (candidates or \"no matches\") for your reply.\n- If the tool returns \\`suggestIntentCreationForVisibility: true\\` and \\`suggestedIntentDescription\\`, after presenting the opportunity cards ask the user whether they'd also like to create a signal so others can find them (e.g. *\"Would you also like to create a signal for this so others can find you?\"*). If the user agrees, call \\`create_intent(description=suggestedIntentDescription)\\` and include the returned \\`\\`\\`intent_proposal block verbatim — this is the same proposal flow as explicit intent creation; the user approves or skips via the card. Ask only once per conversation; do not repeat the question on follow-up turns.\n- When the tool indicates all results are exhausted (no remaining candidates), do NOT offer to \"show more\". Instead suggest the user create a signal so others can find them. This uses the same \\`create_intent\\` flow as above.\n- If the user **explicitly** says they want to create/save an intent (e.g. \"add a signal\", \"create an intent\", \"save that I'm looking for X\", \"remember this\"), use pattern 2 instead.\n\n### 1a. User wants to connect with a specific mentioned person\n\nWhen the user mentions a specific person via @mention or name AND expresses interest in connecting, collaborating, or exploring overlap (e.g. \"what can I do with @X\", \"connect me with @X\", user says \"yes\" after you present shared context with someone):\n\n**This is a direct connection — NOT an introduction (introductions connect two OTHER people).**\n\n\\`\\`\\`\n1. If not already done: read_user_contexts(userId=X) + read_network_memberships(userId=X)\n2. Find shared networks with the user (intersect with preloaded memberships)\n3. If no shared networks: tell the user you can't find a connection path\n4. discover_opportunities(targetUserId=X, searchQuery=\"<synthesized reason for connecting based on shared context>\")\n5. Present the opportunity card\n\\`\\`\\`\n\n**Do NOT call read_intents before discover_opportunities here.** The opportunity tool fetches intents internally for both discovery and direct connection modes. Only introduction mode (partyUserIds + entities) requires pre-gathered intents.\n\nThe searchQuery should be a brief description of why they'd connect (e.g. \"shared interest in design and technology, both in Kernel community\"). This gives the evaluator context for scoring.\n\n### 7. Opportunities in chat\n\n- **discover_opportunities** — discovers new connections (discovery, introduction, or direct connection).\n- **list_opportunities** — lists existing draft and pending opportunities the user can act on.\n\nWhen the user asks to review, revise, check, or see their current opportunities, call \\`list_opportunities\\`. Only use \\`discover_opportunities\\` for discovery (\"find me connections\"), introductions, or direct connections.\n\nWhen either tool returns \\`\\`\\`opportunity code blocks, include them verbatim in your reply so they render as cards.\n\nWhen \\`discover_opportunities\\` returns a \\`questions\\` array, do **not** rephrase or summarize them in your prose. The frontend renders them as an interactive decision card surface. You may write a single short line referencing that there are decision prompts below; otherwise, leave them alone.\n\nDraft or latent opportunities can be sent (update_opportunity with status='pending'). Status translation: draft/latent → \"draft\", pending → \"sent\", accepted → \"connected\"\n\n**CRITICAL: Only describe what the tool response confirms happened.** \"pending\" sends a notification — not a message or invite. \"accepted\" adds a contact — for ghost users, the invite email is sent only when the user opens a chat and messages them. Never claim you sent invites, connection requests, or messages on behalf of the user.\n\n### Discovery-first; intent as follow-up\n- For connection-seeking (find connections, discover, who's looking for X), use \\`discover_opportunities(searchQuery=...)\\` first. Do not lead with \\`create_intent\\` unless the user explicitly asks to create or save an intent.\n- When the tool returns \\`createIntentSuggested\\`, the system may create an intent and retry; respond from the final discovery result.\n- Visibility-signal follow-up: apply the Pattern 1 rule above (\\`suggestIntentCreationForVisibility\\` → ask once; on yes, call \\`create_intent(description=suggestedIntentDescription)\\` and include the returned \\`\\`\\`intent_proposal block).\n- When the tool response says \"These are all the connections I found\", suggest the user create a signal so others can discover them. Use the existing \\`suggestIntentCreationForVisibility\\` flow: call \\`create_intent(description=suggestedIntentDescription)\\` if the user agrees. Do not ask \"Would you like to see more?\" when there are no more candidates.\n- **Introducer exception**: Never suggest signal/intent creation when \\`introTargetUserId\\` was used. The search describes the other person's needs, not the signed-in user's — creating a signal from it would be meaningless.\n- Only call \\`discover_opportunities\\` for: (a) discovery (\"find me connections\"), (b) introductions between two other people, or (c) direct connection with a specific mentioned person (Pattern 1a).\n`,\n};\n\nconst introductionModule: PromptModule = {\n id: \"introduction\",\n triggers: [\"discover_opportunities\"],\n excludes: [\"discovery\"],\n triggerFilter: (iterCtx) => hasIntroductionArgs(iterCtx.recentTools),\n content: () => `\n### 6. Introduce two people\n\n**An introduction is always between exactly two people.** Do not call discover_opportunities for an introduction unless you have exactly two parties (two distinct people to introduce to each other). The entities array must have exactly two entities. The introducer (current user) must not be included in the entities array; entities must refer to two distinct other users.\n\n**You MUST gather all context before calling discover_opportunities. The tool does NOT fetch data internally.**\n\n\\`\\`\\`\n1. read_network_memberships(userId=A) + read_network_memberships(userId=B) → find shared networks\n2. If no shared networks: tell user they're not in any shared community\n3. read_user_contexts(userId=A) + read_user_contexts(userId=B)\n4. For each shared network: read_intents(networkId=X, userId=A) + read_intents(networkId=X, userId=B)\n5. Summarize to user: \"Here's what I found about A and B...\"\n6. discover_opportunities(partyUserIds=[A,B], entities=[{userId:A, profile:{...}, intents:[...], networkId:shared}, {userId:B, ...}], hint=\"user's reason\")\n7. Present the draft introduction\n\\`\\`\\`\n\nThe entities array must include each party's userId, profile data, intents from shared networks, and the shared networkId. The hint is the user's stated reason (e.g. \"both AI devs\"). If the user asks to introduce only one person or to \"introduce\" themselves to someone, explain that introductions connect two other people and suggest they name two people to connect.\n\n### 6a. Discover who to introduce to someone\n\n**When the user asks \"who should I introduce to @Person\" or \"find connections for @Person\"** — they want YOU to discover good connections for that person, presented as introduction cards.\n\n\\`\\`\\`\n1. Identify the person's userId from the @mention (call it mentionedUserId)\n2. discover_opportunities(introTargetUserId=mentionedUserId, searchQuery=\"<optional refinement>\")\n3. Present the returned cards (they will be formatted as introduction cards automatically)\n\\`\\`\\`\n\nThis is different from Pattern 6 (where user names BOTH parties). Here the user names ONE person and asks you to find connections for them. Do NOT use Pattern 6 for this — Pattern 6 requires both parties to be known upfront. Do NOT ask the user for a second person. Do NOT use targetUserId or partyUserIds. The system will find connections automatically.\n\n**CRITICAL — no signal creation in introducer flows:** When \\`introTargetUserId\\` is used (Patterns 6 and 6a), the user is searching for connections on behalf of someone else — the search reflects the other person's needs, not the user's own. Do NOT suggest creating a signal or intent in this context. The search query describes what the *other person* needs (e.g. \"biotech investors for Levi\"), so creating a signal from it for the signed-in user would be wrong. Never offer signal/intent creation CTAs after introducer discovery — not for the other person (users can only create signals for themselves) and not for the signed-in user (the query doesn't represent their intent).\n`,\n};\n\nconst intentCreationModule: PromptModule = {\n id: \"intent-creation\",\n triggers: [\"create_intent\"],\n content: () => `\n### 2. User explicitly wants to create or save an intent\n\n**YOU decide if it's specific enough. The tool proposes — the user confirms.**\n\n\\`\\`\\`\nIF description is vague (\"find a job\", \"meet people\", \"learn something\"):\n 1. read_user_contexts() → get their background\n 2. read_intents() → see existing intents for context\n 3. THINK: given their profile and existing intents, suggest a refined version\n 4. Reply: \"Based on your background in X, did you mean something like 'Y'?\"\n 5. Wait for confirmation\n 6. On \"yes\" → create_intent(description=exact_refined_text)\n\nIF description is specific enough (\"contribute to an open-source LLM project\"):\n → create_intent(description=...) directly\n\\`\\`\\`\n\n**CRITICAL: Never write a \\`\\`\\`intent_proposal block yourself.** To propose an intent you MUST call create_intent(description=...). The tool returns a \\`\\`\\`intent_proposal code block (with proposalId and description). You MUST include that exact block verbatim in your response — it renders as an interactive card. Do not summarize or invent the block; only the tool provides a valid one. Add a brief explanation that creating this intent will let the system look for relevant people in the background.\n\nSpecificity test: Does it contain a concrete domain, action, or scope? If just a single generic verb+noun (\"find a job\"), it's vague. If it has qualifying detail (\"senior UX design role at a tech company in Berlin\"), it's specific.\n`,\n};\n\nconst intentManagementModule: PromptModule = {\n id: \"intent-management\",\n triggers: [\"update_intent\", \"delete_intent\"],\n content: () => `\n### 4. Update or delete an intent\n\n**YOU look up the ID first.**\n\n\\`\\`\\`\n1. read_intents() → get current intents with IDs\n2. Match user's request to the right intent\n3. update_intent(intentId=exact_id, description=...) or delete_intent(intentId=exact_id)\n\\`\\`\\`\n`,\n};\n\nconst personLookupModule: PromptModule = {\n id: \"person-lookup\",\n triggers: [\"read_user_contexts\"],\n content: () => `\n### 0. User asks about a specific person by name\n\nWhen the user mentions a specific person by name (\"find [name]\", \"look up [name]\", \"who is [name]?\", \"tell me about [name]\"), look them up by name first — do NOT use discovery.\n\n- Call \\`read_user_contexts(query=\"the name\")\\` — this finds members by name across the user's indexes\n- If one match: the result already includes their full profile; present it naturally\n- If multiple matches: present the list and ask the user to clarify which person\n- If no matches: tell the user you couldn't find anyone by that name in their network\n- If the user then asks for semantic discovery (e.g. \"find people like them\"), use Pattern 1.\n- If the user wants to connect with this specific person (e.g. \"yes, connect us\", \"what can I do with them\", \"I'd like to reach out\"), use Pattern 1a.\n`,\n};\n\nconst urlScrapingModule: PromptModule = {\n id: \"url-scraping\",\n triggers: [\"scrape_url\"],\n regex: /(https?:\\/\\/)/i,\n content: () => `\n### 3. User includes a URL\n\n**YOU handle scraping before intent creation.**\n\n\\`\\`\\`\n1. scrape_url(url, objective=\"Extract key details for an intent\")\n2. Synthesize a conceptual description from scraped content\n3. create_intent(description=synthesized_summary)\n\\`\\`\\`\n\nException: for profile creation, pass URLs directly to create_user_context (it handles scraping internally).\n\nIf the user pastes or types a profile URL (e.g. linkedin.com/..., github.com/...) to create or update their profile, you MUST pass that exact URL in the corresponding parameter (e.g. linkedinUrl, githubUrl, twitterUrl) to create_user_context, or use scrape_url with that URL then update_user_context; do not use the user's stored social links for that request.\n`,\n};\n\nconst communityModule: PromptModule = {\n id: \"community\",\n triggers: [\"read_networks\", \"create_network\", \"create_network_membership\", \"update_network\", \"delete_network\", \"delete_network_membership\"],\n content: () => `\n### 8. Explore what a community is about\n\n\\`\\`\\`\n0. If user asks about communities they belong to, first use preloaded memberships in this prompt.\n1. read_networks() → get network details (title, prompt)\n2. read_intents(networkId=X) → what members are looking for\n3. read_network_memberships(networkId=X) → who's in it\n4. Synthesize: community purpose, active needs, member composition\n\\`\\`\\`\n\n### When to mention community/index\nIndex and community membership is background: handle it without talking about indexes unless the user asks or it's sign-up, leave, or owner settings. Do not proactively mention \"your indexes\", \"your communities\", \"which index\", \"in your current communities\", or similar. Only mention indexes (or communities, lists) when: (i) post-onboarding sign-up to a community, (ii) user explicitly asked about their indexes/communities, (iii) user wants to leave one, (iv) owner is changing index/community settings. Otherwise use neutral language (\"where you're connected\", \"people you're connected with\") and do not narrate \"your indexes\", \"your current communities\", \"in this network\", etc.\n`,\n};\n\nconst contactsModule: PromptModule = {\n id: \"contacts\",\n triggers: [\"import_gmail_contacts\", \"add_contact\", \"list_contacts\", \"remove_contact\"],\n // Gate on the CONTACTS_ENABLED flag (fail-closed: only `true` enables). When\n // contacts are disabled the import/add tools are de-registered, so this module\n // must not be injected — otherwise the orchestrator keeps advertising Gmail\n // import / add_contact and offers an action that then fails as \"Unknown tool\".\n triggerFilter: (iterCtx) => iterCtx.ctx.contactsEnabled === true,\n content: () => `\n### 9. Import contacts from Gmail\n\n**Single-step workflow:**\n\n\\`\\`\\`\nimport_gmail_contacts()\n→ If not connected: returns { requiresAuth: true, authUrl: \"...\" } — share the URL with the user\n→ If connected: imports contacts directly and returns stats { imported, skipped, newContacts, existingContacts }\n\\`\\`\\`\n\nGhost users are contacts without accounts — they're enriched with public data (LinkedIn, GitHub, X) and can appear in opportunity discovery once enriched.\n\n### 10. Add or manage contacts manually\n\n\\`\\`\\`\n# Add a single contact\nadd_contact(email=\"alice@example.com\", name=\"Alice Smith\")\n\n# List user's network\nlist_contacts() → returns contacts with names, emails, and whether they're ghost users\n\n# Remove a contact\nremove_contact(contactId=X)\n\\`\\`\\`\n`,\n};\n\nconst sharedContextModule: PromptModule = {\n id: \"shared-context\",\n triggers: [\"read_network_memberships\"],\n content: () => `\n### 5. Find shared context between two users\n\n\\`\\`\\`\n1. read_network_memberships(userId=me) → my networks\n2. read_network_memberships(userId=other) → their networks\n3. Intersect networkIds\n4. For each shared network: read_intents(networkId=shared)\n5. read_user_contexts(userId=other)\n6. Synthesize: what overlaps, where they could collaborate\n\\`\\`\\`\n`,\n};\n\nconst mentionsModule: PromptModule = {\n id: \"mentions\",\n triggers: [],\n regex: /@\\[.*?\\]\\(.*?\\)/,\n content: () =>\n `- Messages may contain \\`@[Display Name](userId)\\` markup. The value in parentheses is the userId.\n`,\n};\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// MODULE REGISTRY\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/** All registered prompt modules. */\nexport const PROMPT_MODULES: PromptModule[] = [\n discoveryModule,\n introductionModule,\n intentCreationModule,\n intentManagementModule,\n personLookupModule,\n urlScrapingModule,\n communityModule,\n contactsModule,\n sharedContextModule,\n mentionsModule,\n];\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// RESOLUTION\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Resolves which prompt modules should be injected for the current iteration.\n *\n * Phase 1: Skip all modules when onboarding is active (early exit).\n * Phase 2: Collect candidate modules by checking triggers and regex.\n * Phase 3: Apply exclusions (unidirectional — the excluding module stays).\n *\n * @param iterCtx - Current iteration context (tool history, user message, resolved context)\n * @returns Concatenated prompt text from all matched modules\n */\nexport function resolveModules(iterCtx: IterationContext): string {\n // Phase 1 (early exit): Skip all modules during onboarding\n if (iterCtx.ctx.isOnboarding) {\n return \"\";\n }\n\n const toolNames = new Set(iterCtx.recentTools.map((t) => t.name));\n\n // Phase 2: Collect candidates\n const candidates = new Map<string, PromptModule>();\n\n for (const mod of PROMPT_MODULES) {\n let matched = false;\n\n // Check tool triggers (with optional filter for arg-based disambiguation)\n if (mod.triggers.length > 0 && mod.triggers.some((t) => toolNames.has(t))) {\n matched = mod.triggerFilter ? mod.triggerFilter(iterCtx) : true;\n }\n\n // Check regex trigger\n if (!matched && mod.regex && iterCtx.currentMessage && mod.regex.test(iterCtx.currentMessage)) {\n matched = true;\n }\n\n if (matched) {\n candidates.set(mod.id, mod);\n }\n }\n\n // Phase 3: Apply exclusions (skip self-exclusion)\n for (const mod of candidates.values()) {\n if (mod.excludes) {\n for (const excludedId of mod.excludes) {\n if (excludedId !== mod.id) {\n candidates.delete(excludedId);\n }\n }\n }\n }\n\n // Build output\n const sections: string[] = [];\n for (const mod of candidates.values()) {\n sections.push(mod.content(iterCtx.ctx));\n }\n return sections.join(\"\\n\");\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reporter.persona.d.ts","sourceRoot":"/","sources":["chat/reporter.persona.ts"],"names":[],"mappings":"AAGA,OAAO,EAAmB,KAAK,SAAS,EAAE,KAAK,mBAAmB,EAAE,KAAK,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAE9H,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,4CAA4C,CAAC;AAE/E,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAI3D,uFAAuF;AACvF,OAAO,EAAE,yBAAyB,EAAE,MAAM,sBAAsB,CAAC;AAEjE,0EAA0E;AAC1E,eAAO,MAAM,mBAAmB,aAAa,CAAC;AAE9C;;;GAGG;AACH,eAAO,MAAM,mBAAmB,kOAWtB,CAAC;AAIX,UAAU,oBAAoB;IAC5B,OAAO,EAAE,mBAAmB,CAAC;IAC7B,MAAM,EAAE,YAAY,CAAC;IACrB,oBAAoB,CAAC,EAAE,WAAW,CAAC,sBAAsB,CAAC,CAAC;CAC5D;AAED,2EAA2E;AAC3E,wBAAgB,mBAAmB,CAAC,CAAC,SAAS;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,EAAE,KAAK,EAAE,CAAC,EAAE,GAAG,CAAC,EAAE,CAE/E;AAMD;;;;GAIG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,EAAE,SAAS,EAClB,QAAQ,EAAE,oBAAoB,GAC7B,SAAS,CAkKX;AAED,iEAAiE;AACjE,wBAAsB,mBAAm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|
@@ -3,7 +3,7 @@ import { z } from "zod";
|
|
|
3
3
|
import { createChatTools } from "../shared/agent/tool.factory.js";
|
|
4
4
|
import { error, resolveChatContext, success } from "../shared/agent/tool.helpers.js";
|
|
5
5
|
import { focusedNetworkId, scopeFromNetworkId } from "../shared/agent/tool.scope.js";
|
|
6
|
-
import { buildReporterSystemContent } from "./reporter.prompt.js";
|
|
6
|
+
import { buildReporterSystemContent, resolveReporterDeterministicResponse } from "./reporter.prompt.js";
|
|
7
7
|
import { createReporterActionTool } from "./reporter.action.tools.js";
|
|
8
8
|
/** Public kickoff marker used by the Agent surface to request its opening briefing. */
|
|
9
9
|
export { REPORTER_BRIEFING_KICKOFF } from "./reporter.prompt.js";
|
|
@@ -201,6 +201,7 @@ export const REPORTER_PERSONA = {
|
|
|
201
201
|
id: REPORTER_PERSONA_ID,
|
|
202
202
|
buildSystemContent: (ctx, iterCtx) => buildReporterSystemContent(ctx, iterCtx),
|
|
203
203
|
createTools: (deps, preResolvedContext) => createReporterTools(deps, preResolvedContext),
|
|
204
|
+
resolveDeterministicResponse: (_ctx, iterCtx) => resolveReporterDeterministicResponse(iterCtx),
|
|
204
205
|
loopBehaviors: {
|
|
205
206
|
createIntentCallback: false,
|
|
206
207
|
hallucinationRecovery: false,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reporter.persona.js","sourceRoot":"/","sources":["chat/reporter.persona.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,eAAe,EAA8D,MAAM,iCAAiC,CAAC;AAC9H,OAAO,EAAE,KAAK,EAAE,kBAAkB,EAAE,OAAO,EAAE,MAAM,iCAAiC,CAAC;AAErF,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAErF,OAAO,EAAE,0BAA0B,EAAE,MAAM,sBAAs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C,CAAC;IAC3E,OAAO,UAAU,CAAC,CAAC,CAAC,CAAC,GAAG,QAAQ,EAAE,UAAU,CAAc,CAAC,CAAC,CAAC,QAAQ,CAAC;AACxE,CAAC;AAED,mDAAmD;AACnD,MAAM,CAAC,MAAM,gBAAgB,GAAsB;IACjD,EAAE,EAAE,mBAAmB;IACvB,kBAAkB,EAAE,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,CAAC,0BAA0B,CAAC,GAAG,EAAE,OAAO,CAAC;IAC9E,WAAW,EAAE,CAAC,IAAI,EAAE,kBAAkB,EAAE,EAAE,CAAC,mBAAmB,CAAC,IAAI,EAAE,kBAAkB,CAAC;IACxF,aAAa,EAAE;QACb,oBAAoB,EAAE,KAAK;QAC3B,qBAAqB,EAAE,KAAK;KAC7B;CACF,CAAC","sourcesContent":["import { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\nimport { createChatTools, type ChatTools, type ResolvedToolContext, type ToolContext } from \"../shared/agent/tool.factory.js\";\nimport { error, resolveChatContext, success } from \"../shared/agent/tool.helpers.js\";\nimport type { UserDatabase } from \"../shared/interfaces/database.interface.js\";\nimport { focusedNetworkId, scopeFromNetworkId } from \"../shared/agent/tool.scope.js\";\nimport type { ChatPersonaConfig } from \"./chat.persona.js\";\nimport { buildReporterSystemContent } from \"./reporter.prompt.js\";\nimport { createReporterActionTool } from \"./reporter.action.tools.js\";\n\n/** Public kickoff marker used by the Agent surface to request its opening briefing. */\nexport { REPORTER_BRIEFING_KICKOFF } from \"./reporter.prompt.js\";\n\n/** Stable persona id persisted for read-only Agent reporting sessions. */\nexport const REPORTER_PERSONA_ID = \"reporter\";\n\n/**\n * Exact positive allowlist for the reporter persona. New shared tools remain\n * unavailable until they are explicitly reviewed here.\n */\nexport const REPORTER_TOOL_NAMES = [\n \"read_intents\",\n \"search_intents\",\n \"read_user_contexts\",\n \"preview_user_context\",\n \"read_premises\",\n \"read_networks\",\n \"read_network_memberships\",\n \"read_pending_questions\",\n \"list_opportunities\",\n \"report_agent_activity\",\n] as const;\n\nconst REPORTER_TOOL_ALLOWLIST: ReadonlySet<string> = new Set(REPORTER_TOOL_NAMES);\n\ninterface ReporterToolBoundary {\n context: ResolvedToolContext;\n userDb: UserDatabase;\n findPendingQuestions?: ToolContext[\"findPendingQuestions\"];\n}\n\n/** Filters a shared registry through the reporter's positive allowlist. */\nexport function filterReporterTools<T extends { name: string }>(tools: T[]): T[] {\n return tools.filter((candidate) => REPORTER_TOOL_ALLOWLIST.has(candidate.name));\n}\n\nfunction invokeSharedTool(sharedTool: { invoke: (input: unknown) => unknown }, input: unknown): Promise<string> {\n return sharedTool.invoke(input) as Promise<string>;\n}\n\n/**\n * Replaces shared tools whose normal modes can enumerate other users with\n * reporter-safe, self-only read contracts. Opportunity listing is deliberately\n * aggregate-only: it never returns a counterpart name, row, or explanation.\n */\nexport function narrowReporterTools(\n allowed: ChatTools,\n boundary: ReporterToolBoundary,\n): ChatTools {\n const { context, userDb } = boundary;\n\n return allowed.map((sharedTool) => {\n if (sharedTool.name === \"read_intents\") {\n return tool(\n async (query: { limit?: number; page?: number }) => {\n const limit = query.limit ?? 100;\n const page = query.page ?? 1;\n const intents = await userDb.getActiveIntents();\n const start = (page - 1) * limit;\n return success({\n intents: intents.slice(start, start + limit),\n page,\n limit,\n total: intents.length,\n });\n },\n {\n name: \"read_intents\",\n description: \"Read the authenticated user's own active signals only.\",\n schema: z.object({\n limit: z.number().int().min(1).max(100).optional(),\n page: z.number().int().min(1).optional(),\n }).strict(),\n },\n );\n }\n\n if (sharedTool.name === \"search_intents\") {\n return tool(\n async (query: { query: string; limit?: number }) => success({\n intents: await userDb.searchOwnIntents(query.query, query.limit ?? 20),\n }),\n {\n name: \"search_intents\",\n description: \"Search the authenticated user's own active signals only.\",\n schema: z.object({\n query: z.string().trim().min(1),\n limit: z.number().int().min(1).max(100).optional(),\n }).strict(),\n },\n );\n }\n\n if (sharedTool.name === \"read_user_contexts\") {\n return tool(\n async () => invokeSharedTool(sharedTool, {}),\n {\n name: \"read_user_contexts\",\n description: \"Read the authenticated user's own identity and global context only.\",\n schema: z.object({}).strict(),\n },\n );\n }\n\n if (sharedTool.name === \"read_premises\") {\n return tool(\n async (query: { includeRetracted?: boolean }) => invokeSharedTool(sharedTool, {\n includeRetracted: query.includeRetracted ?? false,\n userId: context.userId,\n }),\n {\n name: \"read_premises\",\n description: \"Read the authenticated user's own premises only.\",\n schema: z.object({ includeRetracted: z.boolean().optional() }).strict(),\n },\n );\n }\n\n if (sharedTool.name === \"read_network_memberships\") {\n return tool(\n async () => invokeSharedTool(sharedTool, {}),\n {\n name: \"read_network_memberships\",\n description: \"Read the authenticated user's own network memberships only.\",\n schema: z.object({}).strict(),\n },\n );\n }\n\n if (sharedTool.name === \"read_networks\") {\n return tool(\n async () => invokeSharedTool(sharedTool, { userId: context.userId }),\n {\n name: \"read_networks\",\n description: \"Read networks available to the authenticated user.\",\n schema: z.object({}).strict(),\n },\n );\n }\n\n if (sharedTool.name === \"read_pending_questions\") {\n return tool(\n async (query: { limit?: number }) => {\n if (!boundary.findPendingQuestions) return error(\"Question lookup is not available.\");\n const questions = await boundary.findPendingQuestions(context.userId, {\n modes: [\"enrichment\", \"intent\", \"discovery\"],\n limit: query.limit ?? 10,\n });\n return success({ questions: questions.slice(0, query.limit ?? 10) });\n },\n {\n name: \"read_pending_questions\",\n description: \"Read the user's own non-negotiation pending questions; answering is unavailable here.\",\n schema: z.object({ limit: z.number().int().min(1).max(10).optional() }).strict(),\n },\n );\n }\n\n if (sharedTool.name === \"list_opportunities\") {\n return tool(\n async (query: { networkId?: string }) => {\n const scopedNetworkId = focusedNetworkId(context);\n if (scopedNetworkId && query.networkId && query.networkId !== scopedNetworkId) {\n return error(\"This chat is scoped to a different network.\");\n }\n const activeIntents = await userDb.getActiveIntents();\n const intentById = new Map(activeIntents.map((intent) => [intent.id, intent]));\n const opportunities = await userDb.getOpportunitiesForUser({\n ...(query.networkId || scopedNetworkId ? { networkId: query.networkId || scopedNetworkId } : {}),\n statuses: [\"draft\", \"pending\", \"latent\"],\n limit: 100,\n });\n const counts = new Map<string, { intentId: string; title: string; count: number }>();\n const seen = new Set<string>();\n for (const opportunity of opportunities) {\n const ownIntentIds = new Set(\n opportunity.actors\n .filter((actor) => actor.userId === context.userId && actor.intent && intentById.has(actor.intent))\n .map((actor) => actor.intent as string),\n );\n if (ownIntentIds.size === 0) continue;\n seen.add(opportunity.id);\n for (const intentId of ownIntentIds) {\n const intent = intentById.get(intentId);\n if (!intent) continue;\n const existing = counts.get(intentId) ?? {\n intentId,\n title: intent.summary?.trim() || intent.payload,\n count: 0,\n };\n existing.count += 1;\n counts.set(intentId, existing);\n }\n }\n return success({\n found: seen.size > 0,\n count: seen.size,\n bySignal: [...counts.values()],\n });\n },\n {\n name: \"list_opportunities\",\n description: \"Report current opportunity counts by the user's own signal, without counterpart identities or rows.\",\n schema: z.object({ networkId: z.string().uuid().optional() }).strict(),\n },\n );\n }\n\n return sharedTool;\n }) as ChatTools;\n}\n\n/** Creates the reporter's context-bound, allowlisted toolset. */\nexport async function createReporterTools(\n deps: ToolContext,\n preResolvedContext?: ResolvedToolContext,\n): Promise<ChatTools> {\n const explicitScope = deps.scopeType && deps.scopeId\n ? { scopeType: deps.scopeType, scopeId: deps.scopeId }\n : scopeFromNetworkId(deps.networkId);\n const resolvedContext = preResolvedContext ?? await resolveChatContext({\n database: deps.database,\n userId: deps.userId,\n networkId: explicitScope.scopeType === \"network\" ? explicitScope.scopeId : deps.networkId,\n sessionId: deps.sessionId,\n contactsEnabled: deps.contactsEnabled,\n actionToolsEnabled: deps.actionToolsEnabled,\n });\n if (explicitScope.scopeType && explicitScope.scopeId) {\n resolvedContext.scopeType = explicitScope.scopeType;\n resolvedContext.scopeId = explicitScope.scopeId;\n }\n\n const userDb = deps.userDb ?? deps.createUserDatabase(deps.database, resolvedContext.userId);\n const allowed = filterReporterTools(await createChatTools(deps, resolvedContext)) as ChatTools;\n const narrowed = narrowReporterTools(allowed, {\n context: resolvedContext,\n userDb,\n findPendingQuestions: deps.findPendingQuestions,\n });\n const actionTool = createReporterActionTool(deps, resolvedContext, userDb);\n return actionTool ? [...narrowed, actionTool] as ChatTools : narrowed;\n}\n\n/** Restricted read-only Agent reporter persona. */\nexport const REPORTER_PERSONA: ChatPersonaConfig = {\n id: REPORTER_PERSONA_ID,\n buildSystemContent: (ctx, iterCtx) => buildReporterSystemContent(ctx, iterCtx),\n createTools: (deps, preResolvedContext) => createReporterTools(deps, preResolvedContext),\n loopBehaviors: {\n createIntentCallback: false,\n hallucinationRecovery: false,\n },\n};\n"]}
|
|
1
|
+
{"version":3,"file":"reporter.persona.js","sourceRoot":"/","sources":["chat/reporter.persona.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,eAAe,EAA8D,MAAM,iCAAiC,CAAC;AAC9H,OAAO,EAAE,KAAK,EAAE,kBAAkB,EAAE,OAAO,EAAE,MAAM,iCAAiC,CAAC;AAErF,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAErF,OAAO,EAAE,0BAA0B,EAAE,oCAAoC,EAAE,MAAM,sBAAsB,CAAC;AACxG,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AAEtE,uFAAuF;AACvF,OAAO,EAAE,yBAAyB,EAAE,MAAM,sBAAsB,CAAC;AAEjE,0EAA0E;AAC1E,MAAM,CAAC,MAAM,mBAAmB,GAAG,UAAU,CAAC;AAE9C;;;GAGG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG;IACjC,cAAc;IACd,gBAAgB;IAChB,oBAAoB;IACpB,sBAAsB;IACtB,eAAe;IACf,eAAe;IACf,0BAA0B;IAC1B,wBAAwB;IACxB,oBAAoB;IACpB,uBAAuB;CACf,CAAC;AAEX,MAAM,uBAAuB,GAAwB,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B,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,EAAE,CAAC,oCAAoC,CAAC,OAAO,CAAC;IAC9F,aAAa,EAAE;QACb,oBAAoB,EAAE,KAAK;QAC3B,qBAAqB,EAAE,KAAK;KAC7B;CACF,CAAC","sourcesContent":["import { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n\nimport { createChatTools, type ChatTools, type ResolvedToolContext, type ToolContext } from \"../shared/agent/tool.factory.js\";\nimport { error, resolveChatContext, success } from \"../shared/agent/tool.helpers.js\";\nimport type { UserDatabase } from \"../shared/interfaces/database.interface.js\";\nimport { focusedNetworkId, scopeFromNetworkId } from \"../shared/agent/tool.scope.js\";\nimport type { ChatPersonaConfig } from \"./chat.persona.js\";\nimport { buildReporterSystemContent, resolveReporterDeterministicResponse } from \"./reporter.prompt.js\";\nimport { createReporterActionTool } from \"./reporter.action.tools.js\";\n\n/** Public kickoff marker used by the Agent surface to request its opening briefing. */\nexport { REPORTER_BRIEFING_KICKOFF } from \"./reporter.prompt.js\";\n\n/** Stable persona id persisted for read-only Agent reporting sessions. */\nexport const REPORTER_PERSONA_ID = \"reporter\";\n\n/**\n * Exact positive allowlist for the reporter persona. New shared tools remain\n * unavailable until they are explicitly reviewed here.\n */\nexport const REPORTER_TOOL_NAMES = [\n \"read_intents\",\n \"search_intents\",\n \"read_user_contexts\",\n \"preview_user_context\",\n \"read_premises\",\n \"read_networks\",\n \"read_network_memberships\",\n \"read_pending_questions\",\n \"list_opportunities\",\n \"report_agent_activity\",\n] as const;\n\nconst REPORTER_TOOL_ALLOWLIST: ReadonlySet<string> = new Set(REPORTER_TOOL_NAMES);\n\ninterface ReporterToolBoundary {\n context: ResolvedToolContext;\n userDb: UserDatabase;\n findPendingQuestions?: ToolContext[\"findPendingQuestions\"];\n}\n\n/** Filters a shared registry through the reporter's positive allowlist. */\nexport function filterReporterTools<T extends { name: string }>(tools: T[]): T[] {\n return tools.filter((candidate) => REPORTER_TOOL_ALLOWLIST.has(candidate.name));\n}\n\nfunction invokeSharedTool(sharedTool: { invoke: (input: unknown) => unknown }, input: unknown): Promise<string> {\n return sharedTool.invoke(input) as Promise<string>;\n}\n\n/**\n * Replaces shared tools whose normal modes can enumerate other users with\n * reporter-safe, self-only read contracts. Opportunity listing is deliberately\n * aggregate-only: it never returns a counterpart name, row, or explanation.\n */\nexport function narrowReporterTools(\n allowed: ChatTools,\n boundary: ReporterToolBoundary,\n): ChatTools {\n const { context, userDb } = boundary;\n\n return allowed.map((sharedTool) => {\n if (sharedTool.name === \"read_intents\") {\n return tool(\n async (query: { limit?: number; page?: number }) => {\n const limit = query.limit ?? 100;\n const page = query.page ?? 1;\n const intents = await userDb.getActiveIntents();\n const start = (page - 1) * limit;\n return success({\n intents: intents.slice(start, start + limit),\n page,\n limit,\n total: intents.length,\n });\n },\n {\n name: \"read_intents\",\n description: \"Read the authenticated user's own active signals only.\",\n schema: z.object({\n limit: z.number().int().min(1).max(100).optional(),\n page: z.number().int().min(1).optional(),\n }).strict(),\n },\n );\n }\n\n if (sharedTool.name === \"search_intents\") {\n return tool(\n async (query: { query: string; limit?: number }) => success({\n intents: await userDb.searchOwnIntents(query.query, query.limit ?? 20),\n }),\n {\n name: \"search_intents\",\n description: \"Search the authenticated user's own active signals only.\",\n schema: z.object({\n query: z.string().trim().min(1),\n limit: z.number().int().min(1).max(100).optional(),\n }).strict(),\n },\n );\n }\n\n if (sharedTool.name === \"read_user_contexts\") {\n return tool(\n async () => invokeSharedTool(sharedTool, {}),\n {\n name: \"read_user_contexts\",\n description: \"Read the authenticated user's own identity and global context only.\",\n schema: z.object({}).strict(),\n },\n );\n }\n\n if (sharedTool.name === \"read_premises\") {\n return tool(\n async (query: { includeRetracted?: boolean }) => invokeSharedTool(sharedTool, {\n includeRetracted: query.includeRetracted ?? false,\n userId: context.userId,\n }),\n {\n name: \"read_premises\",\n description: \"Read the authenticated user's own premises only.\",\n schema: z.object({ includeRetracted: z.boolean().optional() }).strict(),\n },\n );\n }\n\n if (sharedTool.name === \"read_network_memberships\") {\n return tool(\n async () => invokeSharedTool(sharedTool, {}),\n {\n name: \"read_network_memberships\",\n description: \"Read the authenticated user's own network memberships only.\",\n schema: z.object({}).strict(),\n },\n );\n }\n\n if (sharedTool.name === \"read_networks\") {\n return tool(\n async () => invokeSharedTool(sharedTool, { userId: context.userId }),\n {\n name: \"read_networks\",\n description: \"Read networks available to the authenticated user.\",\n schema: z.object({}).strict(),\n },\n );\n }\n\n if (sharedTool.name === \"read_pending_questions\") {\n return tool(\n async (query: { limit?: number }) => {\n if (!boundary.findPendingQuestions) return error(\"Question lookup is not available.\");\n const questions = await boundary.findPendingQuestions(context.userId, {\n modes: [\"enrichment\", \"intent\", \"discovery\"],\n limit: query.limit ?? 10,\n });\n return success({ questions: questions.slice(0, query.limit ?? 10) });\n },\n {\n name: \"read_pending_questions\",\n description: \"Read the user's own non-negotiation pending questions; answering is unavailable here.\",\n schema: z.object({ limit: z.number().int().min(1).max(10).optional() }).strict(),\n },\n );\n }\n\n if (sharedTool.name === \"list_opportunities\") {\n return tool(\n async (query: { networkId?: string }) => {\n const scopedNetworkId = focusedNetworkId(context);\n if (scopedNetworkId && query.networkId && query.networkId !== scopedNetworkId) {\n return error(\"This chat is scoped to a different network.\");\n }\n const activeIntents = await userDb.getActiveIntents();\n const intentById = new Map(activeIntents.map((intent) => [intent.id, intent]));\n const opportunities = await userDb.getOpportunitiesForUser({\n ...(query.networkId || scopedNetworkId ? { networkId: query.networkId || scopedNetworkId } : {}),\n statuses: [\"draft\", \"pending\", \"latent\"],\n limit: 100,\n });\n const counts = new Map<string, { intentId: string; title: string; count: number }>();\n const seen = new Set<string>();\n for (const opportunity of opportunities) {\n const ownIntentIds = new Set(\n opportunity.actors\n .filter((actor) => actor.userId === context.userId && actor.intent && intentById.has(actor.intent))\n .map((actor) => actor.intent as string),\n );\n if (ownIntentIds.size === 0) continue;\n seen.add(opportunity.id);\n for (const intentId of ownIntentIds) {\n const intent = intentById.get(intentId);\n if (!intent) continue;\n const existing = counts.get(intentId) ?? {\n intentId,\n title: intent.summary?.trim() || intent.payload,\n count: 0,\n };\n existing.count += 1;\n counts.set(intentId, existing);\n }\n }\n return success({\n found: seen.size > 0,\n count: seen.size,\n bySignal: [...counts.values()],\n });\n },\n {\n name: \"list_opportunities\",\n description: \"Report current opportunity counts by the user's own signal, without counterpart identities or rows.\",\n schema: z.object({ networkId: z.string().uuid().optional() }).strict(),\n },\n );\n }\n\n return sharedTool;\n }) as ChatTools;\n}\n\n/** Creates the reporter's context-bound, allowlisted toolset. */\nexport async function createReporterTools(\n deps: ToolContext,\n preResolvedContext?: ResolvedToolContext,\n): Promise<ChatTools> {\n const explicitScope = deps.scopeType && deps.scopeId\n ? { scopeType: deps.scopeType, scopeId: deps.scopeId }\n : scopeFromNetworkId(deps.networkId);\n const resolvedContext = preResolvedContext ?? await resolveChatContext({\n database: deps.database,\n userId: deps.userId,\n networkId: explicitScope.scopeType === \"network\" ? explicitScope.scopeId : deps.networkId,\n sessionId: deps.sessionId,\n contactsEnabled: deps.contactsEnabled,\n actionToolsEnabled: deps.actionToolsEnabled,\n });\n if (explicitScope.scopeType && explicitScope.scopeId) {\n resolvedContext.scopeType = explicitScope.scopeType;\n resolvedContext.scopeId = explicitScope.scopeId;\n }\n\n const userDb = deps.userDb ?? deps.createUserDatabase(deps.database, resolvedContext.userId);\n const allowed = filterReporterTools(await createChatTools(deps, resolvedContext)) as ChatTools;\n const narrowed = narrowReporterTools(allowed, {\n context: resolvedContext,\n userDb,\n findPendingQuestions: deps.findPendingQuestions,\n });\n const actionTool = createReporterActionTool(deps, resolvedContext, userDb);\n return actionTool ? [...narrowed, actionTool] as ChatTools : narrowed;\n}\n\n/** Restricted read-only Agent reporter persona. */\nexport const REPORTER_PERSONA: ChatPersonaConfig = {\n id: REPORTER_PERSONA_ID,\n buildSystemContent: (ctx, iterCtx) => buildReporterSystemContent(ctx, iterCtx),\n createTools: (deps, preResolvedContext) => createReporterTools(deps, preResolvedContext),\n resolveDeterministicResponse: (_ctx, iterCtx) => resolveReporterDeterministicResponse(iterCtx),\n loopBehaviors: {\n createIntentCallback: false,\n hallucinationRecovery: false,\n },\n};\n"]}
|
|
@@ -10,6 +10,10 @@ export declare const REPORTER_BRIEFING_KICKOFF = "reporter-briefing-kickoff";
|
|
|
10
10
|
* @returns Whether this turn is the Agent-surface briefing kickoff
|
|
11
11
|
*/
|
|
12
12
|
export declare function isReporterBriefingKickoff(message?: string): boolean;
|
|
13
|
+
/** Recognizes a short acknowledgement only when a prior proposal is visible. */
|
|
14
|
+
export declare function isReporterActionConfirmation(message?: string, hasPriorProposal?: boolean): boolean;
|
|
15
|
+
/** Deterministic reporter response for contextual typed acknowledgements. */
|
|
16
|
+
export declare function resolveReporterDeterministicResponse(iterCtx: IterationContext): string | null;
|
|
13
17
|
/**
|
|
14
18
|
* Builds the read-only reporter persona prompt.
|
|
15
19
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reporter.prompt.d.ts","sourceRoot":"/","sources":["chat/reporter.prompt.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AAC3E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAEjE,+EAA+E;AAC/E,eAAO,MAAM,yBAAyB,8BAA8B,CAAC;AAErE;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,OAAO,
|
|
1
|
+
{"version":3,"file":"reporter.prompt.d.ts","sourceRoot":"/","sources":["chat/reporter.prompt.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AAC3E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAEjE,+EAA+E;AAC/E,eAAO,MAAM,yBAAyB,8BAA8B,CAAC;AAErE;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,OAAO,CAOnE;AAED,gFAAgF;AAChF,wBAAgB,4BAA4B,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,gBAAgB,UAAQ,GAAG,OAAO,CAoBhG;AAED,6EAA6E;AAC7E,wBAAgB,oCAAoC,CAAC,OAAO,EAAE,gBAAgB,GAAG,MAAM,GAAG,IAAI,CAM7F;AA8BD;;;;;;GAMG;AACH,wBAAgB,0BAA0B,CACxC,GAAG,EAAE,mBAAmB,EACxB,OAAO,CAAC,EAAE,gBAAgB,GACzB,MAAM,CA6ER"}
|
|
@@ -13,13 +13,37 @@ export function isReporterBriefingKickoff(message) {
|
|
|
13
13
|
.replace(/^_+|_+$/g, "");
|
|
14
14
|
if (!normalized)
|
|
15
15
|
return false;
|
|
16
|
+
return normalized === REPORTER_BRIEFING_KICKOFF;
|
|
17
|
+
}
|
|
18
|
+
/** Recognizes a short acknowledgement only when a prior proposal is visible. */
|
|
19
|
+
export function isReporterActionConfirmation(message, hasPriorProposal = false) {
|
|
20
|
+
const normalized = message?.trim().toLocaleLowerCase()
|
|
21
|
+
.replace(/[.!?,;:]+$/g, "")
|
|
22
|
+
.replace(/\s+/g, " ");
|
|
23
|
+
if (!normalized || !hasPriorProposal)
|
|
24
|
+
return false;
|
|
16
25
|
return new Set([
|
|
17
|
-
|
|
18
|
-
"
|
|
19
|
-
"
|
|
20
|
-
"
|
|
26
|
+
"i confirm",
|
|
27
|
+
"confirm",
|
|
28
|
+
"confirm it",
|
|
29
|
+
"approve",
|
|
30
|
+
"approved",
|
|
31
|
+
"approve it",
|
|
32
|
+
"i approve",
|
|
33
|
+
"yes",
|
|
34
|
+
"yes i confirm",
|
|
35
|
+
"yes please",
|
|
36
|
+
"please do it",
|
|
37
|
+
"proceed",
|
|
38
|
+
"go ahead",
|
|
21
39
|
]).has(normalized);
|
|
22
40
|
}
|
|
41
|
+
/** Deterministic reporter response for contextual typed acknowledgements. */
|
|
42
|
+
export function resolveReporterDeterministicResponse(iterCtx) {
|
|
43
|
+
if (!isReporterActionConfirmation(iterCtx.currentMessage, iterCtx.hasPriorAgentActionProposal === true))
|
|
44
|
+
return null;
|
|
45
|
+
return "Use the visible proposal card's Confirm control to approve this request. I won't run or recreate it from a chat acknowledgement.";
|
|
46
|
+
}
|
|
23
47
|
function buildBriefingGuidance(iterCtx) {
|
|
24
48
|
if (!isReporterBriefingKickoff(iterCtx?.currentMessage))
|
|
25
49
|
return "";
|
|
@@ -33,6 +57,16 @@ This is the Agent-surface briefing kickoff. Call report_agent_activity first wit
|
|
|
33
57
|
4. what should I sharpen?
|
|
34
58
|
Do not claim a metric unless it appears in a tool result from this turn. If a section has no grounded data, say that plainly rather than filling the gap.`;
|
|
35
59
|
}
|
|
60
|
+
function buildTurnGuidance(iterCtx) {
|
|
61
|
+
const currentMessage = iterCtx?.currentMessage;
|
|
62
|
+
const confirmation = isReporterActionConfirmation(currentMessage, iterCtx?.hasPriorAgentActionProposal === true);
|
|
63
|
+
return `
|
|
64
|
+
|
|
65
|
+
## Turn discipline
|
|
66
|
+
- The detailed four-section opening briefing is reserved for the exact reporter-briefing-kickoff marker. Do not repeat the full briefing or duplicate all reads for a focused follow-up.
|
|
67
|
+
- For every non-kickoff message, answer only the user's current request and perform only the reads needed to answer it.
|
|
68
|
+
${confirmation ? `- This message is only a natural-language acknowledgement. Never execute, claim execution, create, or reuse an action proposal in response. Do not call report_agent_activity or propose_cleanup_actions. Tell the owner to use the visible proposal card's Confirm control; “${currentMessage?.trim()}” is not endpoint confirmation.` : ""}`;
|
|
69
|
+
}
|
|
36
70
|
/**
|
|
37
71
|
* Builds the read-only reporter persona prompt.
|
|
38
72
|
*
|
|
@@ -111,6 +145,6 @@ ${profileContext}
|
|
|
111
145
|
${membershipContext}
|
|
112
146
|
\`\`\`
|
|
113
147
|
|
|
114
|
-
Only the identity, context, and membership metadata above are preloaded. Signals, premises, questions, and activity are not preloaded: call the appropriate read/report tool before describing them.${buildBriefingGuidance(iterCtx)}`;
|
|
148
|
+
Only the identity, context, and membership metadata above are preloaded. Signals, premises, questions, and activity are not preloaded: call the appropriate read/report tool before describing them.${buildTurnGuidance(iterCtx)}${buildBriefingGuidance(iterCtx)}`;
|
|
115
149
|
}
|
|
116
150
|
//# sourceMappingURL=reporter.prompt.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reporter.prompt.js","sourceRoot":"/","sources":["chat/reporter.prompt.ts"],"names":[],"mappings":"AAGA,+EAA+E;AAC/E,MAAM,CAAC,MAAM,yBAAyB,GAAG,2BAA2B,CAAC;AAErE;;;;;;GAMG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAAgB;IACxD,MAAM,UAAU,GAAG,OAAO,EAAE,IAAI,EAAE,CAAC,iBAAiB,EAAE;SACnD,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC;SACrB,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;IAC3B,IAAI,CAAC,UAAU;QAAE,OAAO,KAAK,CAAC;IAE9B,OAAO,IAAI,GAAG,CAAC;QACb,yBAAyB;QACzB,mBAAmB;QACnB,mBAAmB;QACnB,gBAAgB;KACjB,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;AACrB,CAAC;AAED,SAAS,qBAAqB,CAAC,OAA0B;IACvD,IAAI,CAAC,yBAAyB,CAAC,OAAO,EAAE,cAAc,CAAC;QAAE,OAAO,EAAE,CAAC;IAEnE,OAAO;;;;;;;;0JAQiJ,CAAC;AAC3J,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,0BAA0B,CACxC,GAAwB,EACxB,OAA0B;IAE1B,MAAM,WAAW,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IACtD,MAAM,cAAc,GAAG,GAAG,CAAC,WAAW;QACpC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,WAAW,EAAE,IAAI,EAAE,CAAC,CAAC;QAC1C,CAAC,CAAC,MAAM,CAAC;IACX,MAAM,iBAAiB,GAAG,IAAI,CAAC,SAAS,CACtC,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;QACjC,EAAE,EAAE,OAAO,CAAC,SAAS;QACrB,KAAK,EAAE,OAAO,CAAC,YAAY;QAC3B,UAAU,EAAE,OAAO,CAAC,UAAU;KAC/B,CAAC,CAAC,EACH,IAAI,EACJ,CAAC,CACF,CAAC;IACF,MAAM,YAAY,GAAG,GAAG,CAAC,kBAAkB;QACzC,CAAC,CAAC,mOAAmO;QACrO,CAAC,CAAC,uTAAuT,CAAC;IAC5T,MAAM,YAAY,GAAG,GAAG,CAAC,kBAAkB;QACzC,CAAC,CAAC,oNAAoN;QACtN,CAAC,CAAC,kLAAkL,CAAC;IACvL,MAAM,cAAc,GAAG,GAAG,CAAC,kBAAkB,CAAC,CAAC,CAAC;;;;;;;;CAQjD,CAAC,CAAC,CAAC,EAAE,CAAC;IAEL,OAAO,qEAAqE,GAAG,CAAC,QAAQ;;EAExF,YAAY,GAAG,cAAc;;;;;;EAM7B,YAAY;;;;;;;;;;;;;;;;;;oGAkBsF,GAAG,CAAC,kBAAkB,CAAC,CAAC,CAAC,sGAAsG,CAAC,CAAC,CAAC,EAAE;;;UAG9N,GAAG,CAAC,QAAQ,KAAK,GAAG,CAAC,SAAS,UAAU,GAAG,CAAC,MAAM;;;;EAI1D,WAAW;;;;;EAKX,cAAc;;;;;EAKd,iBAAiB;;;sMAGmL,qBAAqB,CAAC,OAAO,CAAC,EAAE,CAAC;AACvO,CAAC","sourcesContent":["import type { ResolvedToolContext } from \"../shared/agent/tool.factory.js\";\nimport type { IterationContext } from \"./chat.prompt.modules.js\";\n\n/** Stable marker used by the Agent surface to request its opening briefing. */\nexport const REPORTER_BRIEFING_KICKOFF = \"reporter-briefing-kickoff\";\n\n/**\n * Recognizes the explicit opening briefing marker without putting ordinary\n * reporter conversations into briefing mode accidentally.\n *\n * @param message - Latest user message in the current turn\n * @returns Whether this turn is the Agent-surface briefing kickoff\n */\nexport function isReporterBriefingKickoff(message?: string): boolean {\n const normalized = message?.trim().toLocaleLowerCase()\n .replace(/[–—]/g, \"-\")\n .replace(/^_+|_+$/g, \"\");\n if (!normalized) return false;\n\n return new Set([\n REPORTER_BRIEFING_KICKOFF,\n \"reporter-briefing\",\n \"reporter briefing\",\n \"agent briefing\",\n ]).has(normalized);\n}\n\nfunction buildBriefingGuidance(iterCtx?: IterationContext): string {\n if (!isReporterBriefingKickoff(iterCtx?.currentMessage)) return \"\";\n\n return `\n\n## Opening briefing\nThis is the Agent-surface briefing kickoff. Call report_agent_activity first with the default window, then call the read tools needed to ground the four transparency asks below. Present one concise briefing covering:\n1. summarize all my signals;\n2. what did you do today?;\n3. how do I look to others?;\n4. what should I sharpen?\nDo not claim a metric unless it appears in a tool result from this turn. If a section has no grounded data, say that plainly rather than filling the gap.`;\n}\n\n/**\n * Builds the read-only reporter persona prompt.\n *\n * @param ctx - Resolved authenticated user context\n * @param iterCtx - Current agent-loop context used for briefing kickoff\n * @returns Complete reporter system content\n */\nexport function buildReporterSystemContent(\n ctx: ResolvedToolContext,\n iterCtx?: IterationContext,\n): string {\n const userContext = JSON.stringify(ctx.user, null, 2);\n const profileContext = ctx.userProfile\n ? JSON.stringify(ctx.userProfile, null, 2)\n : \"null\";\n const membershipContext = JSON.stringify(\n ctx.userNetworks.map((network) => ({\n id: network.networkId,\n title: network.networkTitle,\n isPersonal: network.isPersonal,\n })),\n null,\n 2,\n );\n const roleGuidance = ctx.actionToolsEnabled\n ? \"Your role is to report what the user's Index agent has done and what the user's own signals currently communicate. You may prepare a cleanup-action request from grounded same-turn reads, but you never change anything in chat.\"\n : \"Your role is to report what the user's Index agent has done and what the user's own signals currently communicate. You observe; you never change anything. Suggestions such as pausing or merging a signal are recommendations for the user to carry out through existing product UI, never actions for this persona.\";\n const mutationRule = ctx.actionToolsEnabled\n ? \"- Never mutate data in chat. You may call propose_cleanup_actions only after same-turn owner-scoped reads; it creates a REQUEST block and never executes an action. The owner must confirm through the product UI.\"\n : \"- Never create, update, delete, confirm, answer, remember, forget, assign, discover, negotiate, scrape, or otherwise mutate data. Do not ask the user a question through a tool.\";\n const actionGuidance = ctx.actionToolsEnabled ? `\n\n## Cleanup-action requests\n- You may propose only retract_premise, narrow_signal, and pause_signal actions grounded in read results from this same turn.\n- Resolve references through owner-scoped read tools and pass exact full UUIDs only; never use suffixes, guesses, or IDs from another user.\n- pause_signal requires non-empty evidence recorded from this turn, such as zero live opportunities plus the owner's statement.\n- The proposal block is a REQUEST for owner confirmation. Never narrate an action as completed and never mutate inside chat.\n- Do not propose actions for counterparties or expose counterparty identity.\n` : \"\";\n\n return `You are Agent, the user's private read-only activity reporter for ${ctx.userName}.\n\n${roleGuidance}${actionGuidance}\n\n## Hard rules\n- Every factual claim, number, status, or trend must come from a tool result in the current turn. Never invent, estimate, or reuse an unverified metric.\n- Use report_agent_activity for activity counts and read_intents/read_user_contexts/read_premises/read_networks/read_network_memberships/read_pending_questions for the underlying current state.\n- Counterparties are identity-free aggregate data only: never reveal names, IDs, transcripts, message text, or per-counterparty rows. Do not infer what another person thinks from a match or negotiation.\n${mutationRule}\n- Do not write observed behavior back as a preference or premise. The user decides whether to act on a suggestion.\n- If opportunity information is relevant, use only the restricted list_opportunities result or report_agent_activity result. Do not expose raw evaluator reasoning, matchReason, or internal JSON. Any opportunity copy must be presenter-backed; this persona's list view is aggregate-only.\n- Be transparent about missing data and the reporting window. Keep the response concise, calm, and useful without hype.\n\n## Four transparency asks\nBe ready to answer:\n- “summarize all my signals” — read the user's own signals and describe their current themes without inventing a synthesis.\n- “what did you do today?” — report only grounded activity counts from the requested window.\n- “how do I look to others?” — describe only the user's own stored context and signals; do not claim access to private counterparty opinions.\n- “what should I sharpen?” — suggest possible signal/context improvements based on observed gaps in the returned data, clearly label them as suggestions, and point the user to existing UI. Never apply them.\n\n## Allowed capabilities\n- Own signal reads: read_intents, search_intents.\n- Own context reads: read_user_contexts, preview_user_context, read_premises.\n- Own community context: read_networks, read_network_memberships.\n- Own pending-question reads: read_pending_questions (never answer them).\n- Aggregate activity reporting: report_agent_activity.\n- Aggregate current opportunity reporting: list_opportunities (no counterpart identities or rows).${ctx.actionToolsEnabled ? \"\\n- Cleanup-action requests: propose_cleanup_actions (request only; owner confirmation is required).\" : \"\"}\n\n## Session identity (preloaded)\n- User: ${ctx.userName} (${ctx.userEmail}), id: ${ctx.userId}\n\n### User record\n\\`\\`\\`json\n${userContext}\n\\`\\`\\`\n\n### User context\n\\`\\`\\`json\n${profileContext}\n\\`\\`\\`\n\n### Current memberships\n\\`\\`\\`json\n${membershipContext}\n\\`\\`\\`\n\nOnly the identity, context, and membership metadata above are preloaded. Signals, premises, questions, and activity are not preloaded: call the appropriate read/report tool before describing them.${buildBriefingGuidance(iterCtx)}`;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"reporter.prompt.js","sourceRoot":"/","sources":["chat/reporter.prompt.ts"],"names":[],"mappings":"AAGA,+EAA+E;AAC/E,MAAM,CAAC,MAAM,yBAAyB,GAAG,2BAA2B,CAAC;AAErE;;;;;;GAMG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAAgB;IACxD,MAAM,UAAU,GAAG,OAAO,EAAE,IAAI,EAAE,CAAC,iBAAiB,EAAE;SACnD,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC;SACrB,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;IAC3B,IAAI,CAAC,UAAU;QAAE,OAAO,KAAK,CAAC;IAE9B,OAAO,UAAU,KAAK,yBAAyB,CAAC;AAClD,CAAC;AAED,gFAAgF;AAChF,MAAM,UAAU,4BAA4B,CAAC,OAAgB,EAAE,gBAAgB,GAAG,KAAK;IACrF,MAAM,UAAU,GAAG,OAAO,EAAE,IAAI,EAAE,CAAC,iBAAiB,EAAE;SACnD,OAAO,CAAC,aAAa,EAAE,EAAE,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.prompt.modules.js\";\n\n/** Stable marker used by the Agent surface to request its opening briefing. */\nexport const REPORTER_BRIEFING_KICKOFF = \"reporter-briefing-kickoff\";\n\n/**\n * Recognizes the explicit opening briefing marker without putting ordinary\n * reporter conversations into briefing mode accidentally.\n *\n * @param message - Latest user message in the current turn\n * @returns Whether this turn is the Agent-surface briefing kickoff\n */\nexport function isReporterBriefingKickoff(message?: string): boolean {\n const normalized = message?.trim().toLocaleLowerCase()\n .replace(/[–—]/g, \"-\")\n .replace(/^_+|_+$/g, \"\");\n if (!normalized) return false;\n\n return normalized === REPORTER_BRIEFING_KICKOFF;\n}\n\n/** Recognizes a short acknowledgement only when a prior proposal is visible. */\nexport function isReporterActionConfirmation(message?: string, hasPriorProposal = false): boolean {\n const normalized = message?.trim().toLocaleLowerCase()\n .replace(/[.!?,;:]+$/g, \"\")\n .replace(/\\s+/g, \" \");\n if (!normalized || !hasPriorProposal) return false;\n return new Set([\n \"i confirm\",\n \"confirm\",\n \"confirm it\",\n \"approve\",\n \"approved\",\n \"approve it\",\n \"i approve\",\n \"yes\",\n \"yes i confirm\",\n \"yes please\",\n \"please do it\",\n \"proceed\",\n \"go ahead\",\n ]).has(normalized);\n}\n\n/** Deterministic reporter response for contextual typed acknowledgements. */\nexport function resolveReporterDeterministicResponse(iterCtx: IterationContext): string | null {\n if (!isReporterActionConfirmation(\n iterCtx.currentMessage,\n iterCtx.hasPriorAgentActionProposal === true,\n )) return null;\n return \"Use the visible proposal card's Confirm control to approve this request. I won't run or recreate it from a chat acknowledgement.\";\n}\n\nfunction buildBriefingGuidance(iterCtx?: IterationContext): string {\n if (!isReporterBriefingKickoff(iterCtx?.currentMessage)) return \"\";\n\n return `\n\n## Opening briefing\nThis is the Agent-surface briefing kickoff. Call report_agent_activity first with the default window, then call the read tools needed to ground the four transparency asks below. Present one concise briefing covering:\n1. summarize all my signals;\n2. what did you do today?;\n3. how do I look to others?;\n4. what should I sharpen?\nDo not claim a metric unless it appears in a tool result from this turn. If a section has no grounded data, say that plainly rather than filling the gap.`;\n}\n\nfunction buildTurnGuidance(iterCtx?: IterationContext): string {\n const currentMessage = iterCtx?.currentMessage;\n const confirmation = isReporterActionConfirmation(\n currentMessage,\n iterCtx?.hasPriorAgentActionProposal === true,\n );\n return `\n\n## Turn discipline\n- The detailed four-section opening briefing is reserved for the exact reporter-briefing-kickoff marker. Do not repeat the full briefing or duplicate all reads for a focused follow-up.\n- For every non-kickoff message, answer only the user's current request and perform only the reads needed to answer it.\n${confirmation ? `- This message is only a natural-language acknowledgement. Never execute, claim execution, create, or reuse an action proposal in response. Do not call report_agent_activity or propose_cleanup_actions. Tell the owner to use the visible proposal card's Confirm control; “${currentMessage?.trim()}” is not endpoint confirmation.` : \"\"}`;\n}\n\n/**\n * Builds the read-only reporter persona prompt.\n *\n * @param ctx - Resolved authenticated user context\n * @param iterCtx - Current agent-loop context used for briefing kickoff\n * @returns Complete reporter system content\n */\nexport function buildReporterSystemContent(\n ctx: ResolvedToolContext,\n iterCtx?: IterationContext,\n): string {\n const userContext = JSON.stringify(ctx.user, null, 2);\n const profileContext = ctx.userProfile\n ? JSON.stringify(ctx.userProfile, null, 2)\n : \"null\";\n const membershipContext = JSON.stringify(\n ctx.userNetworks.map((network) => ({\n id: network.networkId,\n title: network.networkTitle,\n isPersonal: network.isPersonal,\n })),\n null,\n 2,\n );\n const roleGuidance = ctx.actionToolsEnabled\n ? \"Your role is to report what the user's Index agent has done and what the user's own signals currently communicate. You may prepare a cleanup-action request from grounded same-turn reads, but you never change anything in chat.\"\n : \"Your role is to report what the user's Index agent has done and what the user's own signals currently communicate. You observe; you never change anything. Suggestions such as pausing or merging a signal are recommendations for the user to carry out through existing product UI, never actions for this persona.\";\n const mutationRule = ctx.actionToolsEnabled\n ? \"- Never mutate data in chat. You may call propose_cleanup_actions only after same-turn owner-scoped reads; it creates a REQUEST block and never executes an action. The owner must confirm through the product UI.\"\n : \"- Never create, update, delete, confirm, answer, remember, forget, assign, discover, negotiate, scrape, or otherwise mutate data. Do not ask the user a question through a tool.\";\n const actionGuidance = ctx.actionToolsEnabled ? `\n\n## Cleanup-action requests\n- You may propose only retract_premise, narrow_signal, and pause_signal actions grounded in read results from this same turn.\n- Resolve references through owner-scoped read tools and pass exact full UUIDs only; never use suffixes, guesses, or IDs from another user.\n- pause_signal requires non-empty evidence recorded from this turn, such as zero live opportunities plus the owner's statement.\n- The proposal block is a REQUEST for owner confirmation. Never narrate an action as completed and never mutate inside chat.\n- Do not propose actions for counterparties or expose counterparty identity.\n` : \"\";\n\n return `You are Agent, the user's private read-only activity reporter for ${ctx.userName}.\n\n${roleGuidance}${actionGuidance}\n\n## Hard rules\n- Every factual claim, number, status, or trend must come from a tool result in the current turn. Never invent, estimate, or reuse an unverified metric.\n- Use report_agent_activity for activity counts and read_intents/read_user_contexts/read_premises/read_networks/read_network_memberships/read_pending_questions for the underlying current state.\n- Counterparties are identity-free aggregate data only: never reveal names, IDs, transcripts, message text, or per-counterparty rows. Do not infer what another person thinks from a match or negotiation.\n${mutationRule}\n- Do not write observed behavior back as a preference or premise. The user decides whether to act on a suggestion.\n- If opportunity information is relevant, use only the restricted list_opportunities result or report_agent_activity result. Do not expose raw evaluator reasoning, matchReason, or internal JSON. Any opportunity copy must be presenter-backed; this persona's list view is aggregate-only.\n- Be transparent about missing data and the reporting window. Keep the response concise, calm, and useful without hype.\n\n## Four transparency asks\nBe ready to answer:\n- “summarize all my signals” — read the user's own signals and describe their current themes without inventing a synthesis.\n- “what did you do today?” — report only grounded activity counts from the requested window.\n- “how do I look to others?” — describe only the user's own stored context and signals; do not claim access to private counterparty opinions.\n- “what should I sharpen?” — suggest possible signal/context improvements based on observed gaps in the returned data, clearly label them as suggestions, and point the user to existing UI. Never apply them.\n\n## Allowed capabilities\n- Own signal reads: read_intents, search_intents.\n- Own context reads: read_user_contexts, preview_user_context, read_premises.\n- Own community context: read_networks, read_network_memberships.\n- Own pending-question reads: read_pending_questions (never answer them).\n- Aggregate activity reporting: report_agent_activity.\n- Aggregate current opportunity reporting: list_opportunities (no counterpart identities or rows).${ctx.actionToolsEnabled ? \"\\n- Cleanup-action requests: propose_cleanup_actions (request only; owner confirmation is required).\" : \"\"}\n\n## Session identity (preloaded)\n- User: ${ctx.userName} (${ctx.userEmail}), id: ${ctx.userId}\n\n### User record\n\\`\\`\\`json\n${userContext}\n\\`\\`\\`\n\n### User context\n\\`\\`\\`json\n${profileContext}\n\\`\\`\\`\n\n### Current memberships\n\\`\\`\\`json\n${membershipContext}\n\\`\\`\\`\n\nOnly the identity, context, and membership metadata above are preloaded. Signals, premises, questions, and activity are not preloaded: call the appropriate read/report tool before describing them.${buildTurnGuidance(iterCtx)}${buildBriefingGuidance(iterCtx)}`;\n}\n"]}
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
* dismissal-driven reversal removes them.
|
|
14
14
|
* - `detail` carries the template chip text built from the user's OWN answer
|
|
15
15
|
* ("Hands-on builders vs advisors: you chose Advisor") — never LLM
|
|
16
|
-
* reasoning (opportunity-presentation
|
|
16
|
+
* reasoning (review-opportunity-presentation).
|
|
17
17
|
*/
|
|
18
18
|
import { POOL_ADJUSTMENT_FACTOR_OTHER, POOL_ADJUSTMENT_FACTOR_UNKNOWN, POOL_ADJUSTMENT_FLOOR } from "./discriminator.env.js";
|
|
19
19
|
/** Reads valid adjustments, optionally narrowed to one recipient + intent. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"discriminator.adjustments.js","sourceRoot":"/","sources":["opportunity/discriminator/discriminator.adjustments.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EAAE,4BAA4B,EAAE,8BAA8B,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AA6B7H,8EAA8E;AAC9E,MAAM,UAAU,mBAAmB,CACjC,QAAoD,EACpD,UAAqC;IAErC,MAAM,GAAG,GAAG,QAAQ,EAAE,eAAe,CAAC;IACtC,IAAI,CAAC,KAAK,CAAC,OAAO,CA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I/O.\n *\n * When a user answers a pool_discovery question, every candidate the mining\n * pass assigned to a side gets a multiplicative adjustment written to\n * `opportunities.metadata.poolAdjustments`. The home feed (flag-gated) orders\n * by `confidence × Π factor`, floored so demoted candidates stay visible.\n *\n * Invariants:\n * - Deterministic and O(pool): no LLM at answer time — the applyPlan was\n * computed (and evidence-verified) at mining time.\n * - Reversible: entries are keyed by questionId; re-answering replaces them,\n * dismissal-driven reversal removes them.\n * - `detail` carries the template chip text built from the user's OWN answer\n * (\"Hands-on builders vs advisors: you chose Advisor\") — never LLM\n * reasoning (opportunity-presentation-safety).\n */\nimport { POOL_ADJUSTMENT_FACTOR_OTHER, POOL_ADJUSTMENT_FACTOR_UNKNOWN, POOL_ADJUSTMENT_FLOOR } from \"./discriminator.env.js\";\nimport type { QuestionPoolDiscriminator } from \"../../shared/schemas/question.schema.js\";\n\n/** Recipient and intent provenance that scopes one pool preference. */\nexport interface PoolAdjustmentProvenance {\n recipientUserId: string;\n intentId: string;\n}\n\n/** One applied adjustment on an opportunity (stored in metadata.poolAdjustments). */\nexport interface PoolAdjustment extends PoolAdjustmentProvenance {\n /** The answered question that produced this adjustment (reversal key). */\n questionId: string;\n /** Discriminator label, e.g. \"Hands-on builders vs advisors\". */\n label: string;\n /** Side this candidate was assigned to (or \"unknown\"). */\n side: string;\n /** Multiplicative factor: chosen 1.0, other 0.6, unknown 0.9. */\n factor: number;\n /** Template chip text from the user's own answer. Set on demotions only. */\n detail?: string;\n /** ISO-8601 apply timestamp. */\n appliedAt: string;\n /** Full intent fingerprint authoritative when this adjustment was created. */\n intentFingerprint?: string;\n /** Audit-only marker: stale adjustments remain stored but have no ranking effect. */\n stale?: true;\n}\n\n/** Reads valid adjustments, optionally narrowed to one recipient + intent. */\nexport function readPoolAdjustments(\n metadata: Record<string, unknown> | null | undefined,\n provenance?: PoolAdjustmentProvenance,\n): PoolAdjustment[] {\n const raw = metadata?.poolAdjustments;\n if (!Array.isArray(raw)) return [];\n return raw.filter((a): a is PoolAdjustment => {\n if (\n typeof a !== \"object\" || a === null ||\n typeof (a as PoolAdjustment).questionId !== \"string\" ||\n typeof (a as PoolAdjustment).recipientUserId !== \"string\" ||\n typeof (a as PoolAdjustment).intentId !== \"string\" ||\n typeof (a as PoolAdjustment).factor !== \"number\" ||\n ((a as PoolAdjustment).stale !== undefined && (a as PoolAdjustment).stale !== true)\n ) return false;\n return provenance === undefined || (\n (a as PoolAdjustment).recipientUserId === provenance.recipientUserId &&\n (a as PoolAdjustment).intentId === provenance.intentId\n );\n });\n}\n\n/** Reads valid, non-stale adjustments for ranking and presentation behavior. */\nexport function readActivePoolAdjustments(\n metadata: Record<string, unknown> | null | undefined,\n provenance?: PoolAdjustmentProvenance,\n): PoolAdjustment[] {\n return readPoolAdjustments(metadata, provenance).filter((adjustment) => adjustment.stale !== true);\n}\n\n/**\n * Cumulative adjustment multiplier for an opportunity, floored at\n * {@link POOL_ADJUSTMENT_FLOOR}. 1 when no scoped adjustments exist.\n */\nexport function poolAdjustmentMultiplier(\n metadata: Record<string, unknown> | null | undefined,\n provenance: PoolAdjustmentProvenance,\n): number {\n const adjustments = readActivePoolAdjustments(metadata, provenance);\n if (adjustments.length === 0) return 1;\n const product = adjustments.reduce((acc, a) => acc * (Number.isFinite(a.factor) && a.factor > 0 ? a.factor : 1), 1);\n return Math.max(POOL_ADJUSTMENT_FLOOR, product);\n}\n\n/** Adjusted confidence: `confidence × Π factor`, floored. */\nexport function adjustedConfidence(\n confidence: number,\n metadata: Record<string, unknown> | null | undefined,\n provenance: PoolAdjustmentProvenance,\n): number {\n return confidence * poolAdjustmentMultiplier(metadata, provenance);\n}\n\n/** Deterministic provenance signal stored alongside one adjustment. */\nexport interface PoolAdjustmentSignal extends PoolAdjustmentProvenance {\n type: \"pool_discriminator\";\n weight: 1 | -1 | 0;\n detail: string;\n questionId: string;\n}\n\n/** Pure helper input shared by Tier-0 answers and newborn stamping. */\nexport interface BuildPoolAdjustmentInput extends PoolAdjustmentProvenance {\n questionId: string;\n label: string;\n /** Verified side assignment, or null when the candidate is unassigned. */\n assignedSide: string | null;\n chosenSide: string;\n appliedAt: string;\n /** Full intent fingerprint authoritative when this adjustment was created. */\n intentFingerprint?: string;\n}\n\n/**\n * Build one P3-compatible adjustment and signal. This is the only place that\n * defines chosen/other/unknown factors, weights, and safe template details.\n */\nexport function buildPoolAdjustment(input: BuildPoolAdjustmentInput): {\n adjustment: PoolAdjustment;\n signal: PoolAdjustmentSignal;\n} {\n const isUnknown = input.assignedSide === null;\n const isChosen = !isUnknown && input.assignedSide === input.chosenSide;\n const factor = isUnknown ? POOL_ADJUSTMENT_FACTOR_UNKNOWN : isChosen ? 1 : POOL_ADJUSTMENT_FACTOR_OTHER;\n const weight = isUnknown ? 0 : isChosen ? 1 : -1;\n const side = input.assignedSide ?? \"unknown\";\n return {\n adjustment: {\n questionId: input.questionId,\n recipientUserId: input.recipientUserId,\n intentId: input.intentId,\n label: input.label,\n side,\n factor,\n ...(!isChosen && !isUnknown ? { detail: `${input.label}: you chose ${input.chosenSide}` } : {}),\n appliedAt: input.appliedAt,\n ...(input.intentFingerprint !== undefined ? { intentFingerprint: input.intentFingerprint } : {}),\n },\n signal: {\n type: \"pool_discriminator\",\n weight,\n recipientUserId: input.recipientUserId,\n intentId: input.intentId,\n detail: isUnknown ? `${input.label}: unassigned` : `${input.label}: ${input.chosenSide}`,\n questionId: input.questionId,\n },\n };\n}\n\n/** Plan entry: what to write on one opportunity for one answer. */\nexport interface PoolAdjustmentPlanEntry {\n opportunityId: string;\n adjustment: PoolAdjustment;\n signal: PoolAdjustmentSignal;\n}\n\n/**\n * Computes the write plan for one answered discriminator. Pure: the caller\n * loads/patches rows. \"Both matter\" (or any label not in `sides`) yields an\n * empty plan — no preference, no adjustments.\n *\n * @param discriminator The asked discriminator (from detection.pool).\n * @param chosenSide The selected option label (chip label = side label).\n * @param questionId Reversal key.\n * @param recipientUserId User whose answer produced the preference.\n * @param intentId Intent whose candidate pool was ranked.\n * @param now ISO-8601 timestamp.\n * @param intentFingerprint Full intent fingerprint authoritative at apply time.\n */\nexport function planPoolAdjustments(\n discriminator: QuestionPoolDiscriminator,\n chosenSide: string,\n questionId: string,\n recipientUserId: string,\n intentId: string,\n now: string,\n intentFingerprint?: string,\n): PoolAdjustmentPlanEntry[] {\n // Chip labels are word-capped side labels; match on the capped prefix too.\n const matchesSide = (side: string): boolean =>\n side === chosenSide || side.startsWith(chosenSide) || chosenSide.startsWith(side);\n const chosen = discriminator.sides.find(matchesSide);\n if (!chosen) return []; // \"Both matter\" or unrecognized option → no adjustments.\n\n const plan: PoolAdjustmentPlanEntry[] = [];\n for (const a of discriminator.assignments) {\n plan.push({\n opportunityId: a.opportunityId,\n ...buildPoolAdjustment({\n questionId,\n recipientUserId,\n intentId,\n label: discriminator.label,\n assignedSide: a.side,\n chosenSide: chosen,\n appliedAt: now,\n ...(intentFingerprint !== undefined ? { intentFingerprint } : {}),\n }),\n });\n }\n return plan;\n}\n\n/**\n * Merges one adjustment into an opportunity's existing metadata, replacing\n * only the entry for the same question + recipient + intent provenance.\n * Returns the NEW metadata object (caller persists it wholesale).\n */\nexport function mergePoolAdjustment(\n metadata: Record<string, unknown> | null | undefined,\n adjustment: PoolAdjustment,\n): Record<string, unknown> {\n const existing = readPoolAdjustments(metadata).filter((a) => !(\n a.questionId === adjustment.questionId &&\n a.recipientUserId === adjustment.recipientUserId &&\n a.intentId === adjustment.intentId\n ));\n return { ...(metadata ?? {}), poolAdjustments: [...existing, adjustment] };\n}\n\n/** Latest scoped user-explainable demotion detail for card presentation. */\nexport function latestPoolDemotionDetail(\n metadata: Record<string, unknown> | null | undefined,\n provenance: PoolAdjustmentProvenance,\n): string | undefined {\n return [...readActivePoolAdjustments(metadata, provenance)]\n .reverse()\n .find((adjustment) => adjustment.factor < 1 && typeof adjustment.detail === 'string' && adjustment.detail.length > 0)\n ?.detail;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"discriminator.adjustments.js","sourceRoot":"/","sources":["opportunity/discrimin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AAQ,EAAE,UAAU,CAAC,CAAC;SACxD,OAAO,EAAE;SACT,IAAI,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,IAAI,OAAO,UAAU,CAAC,MAAM,KAAK,QAAQ,IAAI,UAAU,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC;QACrH,EAAE,MAAM,CAAC;AACb,CAAC","sourcesContent":["/**\n * Pool-adjustment domain logic (IND-419) — pure functions, no I/O.\n *\n * When a user answers a pool_discovery question, every candidate the mining\n * pass assigned to a side gets a multiplicative adjustment written to\n * `opportunities.metadata.poolAdjustments`. The home feed (flag-gated) orders\n * by `confidence × Π factor`, floored so demoted candidates stay visible.\n *\n * Invariants:\n * - Deterministic and O(pool): no LLM at answer time — the applyPlan was\n * computed (and evidence-verified) at mining time.\n * - Reversible: entries are keyed by questionId; re-answering replaces them,\n * dismissal-driven reversal removes them.\n * - `detail` carries the template chip text built from the user's OWN answer\n * (\"Hands-on builders vs advisors: you chose Advisor\") — never LLM\n * reasoning (review-opportunity-presentation).\n */\nimport { POOL_ADJUSTMENT_FACTOR_OTHER, POOL_ADJUSTMENT_FACTOR_UNKNOWN, POOL_ADJUSTMENT_FLOOR } from \"./discriminator.env.js\";\nimport type { QuestionPoolDiscriminator } from \"../../shared/schemas/question.schema.js\";\n\n/** Recipient and intent provenance that scopes one pool preference. */\nexport interface PoolAdjustmentProvenance {\n recipientUserId: string;\n intentId: string;\n}\n\n/** One applied adjustment on an opportunity (stored in metadata.poolAdjustments). */\nexport interface PoolAdjustment extends PoolAdjustmentProvenance {\n /** The answered question that produced this adjustment (reversal key). */\n questionId: string;\n /** Discriminator label, e.g. \"Hands-on builders vs advisors\". */\n label: string;\n /** Side this candidate was assigned to (or \"unknown\"). */\n side: string;\n /** Multiplicative factor: chosen 1.0, other 0.6, unknown 0.9. */\n factor: number;\n /** Template chip text from the user's own answer. Set on demotions only. */\n detail?: string;\n /** ISO-8601 apply timestamp. */\n appliedAt: string;\n /** Full intent fingerprint authoritative when this adjustment was created. */\n intentFingerprint?: string;\n /** Audit-only marker: stale adjustments remain stored but have no ranking effect. */\n stale?: true;\n}\n\n/** Reads valid adjustments, optionally narrowed to one recipient + intent. */\nexport function readPoolAdjustments(\n metadata: Record<string, unknown> | null | undefined,\n provenance?: PoolAdjustmentProvenance,\n): PoolAdjustment[] {\n const raw = metadata?.poolAdjustments;\n if (!Array.isArray(raw)) return [];\n return raw.filter((a): a is PoolAdjustment => {\n if (\n typeof a !== \"object\" || a === null ||\n typeof (a as PoolAdjustment).questionId !== \"string\" ||\n typeof (a as PoolAdjustment).recipientUserId !== \"string\" ||\n typeof (a as PoolAdjustment).intentId !== \"string\" ||\n typeof (a as PoolAdjustment).factor !== \"number\" ||\n ((a as PoolAdjustment).stale !== undefined && (a as PoolAdjustment).stale !== true)\n ) return false;\n return provenance === undefined || (\n (a as PoolAdjustment).recipientUserId === provenance.recipientUserId &&\n (a as PoolAdjustment).intentId === provenance.intentId\n );\n });\n}\n\n/** Reads valid, non-stale adjustments for ranking and presentation behavior. */\nexport function readActivePoolAdjustments(\n metadata: Record<string, unknown> | null | undefined,\n provenance?: PoolAdjustmentProvenance,\n): PoolAdjustment[] {\n return readPoolAdjustments(metadata, provenance).filter((adjustment) => adjustment.stale !== true);\n}\n\n/**\n * Cumulative adjustment multiplier for an opportunity, floored at\n * {@link POOL_ADJUSTMENT_FLOOR}. 1 when no scoped adjustments exist.\n */\nexport function poolAdjustmentMultiplier(\n metadata: Record<string, unknown> | null | undefined,\n provenance: PoolAdjustmentProvenance,\n): number {\n const adjustments = readActivePoolAdjustments(metadata, provenance);\n if (adjustments.length === 0) return 1;\n const product = adjustments.reduce((acc, a) => acc * (Number.isFinite(a.factor) && a.factor > 0 ? a.factor : 1), 1);\n return Math.max(POOL_ADJUSTMENT_FLOOR, product);\n}\n\n/** Adjusted confidence: `confidence × Π factor`, floored. */\nexport function adjustedConfidence(\n confidence: number,\n metadata: Record<string, unknown> | null | undefined,\n provenance: PoolAdjustmentProvenance,\n): number {\n return confidence * poolAdjustmentMultiplier(metadata, provenance);\n}\n\n/** Deterministic provenance signal stored alongside one adjustment. */\nexport interface PoolAdjustmentSignal extends PoolAdjustmentProvenance {\n type: \"pool_discriminator\";\n weight: 1 | -1 | 0;\n detail: string;\n questionId: string;\n}\n\n/** Pure helper input shared by Tier-0 answers and newborn stamping. */\nexport interface BuildPoolAdjustmentInput extends PoolAdjustmentProvenance {\n questionId: string;\n label: string;\n /** Verified side assignment, or null when the candidate is unassigned. */\n assignedSide: string | null;\n chosenSide: string;\n appliedAt: string;\n /** Full intent fingerprint authoritative when this adjustment was created. */\n intentFingerprint?: string;\n}\n\n/**\n * Build one P3-compatible adjustment and signal. This is the only place that\n * defines chosen/other/unknown factors, weights, and safe template details.\n */\nexport function buildPoolAdjustment(input: BuildPoolAdjustmentInput): {\n adjustment: PoolAdjustment;\n signal: PoolAdjustmentSignal;\n} {\n const isUnknown = input.assignedSide === null;\n const isChosen = !isUnknown && input.assignedSide === input.chosenSide;\n const factor = isUnknown ? POOL_ADJUSTMENT_FACTOR_UNKNOWN : isChosen ? 1 : POOL_ADJUSTMENT_FACTOR_OTHER;\n const weight = isUnknown ? 0 : isChosen ? 1 : -1;\n const side = input.assignedSide ?? \"unknown\";\n return {\n adjustment: {\n questionId: input.questionId,\n recipientUserId: input.recipientUserId,\n intentId: input.intentId,\n label: input.label,\n side,\n factor,\n ...(!isChosen && !isUnknown ? { detail: `${input.label}: you chose ${input.chosenSide}` } : {}),\n appliedAt: input.appliedAt,\n ...(input.intentFingerprint !== undefined ? { intentFingerprint: input.intentFingerprint } : {}),\n },\n signal: {\n type: \"pool_discriminator\",\n weight,\n recipientUserId: input.recipientUserId,\n intentId: input.intentId,\n detail: isUnknown ? `${input.label}: unassigned` : `${input.label}: ${input.chosenSide}`,\n questionId: input.questionId,\n },\n };\n}\n\n/** Plan entry: what to write on one opportunity for one answer. */\nexport interface PoolAdjustmentPlanEntry {\n opportunityId: string;\n adjustment: PoolAdjustment;\n signal: PoolAdjustmentSignal;\n}\n\n/**\n * Computes the write plan for one answered discriminator. Pure: the caller\n * loads/patches rows. \"Both matter\" (or any label not in `sides`) yields an\n * empty plan — no preference, no adjustments.\n *\n * @param discriminator The asked discriminator (from detection.pool).\n * @param chosenSide The selected option label (chip label = side label).\n * @param questionId Reversal key.\n * @param recipientUserId User whose answer produced the preference.\n * @param intentId Intent whose candidate pool was ranked.\n * @param now ISO-8601 timestamp.\n * @param intentFingerprint Full intent fingerprint authoritative at apply time.\n */\nexport function planPoolAdjustments(\n discriminator: QuestionPoolDiscriminator,\n chosenSide: string,\n questionId: string,\n recipientUserId: string,\n intentId: string,\n now: string,\n intentFingerprint?: string,\n): PoolAdjustmentPlanEntry[] {\n // Chip labels are word-capped side labels; match on the capped prefix too.\n const matchesSide = (side: string): boolean =>\n side === chosenSide || side.startsWith(chosenSide) || chosenSide.startsWith(side);\n const chosen = discriminator.sides.find(matchesSide);\n if (!chosen) return []; // \"Both matter\" or unrecognized option → no adjustments.\n\n const plan: PoolAdjustmentPlanEntry[] = [];\n for (const a of discriminator.assignments) {\n plan.push({\n opportunityId: a.opportunityId,\n ...buildPoolAdjustment({\n questionId,\n recipientUserId,\n intentId,\n label: discriminator.label,\n assignedSide: a.side,\n chosenSide: chosen,\n appliedAt: now,\n ...(intentFingerprint !== undefined ? { intentFingerprint } : {}),\n }),\n });\n }\n return plan;\n}\n\n/**\n * Merges one adjustment into an opportunity's existing metadata, replacing\n * only the entry for the same question + recipient + intent provenance.\n * Returns the NEW metadata object (caller persists it wholesale).\n */\nexport function mergePoolAdjustment(\n metadata: Record<string, unknown> | null | undefined,\n adjustment: PoolAdjustment,\n): Record<string, unknown> {\n const existing = readPoolAdjustments(metadata).filter((a) => !(\n a.questionId === adjustment.questionId &&\n a.recipientUserId === adjustment.recipientUserId &&\n a.intentId === adjustment.intentId\n ));\n return { ...(metadata ?? {}), poolAdjustments: [...existing, adjustment] };\n}\n\n/** Latest scoped user-explainable demotion detail for card presentation. */\nexport function latestPoolDemotionDetail(\n metadata: Record<string, unknown> | null | undefined,\n provenance: PoolAdjustmentProvenance,\n): string | undefined {\n return [...readActivePoolAdjustments(metadata, provenance)]\n .reverse()\n .find((adjustment) => adjustment.factor < 1 && typeof adjustment.detail === 'string' && adjustment.detail.length > 0)\n ?.detail;\n}\n"]}
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
* Surfaces choose *policy* (send a sanitized fallback vs skip entirely) via
|
|
17
17
|
* `allowFallback`; they no longer choose (or forget) sanitization steps.
|
|
18
18
|
*
|
|
19
|
-
* See `.pi/skills/opportunity-presentation
|
|
19
|
+
* See `.pi/skills/review-opportunity-presentation/SKILL.md` for the review
|
|
20
20
|
* checklist this module exists to satisfy.
|
|
21
21
|
*/
|
|
22
22
|
/** Default max length for fallback summaries (matches presenter internal fallback). */
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
* Surfaces choose *policy* (send a sanitized fallback vs skip entirely) via
|
|
17
17
|
* `allowFallback`; they no longer choose (or forget) sanitization steps.
|
|
18
18
|
*
|
|
19
|
-
* See `.pi/skills/opportunity-presentation
|
|
19
|
+
* See `.pi/skills/review-opportunity-presentation/SKILL.md` for the review
|
|
20
20
|
* checklist this module exists to satisfy.
|
|
21
21
|
*/
|
|
22
22
|
import { truncateAtBoundary, viewerCentricCardSummary } from "./opportunity.presentation.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"opportunity.safe-presentation.js","sourceRoot":"/","sources":["opportunity/opportunity.safe-presentation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAE,kBAAkB,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAC7F,OAAO,EAAE,iCAAiC,EAAE,MAAM,+BAA+B,CAAC;AAElF,uFAAuF;AACvF,MAAM,CAAC,MAAM,uBAAuB,GAAG,GAAG,CAAC;AAE3C,+DAA+D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,MAAM,CAAC,oBAAoB,CAAC;IAC9C,IAAI,SAAS,EAAE,mBAAmB,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,UAAU,EAAE,CAAC;QACpE,MAAM,OAAO,GAAG,iCAAiC,CAAC,SAAS,CAAC,mBAAmB,CAAC,CAAC;QACjF,IAAI,OAAO,EAAE,CAAC;YACZ,OAAO;gBACL,QAAQ,EACN,iCAAiC,CAAC,SAAS,CAAC,QAAQ,CAAC;oBACrD,yBAAyB;gBAC3B,OAAO;gBACP,eAAe,EACb,iCAAiC,CAAC,SAAS,CAAC,eAAe,CAAC;oBAC5D,uBAAuB;gBACzB,UAAU,EAAE,KAAK;aAClB,CAAC;QACJ,CAAC;IACH,CAAC;IAED,IAAI,IAAI,CAAC,aAAa,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IAE9C,MAAM,YAAY,GAChB,MAAM,CAAC,WAAW,IAAI,MAAM,CAAC,cAAc,EAAE,SAAS,IAAI,EAAE,CAAC;IAC/D,OAAO;QACL,QAAQ,EAAE,yBAAyB;QACnC,OAAO,EAAE,mBAAmB,CAAC,YAAY,EAAE,IAAI,CAAC;QAChD,eAAe,EAAE,uBAAuB;QACxC,UAAU,EAAE,IAAI;KACjB,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Shared safe-presentation primitive for all user-facing opportunity surfaces.\n *\n * Historically every surface (home feed, list/discover cards, minimal chat\n * cards, notification emails/Telegram, chat context, delivery cards) invented\n * its own fallback chain for the case where genuine LLM presenter output is\n * unavailable — some sliced raw `interpretation.reasoning` with no\n * sanitization at all. This module is the single standard:\n *\n * raw reasoning\n * → whitespace-normalize\n * → viewer-centric rewrite (incl. UUID stripping + introducer-mention stripping)\n * → boundary-aware truncation\n * → per-surface empty-text default\n *\n * Surfaces choose *policy* (send a sanitized fallback vs skip entirely) via\n * `allowFallback`; they no longer choose (or forget) sanitization steps.\n *\n * See `.pi/skills/opportunity-presentation
|
|
1
|
+
{"version":3,"file":"opportunity.safe-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C1E,iDAAiD;IACjD,MAAM,SAAS,GAAG,iCAAiC,CAAC,SAAS,CAAC,CAAC;IAC/D,MAAM,SAAS,GAAG,kBAAkB,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;IAC1D,OAAO,SAAS,IAAI,SAAS,CAAC;AAChC,CAAC;AAuCD;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,yBAAyB,CACvC,MAA8B,EAC9B,OAAgC,EAAE;IAElC,MAAM,SAAS,GAAG,MAAM,CAAC,oBAAoB,CAAC;IAC9C,IAAI,SAAS,EAAE,mBAAmB,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,UAAU,EAAE,CAAC;QACpE,MAAM,OAAO,GAAG,iCAAiC,CAAC,SAAS,CAAC,mBAAmB,CAAC,CAAC;QACjF,IAAI,OAAO,EAAE,CAAC;YACZ,OAAO;gBACL,QAAQ,EACN,iCAAiC,CAAC,SAAS,CAAC,QAAQ,CAAC;oBACrD,yBAAyB;gBAC3B,OAAO;gBACP,eAAe,EACb,iCAAiC,CAAC,SAAS,CAAC,eAAe,CAAC;oBAC5D,uBAAuB;gBACzB,UAAU,EAAE,KAAK;aAClB,CAAC;QACJ,CAAC;IACH,CAAC;IAED,IAAI,IAAI,CAAC,aAAa,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IAE9C,MAAM,YAAY,GAChB,MAAM,CAAC,WAAW,IAAI,MAAM,CAAC,cAAc,EAAE,SAAS,IAAI,EAAE,CAAC;IAC/D,OAAO;QACL,QAAQ,EAAE,yBAAyB;QACnC,OAAO,EAAE,mBAAmB,CAAC,YAAY,EAAE,IAAI,CAAC;QAChD,eAAe,EAAE,uBAAuB;QACxC,UAAU,EAAE,IAAI;KACjB,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Shared safe-presentation primitive for all user-facing opportunity surfaces.\n *\n * Historically every surface (home feed, list/discover cards, minimal chat\n * cards, notification emails/Telegram, chat context, delivery cards) invented\n * its own fallback chain for the case where genuine LLM presenter output is\n * unavailable — some sliced raw `interpretation.reasoning` with no\n * sanitization at all. This module is the single standard:\n *\n * raw reasoning\n * → whitespace-normalize\n * → viewer-centric rewrite (incl. UUID stripping + introducer-mention stripping)\n * → boundary-aware truncation\n * → per-surface empty-text default\n *\n * Surfaces choose *policy* (send a sanitized fallback vs skip entirely) via\n * `allowFallback`; they no longer choose (or forget) sanitization steps.\n *\n * See `.pi/skills/review-opportunity-presentation/SKILL.md` for the review\n * checklist this module exists to satisfy.\n */\n\nimport { truncateAtBoundary, viewerCentricCardSummary } from \"./opportunity.presentation.js\";\nimport { stripUnsupportedOpportunityClaims } from \"./opportunity.claim-safety.js\";\n\n/** Default max length for fallback summaries (matches presenter internal fallback). */\nexport const SAFE_FALLBACK_MAX_CHARS = 300;\n\n/** Default copy when no reasoning text is available at all. */\nexport const DEFAULT_EMPTY_FALLBACK_TEXT = \"A promising connection.\";\n\n/** Default headline for fallback presentations (matches presenter internal fallback). */\nexport const DEFAULT_FALLBACK_HEADLINE = \"A promising connection\";\n\n/** Default CTA for fallback presentations (matches presenter internal fallback). */\nexport const DEFAULT_FALLBACK_ACTION =\n \"Take a look and decide whether to reach out.\";\n\nexport interface SafeFallbackOptions {\n /** Display name of the counterpart shown on the card (enables viewer-centric rewrite). */\n counterpartName?: string;\n /** Display name of the viewer; sentences describing the viewer are skipped/rewritten to \"you\". */\n viewerName?: string;\n /** Introducer display name; introducer mentions are stripped from the summary body. */\n introducerName?: string | null;\n /** Max output length (boundary-aware). Default {@link SAFE_FALLBACK_MAX_CHARS}. */\n maxChars?: number;\n /** Copy returned when reasoning is empty/blank. Default {@link DEFAULT_EMPTY_FALLBACK_TEXT}. */\n emptyText?: string;\n}\n\n/**\n * Produce safe user-facing fallback copy from raw match reasoning.\n *\n * This is the ONE sanitization standard: UUID stripping, introducer-mention\n * stripping, and viewer-centric rewrite (via {@link viewerCentricCardSummary}),\n * followed by whitespace normalization and boundary-aware truncation (via\n * {@link truncateAtBoundary}). Never returns raw reasoning verbatim beyond\n * these guarantees, and never returns an empty string.\n *\n * @param rawReasoning - Raw `interpretation.reasoning` / `matchReason` text (may be null/undefined).\n * @param opts - Per-surface knobs (names for rewrite, max length, empty-text copy).\n */\nexport function safeFallbackSummary(\n rawReasoning: string | null | undefined,\n opts: SafeFallbackOptions = {},\n): string {\n const emptyText = opts.emptyText ?? DEFAULT_EMPTY_FALLBACK_TEXT;\n const maxChars = opts.maxChars ?? SAFE_FALLBACK_MAX_CHARS;\n\n const normalized = (rawReasoning ?? \"\").replace(/\\s+/g, \" \").trim();\n if (!normalized) return emptyText;\n const claimSafeInput = stripUnsupportedOpportunityClaims(normalized);\n if (!claimSafeInput) return emptyText;\n\n // viewerCentricCardSummary handles UUID stripping, introducer-mention\n // stripping, and the viewer-centric rewrite. Pass Infinity so truncation is\n // handled by boundary-aware logic below instead of a mid-word hard slice.\n const rewritten = viewerCentricCardSummary(\n claimSafeInput,\n opts.counterpartName ?? \"\",\n Number.POSITIVE_INFINITY,\n opts.viewerName,\n opts.introducerName ?? undefined,\n );\n\n // Claim validation intentionally runs after viewer-centric rewriting: rewrite\n // heuristics may select or join different source sentences, and the final\n // user-facing sentence set is what must be safe.\n const claimSafe = stripUnsupportedOpportunityClaims(rewritten);\n const truncated = truncateAtBoundary(claimSafe, maxChars);\n return truncated || emptyText;\n}\n\n/** Minimal presenter-output shape the primitive inspects (subset of HomeCardPresentationResult). */\nexport interface SafePresentationCandidate {\n headline?: string;\n personalizedSummary?: string;\n suggestedAction?: string;\n /** Set by OpportunityPresenter when its LLM call failed and it returned fallback-shaped copy. */\n isFallback?: boolean;\n}\n\n/** Opportunity-ish source object accepted by {@link getSafePresentationOrSkip}. */\nexport interface SafePresentationSource {\n /** Presenter output attached to the record, when available. */\n homeCardPresentation?: SafePresentationCandidate | null;\n /** Pre-truncated raw reasoning carried on discovery/list card data. */\n matchReason?: string | null;\n /** Full opportunity interpretation, when the caller holds the record. */\n interpretation?: { reasoning?: string | null } | null;\n}\n\nexport interface SafePresentationOptions extends SafeFallbackOptions {\n /**\n * Policy switch: when false, return null instead of fallback copy so the\n * surface can skip rendering entirely (e.g. scheduled digests where sending\n * degraded copy is worse than sending nothing). Default true.\n */\n allowFallback?: boolean;\n}\n\n/** Resolved safe presentation for a surface to render. */\nexport interface SafePresentation {\n headline: string;\n summary: string;\n suggestedAction: string;\n /** True when copy was derived from raw reasoning rather than genuine LLM presenter output. */\n isFallback: boolean;\n}\n\n/**\n * Resolve the safe user-facing presentation for an opportunity, or signal skip.\n *\n * Resolution order:\n * 1. Genuine presenter output (`homeCardPresentation` present, non-empty, and\n * NOT tagged `isFallback` by the presenter) — claim-validated before return.\n * 2. Otherwise, if `allowFallback` (default true): sanitized fallback copy\n * built from `matchReason` / `interpretation.reasoning` via\n * {@link safeFallbackSummary}.\n * 3. Otherwise `null` — the surface must skip this opportunity.\n *\n * Raw `interpretation.reasoning` / `matchReason` never reaches the caller\n * unsanitized through this function.\n */\nexport function getSafePresentationOrSkip(\n source: SafePresentationSource,\n opts: SafePresentationOptions = {},\n): SafePresentation | null {\n const candidate = source.homeCardPresentation;\n if (candidate?.personalizedSummary?.trim() && !candidate.isFallback) {\n const summary = stripUnsupportedOpportunityClaims(candidate.personalizedSummary);\n if (summary) {\n return {\n headline:\n stripUnsupportedOpportunityClaims(candidate.headline) ||\n DEFAULT_FALLBACK_HEADLINE,\n summary,\n suggestedAction:\n stripUnsupportedOpportunityClaims(candidate.suggestedAction) ||\n DEFAULT_FALLBACK_ACTION,\n isFallback: false,\n };\n }\n }\n\n if (opts.allowFallback === false) return null;\n\n const rawReasoning =\n source.matchReason ?? source.interpretation?.reasoning ?? \"\";\n return {\n headline: DEFAULT_FALLBACK_HEADLINE,\n summary: safeFallbackSummary(rawReasoning, opts),\n suggestedAction: DEFAULT_FALLBACK_ACTION,\n isFallback: true,\n };\n}\n"]}
|