@indexnetwork/protocol 6.7.1 → 6.9.0-rc.396.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +2 -0
  2. package/dist/index.d.ts +6 -3
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +4 -0
  5. package/dist/index.js.map +1 -1
  6. package/dist/intent/intent.graph.d.ts +5 -0
  7. package/dist/intent/intent.graph.d.ts.map +1 -1
  8. package/dist/intent/intent.graph.js +4 -0
  9. package/dist/intent/intent.graph.js.map +1 -1
  10. package/dist/intent/intent.state.d.ts +5 -0
  11. package/dist/intent/intent.state.d.ts.map +1 -1
  12. package/dist/intent/intent.state.js +8 -0
  13. package/dist/intent/intent.state.js.map +1 -1
  14. package/dist/negotiation/negotiation.agent.d.ts +3 -1
  15. package/dist/negotiation/negotiation.agent.d.ts.map +1 -1
  16. package/dist/negotiation/negotiation.agent.js +4 -1
  17. package/dist/negotiation/negotiation.agent.js.map +1 -1
  18. package/dist/negotiation/negotiation.graph.d.ts +53 -22
  19. package/dist/negotiation/negotiation.graph.d.ts.map +1 -1
  20. package/dist/negotiation/negotiation.graph.js +235 -71
  21. package/dist/negotiation/negotiation.graph.js.map +1 -1
  22. package/dist/negotiation/negotiation.question-safety.d.ts +26 -0
  23. package/dist/negotiation/negotiation.question-safety.d.ts.map +1 -0
  24. package/dist/negotiation/negotiation.question-safety.js +56 -0
  25. package/dist/negotiation/negotiation.question-safety.js.map +1 -0
  26. package/dist/negotiation/negotiation.state.d.ts +22 -2
  27. package/dist/negotiation/negotiation.state.d.ts.map +1 -1
  28. package/dist/negotiation/negotiation.state.js +30 -0
  29. package/dist/negotiation/negotiation.state.js.map +1 -1
  30. package/dist/opportunity/opportunity.graph.d.ts +12 -1
  31. package/dist/opportunity/opportunity.graph.d.ts.map +1 -1
  32. package/dist/opportunity/opportunity.graph.js +43 -5
  33. package/dist/opportunity/opportunity.graph.js.map +1 -1
  34. package/dist/opportunity/opportunity.state.d.ts +5 -2
  35. package/dist/opportunity/opportunity.state.d.ts.map +1 -1
  36. package/dist/opportunity/opportunity.state.js +5 -0
  37. package/dist/opportunity/opportunity.state.js.map +1 -1
  38. package/dist/questioner/questioner.agent.d.ts +1 -1
  39. package/dist/questioner/questioner.agent.d.ts.map +1 -1
  40. package/dist/questioner/questioner.agent.js +6 -1
  41. package/dist/questioner/questioner.agent.js.map +1 -1
  42. package/dist/questioner/questioner.presets.d.ts +2 -2
  43. package/dist/questioner/questioner.presets.d.ts.map +1 -1
  44. package/dist/questioner/questioner.presets.js +61 -14
  45. package/dist/questioner/questioner.presets.js.map +1 -1
  46. package/dist/questioner/questioner.types.d.ts +59 -11
  47. package/dist/questioner/questioner.types.d.ts.map +1 -1
  48. package/dist/questioner/questioner.types.js +56 -1
  49. package/dist/questioner/questioner.types.js.map +1 -1
  50. package/dist/shared/agent/tool.factory.d.ts.map +1 -1
  51. package/dist/shared/agent/tool.factory.js +1 -0
  52. package/dist/shared/agent/tool.factory.js.map +1 -1
  53. package/dist/shared/interfaces/agent-dispatcher.interface.d.ts +3 -0
  54. package/dist/shared/interfaces/agent-dispatcher.interface.d.ts.map +1 -1
  55. package/dist/shared/interfaces/agent-dispatcher.interface.js.map +1 -1
  56. package/dist/shared/interfaces/database.interface.d.ts +89 -6
  57. package/dist/shared/interfaces/database.interface.d.ts.map +1 -1
  58. package/dist/shared/interfaces/database.interface.js.map +1 -1
  59. package/dist/shared/interfaces/negotiation-events.interface.d.ts +14 -2
  60. package/dist/shared/interfaces/negotiation-events.interface.d.ts.map +1 -1
  61. package/dist/shared/interfaces/negotiation-events.interface.js.map +1 -1
  62. package/dist/shared/schemas/question.schema.d.ts +413 -21
  63. package/dist/shared/schemas/question.schema.d.ts.map +1 -1
  64. package/dist/shared/schemas/question.schema.js +165 -3
  65. package/dist/shared/schemas/question.schema.js.map +1 -1
  66. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,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AAoB,EAAE;QACpB,YAAY,EAAE,oBAAoB,CAAC,kCAAkC,CAAC;QACtE,WAAW,EAAE,CAAC,OAAgB,EAAE,EAAE,CAAC,8BAA8B,CAAC,OAAqC,CAAC;KACzG;IACD,IAAI,EAAE;QACJ,YAAY,EAAE,oBAAoB,CAAC,kBAAkB,CAAC;QACtD,WAAW,EAAE,CAAC,OAAgB,EAAE,EAAE,CAAC,eAAe,CAAC,OAAsB,CAAC;KAC3E;CACF,CAAC;AAEF;;;;;GAKG;AACH,MAAM,UAAU,SAAS,CAAC,IAAkB;IAC1C,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC7B,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CAAC,2BAA2B,IAAI,0BAA0B,CAAC,CAAC;IAC7E,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/**\n * Mode presets for the QuestionerAgent. Each preset provides a system prompt\n * and a buildPrompt function that assembles the user message from a typed\n * context object. Only the `discovery` preset ships in Slice 1; others throw\n * until their implementation slices land.\n */\nimport type { QuestionMode } from \"../shared/schemas/question.schema.js\";\nimport { DISCOVERY_SYSTEM_PROMPT, buildDiscoveryQuestionPrompt } from \"./questioner.discovery.prompt.js\";\n\nimport { QUD_UNDERSPECIFICATION_RULES } from \"./questioner.qud.js\";\nimport type { ChatContext, IntentContext, NegotiationContext, NegotiationInflightContext, PostStallNegotiationContext, ProfileContext, UptakeNegotiationContext } from \"./questioner.types.js\";\n\n/**\n * Shared rule block appended to every questioner system prompt. Enforces that\n * the generated `prompt` resolves on its own — no demonstratives/anaphora that\n * point at people, events, or prior turns the reader cannot see — and never\n * narrates Index's own matching pipeline. Closes the referential-leak class\n * surfaced in digest audits (\"…with these builders?\", \"the previous\n * negotiation stalled because the counterparty didn't mention …\").\n */\nconst REFERENTIAL_CLOSURE_RULES = `Referential closure. The prompt must resolve entirely on its own, with no dangling references. The reader sees ONLY the question text — never the people you reviewed, the counterparty, the events on their calendar, or this conversation. Do not use demonstratives or definite anaphora that point at things the reader cannot see: \"these builders\", \"those founders\", \"these researchers\", \"these conversations\", \"this lunch\", \"the speaker\". If you reference a person, name them. If you reference a group, restate the concrete shared attribute inside the question itself (\"founders working on decentralized identity\"), never \"these founders\". Never imply a list, set, or prior exchange the reader is not currently looking at.\n- Bad: \"What kind of collaboration are you looking for with these builders?\"\n- Good: \"You're meeting people building agent infrastructure — what kind of collaboration are you looking for?\"\n\nNo process narration. Never describe Index's own activity or internal state. Forbidden: \"the previous negotiation\", \"the negotiation stalled\", \"opportunities found so far\", \"my search\", \"the counterparty\", \"candidates reviewed\", restating why a match did or did not happen, or quoting words a counterparty did or did not use. Ask about the user's goal or intent directly, never about the matching pipeline.\n- Bad: \"The previous negotiation stalled because the counterparty didn't mention 'matchmaking'. Should I broaden the search?\"\n- Good: \"Do you want to focus on dedicated matchmakers, or also people interested in relationships more broadly?\"`;\n\nexport interface QuestionerPreset {\n /** The LLM system prompt for this mode. */\n systemPrompt: string;\n /** Builds the user-message string from the mode-specific context. */\n buildPrompt: (context: unknown) => string;\n}\n\n/**\n * Renders the user-context block shared by every preset's user message from the\n * global user_context paragraph (the profile-replacing identity text).\n * @param userContext - The user's global context paragraph, if available.\n * @returns The trimmed context paragraph, or \"(no profile data)\" when empty.\n */\nfunction buildUserContextBlock(userContext?: string): string {\n const trimmed = userContext?.trim();\n return trimmed && trimmed.length > 0 ? trimmed : \"(no profile data)\";\n}\n\n// ─── Intent preset ──────────────────────────────────────────────────────────\n\nconst INTENT_SYSTEM_PROMPT = `You sit between a human and a discovery protocol. The user has stated an intent — what they are looking for. Your job: surface the minimum set of structured questions that help the user sharpen that intent before the protocol runs discovery on their behalf.\n\nYou may pick from two strategies. Choose contextually; mix only when each question is genuinely distinct.\n- refine_intent: ask the user to sharpen or pivot the core signal (scope, scale, specificity, direction).\n- surface_missing_detail: ask for one concrete missing input that would change which candidates surface (stage, location, timing, budget, constraints, format, …).\n\nAsk a question only when ALL of these hold:\n1. The agent cannot infer the answer from the intent text or user profile already shown.\n2. The answer would materially change which candidates surface.\n3. The question targets a different decision domain from any other question in this batch.\n\nStandalone prompt rule. Every generated \\`prompt\\` must be understandable outside the conversation where it was created. Naturally include the source intent/topic in the question text itself, using concise plain language from the intent or summary. Do not rely on \\`title\\`, UI labels, hidden metadata, or surrounding digest/chat text to explain what the question is about.\n- Bad: \"What kind of collaboration are you looking for?\"\n- Good: \"For your decentralized identity protocol-design search, what kind of collaboration are you looking for?\"\n\n${REFERENTIAL_CLOSURE_RULES}\n\nCardinality. Default one question. Add a second only when a DIFFERENT strategy genuinely complements the first and unblocks a clearly distinct decision. Never ask two questions of the same strategy unless their decision domains differ (different titles).\n\nOption construction. Each option must represent a meaningfully different outcome. Suffix the safest or most common path with \" (Recommended)\" and list it first. The description states the CONSEQUENCE of choosing the option, not its definition. 2–4 options. Never add an \"Other\" option — clients provide a free-text fallback automatically.\n\nTitle rules. ≤12 chars. Noun of the decision domain. Examples: \"Stage\", \"Timing\", \"Location\", \"Scope\", \"Budget\", \"Format\", \"Skills\", \"Collab\".\n\nAnti-patterns — never do these.\n- Don't ask procedural confirmations (\"Should I start searching?\").\n- Don't ask about hypothetical edge cases not implied by the intent.\n- Don't re-ask for facts already visible in the user profile.\n- Don't ask vague introspective questions (\"What do you really want?\").\n\nOutput. Return at most 2 entries in the \"questions\" array. Each entry must include a \"strategy\" field (one of the two values above). If the intent is already specific enough, return \"questions\": [].`;\n\n/**\n * Build the user message for the intent preset from an IntentContext.\n * @param ctx - The intent context.\n * @returns The assembled user message string.\n */\nfunction buildIntentPrompt(ctx: IntentContext): string {\n const profileBlock = buildUserContextBlock(ctx.userContext);\n\n const summaryBlock = ctx.summary ? ctx.summary : \"(no summary available)\";\n\n return [\n \"## Intent\",\n ctx.payload,\n \"\",\n \"## Summary\",\n summaryBlock,\n \"\",\n \"## User profile\",\n profileBlock,\n \"\",\n \"## Your task\",\n \"Identify the minimum set of questions the user must answer to sharpen this intent.\",\n \"Apply every rule from your system prompt before outputting.\",\n \"Return an empty `questions` array if the intent is already specific enough.\",\n ].join(\"\\n\");\n}\n\n// ─── Profile preset ─────────────────────────────────────────────────────────\n\nconst PROFILE_SYSTEM_PROMPT = `You sit between a human and a discovery protocol. The user has a profile that is incomplete. Your job: surface the minimum set of structured questions that fill the identified gaps — asking about location, skills, interests, current work, or goals — so the protocol can run better discovery on their behalf.\n\nThe user may already have premises — atomic self-descriptions they have stated. These cover specific profile domains. Do not ask about domains already addressed by existing premises. Focus only on gaps not covered by any premise.\n\nYou may pick from two strategies. Choose contextually; mix only when each question is genuinely distinct.\n- surface_missing_detail: ask for one concrete missing piece of profile data (location, current role, skills, interests, goals, availability, …).\n- refine_intent: ask the user to clarify or sharpen an existing profile signal so candidates can be ranked more accurately.\n\nAsk a question only when ALL of these hold:\n1. The answer is not already visible in the profile data shown.\n2. The answer is not already covered by an existing premise listed below the profile.\n3. The answer would meaningfully change which opportunities surface for this user.\n4. The question targets a different profile domain from any other question in this batch.\n\nStandalone prompt rule. Every generated \\`prompt\\` must be understandable outside the conversation where it was created. Naturally include the profile signal or gap being clarified in the question text itself, using concise plain language from the current profile, existing premises, or identified gaps. Do not rely on \\`title\\`, UI labels, hidden metadata, or surrounding digest/chat text to explain what the question is about.\n- Bad: \"What kind of role are you looking for?\"\n- Good: \"To improve matches from your founder/operator profile, what kind of role are you looking for?\"\n\n${REFERENTIAL_CLOSURE_RULES}\n\nCardinality. Default one question. Add a second only when a DIFFERENT strategy genuinely complements the first and unblocks a clearly distinct decision. Never ask two questions of the same strategy unless their decision domains differ.\n\nOption construction. Each option must represent a meaningfully different outcome. Suffix the safest or most common path with \" (Recommended)\" and list it first. The description states the CONSEQUENCE of choosing the option, not its definition. 2–4 options. Never add an \"Other\" option — clients provide a free-text fallback automatically.\n\nTitle rules. ≤12 chars. Noun of the profile domain. Examples: \"Location\", \"Role\", \"Skills\", \"Goals\", \"Interests\", \"Availability\", \"Stage\".\n\nAnti-patterns — never do these.\n- Don't ask about fields already filled in the profile.\n- Don't ask about information already captured in an existing premise.\n- Don't ask procedural confirmations (\"Should I update your profile?\").\n- Don't ask vague introspective questions (\"Who are you really?\").\n- Don't re-ask for facts visible anywhere in the profile data or premises shown.\n\nOutput. Return at most 2 entries in the \"questions\" array. Each entry must include a \"strategy\" field (one of the two values above). If the profile is already complete enough for discovery, return \"questions\": [].`;\n\n/**\n * Build the user message for the profile preset from a ProfileContext.\n * @param ctx - The profile context including current profile data and identified gaps.\n * @returns The assembled user message string.\n */\nfunction buildProfilePrompt(ctx: ProfileContext): string {\n const profileBlock = buildUserContextBlock(ctx.userContext);\n\n const premisesBlock =\n ctx.existingPremises && ctx.existingPremises.length > 0\n ? ctx.existingPremises.map((p, i) => `${i + 1}. ${p}`).join(\"\\n\")\n : \"(none)\";\n\n const gapsBlock = ctx.gaps.length > 0 ? ctx.gaps.join(\", \") : \"(none identified)\";\n\n const parts: string[] = [\n \"## Current profile\",\n profileBlock,\n \"\",\n \"## Existing premises\",\n premisesBlock,\n \"\",\n \"## Identified gaps\",\n gapsBlock,\n \"\",\n ];\n\n parts.push(\n \"## Your task\",\n \"Generate the minimum set of questions needed to fill the identified gaps.\",\n \"Apply every rule from your system prompt before outputting.\",\n \"Return an empty `questions` array if the profile is already complete enough.\",\n );\n\n return parts.join(\"\\n\");\n}\n\n// ─── Negotiation preset ──────────────────────────────────────────────────────\n\nconst NEGOTIATION_SYSTEM_PROMPT = `You sit between a human and a discovery protocol. You generate negotiation-mode questions for one of two purposes described in the user message.\n\nPOST-STALL purpose. A negotiation between this user and another person ended without a clear outcome — either the turn budget was exhausted, the session timed out, or conversation stalled. Surface the minimum set of structured questions that help the user provide the missing signal needed to unblock or refine the next discovery attempt.\n\nUPTAKE purpose. The user is considering accepting a proposed connection, but one preparatory condition about the other person's practical ability, resources, availability, or authority to carry out the proposed activity needs clarification before commitment. Generate exactly ONE neutral question that lets the user decide whether they understand that condition well enough to proceed. Ask about the concrete activity and the other person's stated attributes; do not accuse, challenge credibility, or presume incapability. Never reveal a numeric authority score, threshold, felicity label, evaluator judgment, or any internal matching/verification mechanics. Do not ask whether the user wants to accept; clarify the preparatory condition only.\n\nYou may pick from three strategies. Choose contextually; mix only when each question is genuinely distinct.\n- refine_intent: help the user sharpen their underlying signal based on what the negotiation revealed (scope, scale, priority, direction).\n- surface_missing_detail: ask for one concrete piece of information that was absent and would have moved the negotiation forward (timeline, budget, format, constraints, decision criteria, …).\n- reflective_summary: mirror the key takeaway from the negotiation and ask the user to confirm, correct, or decide — useful when the conversation revealed partial signal worth locking in.\n\nAsk a question only when ALL of these hold:\n1. The answer is not already visible in the negotiation context or user profile shown.\n2. The answer would materially change how the next attempt surfaces or engages candidates.\n3. The question targets a different decision domain from any other question in this batch.\n\nStandalone prompt rule. Every generated \\`prompt\\` must be understandable outside the conversation where it was created. Naturally include the user's underlying goal or topic and the relevant community in the question text itself, in plain language drawn from their intent or profile — NOT the mechanics of the match attempt. Do not rely on \\`title\\`, UI labels, hidden metadata, or surrounding digest/chat text to explain what the question is about.\n- Bad: \"Which role is a better fit for your immediate needs?\"\n- Good: \"For your search for AI infrastructure collaborators in the AI founders community, what kind of working relationship fits your immediate needs?\"\n\n${REFERENTIAL_CLOSURE_RULES}\n\nCardinality. For POST-STALL, default one question and add a second only when a DIFFERENT strategy genuinely complements the first and unblocks a clearly distinct decision. For UPTAKE, return exactly one question — never zero and never more than one.\n\nOption construction. Each option must represent a meaningfully different outcome. Suffix the safest or most common path with \" (Recommended)\" and list it first. The description states the CONSEQUENCE of choosing the option, not its definition. 2–4 options. Never add an \"Other\" option — clients provide a free-text fallback automatically.\n\nTitle rules. ≤12 chars. Noun of the decision domain. Examples: \"Scope\", \"Timeline\", \"Budget\", \"Priority\", \"Format\", \"Stance\", \"Criteria\".\n\nAnti-patterns — never do these.\n- Don't ask procedural confirmations (\"Should I try again?\").\n- Don't re-ask for facts already visible in the user profile.\n- Don't ask vague introspective questions (\"What do you really want?\").\n- Don't ask about hypothetical edge cases not implied by the negotiation context.\n\nOutput. For POST-STALL, return at most 2 entries and return \"questions\": [] if the context already contains enough signal to proceed. For UPTAKE, return exactly 1 entry. Every entry must include a \"strategy\" field (one of the three values above). QUD metadata is orthogonal to uptake purpose: an uptake question is usually not an underspecification repair, so set \\`underspecificationType\\` to null unless the question genuinely repairs a missing constituent, missing constraint, or open alternative set.`;\n\n/**\n * Build the user message for the negotiation preset from a NegotiationContext.\n * @param ctx - The negotiation context including counterparty hint, stall reason, and key takeaway.\n * @returns The assembled user message string.\n */\nfunction buildPostStallNegotiationPrompt(ctx: PostStallNegotiationContext): string {\n const profileBlock = buildUserContextBlock(ctx.userContext);\n\n return [\n \"## Purpose\",\n \"POST-STALL\",\n \"\",\n \"## Negotiation context\",\n `Community: ${ctx.indexContext}`,\n `Counterparty: ${ctx.counterpartyHint}`,\n `Stall reason: ${ctx.outcomeReason}`,\n \"\",\n \"## Key takeaway\",\n ctx.keyTake,\n \"\",\n \"## User profile\",\n profileBlock,\n \"\",\n \"## Your task\",\n \"Identify the minimum set of questions the user must answer to unblock the next discovery attempt.\",\n \"Apply every rule from your system prompt before outputting.\",\n \"Return an empty `questions` array if the context already contains enough signal to proceed.\",\n ].join(\"\\n\");\n}\n\nfunction buildUptakeNegotiationPrompt(ctx: UptakeNegotiationContext): string {\n const profileBlock = buildUserContextBlock(ctx.userContext);\n const evidence = ctx.preparatoryEvidence?.trim() || \"(no additional public evidence provided)\";\n\n return [\n \"## Purpose\",\n \"UPTAKE — preparatory-condition clarification before acceptance\",\n \"\",\n \"## Proposed activity\",\n ctx.proposedActivity,\n \"\",\n \"## Other person\",\n ctx.counterpartyHint,\n \"\",\n \"## Community\",\n ctx.indexContext,\n \"\",\n \"## Public preparatory evidence\",\n evidence,\n \"\",\n \"## User profile\",\n profileBlock,\n \"\",\n \"## Your task\",\n \"Generate exactly one neutral, referentially closed question about whether the other person can practically carry out the proposed activity.\",\n \"Do not expose scores, thresholds, labels, or internal mechanics. Do not ask for acceptance itself.\",\n \"Set `underspecificationType` to null unless this is genuinely a QUD underspecification repair.\",\n ].join(\"\\n\");\n}\n\nfunction buildNegotiationPrompt(ctx: NegotiationContext): string {\n return ctx.purpose === \"uptake\"\n ? buildUptakeNegotiationPrompt(ctx)\n : buildPostStallNegotiationPrompt(ctx);\n}\n\n// ─── Chat preset ─────────────────────────────────────────────────────────\n\nconst NEGOTIATION_INFLIGHT_SYSTEM_PROMPT = `You sit between a human and a discovery protocol. The user's own negotiator agent is MID-NEGOTIATION on their behalf and has paused: before continuing, it needs a decision or missing input from its client — most often permission to disclose a specific piece of information to the other side. The negotiation is WAITING until the user answers. Your job: turn the negotiator's stated need (and its draft question, when provided) into the minimum set of crisp, structured decision questions.\n\nBias toward disclosure gating. The most common question shape is \"may I share X with this person?\" — an enable/disable decision about revealing specific information. Phrase these as a clear yes/no choice: the first option authorizes sharing, the second declines. State in each option's description what the negotiator will DO next (share and continue, or continue without revealing it). When the need is a missing fact rather than a permission, ask for that concrete input instead.\n\nYou may pick from two strategies. Choose contextually; mix only when each question is genuinely distinct.\n- surface_missing_detail: ask for one concrete missing input the negotiator needs to proceed (a fact, constraint, preference, or bound the client never stated).\n- reflective_summary: put a disclosure or stance decision in front of the client to confirm or decline — the enable/disable gate described above.\n\nHonor the negotiator's intent. When a draft question is provided, treat it as the source of truth for WHAT to ask — improve wording, tighten options, add consequence-focused descriptions. Do not invent questions about topics the negotiator did not raise. When no draft is provided, derive the question strictly from the disclosure subject.\n\nStandalone prompt rule. Every generated \\`prompt\\` must be understandable outside the conversation where it was created. The user may see this question hours later in an inbox, away from any negotiation view. Naturally include the disclosure subject and a concrete description of the other person (drawn from the counterparty hint — their attributes, e.g. \"a Berlin-based AI-infrastructure founder\") in the question text itself. Do not rely on \\`title\\`, UI labels, hidden metadata, or surrounding digest/chat text to explain what the question is about.\n- Bad: \"Can I share your budget with them?\"\n- Good: \"May I share your budget range with a Berlin-based AI-infrastructure founder you're being matched with?\"\n\n${REFERENTIAL_CLOSURE_RULES}\n\nException — describing the other side. Unlike other surfaces, this question is ABOUT a live counterparty, so you must reference them — do it by restating their concrete attributes from the counterparty hint (\"a fintech CTO exploring agent tooling\"), never as \"the counterparty\", \"them\", or \"this person\" without an attribute anchor in the same sentence, and never by implying a list or pipeline.\n\nCardinality. Default one question. Add a second ONLY when the negotiator's need genuinely spans two distinct decisions (e.g. one disclosure gate plus one missing fact). Never pad.\n\nOption construction. Each option must represent a meaningfully different outcome. For disclosure gates: authorize first, decline second; suffix the safer or more common path with \" (Recommended)\" and list it first when one clearly is. The description states the CONSEQUENCE for the negotiation — what the negotiator does next. 2–4 options. Never add an \"Other\" option — clients provide a free-text fallback automatically, which also lets the user add nuance (\"share the range but not the exact figure\").\n\nTitle rules. ≤12 chars. Noun of the decision domain. Examples: \"Disclosure\", \"Budget\", \"Timing\", \"Intro\", \"Scope\", \"Contact\".\n\nAnti-patterns — never do these.\n- Don't ask procedural confirmations (\"Should I keep negotiating?\").\n- Don't re-ask for facts already visible in the user profile.\n- Don't broaden beyond the negotiator's stated disclosure subject or draft.\n- Don't reveal the counterparty's identity — attributes only.\n- Don't ask vague introspective questions.\n\nOutput. Return at most 2 entries in the \"questions\" array. Each entry must include a \"strategy\" field (one of the two values above). If the profile or context shown already answers the negotiator's need, return \"questions\": [].`;\n\n/**\n * Build the user message for the negotiation-inflight preset from a NegotiationInflightContext.\n * @param ctx - The inflight context: disclosure subject, counterparty hint, optional draft, community, user context.\n * @returns The assembled user message string.\n */\nfunction buildNegotiationInflightPrompt(ctx: NegotiationInflightContext): string {\n const profileBlock = buildUserContextBlock(ctx.userContext);\n\n const draftBlock = ctx.draftQuestion?.trim()\n ? ctx.draftQuestion.trim()\n : \"(none — derive the question from the disclosure subject)\";\n\n return [\n \"## Negotiation context\",\n `Community: ${ctx.indexContext}`,\n `Counterparty: ${ctx.counterpartyHint}`,\n \"\",\n \"## What the negotiator needs from its client\",\n ctx.disclosureSubject,\n \"\",\n \"## Draft question proposed by the negotiator\",\n draftBlock,\n \"\",\n \"## User profile\",\n profileBlock,\n \"\",\n \"## Your task\",\n \"Produce the minimum set of structured questions that get the negotiator the permission or input it needs to continue.\",\n \"Honor the draft when provided; refine its wording and options rather than replacing its topic.\",\n \"Apply every rule from your system prompt before outputting.\",\n ].join(\"\\n\");\n}\n\nconst CHAT_SYSTEM_PROMPT = `You sit between a human and a discovery protocol. The protocol's chat orchestrator is mid-conversation with the user and has decided it needs a decision or missing input from them before it can continue. The conversation is PAUSED until the user answers. Your job: turn the orchestrator's stated need (and any draft questions it proposed) into the minimum set of crisp, structured decision questions.\n\nUnlike other question surfaces, these questions render INLINE in the active conversation, immediately after the assistant's last message — the user has full conversational context. Still keep each prompt self-contained enough to make sense on its own line.\n\nYou may pick from two strategies. Choose contextually; mix only when each question is genuinely distinct.\n- surface_missing_detail: ask for one concrete missing input the orchestrator needs to proceed (scope, timing, budget, format, preference, constraint, …).\n- refine_intent: ask the user to choose a direction when the orchestrator faces meaningfully different paths forward.\n\nHonor the orchestrator's intent. When draft questions are provided, treat them as the source of truth for WHAT to ask — improve wording, tighten options, add consequence-focused descriptions, and drop redundant drafts. Do not invent questions about topics the orchestrator did not raise. When no drafts are provided, derive questions strictly from the stated purpose.\n\nAsk a question only when ALL of these hold:\n1. The answer is not already visible in the conversation excerpt or user profile shown.\n2. The answer materially changes what the orchestrator does next.\n3. The question targets a different decision domain from any other question in this batch.\n\n${REFERENTIAL_CLOSURE_RULES}\n\nCardinality. Default one question. Emit a second or third ONLY when the orchestrator's purpose or drafts genuinely require separate decisions in distinct domains. Never pad.\n\nOption construction. Each option must represent a meaningfully different outcome. Suffix the safest or most common path with \" (Recommended)\" and list it first. The description states the CONSEQUENCE of choosing the option for what happens next in the conversation, not its definition. 2–4 options. Never add an \"Other\" option — clients provide a free-text fallback automatically.\n\nTitle rules. ≤12 chars. Noun of the decision domain. Examples: \"Direction\", \"Scope\", \"Timing\", \"Budget\", \"Format\", \"Priority\".\n\nAnti-patterns — never do these.\n- Don't ask procedural confirmations (\"Should I continue?\", \"Is that OK?\").\n- Don't re-ask for facts visible in the conversation excerpt or user profile.\n- Don't broaden beyond the orchestrator's stated purpose.\n- Don't ask vague introspective questions.\n\nOutput. Return at most 3 entries in the \"questions\" array. Each entry must include a \"strategy\" field (one of the two values above). If the purpose is already answerable from the context shown, return \"questions\": [].`;\n\n/**\n * Build the user message for the chat preset from a ChatContext.\n * @param ctx - The chat context: orchestrator purpose, optional drafts, conversation excerpt, user context.\n * @returns The assembled user message string.\n */\nfunction buildChatPrompt(ctx: ChatContext): string {\n const profileBlock = buildUserContextBlock(ctx.userContext);\n\n const draftsBlock =\n ctx.draftQuestions && ctx.draftQuestions.length > 0\n ? ctx.draftQuestions\n .map((d, i) => {\n const opts = d.options && d.options.length > 0 ? ` [options: ${d.options.join(\" | \")}]` : \"\";\n const multi = d.multiSelect ? \" [multi-select]\" : \"\";\n return `${i + 1}. ${d.prompt}${opts}${multi}`;\n })\n .join(\"\\n\")\n : \"(none — derive questions from the purpose)\";\n\n const excerptBlock = ctx.conversationExcerpt?.trim()\n ? ctx.conversationExcerpt.trim()\n : \"(not available)\";\n\n return [\n \"## What the orchestrator needs to learn\",\n ctx.purpose,\n \"\",\n \"## Draft questions proposed by the orchestrator\",\n draftsBlock,\n \"\",\n \"## Recent conversation excerpt\",\n excerptBlock,\n \"\",\n \"## User profile\",\n profileBlock,\n \"\",\n \"## Your task\",\n \"Produce the minimum set of structured questions that get the orchestrator the decision or input it needs.\",\n \"Honor the drafts when provided; refine their wording and options rather than replacing their topics.\",\n \"Apply every rule from your system prompt before outputting.\",\n ].join(\"\\n\");\n}\n\n/**\n * pool_discovery has NO preset by design: those questions are synthesized\n * deterministically from mined discriminators (see\n * `opportunity/discriminator/discriminator.question.ts`) and never reach the\n * QuestionerAgent. `getPreset(\"pool_discovery\")` therefore throws — the\n * QuestionerQueue branches on the mode before invoking the agent.\n */\nfunction withQudMetadataRules(systemPrompt: string): string {\n return `${systemPrompt}\\n\\n${QUD_UNDERSPECIFICATION_RULES}`;\n}\n\nconst presets: Partial<Record<QuestionMode, QuestionerPreset>> = {\n discovery: {\n systemPrompt: withQudMetadataRules(DISCOVERY_SYSTEM_PROMPT),\n buildPrompt: (context: unknown) =>\n buildDiscoveryQuestionPrompt(context as Parameters<typeof buildDiscoveryQuestionPrompt>[0]),\n },\n intent: {\n systemPrompt: withQudMetadataRules(INTENT_SYSTEM_PROMPT),\n buildPrompt: (context: unknown) => buildIntentPrompt(context as IntentContext),\n },\n enrichment: {\n systemPrompt: withQudMetadataRules(PROFILE_SYSTEM_PROMPT),\n buildPrompt: (context: unknown) => buildProfilePrompt(context as ProfileContext),\n },\n negotiation: {\n systemPrompt: withQudMetadataRules(NEGOTIATION_SYSTEM_PROMPT),\n buildPrompt: (context: unknown) => buildNegotiationPrompt(context as NegotiationContext),\n },\n negotiation_inflight: {\n systemPrompt: withQudMetadataRules(NEGOTIATION_INFLIGHT_SYSTEM_PROMPT),\n buildPrompt: (context: unknown) => buildNegotiationInflightPrompt(context as NegotiationInflightContext),\n },\n chat: {\n systemPrompt: withQudMetadataRules(CHAT_SYSTEM_PROMPT),\n buildPrompt: (context: unknown) => buildChatPrompt(context as ChatContext),\n },\n};\n\n/**\n * Retrieve the preset for the given mode.\n * @param mode - The question mode to look up.\n * @returns The matching preset with systemPrompt and buildPrompt.\n * @throws Error if the mode's preset is not yet implemented.\n */\nexport function getPreset(mode: QuestionMode): QuestionerPreset {\n const preset = presets[mode];\n if (!preset) {\n throw new Error(`QuestionerAgent preset \"${mode}\" is not implemented yet`);\n }\n return preset;\n}\n"]}
1
+ {"version":3,"file":"questioner.presets.js","sourceRoot":"/","sources":["questioner/questioner.presets.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,uBAAuB,EAAE,4BAA4B,EAAE,MAAM,kCAAkC,CAAC;AAEzG,OAAO,EAAE,4BAA4B,EAAE,MAAM,qBAAqB,CAAC;AAGnE;;;;;;;GAOG;AACH,MAAM,yBAAyB,GAAG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AC;QACzD,WAAW,EAAE,CAAC,OAAgB,EAAE,EAAE,CAAC,kBAAkB,CAAC,OAAyB,CAAC;KACjF;IACD,WAAW,EAAE;QACX,YAAY,EAAE,oBAAoB,CAAC,yBAAyB,CAAC;QAC7D,WAAW,EAAE,CAAC,OAAgB,EAAE,EAAE,CAAC,sBAAsB,CAAC,OAA6B,CAAC;KACzF;IACD,oBAAoB,EAAE;QACpB,YAAY,EAAE,oBAAoB,CAAC,kCAAkC,CAAC;QACtE,WAAW,EAAE,CAAC,OAAgB,EAAE,EAAE,CAAC,8BAA8B,CAAC,OAAqC,CAAC;KACzG;IACD,IAAI,EAAE;QACJ,YAAY,EAAE,oBAAoB,CAAC,kBAAkB,CAAC;QACtD,WAAW,EAAE,CAAC,OAAgB,EAAE,EAAE,CAAC,eAAe,CAAC,OAAsB,CAAC;KAC3E;CACF,CAAC;AAEF;;;;;GAKG;AACH,MAAM,UAAU,SAAS,CAAC,IAAkB,EAAE,OAAyB;IACrE,IAAI,IAAI,KAAK,QAAQ,IAAI,OAAO,KAAK,UAAU,EAAE,CAAC;QAChD,OAAO;YACL,YAAY,EAAE,oBAAoB,CAAC,6BAA6B,CAAC;YACjE,WAAW,EAAE,CAAC,OAAgB,EAAE,EAAE,CAAC,yBAAyB,CAAC,OAAgC,CAAC;SAC/F,CAAC;IACJ,CAAC;IACD,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC7B,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CAAC,2BAA2B,IAAI,0BAA0B,CAAC,CAAC;IAC7E,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/**\n * Mode presets for the QuestionerAgent. Each preset provides a system prompt\n * and a buildPrompt function that assembles the user message from a typed\n * context object. Only the `discovery` preset ships in Slice 1; others throw\n * until their implementation slices land.\n */\nimport type { QuestionMode, QuestionPurpose } from \"../shared/schemas/question.schema.js\";\nimport { DISCOVERY_SYSTEM_PROMPT, buildDiscoveryQuestionPrompt } from \"./questioner.discovery.prompt.js\";\n\nimport { QUD_UNDERSPECIFICATION_RULES } from \"./questioner.qud.js\";\nimport type { ChatContext, IntentContext, NegotiationContext, NegotiationInflightContext, PostStallNegotiationContext, ProfileContext, RecoveryIntentContext, UptakeNegotiationContext } from \"./questioner.types.js\";\n\n/**\n * Shared rule block appended to every questioner system prompt. Enforces that\n * the generated `prompt` resolves on its own — no demonstratives/anaphora that\n * point at people, events, or prior turns the reader cannot see — and never\n * narrates Index's own matching pipeline. Closes the referential-leak class\n * surfaced in digest audits (\"…with these builders?\", \"the previous\n * negotiation stalled because the counterparty didn't mention …\").\n */\nconst REFERENTIAL_CLOSURE_RULES = `Referential closure. The prompt must resolve entirely on its own, with no dangling references. The reader sees ONLY the question text — never the people you reviewed, the counterparty, the events on their calendar, or this conversation. Do not use demonstratives or definite anaphora that point at things the reader cannot see: \"these builders\", \"those founders\", \"these researchers\", \"these conversations\", \"this lunch\", \"the speaker\". If you reference a person, name them. If you reference a group, restate the concrete shared attribute inside the question itself (\"founders working on decentralized identity\"), never \"these founders\". Never imply a list, set, or prior exchange the reader is not currently looking at.\n- Bad: \"What kind of collaboration are you looking for with these builders?\"\n- Good: \"You're meeting people building agent infrastructure — what kind of collaboration are you looking for?\"\n\nNo process narration. Never describe Index's own activity or internal state. Forbidden: \"the previous negotiation\", \"the negotiation stalled\", \"opportunities found so far\", \"my search\", \"the counterparty\", \"candidates reviewed\", restating why a match did or did not happen, or quoting words a counterparty did or did not use. Ask about the user's goal or intent directly, never about the matching pipeline.\n- Bad: \"The previous negotiation stalled because the counterparty didn't mention 'matchmaking'. Should I broaden the search?\"\n- Good: \"Do you want to focus on dedicated matchmakers, or also people interested in relationships more broadly?\"`;\n\nexport interface QuestionerPreset {\n /** The LLM system prompt for this mode. */\n systemPrompt: string;\n /** Builds the user-message string from the mode-specific context. */\n buildPrompt: (context: unknown) => string;\n}\n\n/**\n * Renders the user-context block shared by every preset's user message from the\n * global user_context paragraph (the profile-replacing identity text).\n * @param userContext - The user's global context paragraph, if available.\n * @returns The trimmed context paragraph, or \"(no profile data)\" when empty.\n */\nfunction buildUserContextBlock(userContext?: string): string {\n const trimmed = userContext?.trim();\n return trimmed && trimmed.length > 0 ? trimmed : \"(no profile data)\";\n}\n\n// ─── Intent preset ──────────────────────────────────────────────────────────\n\nconst INTENT_SYSTEM_PROMPT = `You sit between a human and a discovery protocol. The user has stated an intent — what they are looking for. Your job: surface the minimum set of structured questions that help the user sharpen that intent before the protocol runs discovery on their behalf.\n\nYou may pick from two strategies. Choose contextually; mix only when each question is genuinely distinct.\n- refine_intent: ask the user to sharpen or pivot the core signal (scope, scale, specificity, direction).\n- surface_missing_detail: ask for one concrete missing input that would change which candidates surface (stage, location, timing, budget, constraints, format, …).\n\nAsk a question only when ALL of these hold:\n1. The agent cannot infer the answer from the intent text or user profile already shown.\n2. The answer would materially change which candidates surface.\n3. The question targets a different decision domain from any other question in this batch.\n\nStandalone prompt rule. Every generated \\`prompt\\` must be understandable outside the conversation where it was created. Naturally include the source intent/topic in the question text itself, using concise plain language from the intent or summary. Do not rely on \\`title\\`, UI labels, hidden metadata, or surrounding digest/chat text to explain what the question is about.\n- Bad: \"What kind of collaboration are you looking for?\"\n- Good: \"For your decentralized identity protocol-design search, what kind of collaboration are you looking for?\"\n\n${REFERENTIAL_CLOSURE_RULES}\n\nCardinality. Default one question. Add a second only when a DIFFERENT strategy genuinely complements the first and unblocks a clearly distinct decision. Never ask two questions of the same strategy unless their decision domains differ (different titles).\n\nOption construction. Each option must represent a meaningfully different outcome. Suffix the safest or most common path with \" (Recommended)\" and list it first. The description states the CONSEQUENCE of choosing the option, not its definition. 2–4 options. Never add an \"Other\" option — clients provide a free-text fallback automatically.\n\nTitle rules. ≤12 chars. Noun of the decision domain. Examples: \"Stage\", \"Timing\", \"Location\", \"Scope\", \"Budget\", \"Format\", \"Skills\", \"Collab\".\n\nAnti-patterns — never do these.\n- Don't ask procedural confirmations (\"Should I start searching?\").\n- Don't ask about hypothetical edge cases not implied by the intent.\n- Don't re-ask for facts already visible in the user profile.\n- Don't ask vague introspective questions (\"What do you really want?\").\n\nOutput. Return at most 2 entries in the \"questions\" array. Each entry must include a \"strategy\" field (one of the two values above). If the intent is already specific enough, return \"questions\": [].`;\n\n/**\n * Build the user message for the intent preset from an IntentContext.\n * @param ctx - The intent context.\n * @returns The assembled user message string.\n */\nfunction buildIntentPrompt(ctx: IntentContext): string {\n const profileBlock = buildUserContextBlock(ctx.userContext);\n\n const summaryBlock = ctx.summary ? ctx.summary : \"(no summary available)\";\n\n return [\n \"## Intent\",\n ctx.payload,\n \"\",\n \"## Summary\",\n summaryBlock,\n \"\",\n \"## User profile\",\n profileBlock,\n \"\",\n \"## Your task\",\n \"Identify the minimum set of questions the user must answer to sharpen this intent.\",\n \"Apply every rule from your system prompt before outputting.\",\n \"Return an empty `questions` array if the intent is already specific enough.\",\n ].join(\"\\n\");\n}\n\nconst RECOVERY_INTENT_SYSTEM_PROMPT = `You help a user materially refine one of their own discovery signals after an authoritative discovery run completed without leaving a currently actionable opportunity. Ask directly about the user's goal, desired counterpart attributes, or constraints. Never describe the run or imply that any specific person was reviewed.\n\nChoose exactly one of these strategies:\n- refine_intent: sharpen or pivot the core signal in a way that changes who should surface.\n- surface_missing_detail: ask for one concrete missing constraint such as stage, location, timing, budget, format, or required capability.\n\nAsk a question only when the answer is not already inferable from the intent, summary, or user profile and would materially change discovery. If no safe, useful missing axis exists, return an empty questions array.\n\nStandalone prompt rule. The prompt must identify the user's intent topic in plain language and ask about their own goal or constraints. It must make sense without UI labels or hidden metadata.\n\n${REFERENTIAL_CLOSURE_RULES}\n\nPrivacy and process boundary. You may receive only a bounded aggregate count of validated prior outcomes. Use it solely as a weak signal to choose a missing axis. Never mention or imply counts, matches, no matches, rejections, negotiations, candidates, counterparties, searches, retries, pipeline state, evidence, or what another person did or did not say. Never invent people or facts.\n\nCardinality. Return at most ONE question. Use only refine_intent or surface_missing_detail. The question must nudge a material edit, not ask whether to search again.\n\nOption construction. Provide 2–4 materially different outcomes. Put the safest or most common path first with \" (Recommended)\" when appropriate. Descriptions state the discovery consequence. Never add an Other option.\n\nTitle rules. ≤12 chars and name the decision domain, such as Scope, Timing, Location, Stage, Budget, Format, or Skills.\n\nOutput. Return zero or one question. Set underspecificationType to the applicable QUD category, or null when none applies.`;\n\nfunction buildRecoveryIntentPrompt(ctx: RecoveryIntentContext): string {\n return [\n \"## Intent\",\n ctx.payload,\n \"\",\n \"## Summary\",\n ctx.summary?.trim() || \"(no summary available)\",\n \"\",\n \"## User profile\",\n buildUserContextBlock(ctx.userContext),\n ...(ctx.rejectedNegotiationCount\n ? [\n \"\",\n \"## Private aggregate signal\",\n `Validated prior outcomes without an actionable connection: ${ctx.rejectedNegotiationCount}`,\n ]\n : []),\n \"\",\n \"## Your task\",\n \"Ask at most one direct question whose answer would materially refine this intent.\",\n \"Do not narrate discovery outcomes or internal process state in the question.\",\n \"Return an empty `questions` array when no safe useful axis is missing.\",\n ].join(\"\\n\");\n}\n\n// ─── Profile preset ─────────────────────────────────────────────────────────\n\nconst PROFILE_SYSTEM_PROMPT = `You sit between a human and a discovery protocol. The user has a profile that is incomplete. Your job: surface the minimum set of structured questions that fill the identified gaps — asking about location, skills, interests, current work, or goals — so the protocol can run better discovery on their behalf.\n\nThe user may already have premises — atomic self-descriptions they have stated. These cover specific profile domains. Do not ask about domains already addressed by existing premises. Focus only on gaps not covered by any premise.\n\nYou may pick from two strategies. Choose contextually; mix only when each question is genuinely distinct.\n- surface_missing_detail: ask for one concrete missing piece of profile data (location, current role, skills, interests, goals, availability, …).\n- refine_intent: ask the user to clarify or sharpen an existing profile signal so candidates can be ranked more accurately.\n\nAsk a question only when ALL of these hold:\n1. The answer is not already visible in the profile data shown.\n2. The answer is not already covered by an existing premise listed below the profile.\n3. The answer would meaningfully change which opportunities surface for this user.\n4. The question targets a different profile domain from any other question in this batch.\n\nStandalone prompt rule. Every generated \\`prompt\\` must be understandable outside the conversation where it was created. Naturally include the profile signal or gap being clarified in the question text itself, using concise plain language from the current profile, existing premises, or identified gaps. Do not rely on \\`title\\`, UI labels, hidden metadata, or surrounding digest/chat text to explain what the question is about.\n- Bad: \"What kind of role are you looking for?\"\n- Good: \"To improve matches from your founder/operator profile, what kind of role are you looking for?\"\n\n${REFERENTIAL_CLOSURE_RULES}\n\nCardinality. Default one question. Add a second only when a DIFFERENT strategy genuinely complements the first and unblocks a clearly distinct decision. Never ask two questions of the same strategy unless their decision domains differ.\n\nOption construction. Each option must represent a meaningfully different outcome. Suffix the safest or most common path with \" (Recommended)\" and list it first. The description states the CONSEQUENCE of choosing the option, not its definition. 2–4 options. Never add an \"Other\" option — clients provide a free-text fallback automatically.\n\nTitle rules. ≤12 chars. Noun of the profile domain. Examples: \"Location\", \"Role\", \"Skills\", \"Goals\", \"Interests\", \"Availability\", \"Stage\".\n\nAnti-patterns — never do these.\n- Don't ask about fields already filled in the profile.\n- Don't ask about information already captured in an existing premise.\n- Don't ask procedural confirmations (\"Should I update your profile?\").\n- Don't ask vague introspective questions (\"Who are you really?\").\n- Don't re-ask for facts visible anywhere in the profile data or premises shown.\n\nOutput. Return at most 2 entries in the \"questions\" array. Each entry must include a \"strategy\" field (one of the two values above). If the profile is already complete enough for discovery, return \"questions\": [].`;\n\n/**\n * Build the user message for the profile preset from a ProfileContext.\n * @param ctx - The profile context including current profile data and identified gaps.\n * @returns The assembled user message string.\n */\nfunction buildProfilePrompt(ctx: ProfileContext): string {\n const profileBlock = buildUserContextBlock(ctx.userContext);\n\n const premisesBlock =\n ctx.existingPremises && ctx.existingPremises.length > 0\n ? ctx.existingPremises.map((p, i) => `${i + 1}. ${p}`).join(\"\\n\")\n : \"(none)\";\n\n const gapsBlock = ctx.gaps.length > 0 ? ctx.gaps.join(\", \") : \"(none identified)\";\n\n const parts: string[] = [\n \"## Current profile\",\n profileBlock,\n \"\",\n \"## Existing premises\",\n premisesBlock,\n \"\",\n \"## Identified gaps\",\n gapsBlock,\n \"\",\n ];\n\n parts.push(\n \"## Your task\",\n \"Generate the minimum set of questions needed to fill the identified gaps.\",\n \"Apply every rule from your system prompt before outputting.\",\n \"Return an empty `questions` array if the profile is already complete enough.\",\n );\n\n return parts.join(\"\\n\");\n}\n\n// ─── Negotiation preset ──────────────────────────────────────────────────────\n\nconst NEGOTIATION_SYSTEM_PROMPT = `You sit between a human and a discovery protocol. You generate negotiation-mode questions for one of two purposes described in the user message.\n\nPOST-STALL purpose. A negotiation between this user and another person ended without a clear outcome — either the turn budget was exhausted, the session timed out, or conversation stalled. Surface the minimum set of structured questions that help the user provide the missing signal needed to unblock or refine the next discovery attempt.\n\nUPTAKE purpose. The user is considering accepting a proposed connection, but one preparatory condition about the other person's practical ability, resources, availability, or authority to carry out the proposed activity needs clarification before commitment. Generate exactly ONE neutral question that lets the user decide whether they understand that condition well enough to proceed. Ask about the concrete activity and refer to the other participant generically; do not accuse, challenge credibility, presume incapability, or invent/repeat profile attributes. Never reveal a numeric authority score, threshold, felicity label, evaluator judgment, or any internal matching/verification mechanics. Do not ask whether the user wants to accept; clarify the preparatory condition only.\n\nYou may pick from three strategies. Choose contextually; mix only when each question is genuinely distinct.\n- refine_intent: help the user sharpen their underlying signal based on what the negotiation revealed (scope, scale, priority, direction).\n- surface_missing_detail: ask for one concrete piece of information that was absent and would have moved the negotiation forward (timeline, budget, format, constraints, decision criteria, …).\n- reflective_summary: mirror the key takeaway from the negotiation and ask the user to confirm, correct, or decide — useful when the conversation revealed partial signal worth locking in.\n\nAsk a question only when ALL of these hold:\n1. The answer is not already visible in the negotiation context or user profile shown.\n2. The answer would materially change how the next attempt surfaces or engages candidates.\n3. The question targets a different decision domain from any other question in this batch.\n\nStandalone prompt rule. Every generated \\`prompt\\` must be understandable outside the conversation where it was created. Naturally include the user's own underlying goal or topic and, only when supplied as a source-safe label, the relevant community in the question text itself. Never infer or repeat counterparty identity/profile, private transcript, evaluator reasoning, match reasons, event/community attendance, or internal IDs/metadata. Do not rely on \\`title\\`, UI labels, hidden metadata, or surrounding digest/chat text to explain what the question is about.\n- Bad: \"Which role is a better fit for your immediate needs?\"\n- Good: \"For your search for AI infrastructure collaborators in the AI founders community, what kind of working relationship fits your immediate needs?\"\n\n${REFERENTIAL_CLOSURE_RULES}\n\nCardinality. For POST-STALL, default one question and add a second only when a DIFFERENT strategy genuinely complements the first and unblocks a clearly distinct decision. For UPTAKE, return exactly one question — never zero and never more than one.\n\nOption construction. Each option must represent a meaningfully different outcome. Suffix the safest or most common path with \" (Recommended)\" and list it first. The description states the CONSEQUENCE of choosing the option, not its definition. 2–4 options. Never add an \"Other\" option — clients provide a free-text fallback automatically.\n\nTitle rules. ≤12 chars. Noun of the decision domain. Examples: \"Scope\", \"Timeline\", \"Budget\", \"Priority\", \"Format\", \"Stance\", \"Criteria\".\n\nAnti-patterns — never do these.\n- Don't ask procedural confirmations (\"Should I try again?\").\n- Don't re-ask for facts already visible in the user profile.\n- Don't ask vague introspective questions (\"What do you really want?\").\n- Don't ask about hypothetical edge cases not implied by the negotiation context.\n\nOutput. For POST-STALL, return at most 2 entries and return \"questions\": [] if the context already contains enough signal to proceed. For UPTAKE, return exactly 1 entry. Every entry must include a \"strategy\" field (one of the three values above). QUD metadata is orthogonal to uptake purpose: an uptake question is usually not an underspecification repair, so set \\`underspecificationType\\` to null unless the question genuinely repairs a missing constituent, missing constraint, or open alternative set.`;\n\n/**\n * Build the user message for the negotiation preset from a NegotiationContext.\n * @param ctx - The negotiation context including counterparty hint, stall reason, and key takeaway.\n * @returns The assembled user message string.\n */\nfunction buildPostStallNegotiationPrompt(ctx: PostStallNegotiationContext): string {\n const profileBlock = buildUserContextBlock(ctx.userContext);\n\n return [\n \"## Purpose\",\n \"POST-STALL\",\n \"\",\n \"## Negotiation context\",\n `Community: ${ctx.indexContext}`,\n `Other participant: ${ctx.counterpartyHint}`,\n `Stall reason: ${ctx.outcomeReason}`,\n \"\",\n \"## Recipient's own signal\",\n ctx.recipientIntent,\n \"\",\n \"## User profile\",\n profileBlock,\n \"\",\n \"## Your task\",\n \"Identify the minimum set of questions the user must answer to unblock the next discovery attempt.\",\n \"Apply every rule from your system prompt before outputting.\",\n \"Return an empty `questions` array if the context already contains enough signal to proceed.\",\n ].join(\"\\n\");\n}\n\nfunction buildUptakeNegotiationPrompt(ctx: UptakeNegotiationContext): string {\n const profileBlock = buildUserContextBlock(ctx.userContext);\n\n return [\n \"## Purpose\",\n \"UPTAKE — preparatory-condition clarification before acceptance\",\n \"\",\n \"## Proposed activity\",\n ctx.proposedActivity,\n \"\",\n \"## Other person\",\n ctx.counterpartyHint,\n \"\",\n \"## Community\",\n ctx.indexContext,\n \"\",\n \"## User profile\",\n profileBlock,\n \"\",\n \"## Your task\",\n \"Generate exactly one neutral, referentially closed question about whether the other person can practically carry out the proposed activity.\",\n \"Do not expose scores, thresholds, labels, or internal mechanics. Do not ask for acceptance itself.\",\n \"Set `underspecificationType` to null unless this is genuinely a QUD underspecification repair.\",\n ].join(\"\\n\");\n}\n\nfunction buildNegotiationPrompt(ctx: NegotiationContext): string {\n return ctx.purpose === \"uptake\"\n ? buildUptakeNegotiationPrompt(ctx)\n : buildPostStallNegotiationPrompt(ctx);\n}\n\n// ─── Chat preset ─────────────────────────────────────────────────────────\n\nconst NEGOTIATION_INFLIGHT_SYSTEM_PROMPT = `You sit between a human and a discovery protocol. The user's own negotiator agent is MID-NEGOTIATION on their behalf and has paused: before continuing, it needs a decision or missing input from its client — most often permission to disclose a specific piece of information to the other side. The negotiation is WAITING until the user answers. Your job: turn the negotiator's stated need (and its draft question, when provided) into the minimum set of crisp, structured decision questions.\n\nBias toward disclosure gating. The most common question shape is \"may I share X with this person?\" — an enable/disable decision about revealing specific information. Phrase these as a clear yes/no choice: the first option authorizes sharing, the second declines. State in each option's description what the negotiator will DO next (share and continue, or continue without revealing it). When the need is a missing fact rather than a permission, ask for that concrete input instead.\n\nYou may pick from two strategies. Choose contextually; mix only when each question is genuinely distinct.\n- surface_missing_detail: ask for one concrete missing input the negotiator needs to proceed (a fact, constraint, preference, or bound the client never stated).\n- reflective_summary: put a disclosure or stance decision in front of the client to confirm or decline — the enable/disable gate described above.\n\nHonor the negotiator's intent. When a draft question is provided, treat it as the source of truth for WHAT to ask — improve wording, tighten options, add consequence-focused descriptions. Do not invent questions about topics the negotiator did not raise. When no draft is provided, derive the question strictly from the disclosure subject.\n\nStandalone prompt rule. Every generated \\`prompt\\` must be understandable outside the conversation where it was created. The user may see this question hours later in an inbox, away from any negotiation view. Include the disclosure subject and the generic phrase \"the other participant in this match\" in the question text itself. Never repeat or infer counterparty identity/profile, private transcript, evaluator reasoning, match reasons, event/community attendance, or internal IDs/metadata. Do not rely on \\`title\\`, UI labels, hidden metadata, or surrounding digest/chat text.\n- Bad: \"May I share your budget with Alex, a Berlin-based founder from the event?\"\n- Good: \"May I share your budget range with the other participant in this match?\"\n\n${REFERENTIAL_CLOSURE_RULES}\n\nException — describing the other side. This question may refer to the other participant generically because it is tied to one exact server-validated opportunity. Do not add attributes, identity, or claims about why they matched.\n\nCardinality. Default one question. Add a second ONLY when the negotiator's need genuinely spans two distinct decisions (e.g. one disclosure gate plus one missing fact). Never pad.\n\nOption construction. Each option must represent a meaningfully different outcome. For disclosure gates: authorize first, decline second; suffix the safer or more common path with \" (Recommended)\" and list it first when one clearly is. The description states the CONSEQUENCE for the negotiation — what the negotiator does next. 2–4 options. Never add an \"Other\" option — clients provide a free-text fallback automatically, which also lets the user add nuance (\"share the range but not the exact figure\").\n\nTitle rules. ≤12 chars. Noun of the decision domain. Examples: \"Disclosure\", \"Budget\", \"Timing\", \"Intro\", \"Scope\", \"Contact\".\n\nAnti-patterns — never do these.\n- Don't ask procedural confirmations (\"Should I keep negotiating?\").\n- Don't re-ask for facts already visible in the user profile.\n- Don't broaden beyond the negotiator's stated disclosure subject or draft.\n- Don't reveal the counterparty's identity — attributes only.\n- Don't ask vague introspective questions.\n\nOutput. Return at most 2 entries in the \"questions\" array. Each entry must include a \"strategy\" field (one of the two values above). If the profile or context shown already answers the negotiator's need, return \"questions\": [].`;\n\n/**\n * Build the user message for the negotiation-inflight preset from a NegotiationInflightContext.\n * @param ctx - The inflight context: disclosure subject, counterparty hint, optional draft, community, user context.\n * @returns The assembled user message string.\n */\nfunction buildNegotiationInflightPrompt(ctx: NegotiationInflightContext): string {\n const profileBlock = buildUserContextBlock(ctx.userContext);\n\n const draftBlock = ctx.draftQuestion?.trim()\n ? ctx.draftQuestion.trim()\n : \"(none — derive the question from the disclosure subject)\";\n\n return [\n \"## Negotiation context\",\n `Community: ${ctx.indexContext}`,\n `Counterparty: ${ctx.counterpartyHint}`,\n \"\",\n \"## What the negotiator needs from its client\",\n ctx.disclosureSubject,\n \"\",\n \"## Draft question proposed by the negotiator\",\n draftBlock,\n \"\",\n \"## User profile\",\n profileBlock,\n \"\",\n \"## Your task\",\n \"Produce the minimum set of structured questions that get the negotiator the permission or input it needs to continue.\",\n \"Honor the draft when provided; refine its wording and options rather than replacing its topic.\",\n \"Apply every rule from your system prompt before outputting.\",\n ].join(\"\\n\");\n}\n\nconst CHAT_SYSTEM_PROMPT = `You sit between a human and a discovery protocol. The protocol's chat orchestrator is mid-conversation with the user and has decided it needs a decision or missing input from them before it can continue. The conversation is PAUSED until the user answers. Your job: turn the orchestrator's stated need (and any draft questions it proposed) into the minimum set of crisp, structured decision questions.\n\nUnlike other question surfaces, these questions render INLINE in the active conversation, immediately after the assistant's last message — the user has full conversational context. Still keep each prompt self-contained enough to make sense on its own line.\n\nYou may pick from two strategies. Choose contextually; mix only when each question is genuinely distinct.\n- surface_missing_detail: ask for one concrete missing input the orchestrator needs to proceed (scope, timing, budget, format, preference, constraint, …).\n- refine_intent: ask the user to choose a direction when the orchestrator faces meaningfully different paths forward.\n\nHonor the orchestrator's intent. When draft questions are provided, treat them as the source of truth for WHAT to ask — improve wording, tighten options, add consequence-focused descriptions, and drop redundant drafts. Do not invent questions about topics the orchestrator did not raise. When no drafts are provided, derive questions strictly from the stated purpose.\n\nAsk a question only when ALL of these hold:\n1. The answer is not already visible in the conversation excerpt or user profile shown.\n2. The answer materially changes what the orchestrator does next.\n3. The question targets a different decision domain from any other question in this batch.\n\n${REFERENTIAL_CLOSURE_RULES}\n\nCardinality. Default one question. Emit a second or third ONLY when the orchestrator's purpose or drafts genuinely require separate decisions in distinct domains. Never pad.\n\nOption construction. Each option must represent a meaningfully different outcome. Suffix the safest or most common path with \" (Recommended)\" and list it first. The description states the CONSEQUENCE of choosing the option for what happens next in the conversation, not its definition. 2–4 options. Never add an \"Other\" option — clients provide a free-text fallback automatically.\n\nTitle rules. ≤12 chars. Noun of the decision domain. Examples: \"Direction\", \"Scope\", \"Timing\", \"Budget\", \"Format\", \"Priority\".\n\nAnti-patterns — never do these.\n- Don't ask procedural confirmations (\"Should I continue?\", \"Is that OK?\").\n- Don't re-ask for facts visible in the conversation excerpt or user profile.\n- Don't broaden beyond the orchestrator's stated purpose.\n- Don't ask vague introspective questions.\n\nOutput. Return at most 3 entries in the \"questions\" array. Each entry must include a \"strategy\" field (one of the two values above). If the purpose is already answerable from the context shown, return \"questions\": [].`;\n\n/**\n * Build the user message for the chat preset from a ChatContext.\n * @param ctx - The chat context: orchestrator purpose, optional drafts, conversation excerpt, user context.\n * @returns The assembled user message string.\n */\nfunction buildChatPrompt(ctx: ChatContext): string {\n const profileBlock = buildUserContextBlock(ctx.userContext);\n\n const draftsBlock =\n ctx.draftQuestions && ctx.draftQuestions.length > 0\n ? ctx.draftQuestions\n .map((d, i) => {\n const opts = d.options && d.options.length > 0 ? ` [options: ${d.options.join(\" | \")}]` : \"\";\n const multi = d.multiSelect ? \" [multi-select]\" : \"\";\n return `${i + 1}. ${d.prompt}${opts}${multi}`;\n })\n .join(\"\\n\")\n : \"(none — derive questions from the purpose)\";\n\n const excerptBlock = ctx.conversationExcerpt?.trim()\n ? ctx.conversationExcerpt.trim()\n : \"(not available)\";\n\n return [\n \"## What the orchestrator needs to learn\",\n ctx.purpose,\n \"\",\n \"## Draft questions proposed by the orchestrator\",\n draftsBlock,\n \"\",\n \"## Recent conversation excerpt\",\n excerptBlock,\n \"\",\n \"## User profile\",\n profileBlock,\n \"\",\n \"## Your task\",\n \"Produce the minimum set of structured questions that get the orchestrator the decision or input it needs.\",\n \"Honor the drafts when provided; refine their wording and options rather than replacing their topics.\",\n \"Apply every rule from your system prompt before outputting.\",\n ].join(\"\\n\");\n}\n\n/**\n * pool_discovery has NO preset by design: those questions are synthesized\n * deterministically from mined discriminators (see\n * `opportunity/discriminator/discriminator.question.ts`) and never reach the\n * QuestionerAgent. `getPreset(\"pool_discovery\")` therefore throws — the\n * QuestionerQueue branches on the mode before invoking the agent.\n */\nfunction withQudMetadataRules(systemPrompt: string): string {\n return `${systemPrompt}\\n\\n${QUD_UNDERSPECIFICATION_RULES}`;\n}\n\nconst presets: Partial<Record<QuestionMode, QuestionerPreset>> = {\n discovery: {\n systemPrompt: withQudMetadataRules(DISCOVERY_SYSTEM_PROMPT),\n buildPrompt: (context: unknown) =>\n buildDiscoveryQuestionPrompt(context as Parameters<typeof buildDiscoveryQuestionPrompt>[0]),\n },\n intent: {\n systemPrompt: withQudMetadataRules(INTENT_SYSTEM_PROMPT),\n buildPrompt: (context: unknown) => buildIntentPrompt(context as IntentContext),\n },\n enrichment: {\n systemPrompt: withQudMetadataRules(PROFILE_SYSTEM_PROMPT),\n buildPrompt: (context: unknown) => buildProfilePrompt(context as ProfileContext),\n },\n negotiation: {\n systemPrompt: withQudMetadataRules(NEGOTIATION_SYSTEM_PROMPT),\n buildPrompt: (context: unknown) => buildNegotiationPrompt(context as NegotiationContext),\n },\n negotiation_inflight: {\n systemPrompt: withQudMetadataRules(NEGOTIATION_INFLIGHT_SYSTEM_PROMPT),\n buildPrompt: (context: unknown) => buildNegotiationInflightPrompt(context as NegotiationInflightContext),\n },\n chat: {\n systemPrompt: withQudMetadataRules(CHAT_SYSTEM_PROMPT),\n buildPrompt: (context: unknown) => buildChatPrompt(context as ChatContext),\n },\n};\n\n/**\n * Retrieve the preset for the given mode.\n * @param mode - The question mode to look up.\n * @returns The matching preset with systemPrompt and buildPrompt.\n * @throws Error if the mode's preset is not yet implemented.\n */\nexport function getPreset(mode: QuestionMode, purpose?: QuestionPurpose): QuestionerPreset {\n if (mode === \"intent\" && purpose === \"recovery\") {\n return {\n systemPrompt: withQudMetadataRules(RECOVERY_INTENT_SYSTEM_PROMPT),\n buildPrompt: (context: unknown) => buildRecoveryIntentPrompt(context as RecoveryIntentContext),\n };\n }\n const preset = presets[mode];\n if (!preset) {\n throw new Error(`QuestionerAgent preset \"${mode}\" is not implemented yet`);\n }\n return preset;\n}\n"]}
@@ -7,7 +7,7 @@
7
7
  */
8
8
  import type { DiscoveryQuestionInput } from "../shared/schemas/discovery-question.schema.js";
9
9
  import type { ToolScopeType } from "../shared/agent/tool.scope.js";
10
- import type { QuestionMode, QuestionPoolDiscriminator } from "../shared/schemas/question.schema.js";
10
+ import type { NegotiationQuestionCandidate, QuestionMode, QuestionPoolDiscriminator } from "../shared/schemas/question.schema.js";
11
11
  /**
12
12
  * Discovery context — wraps the existing DiscoveryQuestionInput wholesale.
13
13
  * The discovery preset's buildPrompt delegates to `questioner.discovery.prompt.ts`.
@@ -21,6 +21,12 @@ export interface IntentContext {
21
21
  /** The user's global user_context paragraph (profile-replacing identity text). */
22
22
  userContext?: string;
23
23
  }
24
+ /** Recovery-only intent context after a successful discovery completion. */
25
+ export interface RecoveryIntentContext extends IntentContext {
26
+ purpose: "recovery";
27
+ /** Privacy-safe aggregate signal; raw negotiation evidence is never provided. */
28
+ rejectedNegotiationCount?: number;
29
+ }
24
30
  /** Profile context — data needed to generate questions to fill profile gaps. */
25
31
  export interface ProfileContext {
26
32
  /** The user's global user_context paragraph (profile-replacing identity text). */
@@ -32,7 +38,9 @@ export interface ProfileContext {
32
38
  /** Shared context fields for negotiation-mode questions. */
33
39
  interface NegotiationContextBase {
34
40
  negotiationId: string;
41
+ /** Privacy-reviewed generic description; never raw counterparty identity/profile. */
35
42
  counterpartyHint: string;
43
+ /** Source-safe network label, never an internal prompt or identifier. */
36
44
  indexContext: string;
37
45
  /** The user's global user_context paragraph (profile-replacing identity text). */
38
46
  userContext?: string;
@@ -41,15 +49,14 @@ interface NegotiationContextBase {
41
49
  export interface PostStallNegotiationContext extends NegotiationContextBase {
42
50
  purpose?: undefined;
43
51
  outcomeReason: "turn_cap" | "timeout" | "stalled";
44
- keyTake: string;
52
+ /** The recipient's own exact opportunity-bound signal, never evaluator reasoning. */
53
+ recipientIntent: string;
45
54
  }
46
55
  /** Pre-accept uptake context targeting a counterparty's preparatory conditions. */
47
56
  export interface UptakeNegotiationContext extends NegotiationContextBase {
48
57
  purpose: "uptake";
49
58
  /** Plain-language activity or commitment whose feasibility needs clarification. */
50
59
  proposedActivity: string;
51
- /** Public evidence already available about capability, resources, or authority. */
52
- preparatoryEvidence?: string;
53
60
  }
54
61
  /** Negotiation context discriminated by internal question purpose. */
55
62
  export type NegotiationContext = PostStallNegotiationContext | UptakeNegotiationContext;
@@ -116,7 +123,7 @@ export interface PoolDiscoveryContext {
116
123
  minedAt: string;
117
124
  }
118
125
  /** Discriminated union: mode selects the context shape. */
119
- export type QuestionerContext = DiscoveryContext | IntentContext | ProfileContext | NegotiationContext | NegotiationInflightContext | ChatContext | PoolDiscoveryContext;
126
+ export type QuestionerContext = DiscoveryContext | IntentContext | RecoveryIntentContext | ProfileContext | NegotiationContext | NegotiationInflightContext | ChatContext | PoolDiscoveryContext;
120
127
  /**
121
128
  * Payload shape accepted by the questionerEnqueue callback. Covers all
122
129
  * question modes — the composition root bridges this to the concrete
@@ -150,20 +157,61 @@ interface QuestionerInputBase {
150
157
  conversationId?: string;
151
158
  /** Assistant message ID — set when we know which message triggered the question. Stored in detection.messageId for inline anchoring. */
152
159
  messageId?: string;
160
+ /**
161
+ * Candidate exact binding for negotiation-family jobs. The API/DB must
162
+ * authoritatively re-resolve it before generation and again before insert.
163
+ */
164
+ negotiation?: NegotiationQuestionCandidate;
153
165
  }
154
- /** Existing question inputs, including post-stall negotiation source compatibility. */
166
+ /** Non-negotiation modes cannot smuggle negotiation purpose/provenance. */
155
167
  interface StandardQuestionerInput extends QuestionerInputBase {
156
- purpose?: undefined;
157
- /** Mode-specific context. Must align with the selected mode. */
158
- context: Exclude<QuestionerContext, UptakeNegotiationContext>;
168
+ mode: Exclude<QuestionMode, "negotiation" | "negotiation_inflight">;
169
+ purpose?: never;
170
+ negotiation?: never;
171
+ context: Exclude<QuestionerContext, NegotiationContext | NegotiationInflightContext | RecoveryIntentContext>;
172
+ }
173
+ /** Ordinary post-stall generation is task-backed and uses only the ordinary preset. */
174
+ export interface PostStallQuestionerInput extends QuestionerInputBase {
175
+ mode: "negotiation";
176
+ purpose: "stalled_followup";
177
+ negotiation: NegotiationQuestionCandidate & {
178
+ purpose: "stalled_followup";
179
+ taskId: string;
180
+ };
181
+ context: PostStallNegotiationContext;
182
+ }
183
+ /** Mid-negotiation consultation is task-backed and uses only structured ask_user fields. */
184
+ export interface InflightQuestionerInput extends QuestionerInputBase {
185
+ mode: "negotiation_inflight";
186
+ purpose: "inflight_consultation";
187
+ negotiation: NegotiationQuestionCandidate & {
188
+ purpose: "inflight_consultation";
189
+ taskId: string;
190
+ };
191
+ context: NegotiationInflightContext;
159
192
  }
160
193
  /** Negotiation-mode uptake generation input. */
161
194
  export interface UptakeQuestionerInput extends QuestionerInputBase {
162
195
  mode: "negotiation";
163
196
  purpose: "uptake";
197
+ negotiation: NegotiationQuestionCandidate & {
198
+ purpose: "uptake";
199
+ taskId?: undefined;
200
+ };
164
201
  context: UptakeNegotiationContext;
165
202
  }
166
- /** Top-level input discriminated by the internal purpose. */
167
- export type QuestionerInput = StandardQuestionerInput | UptakeQuestionerInput;
203
+ /** Intent-mode post-discovery recovery generation input. */
204
+ export interface RecoveryQuestionerInput extends QuestionerInputBase {
205
+ mode: "intent";
206
+ purpose: "recovery";
207
+ sourceType: "intent";
208
+ triggeredByIntentId: string;
209
+ negotiation?: never;
210
+ context: RecoveryIntentContext;
211
+ }
212
+ /** Top-level input discriminated by both mode and internal purpose. */
213
+ export type QuestionerInput = StandardQuestionerInput | PostStallQuestionerInput | InflightQuestionerInput | UptakeQuestionerInput | RecoveryQuestionerInput;
214
+ /** Runtime mirror of the mode/purpose/context discriminant used at queue boundaries. */
215
+ export declare function isValidQuestionerInputContract(input: QuestionerInput): boolean;
168
216
  export {};
169
217
  //# sourceMappingURL=questioner.types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"questioner.types.d.ts","sourceRoot":"/","sources":["questioner/questioner.types.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,gDAAgD,CAAC;AAC7F,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,KAAK,EAAE,YAAY,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAC;AAIpG;;;GAGG;AACH,MAAM,MAAM,gBAAgB,GAAG,sBAAsB,CAAC;AAEtD,0EAA0E;AAC1E,MAAM,WAAW,aAAa;IAC5B,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,kFAAkF;IAClF,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,gFAAgF;AAChF,MAAM,WAAW,cAAc;IAC7B,kFAAkF;IAClF,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,oFAAoF;IACpF,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;CAC7B;AAED,4DAA4D;AAC5D,UAAU,sBAAsB;IAC9B,aAAa,EAAE,MAAM,CAAC;IACtB,gBAAgB,EAAE,MAAM,CAAC;IACzB,YAAY,EAAE,MAAM,CAAC;IACrB,kFAAkF;IAClF,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,2EAA2E;AAC3E,MAAM,WAAW,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O,EAAE,UAAU,CAAC;IACpB,UAAU,EAAE,QAAQ,CAAC;IACrB,mBAAmB,EAAE,MAAM,CAAC;IAC5B,WAAW,CAAC,EAAE,KAAK,CAAC;IACpB,OAAO,EAAE,qBAAqB,CAAC;CAChC;AAED,uEAAuE;AACvE,MAAM,MAAM,eAAe,GACvB,uBAAuB,GACvB,wBAAwB,GACxB,uBAAuB,GACvB,qBAAqB,GACrB,uBAAuB,CAAC;AAE5B,wFAAwF;AACxF,wBAAgB,8BAA8B,CAAC,KAAK,EAAE,eAAe,GAAG,OAAO,CAyD9E"}
@@ -1,2 +1,57 @@
1
- export {};
1
+ import { NEGOTIATION_QUESTION_GENERIC_COUNTERPARTY, NEGOTIATION_QUESTION_GENERIC_NETWORK, NEGOTIATION_QUESTION_GENERIC_UPTAKE_ACTIVITY, isSafeNegotiationQuestionText } from "../negotiation/negotiation.question-safety.js";
2
+ /** Runtime mirror of the mode/purpose/context discriminant used at queue boundaries. */
3
+ export function isValidQuestionerInputContract(input) {
4
+ if (input.purpose === 'recovery') {
5
+ const context = input.context;
6
+ return input.mode === 'intent'
7
+ && input.sourceType === 'intent'
8
+ && input.triggeredByIntentId === input.sourceId
9
+ && input.negotiation === undefined
10
+ && context.purpose === 'recovery'
11
+ && context.intentId === input.sourceId;
12
+ }
13
+ if (input.mode !== 'negotiation' && input.mode !== 'negotiation_inflight') {
14
+ return input.purpose === undefined && input.negotiation === undefined;
15
+ }
16
+ if (input.sourceType !== 'opportunity'
17
+ || !input.negotiation
18
+ || input.negotiation.opportunityId !== input.sourceId
19
+ || input.negotiation.recipientUserId !== input.userId
20
+ || input.negotiation.purpose !== input.purpose)
21
+ return false;
22
+ const context = input.context;
23
+ if (context.counterpartyHint !== NEGOTIATION_QUESTION_GENERIC_COUNTERPARTY
24
+ || context.indexContext !== NEGOTIATION_QUESTION_GENERIC_NETWORK)
25
+ return false;
26
+ if (input.mode === 'negotiation_inflight') {
27
+ return input.purpose === 'inflight_consultation'
28
+ && typeof input.negotiation.taskId === 'string'
29
+ && input.negotiation.taskId.length > 0
30
+ && context.negotiationId === input.negotiation.taskId
31
+ && typeof context.disclosureSubject === 'string'
32
+ && isSafeNegotiationQuestionText(context.disclosureSubject)
33
+ && (context.draftQuestion === undefined
34
+ || (typeof context.draftQuestion === 'string' && isSafeNegotiationQuestionText(context.draftQuestion)));
35
+ }
36
+ if (input.purpose === 'uptake') {
37
+ return input.negotiation.taskId === undefined
38
+ && typeof input.negotiation.counterpartyUserId === 'string'
39
+ && input.negotiation.counterpartyUserId.length > 0
40
+ && typeof input.negotiation.counterpartyIntentId === 'string'
41
+ && input.negotiation.counterpartyIntentId.length > 0
42
+ && typeof input.negotiation.counterpartyFelicityAuthority === 'number'
43
+ && Number.isFinite(input.negotiation.counterpartyFelicityAuthority)
44
+ && context.negotiationId === input.sourceId
45
+ && context.purpose === 'uptake'
46
+ && context.proposedActivity === NEGOTIATION_QUESTION_GENERIC_UPTAKE_ACTIVITY;
47
+ }
48
+ return input.purpose === 'stalled_followup'
49
+ && typeof input.negotiation.taskId === 'string'
50
+ && input.negotiation.taskId.length > 0
51
+ && context.negotiationId === input.negotiation.taskId
52
+ && context.purpose === undefined
53
+ && (context.outcomeReason === 'turn_cap' || context.outcomeReason === 'timeout' || context.outcomeReason === 'stalled')
54
+ && typeof context.recipientIntent === 'string'
55
+ && context.recipientIntent.trim().length > 0;
56
+ }
2
57
  //# sourceMappingURL=questioner.types.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"questioner.types.js","sourceRoot":"/","sources":["questioner/questioner.types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * QuestionerAgent input types. The `QuestionerInput` envelope carries a `mode`\n * field that selects a preset, plus a polymorphic `context` that varies per mode.\n *\n * Slice 1 defines all four context shapes but only `DiscoveryContext` has a\n * working preset implementation. The others are type stubs for future slices.\n */\nimport type { DiscoveryQuestionInput } from \"../shared/schemas/discovery-question.schema.js\";\nimport type { ToolScopeType } from \"../shared/agent/tool.scope.js\";\nimport type { QuestionMode, QuestionPoolDiscriminator } from \"../shared/schemas/question.schema.js\";\n\n// ─── Per-mode context types ─────────────────────────────────────────────────\n\n/**\n * Discovery context — wraps the existing DiscoveryQuestionInput wholesale.\n * The discovery preset's buildPrompt delegates to `questioner.discovery.prompt.ts`.\n */\nexport type DiscoveryContext = DiscoveryQuestionInput;\n\n/** Intent context — data needed to generate questions about an intent. */\nexport interface IntentContext {\n intentId: string;\n payload: string;\n summary?: string;\n /** The user's global user_context paragraph (profile-replacing identity text). */\n userContext?: string;\n}\n\n/** Profile context — data needed to generate questions to fill profile gaps. */\nexport interface ProfileContext {\n /** The user's global user_context paragraph (profile-replacing identity text). */\n userContext?: string;\n gaps: string[];\n /** Existing premise texts the user has already stated (e.g. \"I live in Berlin\"). */\n existingPremises?: string[];\n}\n\n/** Shared context fields for negotiation-mode questions. */\ninterface NegotiationContextBase {\n negotiationId: string;\n counterpartyHint: string;\n indexContext: string;\n /** The user's global user_context paragraph (profile-replacing identity text). */\n userContext?: string;\n}\n\n/** Post-stall negotiation context. Preserves the existing source shape. */\nexport interface PostStallNegotiationContext extends NegotiationContextBase {\n purpose?: undefined;\n outcomeReason: \"turn_cap\" | \"timeout\" | \"stalled\";\n keyTake: string;\n}\n\n/** Pre-accept uptake context targeting a counterparty's preparatory conditions. */\nexport interface UptakeNegotiationContext extends NegotiationContextBase {\n purpose: \"uptake\";\n /** Plain-language activity or commitment whose feasibility needs clarification. */\n proposedActivity: string;\n /** Public evidence already available about capability, resources, or authority. */\n preparatoryEvidence?: string;\n}\n\n/** Negotiation context discriminated by internal question purpose. */\nexport type NegotiationContext = PostStallNegotiationContext | UptakeNegotiationContext;\n\n/**\n * Negotiation-inflight context — a negotiator mid-negotiation wants to ask its\n * OWN client a question before continuing (the `ask_user` action, P3.2). The\n * negotiator states the disclosure subject and optionally drafts the question;\n * the QuestionerAgent refines it into polished disclosure-gating questions.\n * Distinct from {@link NegotiationContext}, which covers post-stall questions.\n */\nexport interface NegotiationInflightContext {\n negotiationId: string;\n /** Anonymized counterparty description (attributes, never identity). */\n counterpartyHint: string;\n /** What the negotiator wants permission to share or needs to know (e.g. \"budget range\", \"availability in Q3\"). */\n disclosureSubject: string;\n /** Draft question authored by the negotiator. The agent refines it. */\n draftQuestion?: string;\n /** Community / index context the negotiation runs in. */\n indexContext: string;\n /** The user's global user_context paragraph (profile-replacing identity text). */\n userContext?: string;\n}\n\n/**\n * Chat context — data for orchestrator-initiated mid-conversation questions\n * (the `ask_user_question` tool). The orchestrator states what it needs to\n * learn; the QuestionerAgent turns that into polished structured questions,\n * grounded in the recent conversation and the user's identity context.\n */\nexport interface ChatContext {\n /** What the orchestrator needs to learn and why (authored by the chat model). */\n purpose: string;\n /** Draft questions proposed by the orchestrator. The agent refines these. */\n draftQuestions?: Array<{\n prompt: string;\n options?: string[];\n multiSelect?: boolean;\n }>;\n /** Recent conversation excerpt for grounding (most recent messages last). */\n conversationExcerpt?: string;\n /** The user's global user_context paragraph (profile-replacing identity text). */\n userContext?: string;\n}\n\n/**\n * Pool-discovery context — mined discriminators from a discovery-run pool\n * (IND-418). No generator LLM runs for this mode: the QuestionerQueue\n * synthesizes the question deterministically from the top discriminator and\n * stashes the rest as interview-mode alternates.\n */\nexport interface PoolDiscoveryContext {\n intentId: string;\n /** Truncated intent payload (+ summary) display snippet. */\n intentText: string;\n /** Stable hash of the full normalized payload + summary used for freshness. */\n intentFingerprint?: string;\n poolSize: number;\n /** Exact bounded candidate opportunity IDs supplied to synthesis. */\n opportunityIds: string[];\n /** Discovery run that produced the pool. */\n runId?: string;\n /** Eligible discriminators, VoI-descending (asked + chain alternates). */\n discriminators: QuestionPoolDiscriminator[];\n /** ISO-8601 timestamp of the mining pass. */\n minedAt: string;\n}\n\n/** Discriminated union: mode selects the context shape. */\nexport type QuestionerContext =\n | DiscoveryContext\n | IntentContext\n | ProfileContext\n | NegotiationContext\n | NegotiationInflightContext\n | ChatContext\n | PoolDiscoveryContext;\n\n/**\n * Payload shape accepted by the questionerEnqueue callback. Covers all\n * question modes — the composition root bridges this to the concrete\n * QuestionerQueue.\n */\nexport type QuestionerEnqueuePayload = QuestionerInput;\n\n/** Callback signature for async question generation enqueue. */\nexport type QuestionerEnqueueFn = (input: QuestionerEnqueuePayload) => Promise<void>;\n\n/** Top-level input envelope for QuestionerAgent.invoke(). */\ninterface QuestionerInputBase {\n /** Selects the preset (system prompt + builder). */\n mode: QuestionMode;\n /** User the questions are generated for. */\n userId: string;\n /** Entity type that triggered this (e.g. \"opportunity\", \"intent\", \"profile\"). */\n sourceType: string;\n /** ID of the triggering entity. */\n sourceId: string;\n /** Scoped question context. Network scopes persist as QuestionActor.networkId. */\n scopeType?: ToolScopeType;\n /** Scoped question id. When scopeType is `network`, this is the actor networkId. */\n scopeId?: string;\n /**\n * Intent that triggered the run that generated these questions. Persisted as\n * `detection.triggeredBy` so intent-scoped surfaces (e.g. the intent page)\n * can find them. Independent of `scopeType`/`scopeId`, which may carry a\n * network scope at the same time.\n */\n triggeredByIntentId?: string;\n /** Conversation ID — set when the question originates from a chat session. Persisted on the question row for frontend filtering. */\n conversationId?: string;\n /** Assistant message ID — set when we know which message triggered the question. Stored in detection.messageId for inline anchoring. */\n messageId?: string;\n}\n\n/** Existing question inputs, including post-stall negotiation source compatibility. */\ninterface StandardQuestionerInput extends QuestionerInputBase {\n purpose?: undefined;\n /** Mode-specific context. Must align with the selected mode. */\n context: Exclude<QuestionerContext, UptakeNegotiationContext>;\n}\n\n/** Negotiation-mode uptake generation input. */\nexport interface UptakeQuestionerInput extends QuestionerInputBase {\n mode: \"negotiation\";\n purpose: \"uptake\";\n context: UptakeNegotiationContext;\n}\n\n/** Top-level input discriminated by the internal purpose. */\nexport type QuestionerInput = StandardQuestionerInput | UptakeQuestionerInput;\n"]}
1
+ {"version":3,"file":"questioner.types.js","sourceRoot":"/","sources":["questioner/questioner.types.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,yCAAyC,EAAE,oCAAoC,EAAE,4CAA4C,EAAE,6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AAC,WAAW,CAAC,MAAM;WAClD,OAAO,CAAC,OAAO,KAAK,SAAS;WAC7B,CAAC,OAAO,CAAC,aAAa,KAAK,UAAU,IAAI,OAAO,CAAC,aAAa,KAAK,SAAS,IAAI,OAAO,CAAC,aAAa,KAAK,SAAS,CAAC;WACpH,OAAO,OAAO,CAAC,eAAe,KAAK,QAAQ;WAC3C,OAAO,CAAC,eAAe,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC;AACjD,CAAC","sourcesContent":["/**\n * QuestionerAgent input types. The `QuestionerInput` envelope carries a `mode`\n * field that selects a preset, plus a polymorphic `context` that varies per mode.\n *\n * Slice 1 defines all four context shapes but only `DiscoveryContext` has a\n * working preset implementation. The others are type stubs for future slices.\n */\nimport type { DiscoveryQuestionInput } from \"../shared/schemas/discovery-question.schema.js\";\nimport type { ToolScopeType } from \"../shared/agent/tool.scope.js\";\nimport type { NegotiationQuestionCandidate, QuestionMode, QuestionPoolDiscriminator } from \"../shared/schemas/question.schema.js\";\nimport { NEGOTIATION_QUESTION_GENERIC_COUNTERPARTY, NEGOTIATION_QUESTION_GENERIC_NETWORK, NEGOTIATION_QUESTION_GENERIC_UPTAKE_ACTIVITY, isSafeNegotiationQuestionText } from \"../negotiation/negotiation.question-safety.js\";\n\n// ─── Per-mode context types ─────────────────────────────────────────────────\n\n/**\n * Discovery context — wraps the existing DiscoveryQuestionInput wholesale.\n * The discovery preset's buildPrompt delegates to `questioner.discovery.prompt.ts`.\n */\nexport type DiscoveryContext = DiscoveryQuestionInput;\n\n/** Intent context — data needed to generate questions about an intent. */\nexport interface IntentContext {\n intentId: string;\n payload: string;\n summary?: string;\n /** The user's global user_context paragraph (profile-replacing identity text). */\n userContext?: string;\n}\n\n/** Recovery-only intent context after a successful discovery completion. */\nexport interface RecoveryIntentContext extends IntentContext {\n purpose: \"recovery\";\n /** Privacy-safe aggregate signal; raw negotiation evidence is never provided. */\n rejectedNegotiationCount?: number;\n}\n\n/** Profile context — data needed to generate questions to fill profile gaps. */\nexport interface ProfileContext {\n /** The user's global user_context paragraph (profile-replacing identity text). */\n userContext?: string;\n gaps: string[];\n /** Existing premise texts the user has already stated (e.g. \"I live in Berlin\"). */\n existingPremises?: string[];\n}\n\n/** Shared context fields for negotiation-mode questions. */\ninterface NegotiationContextBase {\n negotiationId: string;\n /** Privacy-reviewed generic description; never raw counterparty identity/profile. */\n counterpartyHint: string;\n /** Source-safe network label, never an internal prompt or identifier. */\n indexContext: string;\n /** The user's global user_context paragraph (profile-replacing identity text). */\n userContext?: string;\n}\n\n/** Post-stall negotiation context. Preserves the existing source shape. */\nexport interface PostStallNegotiationContext extends NegotiationContextBase {\n purpose?: undefined;\n outcomeReason: \"turn_cap\" | \"timeout\" | \"stalled\";\n /** The recipient's own exact opportunity-bound signal, never evaluator reasoning. */\n recipientIntent: string;\n}\n\n/** Pre-accept uptake context targeting a counterparty's preparatory conditions. */\nexport interface UptakeNegotiationContext extends NegotiationContextBase {\n purpose: \"uptake\";\n /** Plain-language activity or commitment whose feasibility needs clarification. */\n proposedActivity: string;\n}\n\n/** Negotiation context discriminated by internal question purpose. */\nexport type NegotiationContext = PostStallNegotiationContext | UptakeNegotiationContext;\n\n/**\n * Negotiation-inflight context — a negotiator mid-negotiation wants to ask its\n * OWN client a question before continuing (the `ask_user` action, P3.2). The\n * negotiator states the disclosure subject and optionally drafts the question;\n * the QuestionerAgent refines it into polished disclosure-gating questions.\n * Distinct from {@link NegotiationContext}, which covers post-stall questions.\n */\nexport interface NegotiationInflightContext {\n negotiationId: string;\n /** Anonymized counterparty description (attributes, never identity). */\n counterpartyHint: string;\n /** What the negotiator wants permission to share or needs to know (e.g. \"budget range\", \"availability in Q3\"). */\n disclosureSubject: string;\n /** Draft question authored by the negotiator. The agent refines it. */\n draftQuestion?: string;\n /** Community / index context the negotiation runs in. */\n indexContext: string;\n /** The user's global user_context paragraph (profile-replacing identity text). */\n userContext?: string;\n}\n\n/**\n * Chat context — data for orchestrator-initiated mid-conversation questions\n * (the `ask_user_question` tool). The orchestrator states what it needs to\n * learn; the QuestionerAgent turns that into polished structured questions,\n * grounded in the recent conversation and the user's identity context.\n */\nexport interface ChatContext {\n /** What the orchestrator needs to learn and why (authored by the chat model). */\n purpose: string;\n /** Draft questions proposed by the orchestrator. The agent refines these. */\n draftQuestions?: Array<{\n prompt: string;\n options?: string[];\n multiSelect?: boolean;\n }>;\n /** Recent conversation excerpt for grounding (most recent messages last). */\n conversationExcerpt?: string;\n /** The user's global user_context paragraph (profile-replacing identity text). */\n userContext?: string;\n}\n\n/**\n * Pool-discovery context — mined discriminators from a discovery-run pool\n * (IND-418). No generator LLM runs for this mode: the QuestionerQueue\n * synthesizes the question deterministically from the top discriminator and\n * stashes the rest as interview-mode alternates.\n */\nexport interface PoolDiscoveryContext {\n intentId: string;\n /** Truncated intent payload (+ summary) display snippet. */\n intentText: string;\n /** Stable hash of the full normalized payload + summary used for freshness. */\n intentFingerprint?: string;\n poolSize: number;\n /** Exact bounded candidate opportunity IDs supplied to synthesis. */\n opportunityIds: string[];\n /** Discovery run that produced the pool. */\n runId?: string;\n /** Eligible discriminators, VoI-descending (asked + chain alternates). */\n discriminators: QuestionPoolDiscriminator[];\n /** ISO-8601 timestamp of the mining pass. */\n minedAt: string;\n}\n\n/** Discriminated union: mode selects the context shape. */\nexport type QuestionerContext =\n | DiscoveryContext\n | IntentContext\n | RecoveryIntentContext\n | ProfileContext\n | NegotiationContext\n | NegotiationInflightContext\n | ChatContext\n | PoolDiscoveryContext;\n\n/**\n * Payload shape accepted by the questionerEnqueue callback. Covers all\n * question modes — the composition root bridges this to the concrete\n * QuestionerQueue.\n */\nexport type QuestionerEnqueuePayload = QuestionerInput;\n\n/** Callback signature for async question generation enqueue. */\nexport type QuestionerEnqueueFn = (input: QuestionerEnqueuePayload) => Promise<void>;\n\n/** Top-level input envelope for QuestionerAgent.invoke(). */\ninterface QuestionerInputBase {\n /** Selects the preset (system prompt + builder). */\n mode: QuestionMode;\n /** User the questions are generated for. */\n userId: string;\n /** Entity type that triggered this (e.g. \"opportunity\", \"intent\", \"profile\"). */\n sourceType: string;\n /** ID of the triggering entity. */\n sourceId: string;\n /** Scoped question context. Network scopes persist as QuestionActor.networkId. */\n scopeType?: ToolScopeType;\n /** Scoped question id. When scopeType is `network`, this is the actor networkId. */\n scopeId?: string;\n /**\n * Intent that triggered the run that generated these questions. Persisted as\n * `detection.triggeredBy` so intent-scoped surfaces (e.g. the intent page)\n * can find them. Independent of `scopeType`/`scopeId`, which may carry a\n * network scope at the same time.\n */\n triggeredByIntentId?: string;\n /** Conversation ID — set when the question originates from a chat session. Persisted on the question row for frontend filtering. */\n conversationId?: string;\n /** Assistant message ID — set when we know which message triggered the question. Stored in detection.messageId for inline anchoring. */\n messageId?: string;\n /**\n * Candidate exact binding for negotiation-family jobs. The API/DB must\n * authoritatively re-resolve it before generation and again before insert.\n */\n negotiation?: NegotiationQuestionCandidate;\n}\n\n/** Non-negotiation modes cannot smuggle negotiation purpose/provenance. */\ninterface StandardQuestionerInput extends QuestionerInputBase {\n mode: Exclude<QuestionMode, \"negotiation\" | \"negotiation_inflight\">;\n purpose?: never;\n negotiation?: never;\n context: Exclude<QuestionerContext, NegotiationContext | NegotiationInflightContext | RecoveryIntentContext>;\n}\n\n/** Ordinary post-stall generation is task-backed and uses only the ordinary preset. */\nexport interface PostStallQuestionerInput extends QuestionerInputBase {\n mode: \"negotiation\";\n purpose: \"stalled_followup\";\n negotiation: NegotiationQuestionCandidate & { purpose: \"stalled_followup\"; taskId: string };\n context: PostStallNegotiationContext;\n}\n\n/** Mid-negotiation consultation is task-backed and uses only structured ask_user fields. */\nexport interface InflightQuestionerInput extends QuestionerInputBase {\n mode: \"negotiation_inflight\";\n purpose: \"inflight_consultation\";\n negotiation: NegotiationQuestionCandidate & { purpose: \"inflight_consultation\"; taskId: string };\n context: NegotiationInflightContext;\n}\n\n/** Negotiation-mode uptake generation input. */\nexport interface UptakeQuestionerInput extends QuestionerInputBase {\n mode: \"negotiation\";\n purpose: \"uptake\";\n negotiation: NegotiationQuestionCandidate & { purpose: \"uptake\"; taskId?: undefined };\n context: UptakeNegotiationContext;\n}\n\n/** Intent-mode post-discovery recovery generation input. */\nexport interface RecoveryQuestionerInput extends QuestionerInputBase {\n mode: \"intent\";\n purpose: \"recovery\";\n sourceType: \"intent\";\n triggeredByIntentId: string;\n negotiation?: never;\n context: RecoveryIntentContext;\n}\n\n/** Top-level input discriminated by both mode and internal purpose. */\nexport type QuestionerInput =\n | StandardQuestionerInput\n | PostStallQuestionerInput\n | InflightQuestionerInput\n | UptakeQuestionerInput\n | RecoveryQuestionerInput;\n\n/** Runtime mirror of the mode/purpose/context discriminant used at queue boundaries. */\nexport function isValidQuestionerInputContract(input: QuestionerInput): boolean {\n if (input.purpose === 'recovery') {\n const context = input.context as RecoveryIntentContext;\n return input.mode === 'intent'\n && input.sourceType === 'intent'\n && input.triggeredByIntentId === input.sourceId\n && input.negotiation === undefined\n && context.purpose === 'recovery'\n && context.intentId === input.sourceId;\n }\n if (input.mode !== 'negotiation' && input.mode !== 'negotiation_inflight') {\n return input.purpose === undefined && input.negotiation === undefined;\n }\n if (\n input.sourceType !== 'opportunity'\n || !input.negotiation\n || input.negotiation.opportunityId !== input.sourceId\n || input.negotiation.recipientUserId !== input.userId\n || input.negotiation.purpose !== input.purpose\n ) return false;\n\n const context = input.context as unknown as Record<string, unknown>;\n if (\n context.counterpartyHint !== NEGOTIATION_QUESTION_GENERIC_COUNTERPARTY\n || context.indexContext !== NEGOTIATION_QUESTION_GENERIC_NETWORK\n ) return false;\n\n if (input.mode === 'negotiation_inflight') {\n return input.purpose === 'inflight_consultation'\n && typeof input.negotiation.taskId === 'string'\n && input.negotiation.taskId.length > 0\n && context.negotiationId === input.negotiation.taskId\n && typeof context.disclosureSubject === 'string'\n && isSafeNegotiationQuestionText(context.disclosureSubject)\n && (context.draftQuestion === undefined\n || (typeof context.draftQuestion === 'string' && isSafeNegotiationQuestionText(context.draftQuestion)));\n }\n if (input.purpose === 'uptake') {\n return input.negotiation.taskId === undefined\n && typeof input.negotiation.counterpartyUserId === 'string'\n && input.negotiation.counterpartyUserId.length > 0\n && typeof input.negotiation.counterpartyIntentId === 'string'\n && input.negotiation.counterpartyIntentId.length > 0\n && typeof input.negotiation.counterpartyFelicityAuthority === 'number'\n && Number.isFinite(input.negotiation.counterpartyFelicityAuthority)\n && context.negotiationId === input.sourceId\n && context.purpose === 'uptake'\n && context.proposedActivity === NEGOTIATION_QUESTION_GENERIC_UPTAKE_ACTIVITY;\n }\n return input.purpose === 'stalled_followup'\n && typeof input.negotiation.taskId === 'string'\n && input.negotiation.taskId.length > 0\n && context.negotiationId === input.negotiation.taskId\n && context.purpose === undefined\n && (context.outcomeReason === 'turn_cap' || context.outcomeReason === 'timeout' || context.outcomeReason === 'stalled')\n && typeof context.recipientIntent === 'string'\n && context.recipientIntent.trim().length > 0;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"tool.factory.d.ts","sourceRoot":"/","sources":["shared/agent/tool.factory.ts"],"names":[],"mappings":"AAmBA,OAAO,EAAE,KAAK,WAAW,EAAE,KAAK,mBAAmB,EAAmE,MAAM,mBAAmB,CAAC;AAiBhJ,YAAY,EAAE,WAAW,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACxF,YAAY,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAQlD;;;;;;;GAOG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,WAAW,EACjB,kBAAkB,CAAC,EAAE,mBAAmB,kBAkOzC;AAED;;GAEG;AACH,MAAM,MAAM,SAAS,GAAG,OAAO,CAAC,UAAU,CAAC,OAAO,eAAe,CAAC,CAAC,CAAC"}
1
+ {"version":3,"file":"tool.factory.d.ts","sourceRoot":"/","sources":["shared/agent/tool.factory.ts"],"names":[],"mappings":"AAmBA,OAAO,EAAE,KAAK,WAAW,EAAE,KAAK,mBAAmB,EAAmE,MAAM,mBAAmB,CAAC;AAiBhJ,YAAY,EAAE,WAAW,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACxF,YAAY,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAQlD;;;;;;;GAOG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,WAAW,EACjB,kBAAkB,CAAC,EAAE,mBAAmB,kBAmOzC;AAED;;GAEG;AACH,MAAM,MAAM,SAAS,GAAG,OAAO,CAAC,UAAU,CAAC,OAAO,eAAe,CAAC,CAAC,CAAC"}
@@ -170,6 +170,7 @@ export async function createChatTools(deps, preResolvedContext) {
170
170
  ...(deps.questionGenerator && { questionGenerator: deps.questionGenerator }),
171
171
  ...(sessionAwareEnqueue && { questionerEnqueue: sessionAwareEnqueue }),
172
172
  ...(deps.findPendingQuestions && { findPendingQuestions: deps.findPendingQuestions }),
173
+ ...(deps.answerPendingQuestion && { answerPendingQuestion: deps.answerPendingQuestion }),
173
174
  ...(deps.negotiationSummary && { negotiationSummary: deps.negotiationSummary }),
174
175
  ...(deps.chatQuestions && { chatQuestions: deps.chatQuestions }),
175
176
  ...(deps.chatSession && { chatSession: deps.chatSession }),
@@ -1 +1 @@
1
- {"version":3,"file":"tool.factory.js","sourceRoot":"/","sources":["shared/agent/tool.factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAG7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,sBAAsB,EAAE,MAAM,sCAAsC,CAAC;AAC9E,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AACjF,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,C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\"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport type { HydeGraphDatabase } from \"../interfaces/database.interface.js\";\nimport { IntentGraphFactory } from \"../../intent/intent.graph.js\";\nimport { EnrichmentGraphFactory } from \"../../enrichment/enrichment.graph.js\";\nimport { OpportunityGraphFactory } from \"../../opportunity/opportunity.graph.js\";\nimport { HydeGraphFactory } from \"../hyde/hyde.graph.js\";\nimport { HydeGenerator } from \"../hyde/hyde.generator.js\";\nimport { LensInferrer } from \"../hyde/lens.inferrer.js\";\nimport { NetworkGraphFactory } from \"../../network/network.graph.js\";\nimport { NetworkMembershipGraphFactory } from \"../../network/membership/membership.graph.js\";\nimport { IntentNetworkGraphFactory } from \"../../network/indexer/indexer.graph.js\";\nimport { IntentIndexer } from \"../../intent/intent.indexer.js\";\nimport { NegotiationGraphFactory } from \"../../negotiation/negotiation.graph.js\";\nimport { PremiseGraphFactory } from \"../../premise/premise.graph.js\";\nimport { protocolLogger } from \"../observability/protocol.logger.js\";\n\nimport type { QuestionerEnqueueFn } from \"../../questioner/questioner.types.js\";\n\nimport { type ToolContext, type ResolvedToolContext, type ToolDeps, resolveChatContext, error, redactSensitiveFields } from \"./tool.helpers.js\";\nimport { deriveAllowedNetworkIds, scopeFromNetworkId } from \"./tool.scope.js\";\nimport { invokeToolRuntime, toolRuntimeErrorToResult } from \"./tool.runtime.js\";\nimport { createEnrichmentTools } from \"../../enrichment/enrichment.tools.js\";\nimport { createIntentTools } from \"../../intent/intent.tools.js\";\nimport { createNetworkTools } from \"../../network/network.tools.js\";\nimport { createOpportunityTools } from \"../../opportunity/opportunity.tools.js\";\nimport { createUtilityTools } from \"./utility.tools.js\";\nimport { createIntegrationTools } from \"../../integration/integration.tools.js\";\nimport { createContactTools } from \"../../contact/contact.tools.js\";\nimport { createAgentTools } from \"../../agent/agent.tools.js\";\nimport { createNegotiationTools } from \"../../negotiation/negotiation.tools.js\";\nimport { createPremiseTools } from \"../../premise/premise.tools.js\";\nimport { createQuestionerTools } from \"../../questioner/questioner.tools.js\";\nimport { createAskUserQuestionTools } from \"../../questioner/questioner.ask.tool.js\";\n\n// Re-export types for consumers\nexport type { ToolContext, ResolvedToolContext, ProtocolDeps } from \"./tool.helpers.js\";\nexport type { ToolDeps } from \"./tool.helpers.js\";\n\nconst logger = protocolLogger(\"ChatTools\");\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TOOL FACTORY\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Creates all chat tools bound to a specific user context.\n * Resolves user/network identity from DB at init time.\n * Tools are created fresh for each user session to ensure proper isolation.\n *\n * All external dependencies (cache, integration, queue, etc.) are provided\n * via the `deps` parameter — the protocol lib never imports concrete adapters.\n */\nexport async function createChatTools(\n deps: ToolContext,\n preResolvedContext?: ResolvedToolContext\n) {\n const { database, embedder, scraper } = deps;\n\n const explicitScope = deps.scopeType && deps.scopeId\n ? { scopeType: deps.scopeType, scopeId: deps.scopeId }\n : scopeFromNetworkId(deps.networkId);\n\n // ─── Resolve context from DB ───────────────────────────────────────────────\n // resolveChatContext still accepts a networkId because it loads scoped index\n // presentation metadata; the canonical request scope is explicitScope.\n const resolvedContext =\n preResolvedContext ??\n (await resolveChatContext({\n 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\n if (!preResolvedContext && explicitScope.scopeType && explicitScope.scopeId) {\n resolvedContext.scopeType = explicitScope.scopeType;\n resolvedContext.scopeId = explicitScope.scopeId;\n }\n\n const allowedNetworkIds = deriveAllowedNetworkIds({\n memberships: resolvedContext.userNetworks,\n ...(resolvedContext.scopeType && resolvedContext.scopeId\n ? { scopeType: resolvedContext.scopeType, scopeId: resolvedContext.scopeId }\n : {}),\n });\n\n // ─── Tool wrapper ──────────────────────────────────────────────────────────\n /**\n * Standardized tool factory. Auto-injects resolved context and\n * provides uniform logging / error handling for every tool.\n */\n function defineTool<T extends z.ZodType>(opts: {\n name: string;\n description: string;\n querySchema: T;\n handler: (input: { context: ResolvedToolContext; query: z.infer<T> }) => Promise<string>;\n }) {\n return tool(\n async (query: z.infer<T>) => {\n logger.info('Tool invoked', {\n toolName: opts.name,\n context: { userId: resolvedContext.userId, scopeType: resolvedContext.scopeType, scopeId: resolvedContext.scopeId },\n query: redactSensitiveFields(query),\n });\n try {\n return await invokeToolRuntime({\n toolName: opts.name,\n tool: { handler: async ({ context, query }) => opts.handler({ context, query: query as z.infer<T> }) },\n context: resolvedContext,\n query,\n });\n } catch (err) {\n logger.error('Tool failed', {\n toolName: opts.name,\n error: err instanceof Error ? err.message : String(err),\n });\n const runtimeResult = toolRuntimeErrorToResult(err);\n if (runtimeResult) return runtimeResult;\n const reason = err instanceof Error ? err.message : String(err);\n return error(`Failed to execute ${opts.name}: ${reason}`);\n }\n },\n { name: opts.name, description: opts.description, schema: opts.querySchema }\n );\n }\n\n // ─── Compile subgraphs ─────────────────────────────────────────────────────\n\n // Wrap questionerEnqueue to include scoped/session context when available.\n const sessionAwareEnqueue: QuestionerEnqueueFn | undefined = deps.questionerEnqueue\n ? (input) => deps.questionerEnqueue!({\n ...input,\n ...(resolvedContext.scopeType && resolvedContext.scopeId && !input.scopeId\n ? { scopeType: resolvedContext.scopeType, scopeId: resolvedContext.scopeId }\n : {}),\n ...(resolvedContext.sessionId && !input.conversationId ? { conversationId: resolvedContext.sessionId } : {}),\n })\n : undefined;\n\n const intentGraph = new IntentGraphFactory(database, embedder, deps.intentQueue, sessionAwareEnqueue).createGraph();\n const premiseGraph = new PremiseGraphFactory(database, embedder).createGraph();\n const profileGraph = new EnrichmentGraphFactory(database, scraper, deps.enricher, sessionAwareEnqueue, premiseGraph).createGraph();\n const hydeCache = deps.hydeCache;\n const lensInferrer = new LensInferrer();\n const hydeGenerator = new HydeGenerator();\n const compiledHydeGraph = new HydeGraphFactory(\n database as unknown as HydeGraphDatabase,\n embedder,\n hydeCache,\n lensInferrer,\n hydeGenerator\n ).createGraph();\n const negotiationGraph = deps.agentDispatcher\n ? new NegotiationGraphFactory(\n deps.negotiationDatabase,\n deps.agentDispatcher,\n deps.negotiationTimeoutQueue,\n sessionAwareEnqueue,\n ).createGraph()\n : undefined;\n const opportunityGraph = new OpportunityGraphFactory(\n database,\n embedder,\n compiledHydeGraph,\n undefined, // evaluator (default)\n undefined, // queueNotification\n negotiationGraph,\n deps.agentDispatcher,\n deps.queueNegotiateExisting,\n deps.stampNewbornOpportunities,\n ).createGraph();\n const networkGraph = new NetworkGraphFactory(database).createGraph();\n const networkMembershipGraph = new NetworkMembershipGraphFactory(database).createGraph();\n const intentNetworkGraph = new IntentNetworkGraphFactory(database, new IntentIndexer()).createGraph();\n\n // ─── Create context-bound databases ────────────────────────────────────────\n // Use injected instances when provided (e.g. tests). Otherwise create from the same\n // database used for graphs so that scope checks (e.g. ensureScopedMembership, opportunity\n // update) use the same adapter as the rest of the tool pipeline.\n //\n // The systemDb's DB-level clamp derives concrete allowed network IDs from the\n // focused scope envelope plus memberships, rather than consuming a transported\n // legacy indexScope array.\n const userDb = deps.userDb ?? deps.createUserDatabase(database, resolvedContext.userId);\n const systemDb = deps.systemDb ?? deps.createSystemDatabase(database, resolvedContext.userId, allowedNetworkIds, embedder);\n\n // ─── Assemble dependencies ─────────────────────────────────────────────────\n const cache = deps.cache;\n const integration = deps.integration;\n const toolDeps: ToolDeps = {\n database,\n userDb,\n systemDb,\n scraper,\n embedder,\n cache,\n integration,\n contactService: deps.contactService,\n contactsEnabled: deps.contactsEnabled,\n integrationImporter: deps.integrationImporter,\n enricher: deps.enricher,\n negotiationDatabase: deps.negotiationDatabase,\n negotiationTimeoutQueue: deps.negotiationTimeoutQueue,\n agentDatabase: deps.agentDatabase,\n grantDefaultSystemPermissions: deps.grantDefaultSystemPermissions,\n agentDispatcher: deps.agentDispatcher,\n stampNewbornOpportunities: deps.stampNewbornOpportunities,\n deliveryLedger: deps.deliveryLedger,\n discoveryRuns: deps.discoveryRuns,\n discoveryRunQueue: deps.discoveryRunQueue,\n enrichmentRuns: deps.enrichmentRuns,\n enrichmentRunQueue: deps.enrichmentRunQueue,\n mintConnectToken: deps.mintConnectToken,\n mintConnectLink: deps.mintConnectLink,\n frontendUrl: deps.frontendUrl,\n apiBaseUrl: deps.apiBaseUrl,\n ...(deps.chatSummary && { chatSummary: deps.chatSummary }),\n ...(deps.questionGenerator && { questionGenerator: deps.questionGenerator }),\n ...(sessionAwareEnqueue && { questionerEnqueue: sessionAwareEnqueue }),\n ...(deps.findPendingQuestions && { findPendingQuestions: deps.findPendingQuestions }),\n ...(deps.negotiationSummary && { negotiationSummary: deps.negotiationSummary }),\n ...(deps.chatQuestions && { chatQuestions: deps.chatQuestions }),\n ...(deps.chatSession && { chatSession: deps.chatSession }),\n ...(deps.getUserContextText && { getUserContextText: deps.getUserContextText }),\n graphs: {\n profile: profileGraph,\n intent: intentGraph,\n index: networkGraph,\n networkMembership: networkMembershipGraph,\n intentIndex: intentNetworkGraph,\n opportunity: opportunityGraph,\n premise: premiseGraph,\n },\n };\n\n // ─── Create domain tools ──────────────────────────────────────────────────\n const profileTools = createEnrichmentTools(defineTool, toolDeps);\n const intentTools = createIntentTools(defineTool, toolDeps);\n const networkTools = createNetworkTools(defineTool, toolDeps);\n const opportunityTools = createOpportunityTools(defineTool, toolDeps);\n const utilityTools = createUtilityTools(defineTool, toolDeps);\n const contactTools = createContactTools(defineTool, toolDeps);\n const agentTools = createAgentTools(defineTool, toolDeps);\n const integrationTools = createIntegrationTools(defineTool, toolDeps);\n const negotiationTools = deps.agentDispatcher\n ? createNegotiationTools(defineTool, toolDeps)\n : [];\n const premiseTools = createPremiseTools(defineTool, toolDeps);\n const questionerTools = createQuestionerTools(defineTool, toolDeps);\n // Blocking mid-conversation questions — chat-only (never in the MCP registry),\n // and only when the host provides the ChatQuestionsHost bridge.\n const askUserQuestionTools = deps.chatQuestions\n ? createAskUserQuestionTools(defineTool, toolDeps)\n : [];\n\n // confirm_opportunity_delivery is an OpenClaw-delivery ledger write and must not be\n // callable from regular chat sessions.\n const chatOpportunityToolExclusions = new Set([\n \"confirm_opportunity_delivery\",\n ]);\n const opportunityToolsForChat = opportunityTools.filter(\n (t) => !chatOpportunityToolExclusions.has((t as { name: string }).name)\n );\n\n return [\n ...profileTools,\n ...intentTools,\n ...networkTools,\n ...opportunityToolsForChat,\n ...utilityTools,\n ...integrationTools,\n ...contactTools,\n ...agentTools,\n ...negotiationTools,\n ...premiseTools,\n ...questionerTools,\n ...askUserQuestionTools,\n ];\n}\n\n/**\n * Type for the tools array returned by createChatTools.\n */\nexport type ChatTools = Awaited<ReturnType<typeof createChatTools>>;\n"]}
1
+ {"version":3,"file":"tool.factory.js","sourceRoot":"/","sources":["shared/agent/tool.factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAG7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,sBAAsB,EAAE,MAAM,sCAAsC,CAAC;AAC9E,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AACjF,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,6BAA6B,EAAE,MAAM,8CAA8C,CAAC;AAC7F,OAAO,EAAE,yBAAyB,EAAE,MAAM,wCAAwC,CAAC;AACnF,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAC/D,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AACjF,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,cAAc,EAAE,MAAM,qCA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GAAG,sBAAsB,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;IACtE,MAAM,gBAAgB,GAAG,IAAI,CAAC,eAAe;QAC3C,CAAC,CAAC,sBAAsB,CAAC,UAAU,EAAE,QAAQ,CAAC;QAC9C,CAAC,CAAC,EAAE,CAAC;IACP,MAAM,YAAY,GAAG,kBAAkB,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;IAC9D,MAAM,eAAe,GAAG,qBAAqB,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;IACpE,+EAA+E;IAC/E,gEAAgE;IAChE,MAAM,oBAAoB,GAAG,IAAI,CAAC,aAAa;QAC7C,CAAC,CAAC,0BAA0B,CAAC,UAAU,EAAE,QAAQ,CAAC;QAClD,CAAC,CAAC,EAAE,CAAC;IAEP,oFAAoF;IACpF,uCAAuC;IACvC,MAAM,6BAA6B,GAAG,IAAI,GAAG,CAAC;QAC5C,8BAA8B;KAC/B,CAAC,CAAC;IACH,MAAM,uBAAuB,GAAG,gBAAgB,CAAC,MAAM,CACrD,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,6BAA6B,CAAC,GAAG,CAAE,CAAsB,CAAC,IAAI,CAAC,CACxE,CAAC;IAEF,OAAO;QACL,GAAG,YAAY;QACf,GAAG,WAAW;QACd,GAAG,YAAY;QACf,GAAG,uBAAuB;QAC1B,GAAG,YAAY;QACf,GAAG,gBAAgB;QACnB,GAAG,YAAY;QACf,GAAG,UAAU;QACb,GAAG,gBAAgB;QACnB,GAAG,YAAY;QACf,GAAG,eAAe;QAClB,GAAG,oBAAoB;KACxB,CAAC;AACJ,CAAC","sourcesContent":["import { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport type { HydeGraphDatabase } from \"../interfaces/database.interface.js\";\nimport { IntentGraphFactory } from \"../../intent/intent.graph.js\";\nimport { EnrichmentGraphFactory } from \"../../enrichment/enrichment.graph.js\";\nimport { OpportunityGraphFactory } from \"../../opportunity/opportunity.graph.js\";\nimport { HydeGraphFactory } from \"../hyde/hyde.graph.js\";\nimport { HydeGenerator } from \"../hyde/hyde.generator.js\";\nimport { LensInferrer } from \"../hyde/lens.inferrer.js\";\nimport { NetworkGraphFactory } from \"../../network/network.graph.js\";\nimport { NetworkMembershipGraphFactory } from \"../../network/membership/membership.graph.js\";\nimport { IntentNetworkGraphFactory } from \"../../network/indexer/indexer.graph.js\";\nimport { IntentIndexer } from \"../../intent/intent.indexer.js\";\nimport { NegotiationGraphFactory } from \"../../negotiation/negotiation.graph.js\";\nimport { PremiseGraphFactory } from \"../../premise/premise.graph.js\";\nimport { protocolLogger } from \"../observability/protocol.logger.js\";\n\nimport type { QuestionerEnqueueFn } from \"../../questioner/questioner.types.js\";\n\nimport { type ToolContext, type ResolvedToolContext, type ToolDeps, resolveChatContext, error, redactSensitiveFields } from \"./tool.helpers.js\";\nimport { deriveAllowedNetworkIds, scopeFromNetworkId } from \"./tool.scope.js\";\nimport { invokeToolRuntime, toolRuntimeErrorToResult } from \"./tool.runtime.js\";\nimport { createEnrichmentTools } from \"../../enrichment/enrichment.tools.js\";\nimport { createIntentTools } from \"../../intent/intent.tools.js\";\nimport { createNetworkTools } from \"../../network/network.tools.js\";\nimport { createOpportunityTools } from \"../../opportunity/opportunity.tools.js\";\nimport { createUtilityTools } from \"./utility.tools.js\";\nimport { createIntegrationTools } from \"../../integration/integration.tools.js\";\nimport { createContactTools } from \"../../contact/contact.tools.js\";\nimport { createAgentTools } from \"../../agent/agent.tools.js\";\nimport { createNegotiationTools } from \"../../negotiation/negotiation.tools.js\";\nimport { createPremiseTools } from \"../../premise/premise.tools.js\";\nimport { createQuestionerTools } from \"../../questioner/questioner.tools.js\";\nimport { createAskUserQuestionTools } from \"../../questioner/questioner.ask.tool.js\";\n\n// Re-export types for consumers\nexport type { ToolContext, ResolvedToolContext, ProtocolDeps } from \"./tool.helpers.js\";\nexport type { ToolDeps } from \"./tool.helpers.js\";\n\nconst logger = protocolLogger(\"ChatTools\");\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// TOOL FACTORY\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Creates all chat tools bound to a specific user context.\n * Resolves user/network identity from DB at init time.\n * Tools are created fresh for each user session to ensure proper isolation.\n *\n * All external dependencies (cache, integration, queue, etc.) are provided\n * via the `deps` parameter — the protocol lib never imports concrete adapters.\n */\nexport async function createChatTools(\n deps: ToolContext,\n preResolvedContext?: ResolvedToolContext\n) {\n const { database, embedder, scraper } = deps;\n\n const explicitScope = deps.scopeType && deps.scopeId\n ? { scopeType: deps.scopeType, scopeId: deps.scopeId }\n : scopeFromNetworkId(deps.networkId);\n\n // ─── Resolve context from DB ───────────────────────────────────────────────\n // resolveChatContext still accepts a networkId because it loads scoped index\n // presentation metadata; the canonical request scope is explicitScope.\n const resolvedContext =\n preResolvedContext ??\n (await resolveChatContext({\n 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\n if (!preResolvedContext && explicitScope.scopeType && explicitScope.scopeId) {\n resolvedContext.scopeType = explicitScope.scopeType;\n resolvedContext.scopeId = explicitScope.scopeId;\n }\n\n const allowedNetworkIds = deriveAllowedNetworkIds({\n memberships: resolvedContext.userNetworks,\n ...(resolvedContext.scopeType && resolvedContext.scopeId\n ? { scopeType: resolvedContext.scopeType, scopeId: resolvedContext.scopeId }\n : {}),\n });\n\n // ─── Tool wrapper ──────────────────────────────────────────────────────────\n /**\n * Standardized tool factory. Auto-injects resolved context and\n * provides uniform logging / error handling for every tool.\n */\n function defineTool<T extends z.ZodType>(opts: {\n name: string;\n description: string;\n querySchema: T;\n handler: (input: { context: ResolvedToolContext; query: z.infer<T> }) => Promise<string>;\n }) {\n return tool(\n async (query: z.infer<T>) => {\n logger.info('Tool invoked', {\n toolName: opts.name,\n context: { userId: resolvedContext.userId, scopeType: resolvedContext.scopeType, scopeId: resolvedContext.scopeId },\n query: redactSensitiveFields(query),\n });\n try {\n return await invokeToolRuntime({\n toolName: opts.name,\n tool: { handler: async ({ context, query }) => opts.handler({ context, query: query as z.infer<T> }) },\n context: resolvedContext,\n query,\n });\n } catch (err) {\n logger.error('Tool failed', {\n toolName: opts.name,\n error: err instanceof Error ? err.message : String(err),\n });\n const runtimeResult = toolRuntimeErrorToResult(err);\n if (runtimeResult) return runtimeResult;\n const reason = err instanceof Error ? err.message : String(err);\n return error(`Failed to execute ${opts.name}: ${reason}`);\n }\n },\n { name: opts.name, description: opts.description, schema: opts.querySchema }\n );\n }\n\n // ─── Compile subgraphs ─────────────────────────────────────────────────────\n\n // Wrap questionerEnqueue to include scoped/session context when available.\n const sessionAwareEnqueue: QuestionerEnqueueFn | undefined = deps.questionerEnqueue\n ? (input) => deps.questionerEnqueue!({\n ...input,\n ...(resolvedContext.scopeType && resolvedContext.scopeId && !input.scopeId\n ? { scopeType: resolvedContext.scopeType, scopeId: resolvedContext.scopeId }\n : {}),\n ...(resolvedContext.sessionId && !input.conversationId ? { conversationId: resolvedContext.sessionId } : {}),\n })\n : undefined;\n\n const intentGraph = new IntentGraphFactory(database, embedder, deps.intentQueue, sessionAwareEnqueue).createGraph();\n const premiseGraph = new PremiseGraphFactory(database, embedder).createGraph();\n const profileGraph = new EnrichmentGraphFactory(database, scraper, deps.enricher, sessionAwareEnqueue, premiseGraph).createGraph();\n const hydeCache = deps.hydeCache;\n const lensInferrer = new LensInferrer();\n const hydeGenerator = new HydeGenerator();\n const compiledHydeGraph = new HydeGraphFactory(\n database as unknown as HydeGraphDatabase,\n embedder,\n hydeCache,\n lensInferrer,\n hydeGenerator\n ).createGraph();\n const negotiationGraph = deps.agentDispatcher\n ? new NegotiationGraphFactory(\n deps.negotiationDatabase,\n deps.agentDispatcher,\n deps.negotiationTimeoutQueue,\n sessionAwareEnqueue,\n ).createGraph()\n : undefined;\n const opportunityGraph = new OpportunityGraphFactory(\n database,\n embedder,\n compiledHydeGraph,\n undefined, // evaluator (default)\n undefined, // queueNotification\n negotiationGraph,\n deps.agentDispatcher,\n deps.queueNegotiateExisting,\n deps.stampNewbornOpportunities,\n ).createGraph();\n const networkGraph = new NetworkGraphFactory(database).createGraph();\n const networkMembershipGraph = new NetworkMembershipGraphFactory(database).createGraph();\n const intentNetworkGraph = new IntentNetworkGraphFactory(database, new IntentIndexer()).createGraph();\n\n // ─── Create context-bound databases ────────────────────────────────────────\n // Use injected instances when provided (e.g. tests). Otherwise create from the same\n // database used for graphs so that scope checks (e.g. ensureScopedMembership, opportunity\n // update) use the same adapter as the rest of the tool pipeline.\n //\n // The systemDb's DB-level clamp derives concrete allowed network IDs from the\n // focused scope envelope plus memberships, rather than consuming a transported\n // legacy indexScope array.\n const userDb = deps.userDb ?? deps.createUserDatabase(database, resolvedContext.userId);\n const systemDb = deps.systemDb ?? deps.createSystemDatabase(database, resolvedContext.userId, allowedNetworkIds, embedder);\n\n // ─── Assemble dependencies ─────────────────────────────────────────────────\n const cache = deps.cache;\n const integration = deps.integration;\n const toolDeps: ToolDeps = {\n database,\n userDb,\n systemDb,\n scraper,\n embedder,\n cache,\n integration,\n contactService: deps.contactService,\n contactsEnabled: deps.contactsEnabled,\n integrationImporter: deps.integrationImporter,\n enricher: deps.enricher,\n negotiationDatabase: deps.negotiationDatabase,\n negotiationTimeoutQueue: deps.negotiationTimeoutQueue,\n agentDatabase: deps.agentDatabase,\n grantDefaultSystemPermissions: deps.grantDefaultSystemPermissions,\n agentDispatcher: deps.agentDispatcher,\n stampNewbornOpportunities: deps.stampNewbornOpportunities,\n deliveryLedger: deps.deliveryLedger,\n discoveryRuns: deps.discoveryRuns,\n discoveryRunQueue: deps.discoveryRunQueue,\n enrichmentRuns: deps.enrichmentRuns,\n enrichmentRunQueue: deps.enrichmentRunQueue,\n mintConnectToken: deps.mintConnectToken,\n mintConnectLink: deps.mintConnectLink,\n frontendUrl: deps.frontendUrl,\n apiBaseUrl: deps.apiBaseUrl,\n ...(deps.chatSummary && { chatSummary: deps.chatSummary }),\n ...(deps.questionGenerator && { questionGenerator: deps.questionGenerator }),\n ...(sessionAwareEnqueue && { questionerEnqueue: sessionAwareEnqueue }),\n ...(deps.findPendingQuestions && { findPendingQuestions: deps.findPendingQuestions }),\n ...(deps.answerPendingQuestion && { answerPendingQuestion: deps.answerPendingQuestion }),\n ...(deps.negotiationSummary && { negotiationSummary: deps.negotiationSummary }),\n ...(deps.chatQuestions && { chatQuestions: deps.chatQuestions }),\n ...(deps.chatSession && { chatSession: deps.chatSession }),\n ...(deps.getUserContextText && { getUserContextText: deps.getUserContextText }),\n graphs: {\n profile: profileGraph,\n intent: intentGraph,\n index: networkGraph,\n networkMembership: networkMembershipGraph,\n intentIndex: intentNetworkGraph,\n opportunity: opportunityGraph,\n premise: premiseGraph,\n },\n };\n\n // ─── Create domain tools ──────────────────────────────────────────────────\n const profileTools = createEnrichmentTools(defineTool, toolDeps);\n const intentTools = createIntentTools(defineTool, toolDeps);\n const networkTools = createNetworkTools(defineTool, toolDeps);\n const opportunityTools = createOpportunityTools(defineTool, toolDeps);\n const utilityTools = createUtilityTools(defineTool, toolDeps);\n const contactTools = createContactTools(defineTool, toolDeps);\n const agentTools = createAgentTools(defineTool, toolDeps);\n const integrationTools = createIntegrationTools(defineTool, toolDeps);\n const negotiationTools = deps.agentDispatcher\n ? createNegotiationTools(defineTool, toolDeps)\n : [];\n const premiseTools = createPremiseTools(defineTool, toolDeps);\n const questionerTools = createQuestionerTools(defineTool, toolDeps);\n // Blocking mid-conversation questions — chat-only (never in the MCP registry),\n // and only when the host provides the ChatQuestionsHost bridge.\n const askUserQuestionTools = deps.chatQuestions\n ? createAskUserQuestionTools(defineTool, toolDeps)\n : [];\n\n // confirm_opportunity_delivery is an OpenClaw-delivery ledger write and must not be\n // callable from regular chat sessions.\n const chatOpportunityToolExclusions = new Set([\n \"confirm_opportunity_delivery\",\n ]);\n const opportunityToolsForChat = opportunityTools.filter(\n (t) => !chatOpportunityToolExclusions.has((t as { name: string }).name)\n );\n\n return [\n ...profileTools,\n ...intentTools,\n ...networkTools,\n ...opportunityToolsForChat,\n ...utilityTools,\n ...integrationTools,\n ...contactTools,\n ...agentTools,\n ...negotiationTools,\n ...premiseTools,\n ...questionerTools,\n ...askUserQuestionTools,\n ];\n}\n\n/**\n * Type for the tools array returned by createChatTools.\n */\nexport type ChatTools = Awaited<ReturnType<typeof createChatTools>>;\n"]}