@indexnetwork/protocol 4.3.7-rc.317.1 → 4.4.0-rc.318.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 (47) hide show
  1. package/dist/chat/chat-streaming.types.d.ts +29 -2
  2. package/dist/chat/chat-streaming.types.d.ts.map +1 -1
  3. package/dist/chat/chat-streaming.types.js +3 -0
  4. package/dist/chat/chat-streaming.types.js.map +1 -1
  5. package/dist/chat/chat.agent.d.ts +15 -0
  6. package/dist/chat/chat.agent.d.ts.map +1 -1
  7. package/dist/chat/chat.agent.js.map +1 -1
  8. package/dist/chat/chat.prompt.d.ts.map +1 -1
  9. package/dist/chat/chat.prompt.js +3 -0
  10. package/dist/chat/chat.prompt.js.map +1 -1
  11. package/dist/chat/chat.streamer.d.ts.map +1 -1
  12. package/dist/chat/chat.streamer.js +9 -1
  13. package/dist/chat/chat.streamer.js.map +1 -1
  14. package/dist/index.d.ts +2 -2
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js.map +1 -1
  17. package/dist/questioner/questioner.ask.tool.d.ts +14 -0
  18. package/dist/questioner/questioner.ask.tool.d.ts.map +1 -0
  19. package/dist/questioner/questioner.ask.tool.js +309 -0
  20. package/dist/questioner/questioner.ask.tool.js.map +1 -0
  21. package/dist/questioner/questioner.presets.d.ts.map +1 -1
  22. package/dist/questioner/questioner.presets.js +73 -0
  23. package/dist/questioner/questioner.presets.js.map +1 -1
  24. package/dist/questioner/questioner.types.d.ts +21 -1
  25. package/dist/questioner/questioner.types.d.ts.map +1 -1
  26. package/dist/questioner/questioner.types.js.map +1 -1
  27. package/dist/shared/agent/tool.factory.d.ts.map +1 -1
  28. package/dist/shared/agent/tool.factory.js +10 -0
  29. package/dist/shared/agent/tool.factory.js.map +1 -1
  30. package/dist/shared/agent/tool.helpers.d.ts +19 -1
  31. package/dist/shared/agent/tool.helpers.d.ts.map +1 -1
  32. package/dist/shared/agent/tool.helpers.js.map +1 -1
  33. package/dist/shared/agent/tool.runtime.d.ts +1 -1
  34. package/dist/shared/agent/tool.runtime.d.ts.map +1 -1
  35. package/dist/shared/agent/tool.runtime.js +14 -3
  36. package/dist/shared/agent/tool.runtime.js.map +1 -1
  37. package/dist/shared/interfaces/questioner.interface.d.ts +26 -0
  38. package/dist/shared/interfaces/questioner.interface.d.ts.map +1 -1
  39. package/dist/shared/interfaces/questioner.interface.js.map +1 -1
  40. package/dist/shared/observability/request-context.d.ts +15 -0
  41. package/dist/shared/observability/request-context.d.ts.map +1 -1
  42. package/dist/shared/observability/request-context.js.map +1 -1
  43. package/dist/shared/schemas/question.schema.d.ts +4 -4
  44. package/dist/shared/schemas/question.schema.d.ts.map +1 -1
  45. package/dist/shared/schemas/question.schema.js +2 -0
  46. package/dist/shared/schemas/question.schema.js.map +1 -1
  47. package/package.json +1 -1
@@ -0,0 +1,309 @@
1
+ /**
2
+ * ask_user_question — blocking mid-conversation questions for the chat
3
+ * orchestrator (AskUserQuestion-style human-in-the-loop).
4
+ *
5
+ * Flow (hybrid authoring):
6
+ * 1. The orchestrator states what it needs to learn (`purpose`) plus optional
7
+ * draft questions.
8
+ * 2. The QuestionerAgent (mode `chat`) refines that into polished structured
9
+ * questions, grounded in the recent conversation excerpt and the user's
10
+ * global context.
11
+ * 3. Questions are persisted (`questions` table, mode `chat`,
12
+ * `conversationId = sessionId`) via the injected {@link ChatQuestionsHost}.
13
+ * 4. A `user_question` trace event streams the persisted questions to the
14
+ * frontend, which renders them inline while the turn stays open.
15
+ * 5. The tool blocks on `awaitAnswers` until the user answers/dismisses
16
+ * through the questions REST endpoints, the wait budget elapses, or the
17
+ * run is aborted. Answers come back as the tool result so the model
18
+ * continues the SAME turn.
19
+ *
20
+ * On timeout the questions remain `pending`: they survive reloads via the
21
+ * conversation-linked question fetch, and a later answer re-enters the chat
22
+ * as a new user turn (frontend responsibility).
23
+ *
24
+ * Chat-only: not registered in the MCP tool registry. The handler also fails
25
+ * gracefully when the session/stream context or host bridge is missing.
26
+ */
27
+ import { z } from "zod";
28
+ import { error, success } from "../shared/agent/tool.helpers.js";
29
+ import { requestContext } from "../shared/observability/request-context.js";
30
+ import { protocolLogger } from "../shared/observability/protocol.logger.js";
31
+ import { QuestionerAgent } from "./questioner.agent.js";
32
+ const logger = protocolLogger("AskUserQuestionTool");
33
+ /** Default in-tool wait budget for the user's answer (4 minutes). */
34
+ const DEFAULT_WAIT_TIMEOUT_MS = 4 * 60 * 1000;
35
+ /** Heartbeat interval while blocked, so SSE transports do not idle out. */
36
+ const WAIT_HEARTBEAT_MS = 15000;
37
+ /** Messages included in the conversation excerpt fed to the QuestionerAgent. */
38
+ const EXCERPT_MESSAGE_COUNT = 10;
39
+ /**
40
+ * Fetch window for the excerpt. Host adapters return the FIRST N messages
41
+ * (ascending) when a limit is passed, so we fetch a wide window and keep the
42
+ * tail to get the most recent exchange.
43
+ */
44
+ const EXCERPT_FETCH_LIMIT = 100;
45
+ /** Max characters per message inside the excerpt. */
46
+ const EXCERPT_MESSAGE_CHARS = 400;
47
+ function waitTimeoutMs() {
48
+ const raw = process.env.CHAT_QUESTION_WAIT_TIMEOUT_MS;
49
+ if (!raw)
50
+ return DEFAULT_WAIT_TIMEOUT_MS;
51
+ const parsed = Number.parseInt(raw, 10);
52
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_WAIT_TIMEOUT_MS;
53
+ }
54
+ // Lazy singleton — construction binds the LLM once; invocations are stateless.
55
+ let questionerAgent = null;
56
+ function getQuestionerAgent() {
57
+ if (!questionerAgent)
58
+ questionerAgent = new QuestionerAgent();
59
+ return questionerAgent;
60
+ }
61
+ /** Test seam: replace or reset the module-level QuestionerAgent singleton. */
62
+ export function setQuestionerAgentForTesting(agent) {
63
+ questionerAgent = agent;
64
+ }
65
+ const draftQuestionSchema = z.object({
66
+ prompt: z
67
+ .string()
68
+ .min(5)
69
+ .max(400)
70
+ .describe("The question to ask, ending in a question mark. Self-contained plain language."),
71
+ options: z
72
+ .array(z.string().min(1).max(120))
73
+ .min(2)
74
+ .max(4)
75
+ .optional()
76
+ .describe("2-4 mutually distinct answer options. Omit to let the question generator derive them."),
77
+ multiSelect: z
78
+ .boolean()
79
+ .optional()
80
+ .describe("True when several options can be picked together (priorities, bundles)."),
81
+ });
82
+ /**
83
+ * Build a fallback Question directly from an orchestrator draft when the
84
+ * QuestionerAgent produced nothing. Requires the draft to carry options.
85
+ */
86
+ function questionFromDraft(draft, index) {
87
+ if (!draft.options || draft.options.length < 2)
88
+ return null;
89
+ return {
90
+ title: `Question ${index + 1}`,
91
+ prompt: draft.prompt.slice(0, 400),
92
+ options: draft.options.slice(0, 4).map((label) => ({
93
+ label: label.slice(0, 120),
94
+ description: label.slice(0, 280),
95
+ })),
96
+ multiSelect: draft.multiSelect ?? false,
97
+ };
98
+ }
99
+ /**
100
+ * Creates the chat-only `ask_user_question` tool. Registered by
101
+ * `createChatTools` only when `deps.chatQuestions` is provided — never part
102
+ * of the MCP tool registry (MCP clients have their own elicitation surface).
103
+ *
104
+ * @param defineTool - Tool factory provided by the composition root.
105
+ * @param deps - Shared tool dependencies; requires `chatQuestions`.
106
+ */
107
+ export function createAskUserQuestionTools(defineTool, deps) {
108
+ const askUserQuestion = defineTool({
109
+ name: "ask_user_question",
110
+ description: "Ask the user 1-3 structured clarifying questions and WAIT for their answer before continuing. " +
111
+ "The conversation pauses: the user sees interactive question cards inline and your turn resumes " +
112
+ "with their selections as the tool result.\n\n" +
113
+ "**Use when** a decision materially changes what you do next — before an expensive operation " +
114
+ "(discovery, creating an intent from ambiguous input), when facing meaningfully different " +
115
+ "directions, or when one concrete missing detail (timing, scope, budget, format) blocks progress.\n\n" +
116
+ "**Do not use** for facts already visible in the conversation or profile, procedural " +
117
+ "confirmations (\"Should I proceed?\"), or open-ended questions better asked in your response text.\n\n" +
118
+ "**Input:** `purpose` states what you need to learn and why. Optionally propose `questions` " +
119
+ "drafts (prompt + 2-4 options); a question generator refines wording and option quality.\n\n" +
120
+ "**Returns:** One entry per question with `status` (`answered`/`dismissed`/`timeout`) and the " +
121
+ "user's `selectedOptions`/`freeText`. On `timeout` the questions stay visible in the " +
122
+ "conversation — acknowledge briefly and end your turn; do NOT repeat the questions in text.",
123
+ querySchema: z.object({
124
+ purpose: z
125
+ .string()
126
+ .min(10)
127
+ .max(600)
128
+ .describe("What you need to learn from the user and why it changes what you do next."),
129
+ questions: z
130
+ .array(draftQuestionSchema)
131
+ .min(1)
132
+ .max(3)
133
+ .optional()
134
+ .describe("Draft questions to ask. The question generator polishes them before display."),
135
+ }),
136
+ handler: async ({ context, query }) => {
137
+ const host = deps.chatQuestions;
138
+ if (!host) {
139
+ return error("Interactive questions are not available in this environment. Ask the user directly in your response text instead.");
140
+ }
141
+ if (context.isMcp || !context.sessionId) {
142
+ return error("Interactive questions require a live chat session. Ask the user directly in your response text instead.");
143
+ }
144
+ const store = requestContext.getStore();
145
+ const emit = store?.traceEmitter;
146
+ const signal = store?.abortSignal;
147
+ if (!emit) {
148
+ return error("Interactive questions require a streaming chat turn. Ask the user directly in your response text instead.");
149
+ }
150
+ const sessionId = context.sessionId;
151
+ // ── 1. Gather grounding context ────────────────────────────────────
152
+ const [conversationExcerpt, userContext] = await Promise.all([
153
+ loadConversationExcerpt(deps, sessionId),
154
+ deps.getUserContextText?.(context.userId).catch(() => "") ?? Promise.resolve(""),
155
+ ]);
156
+ // ── 2. Generate polished questions (hybrid: drafts + QuestionerAgent) ──
157
+ const chatContext = {
158
+ purpose: query.purpose,
159
+ ...(query.questions?.length ? { draftQuestions: query.questions } : {}),
160
+ ...(conversationExcerpt ? { conversationExcerpt } : {}),
161
+ ...(userContext ? { userContext } : {}),
162
+ };
163
+ let generated = null;
164
+ try {
165
+ generated = await getQuestionerAgent().invoke({
166
+ mode: "chat",
167
+ userId: context.userId,
168
+ sourceType: "conversation",
169
+ sourceId: sessionId,
170
+ context: chatContext,
171
+ conversationId: sessionId,
172
+ }, signal ? { signal } : undefined);
173
+ }
174
+ catch (err) {
175
+ logger.warn("QuestionerAgent invocation failed", {
176
+ error: err instanceof Error ? err.message : String(err),
177
+ });
178
+ }
179
+ let finalQuestions;
180
+ let strategies;
181
+ if (generated && generated.questions.length > 0) {
182
+ finalQuestions = generated.questions;
183
+ strategies = generated.strategies;
184
+ }
185
+ else {
186
+ // Fallback: use the orchestrator's own drafts verbatim (options required).
187
+ const fromDrafts = (query.questions ?? [])
188
+ .map((d, i) => questionFromDraft(d, i))
189
+ .filter((q) => q !== null);
190
+ if (fromDrafts.length === 0) {
191
+ return error("Could not prepare structured questions. Ask the user directly in your response text instead.");
192
+ }
193
+ finalQuestions = fromDrafts;
194
+ strategies = fromDrafts.map(() => "surface_missing_detail");
195
+ }
196
+ if (signal?.aborted) {
197
+ return error("The chat turn was cancelled before the questions could be shown.");
198
+ }
199
+ // ── 3. Persist (mode `chat`, linked to this conversation) ──────────
200
+ const timestamp = new Date().toISOString();
201
+ const batch = finalQuestions.map((payload, i) => ({
202
+ detection: {
203
+ mode: "chat",
204
+ sourceType: "conversation",
205
+ sourceId: sessionId,
206
+ timestamp,
207
+ },
208
+ actors: [{ userId: context.userId, role: "subject" }],
209
+ payload,
210
+ strategy: strategies[i] ?? "surface_missing_detail",
211
+ conversationId: sessionId,
212
+ }));
213
+ let persisted;
214
+ try {
215
+ persisted = await host.persist(batch);
216
+ }
217
+ catch (err) {
218
+ logger.error("Failed to persist chat questions", {
219
+ error: err instanceof Error ? err.message : String(err),
220
+ });
221
+ return error("Could not deliver the questions to the user. Ask directly in your response text instead.");
222
+ }
223
+ // ── 4. Stream the cards to the frontend ────────────────────────────
224
+ emit({
225
+ type: "user_question",
226
+ questions: persisted.map((q) => ({
227
+ id: q.id,
228
+ title: q.payload.title,
229
+ prompt: q.payload.prompt,
230
+ options: q.payload.options,
231
+ multiSelect: q.payload.multiSelect,
232
+ })),
233
+ });
234
+ // ── 5. Block until answered / dismissed / timeout / abort ──────────
235
+ const heartbeat = setInterval(() => {
236
+ try {
237
+ emit({ type: "status", message: "Waiting for your answer…" });
238
+ }
239
+ catch {
240
+ /* stream may be closing; the wait resolves via timeout/abort */
241
+ }
242
+ }, WAIT_HEARTBEAT_MS);
243
+ let outcomes;
244
+ try {
245
+ outcomes = await host.awaitAnswers(persisted.map((q) => q.id), { timeoutMs: waitTimeoutMs(), ...(signal ? { signal } : {}) });
246
+ }
247
+ finally {
248
+ clearInterval(heartbeat);
249
+ }
250
+ const byId = new Map(persisted.map((q) => [q.id, q]));
251
+ const results = outcomes.map((o) => {
252
+ const q = byId.get(o.questionId);
253
+ return {
254
+ questionId: o.questionId,
255
+ prompt: q?.payload.prompt ?? "",
256
+ status: o.status,
257
+ ...(o.answer
258
+ ? {
259
+ selectedOptions: o.answer.selectedOptions,
260
+ ...(o.answer.freeText ? { freeText: o.answer.freeText } : {}),
261
+ }
262
+ : {}),
263
+ };
264
+ });
265
+ const answeredCount = results.filter((r) => r.status === "answered").length;
266
+ const timedOut = results.some((r) => r.status === "timeout");
267
+ return success({
268
+ answers: results,
269
+ summary: `${answeredCount} of ${results.length} question(s) answered`,
270
+ ...(timedOut
271
+ ? {
272
+ guidance: "The user has not answered the remaining question(s) yet. They stay visible in the conversation — acknowledge briefly, do NOT repeat the questions in text, and end your turn.",
273
+ }
274
+ : {}),
275
+ });
276
+ },
277
+ });
278
+ return [askUserQuestion];
279
+ }
280
+ /**
281
+ * Load a compact excerpt of the most recent conversation messages for the
282
+ * QuestionerAgent's grounding. Best-effort: returns "" on any failure or when
283
+ * no chat session reader is available. Note: the in-flight user message is
284
+ * not yet persisted; the orchestrator's `purpose` carries that context.
285
+ */
286
+ async function loadConversationExcerpt(deps, sessionId) {
287
+ if (!deps.chatSession)
288
+ return "";
289
+ try {
290
+ const messages = await deps.chatSession.getSessionMessages(sessionId, EXCERPT_FETCH_LIMIT);
291
+ if (!messages || messages.length === 0)
292
+ return "";
293
+ return messages
294
+ .slice(-EXCERPT_MESSAGE_COUNT)
295
+ .map((m) => {
296
+ const role = m.role === "assistant" ? "Assistant" : "User";
297
+ const text = (m.content ?? "").replace(/\s+/g, " ").trim();
298
+ return `${role}: ${text.slice(0, EXCERPT_MESSAGE_CHARS)}`;
299
+ })
300
+ .join("\n");
301
+ }
302
+ catch (err) {
303
+ logger.warn("Failed to load conversation excerpt", {
304
+ error: err instanceof Error ? err.message : String(err),
305
+ });
306
+ return "";
307
+ }
308
+ }
309
+ //# sourceMappingURL=questioner.ask.tool.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"questioner.ask.tool.js","sourceRoot":"/","sources":["questioner/questioner.ask.tool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAG5E,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAGxD,MAAM,MAAM,GAAG,cAAc,CAAC,qBAAqB,CAAC,CAAC;AAErD,qEAAqE;AACrE,MAAM,uBAAuB,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;AAE9C,2EAA2E;AAC3E,MAAM,iBAAiB,GAAG,KAAM,CAAC;AAEjC,gFAAgF;AAChF,MAAM,qBAAqB,GAAG,EAAE,CAAC;AAEjC;;;;GAIG;AACH,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAEhC,qDAAqD;AACrD,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAElC,SAAS,aAAa;IACpB,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,6BAA6B,CAAC;IACtD,IAAI,CAAC,GAAG;QAAE,OAAO,uBAAuB,CAAC;IACzC,MAAM,MAAM,GAAG,MAAM,CAAC,QAAQ,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IAC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AG,MAAM,IAAI,CAAC,WAAW,CAAC,kBAAkB,CAAC,SAAS,EAAE,mBAAmB,CAAC,CAAC;QAC3F,IAAI,CAAC,QAAQ,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,EAAE,CAAC;QAClD,OAAO,QAAQ;aACZ,KAAK,CAAC,CAAC,qBAAqB,CAAC;aAC7B,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE;YACT,MAAM,IAAI,GAAG,CAAC,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC;YAC3D,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;YAC3D,OAAO,GAAG,IAAI,KAAK,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,qBAAqB,CAAC,EAAE,CAAC;QAC5D,CAAC,CAAC;aACD,IAAI,CAAC,IAAI,CAAC,CAAC;IAChB,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,CAAC,IAAI,CAAC,qCAAqC,EAAE;YACjD,KAAK,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC;SACxD,CAAC,CAAC;QACH,OAAO,EAAE,CAAC;IACZ,CAAC;AACH,CAAC","sourcesContent":["/**\n * ask_user_question — blocking mid-conversation questions for the chat\n * orchestrator (AskUserQuestion-style human-in-the-loop).\n *\n * Flow (hybrid authoring):\n * 1. The orchestrator states what it needs to learn (`purpose`) plus optional\n * draft questions.\n * 2. The QuestionerAgent (mode `chat`) refines that into polished structured\n * questions, grounded in the recent conversation excerpt and the user's\n * global context.\n * 3. Questions are persisted (`questions` table, mode `chat`,\n * `conversationId = sessionId`) via the injected {@link ChatQuestionsHost}.\n * 4. A `user_question` trace event streams the persisted questions to the\n * frontend, which renders them inline while the turn stays open.\n * 5. The tool blocks on `awaitAnswers` until the user answers/dismisses\n * through the questions REST endpoints, the wait budget elapses, or the\n * run is aborted. Answers come back as the tool result so the model\n * continues the SAME turn.\n *\n * On timeout the questions remain `pending`: they survive reloads via the\n * conversation-linked question fetch, and a later answer re-enters the chat\n * as a new user turn (frontend responsibility).\n *\n * Chat-only: not registered in the MCP tool registry. The handler also fails\n * gracefully when the session/stream context or host bridge is missing.\n */\nimport { z } from \"zod\";\n\nimport type { DefineTool, ToolDeps } from \"../shared/agent/tool.helpers.js\";\nimport { error, success } from \"../shared/agent/tool.helpers.js\";\nimport { requestContext } from \"../shared/observability/request-context.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport type { PersistableQuestion, PersistedQuestion, ChatQuestionAnswerOutcome } from \"../shared/interfaces/questioner.interface.js\";\nimport type { Question, QuestionStrategy } from \"../shared/schemas/question.schema.js\";\nimport { QuestionerAgent } from \"./questioner.agent.js\";\nimport type { ChatContext } from \"./questioner.types.js\";\n\nconst logger = protocolLogger(\"AskUserQuestionTool\");\n\n/** Default in-tool wait budget for the user's answer (4 minutes). */\nconst DEFAULT_WAIT_TIMEOUT_MS = 4 * 60 * 1000;\n\n/** Heartbeat interval while blocked, so SSE transports do not idle out. */\nconst WAIT_HEARTBEAT_MS = 15_000;\n\n/** Messages included in the conversation excerpt fed to the QuestionerAgent. */\nconst EXCERPT_MESSAGE_COUNT = 10;\n\n/**\n * Fetch window for the excerpt. Host adapters return the FIRST N messages\n * (ascending) when a limit is passed, so we fetch a wide window and keep the\n * tail to get the most recent exchange.\n */\nconst EXCERPT_FETCH_LIMIT = 100;\n\n/** Max characters per message inside the excerpt. */\nconst EXCERPT_MESSAGE_CHARS = 400;\n\nfunction waitTimeoutMs(): number {\n const raw = process.env.CHAT_QUESTION_WAIT_TIMEOUT_MS;\n if (!raw) return DEFAULT_WAIT_TIMEOUT_MS;\n const parsed = Number.parseInt(raw, 10);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_WAIT_TIMEOUT_MS;\n}\n\n// Lazy singleton — construction binds the LLM once; invocations are stateless.\nlet questionerAgent: QuestionerAgent | null = null;\nfunction getQuestionerAgent(): QuestionerAgent {\n if (!questionerAgent) questionerAgent = new QuestionerAgent();\n return questionerAgent;\n}\n\n/** Test seam: replace or reset the module-level QuestionerAgent singleton. */\nexport function setQuestionerAgentForTesting(agent: QuestionerAgent | null): void {\n questionerAgent = agent;\n}\n\nconst draftQuestionSchema = z.object({\n prompt: z\n .string()\n .min(5)\n .max(400)\n .describe(\"The question to ask, ending in a question mark. Self-contained plain language.\"),\n options: z\n .array(z.string().min(1).max(120))\n .min(2)\n .max(4)\n .optional()\n .describe(\"2-4 mutually distinct answer options. Omit to let the question generator derive them.\"),\n multiSelect: z\n .boolean()\n .optional()\n .describe(\"True when several options can be picked together (priorities, bundles).\"),\n});\n\n/**\n * Build a fallback Question directly from an orchestrator draft when the\n * QuestionerAgent produced nothing. Requires the draft to carry options.\n */\nfunction questionFromDraft(draft: z.infer<typeof draftQuestionSchema>, index: number): Question | null {\n if (!draft.options || draft.options.length < 2) return null;\n return {\n title: `Question ${index + 1}`,\n prompt: draft.prompt.slice(0, 400),\n options: draft.options.slice(0, 4).map((label) => ({\n label: label.slice(0, 120),\n description: label.slice(0, 280),\n })),\n multiSelect: draft.multiSelect ?? false,\n };\n}\n\n/**\n * Creates the chat-only `ask_user_question` tool. Registered by\n * `createChatTools` only when `deps.chatQuestions` is provided — never part\n * of the MCP tool registry (MCP clients have their own elicitation surface).\n *\n * @param defineTool - Tool factory provided by the composition root.\n * @param deps - Shared tool dependencies; requires `chatQuestions`.\n */\nexport function createAskUserQuestionTools(defineTool: DefineTool, deps: ToolDeps) {\n const askUserQuestion = defineTool({\n name: \"ask_user_question\",\n description:\n \"Ask the user 1-3 structured clarifying questions and WAIT for their answer before continuing. \" +\n \"The conversation pauses: the user sees interactive question cards inline and your turn resumes \" +\n \"with their selections as the tool result.\\n\\n\" +\n \"**Use when** a decision materially changes what you do next — before an expensive operation \" +\n \"(discovery, creating an intent from ambiguous input), when facing meaningfully different \" +\n \"directions, or when one concrete missing detail (timing, scope, budget, format) blocks progress.\\n\\n\" +\n \"**Do not use** for facts already visible in the conversation or profile, procedural \" +\n \"confirmations (\\\"Should I proceed?\\\"), or open-ended questions better asked in your response text.\\n\\n\" +\n \"**Input:** `purpose` states what you need to learn and why. Optionally propose `questions` \" +\n \"drafts (prompt + 2-4 options); a question generator refines wording and option quality.\\n\\n\" +\n \"**Returns:** One entry per question with `status` (`answered`/`dismissed`/`timeout`) and the \" +\n \"user's `selectedOptions`/`freeText`. On `timeout` the questions stay visible in the \" +\n \"conversation — acknowledge briefly and end your turn; do NOT repeat the questions in text.\",\n querySchema: z.object({\n purpose: z\n .string()\n .min(10)\n .max(600)\n .describe(\"What you need to learn from the user and why it changes what you do next.\"),\n questions: z\n .array(draftQuestionSchema)\n .min(1)\n .max(3)\n .optional()\n .describe(\"Draft questions to ask. The question generator polishes them before display.\"),\n }),\n handler: async ({ context, query }) => {\n const host = deps.chatQuestions;\n if (!host) {\n return error(\n \"Interactive questions are not available in this environment. Ask the user directly in your response text instead.\",\n );\n }\n if (context.isMcp || !context.sessionId) {\n return error(\n \"Interactive questions require a live chat session. Ask the user directly in your response text instead.\",\n );\n }\n const store = requestContext.getStore();\n const emit = store?.traceEmitter;\n const signal = store?.abortSignal;\n if (!emit) {\n return error(\n \"Interactive questions require a streaming chat turn. Ask the user directly in your response text instead.\",\n );\n }\n\n const sessionId = context.sessionId;\n\n // ── 1. Gather grounding context ────────────────────────────────────\n const [conversationExcerpt, userContext] = await Promise.all([\n loadConversationExcerpt(deps, sessionId),\n deps.getUserContextText?.(context.userId).catch(() => \"\") ?? Promise.resolve(\"\"),\n ]);\n\n // ── 2. Generate polished questions (hybrid: drafts + QuestionerAgent) ──\n const chatContext: ChatContext = {\n purpose: query.purpose,\n ...(query.questions?.length ? { draftQuestions: query.questions } : {}),\n ...(conversationExcerpt ? { conversationExcerpt } : {}),\n ...(userContext ? { userContext } : {}),\n };\n\n let generated: { questions: Question[]; strategies: QuestionStrategy[] } | null = null;\n try {\n generated = await getQuestionerAgent().invoke(\n {\n mode: \"chat\",\n userId: context.userId,\n sourceType: \"conversation\",\n sourceId: sessionId,\n context: chatContext,\n conversationId: sessionId,\n },\n signal ? { signal } : undefined,\n );\n } catch (err) {\n logger.warn(\"QuestionerAgent invocation failed\", {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n\n let finalQuestions: Question[];\n let strategies: QuestionStrategy[];\n if (generated && generated.questions.length > 0) {\n finalQuestions = generated.questions;\n strategies = generated.strategies;\n } else {\n // Fallback: use the orchestrator's own drafts verbatim (options required).\n const fromDrafts = (query.questions ?? [])\n .map((d, i) => questionFromDraft(d, i))\n .filter((q): q is Question => q !== null);\n if (fromDrafts.length === 0) {\n return error(\n \"Could not prepare structured questions. Ask the user directly in your response text instead.\",\n );\n }\n finalQuestions = fromDrafts;\n strategies = fromDrafts.map(() => \"surface_missing_detail\" as const);\n }\n\n if (signal?.aborted) {\n return error(\"The chat turn was cancelled before the questions could be shown.\");\n }\n\n // ── 3. Persist (mode `chat`, linked to this conversation) ──────────\n const timestamp = new Date().toISOString();\n const batch: PersistableQuestion[] = finalQuestions.map((payload, i) => ({\n detection: {\n mode: \"chat\",\n sourceType: \"conversation\",\n sourceId: sessionId,\n timestamp,\n },\n actors: [{ userId: context.userId, role: \"subject\" as const }],\n payload,\n strategy: strategies[i] ?? \"surface_missing_detail\",\n conversationId: sessionId,\n }));\n\n let persisted: PersistedQuestion[];\n try {\n persisted = await host.persist(batch);\n } catch (err) {\n logger.error(\"Failed to persist chat questions\", {\n error: err instanceof Error ? err.message : String(err),\n });\n return error(\"Could not deliver the questions to the user. Ask directly in your response text instead.\");\n }\n\n // ── 4. Stream the cards to the frontend ────────────────────────────\n emit({\n type: \"user_question\",\n questions: persisted.map((q) => ({\n id: q.id,\n title: q.payload.title,\n prompt: q.payload.prompt,\n options: q.payload.options,\n multiSelect: q.payload.multiSelect,\n })),\n });\n\n // ── 5. Block until answered / dismissed / timeout / abort ──────────\n const heartbeat = setInterval(() => {\n try {\n emit({ type: \"status\", message: \"Waiting for your answer…\" });\n } catch {\n /* stream may be closing; the wait resolves via timeout/abort */\n }\n }, WAIT_HEARTBEAT_MS);\n\n let outcomes: ChatQuestionAnswerOutcome[];\n try {\n outcomes = await host.awaitAnswers(\n persisted.map((q) => q.id),\n { timeoutMs: waitTimeoutMs(), ...(signal ? { signal } : {}) },\n );\n } finally {\n clearInterval(heartbeat);\n }\n\n const byId = new Map(persisted.map((q) => [q.id, q]));\n const results = outcomes.map((o) => {\n const q = byId.get(o.questionId);\n return {\n questionId: o.questionId,\n prompt: q?.payload.prompt ?? \"\",\n status: o.status,\n ...(o.answer\n ? {\n selectedOptions: o.answer.selectedOptions,\n ...(o.answer.freeText ? { freeText: o.answer.freeText } : {}),\n }\n : {}),\n };\n });\n\n const answeredCount = results.filter((r) => r.status === \"answered\").length;\n const timedOut = results.some((r) => r.status === \"timeout\");\n\n return success({\n answers: results,\n summary: `${answeredCount} of ${results.length} question(s) answered`,\n ...(timedOut\n ? {\n guidance:\n \"The user has not answered the remaining question(s) yet. They stay visible in the conversation — acknowledge briefly, do NOT repeat the questions in text, and end your turn.\",\n }\n : {}),\n });\n },\n });\n\n return [askUserQuestion] as const;\n}\n\n/**\n * Load a compact excerpt of the most recent conversation messages for the\n * QuestionerAgent's grounding. Best-effort: returns \"\" on any failure or when\n * no chat session reader is available. Note: the in-flight user message is\n * not yet persisted; the orchestrator's `purpose` carries that context.\n */\nasync function loadConversationExcerpt(deps: ToolDeps, sessionId: string): Promise<string> {\n if (!deps.chatSession) return \"\";\n try {\n const messages = await deps.chatSession.getSessionMessages(sessionId, EXCERPT_FETCH_LIMIT);\n if (!messages || messages.length === 0) return \"\";\n return messages\n .slice(-EXCERPT_MESSAGE_COUNT)\n .map((m) => {\n const role = m.role === \"assistant\" ? \"Assistant\" : \"User\";\n const text = (m.content ?? \"\").replace(/\\s+/g, \" \").trim();\n return `${role}: ${text.slice(0, EXCERPT_MESSAGE_CHARS)}`;\n })\n .join(\"\\n\");\n } catch (err) {\n logger.warn(\"Failed to load conversation excerpt\", {\n error: err instanceof Error ? err.message : String(err),\n });\n return \"\";\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"questioner.presets.d.ts","sourceRoot":"/","sources":["questioner/questioner.presets.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sCAAsC,CAAC;AAqBzE,MAAM,WAAW,gBAAgB;IAC/B,2CAA2C;IAC3C,YAAY,EAAE,MAAM,CAAC;IACrB,qEAAqE;IACrE,WAAW,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,MAAM,CAAC;CAC3C;AAoOD;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,YAAY,GAAG,gBAAgB,CAM9D"}
1
+ {"version":3,"file":"questioner.presets.d.ts","sourceRoot":"/","sources":["questioner/questioner.presets.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sCAAsC,CAAC;AAqBzE,MAAM,WAAW,gBAAgB;IAC/B,2CAA2C;IAC3C,YAAY,EAAE,MAAM,CAAC;IACrB,qEAAqE;IACrE,WAAW,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,MAAM,CAAC;CAC3C;AAoTD;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,YAAY,GAAG,gBAAgB,CAM9D"}
@@ -196,6 +196,75 @@ function buildNegotiationPrompt(ctx) {
196
196
  "Return an empty `questions` array if the context already contains enough signal to proceed.",
197
197
  ].join("\n");
198
198
  }
199
+ // ─── Chat preset ─────────────────────────────────────────────────────────
200
+ const 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.
201
+
202
+ Unlike 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.
203
+
204
+ You may pick from two strategies. Choose contextually; mix only when each question is genuinely distinct.
205
+ - surface_missing_detail: ask for one concrete missing input the orchestrator needs to proceed (scope, timing, budget, format, preference, constraint, …).
206
+ - refine_intent: ask the user to choose a direction when the orchestrator faces meaningfully different paths forward.
207
+
208
+ Honor 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.
209
+
210
+ Ask a question only when ALL of these hold:
211
+ 1. The answer is not already visible in the conversation excerpt or user profile shown.
212
+ 2. The answer materially changes what the orchestrator does next.
213
+ 3. The question targets a different decision domain from any other question in this batch.
214
+
215
+ ${REFERENTIAL_CLOSURE_RULES}
216
+
217
+ Cardinality. 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.
218
+
219
+ Option 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.
220
+
221
+ Title rules. ≤12 chars. Noun of the decision domain. Examples: "Direction", "Scope", "Timing", "Budget", "Format", "Priority".
222
+
223
+ Anti-patterns — never do these.
224
+ - Don't ask procedural confirmations ("Should I continue?", "Is that OK?").
225
+ - Don't re-ask for facts visible in the conversation excerpt or user profile.
226
+ - Don't broaden beyond the orchestrator's stated purpose.
227
+ - Don't ask vague introspective questions.
228
+
229
+ Output. 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": [].`;
230
+ /**
231
+ * Build the user message for the chat preset from a ChatContext.
232
+ * @param ctx - The chat context: orchestrator purpose, optional drafts, conversation excerpt, user context.
233
+ * @returns The assembled user message string.
234
+ */
235
+ function buildChatPrompt(ctx) {
236
+ const profileBlock = buildUserContextBlock(ctx.userContext);
237
+ const draftsBlock = ctx.draftQuestions && ctx.draftQuestions.length > 0
238
+ ? ctx.draftQuestions
239
+ .map((d, i) => {
240
+ const opts = d.options && d.options.length > 0 ? ` [options: ${d.options.join(" | ")}]` : "";
241
+ const multi = d.multiSelect ? " [multi-select]" : "";
242
+ return `${i + 1}. ${d.prompt}${opts}${multi}`;
243
+ })
244
+ .join("\n")
245
+ : "(none — derive questions from the purpose)";
246
+ const excerptBlock = ctx.conversationExcerpt?.trim()
247
+ ? ctx.conversationExcerpt.trim()
248
+ : "(not available)";
249
+ return [
250
+ "## What the orchestrator needs to learn",
251
+ ctx.purpose,
252
+ "",
253
+ "## Draft questions proposed by the orchestrator",
254
+ draftsBlock,
255
+ "",
256
+ "## Recent conversation excerpt",
257
+ excerptBlock,
258
+ "",
259
+ "## User profile",
260
+ profileBlock,
261
+ "",
262
+ "## Your task",
263
+ "Produce the minimum set of structured questions that get the orchestrator the decision or input it needs.",
264
+ "Honor the drafts when provided; refine their wording and options rather than replacing their topics.",
265
+ "Apply every rule from your system prompt before outputting.",
266
+ ].join("\n");
267
+ }
199
268
  const presets = {
200
269
  discovery: {
201
270
  systemPrompt: DISCOVERY_SYSTEM_PROMPT,
@@ -213,6 +282,10 @@ const presets = {
213
282
  systemPrompt: NEGOTIATION_SYSTEM_PROMPT,
214
283
  buildPrompt: (context) => buildNegotiationPrompt(context),
215
284
  },
285
+ chat: {
286
+ systemPrompt: CHAT_SYSTEM_PROMPT,
287
+ buildPrompt: (context) => buildChatPrompt(context),
288
+ },
216
289
  };
217
290
  /**
218
291
  * Retrieve the preset for the given mode.
@@ -1 +1 @@
1
- {"version":3,"file":"questioner.presets.js","source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AAE;QACF,cAAc;QACd,mGAAmG;QACnG,6DAA6D;QAC7D,6FAA6F;KAC9F,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACf,CAAC;AAED,MAAM,OAAO,GAA2C;IACtD,SAAS,EAAE;QACT,YAAY,EAAE,uBAAuB;QACrC,WAAW,EAAE,CAAC,OAAgB,EAAE,EAAE,CAChC,oBAAoB,CAAC,OAAqD,CAAC;KAC9E;IACD,MAAM,EAAE;QACN,YAAY,EAAE,oBAAoB;QAClC,WAAW,EAAE,CAAC,OAAgB,EAAE,EAAE,CAAC,iBAAiB,CAAC,OAAwB,CAAC;KAC/E;IACD,UAAU,EAAE;QACV,YAAY,EAAE,qBAAqB;QACnC,WAAW,EAAE,CAAC,OAAgB,EAAE,EAAE,CAAC,kBAAkB,CAAC,OAAyB,CAAC;KACjF;IACD,WAAW,EAAE;QACX,YAAY,EAAE,yBAAyB;QACvC,WAAW,EAAE,CAAC,OAAgB,EAAE,EAAE,CAAC,sBAAsB,CAAC,OAA6B,CAAC;KACzF;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 { SYSTEM_PROMPT as DISCOVERY_SYSTEM_PROMPT, buildQuestionPrompt as buildDiscoveryPrompt } from \"../opportunity/question.prompt.js\";\n\nimport type { IntentContext, NegotiationContext, ProfileContext } 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. A negotiation between this user and a counterparty has ended without a clear outcome — either the turn budget was exhausted, the session timed out, or conversation stalled. Your job: surface the minimum set of structured questions that help the user provide the missing signal needed to unblock or refine the next discovery attempt on their behalf.\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. 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 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. Return at most 2 entries in the \"questions\" array. Each entry must include a \"strategy\" field (one of the three values above). If the context already contains enough signal to proceed, return \"questions\": [].`;\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 buildNegotiationPrompt(ctx: NegotiationContext): string {\n const profileBlock = buildUserContextBlock(ctx.userContext);\n\n return [\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\nconst presets: Record<QuestionMode, QuestionerPreset> = {\n discovery: {\n systemPrompt: DISCOVERY_SYSTEM_PROMPT,\n buildPrompt: (context: unknown) =>\n buildDiscoveryPrompt(context as Parameters<typeof buildDiscoveryPrompt>[0]),\n },\n intent: {\n systemPrompt: INTENT_SYSTEM_PROMPT,\n buildPrompt: (context: unknown) => buildIntentPrompt(context as IntentContext),\n },\n enrichment: {\n systemPrompt: PROFILE_SYSTEM_PROMPT,\n buildPrompt: (context: unknown) => buildProfilePrompt(context as ProfileContext),\n },\n negotiation: {\n systemPrompt: NEGOTIATION_SYSTEM_PROMPT,\n buildPrompt: (context: unknown) => buildNegotiationPrompt(context as NegotiationContext),\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;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,EAAE;QACF,iDAAiD;QACjD,WAAW;QACX,EAAE;QACF,gCAAgC;QAChC,YAAY;QACZ,EAAE;QACF,iBAAiB;QACjB,YAAY;QACZ,EAAE;QACF,cAAc;QACd,2GAA2G;QAC3G,sGAAsG;QACtG,6DAA6D;KAC9D,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACf,CAAC;AAED,MAAM,OAAO,GAA2C;IACtD,SAAS,EAAE;QACT,YAAY,EAAE,uBAAuB;QACrC,WAAW,EAAE,CAAC,OAAgB,EAAE,EAAE,CAChC,oBAAoB,CAAC,OAAqD,CAAC;KAC9E;IACD,MAAM,EAAE;QACN,YAAY,EAAE,oBAAoB;QAClC,WAAW,EAAE,CAAC,OAAgB,EAAE,EAAE,CAAC,iBAAiB,CAAC,OAAwB,CAAC;KAC/E;IACD,UAAU,EAAE;QACV,YAAY,EAAE,qBAAqB;QACnC,WAAW,EAAE,CAAC,OAAgB,EAAE,EAAE,CAAC,kBAAkB,CAAC,OAAyB,CAAC;KACjF;IACD,WAAW,EAAE;QACX,YAAY,EAAE,yBAAyB;QACvC,WAAW,EAAE,CAAC,OAAgB,EAAE,EAAE,CAAC,sBAAsB,CAAC,OAA6B,CAAC;KACzF;IACD,IAAI,EAAE;QACJ,YAAY,EAAE,kBAAkB;QAChC,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 { SYSTEM_PROMPT as DISCOVERY_SYSTEM_PROMPT, buildQuestionPrompt as buildDiscoveryPrompt } from \"../opportunity/question.prompt.js\";\n\nimport type { ChatContext, IntentContext, NegotiationContext, ProfileContext } 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. A negotiation between this user and a counterparty has ended without a clear outcome — either the turn budget was exhausted, the session timed out, or conversation stalled. Your job: surface the minimum set of structured questions that help the user provide the missing signal needed to unblock or refine the next discovery attempt on their behalf.\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. 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 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. Return at most 2 entries in the \"questions\" array. Each entry must include a \"strategy\" field (one of the three values above). If the context already contains enough signal to proceed, return \"questions\": [].`;\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 buildNegotiationPrompt(ctx: NegotiationContext): string {\n const profileBlock = buildUserContextBlock(ctx.userContext);\n\n return [\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\n// ─── Chat preset ─────────────────────────────────────────────────────────\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\nconst presets: Record<QuestionMode, QuestionerPreset> = {\n discovery: {\n systemPrompt: DISCOVERY_SYSTEM_PROMPT,\n buildPrompt: (context: unknown) =>\n buildDiscoveryPrompt(context as Parameters<typeof buildDiscoveryPrompt>[0]),\n },\n intent: {\n systemPrompt: INTENT_SYSTEM_PROMPT,\n buildPrompt: (context: unknown) => buildIntentPrompt(context as IntentContext),\n },\n enrichment: {\n systemPrompt: PROFILE_SYSTEM_PROMPT,\n buildPrompt: (context: unknown) => buildProfilePrompt(context as ProfileContext),\n },\n negotiation: {\n systemPrompt: NEGOTIATION_SYSTEM_PROMPT,\n buildPrompt: (context: unknown) => buildNegotiationPrompt(context as NegotiationContext),\n },\n chat: {\n systemPrompt: 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"]}
@@ -39,8 +39,28 @@ export interface NegotiationContext {
39
39
  /** The user's global user_context paragraph (profile-replacing identity text). */
40
40
  userContext?: string;
41
41
  }
42
+ /**
43
+ * Chat context — data for orchestrator-initiated mid-conversation questions
44
+ * (the `ask_user_question` tool). The orchestrator states what it needs to
45
+ * learn; the QuestionerAgent turns that into polished structured questions,
46
+ * grounded in the recent conversation and the user's identity context.
47
+ */
48
+ export interface ChatContext {
49
+ /** What the orchestrator needs to learn and why (authored by the chat model). */
50
+ purpose: string;
51
+ /** Draft questions proposed by the orchestrator. The agent refines these. */
52
+ draftQuestions?: Array<{
53
+ prompt: string;
54
+ options?: string[];
55
+ multiSelect?: boolean;
56
+ }>;
57
+ /** Recent conversation excerpt for grounding (most recent messages last). */
58
+ conversationExcerpt?: string;
59
+ /** The user's global user_context paragraph (profile-replacing identity text). */
60
+ userContext?: string;
61
+ }
42
62
  /** Discriminated union: mode selects the context shape. */
43
- export type QuestionerContext = DiscoveryContext | IntentContext | ProfileContext | NegotiationContext;
63
+ export type QuestionerContext = DiscoveryContext | IntentContext | ProfileContext | NegotiationContext | ChatContext;
44
64
  /**
45
65
  * Payload shape accepted by the questionerEnqueue callback. Covers all
46
66
  * question modes — the composition root bridges this to the concrete
@@ -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,mCAAmC,CAAC;AAChF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sCAAsC,CAAC;AAIzE;;;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,CAA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