@indexnetwork/protocol 6.9.0-rc.396.1 → 6.10.0-rc.398.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.
@@ -4,6 +4,7 @@ import type { ScreenDecisionRecord } from "./negotiation.screen.js";
4
4
  import type { DeadlockShiftRecord } from "./negotiation.deadlock.js";
5
5
  import type { NegotiatorMemoryEntry } from "./negotiation.memory.js";
6
6
  import { type NegotiationProtocolVersion } from "../shared/schemas/negotiation-state.schema.js";
7
+ import type { NegotiationConsultationReason } from "./negotiation.consultation-policy.js";
7
8
  /**
8
9
  * Zod schema for a single negotiation turn (DataPart payload in A2A message).
9
10
  * Accepts the full v1+v2 action union — which subset is valid for a given turn
@@ -358,6 +359,8 @@ export declare const NegotiationGraphState: import("@langchain/langgraph").Annot
358
359
  continuationExecution: import("@langchain/langgraph").BaseChannel<NegotiationContinuationExecution | undefined, NegotiationContinuationExecution | import("@langchain/langgraph").OverwriteValue<NegotiationContinuationExecution | undefined> | undefined, unknown>;
359
360
  continuationReceipt: import("@langchain/langgraph").BaseChannel<NegotiationContinuationReceipt | undefined, NegotiationContinuationReceipt | import("@langchain/langgraph").OverwriteValue<NegotiationContinuationReceipt | undefined> | undefined, unknown>;
360
361
  privateConsultation: import("@langchain/langgraph").BaseChannel<NegotiationPrivateConsultation | undefined, NegotiationPrivateConsultation | import("@langchain/langgraph").OverwriteValue<NegotiationPrivateConsultation | undefined> | undefined, unknown>;
362
+ /** Server-only IND-508 category recovered from the exact prior task binding. */
363
+ consultationPolicyReason: import("@langchain/langgraph").BaseChannel<NegotiationConsultationReason | undefined, NegotiationConsultationReason | import("@langchain/langgraph").OverwriteValue<NegotiationConsultationReason | undefined> | undefined, unknown>;
361
364
  conversationId: import("@langchain/langgraph").BaseChannel<string, string | import("@langchain/langgraph").OverwriteValue<string>, unknown>;
362
365
  taskId: import("@langchain/langgraph").BaseChannel<string, string | import("@langchain/langgraph").OverwriteValue<string>, unknown>;
363
366
  messages: import("@langchain/langgraph").BaseChannel<NegotiationMessage[], NegotiationMessage[] | import("@langchain/langgraph").OverwriteValue<NegotiationMessage[]>, unknown>;
@@ -1 +1 @@
1
- {"version":3,"file":"negotiation.state.d.ts","sourceRoot":"/","sources":["negotiation/negotiation.state.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,gCAAgC,EAAE,8BAA8B,EAAE,8BAA8B,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,4CAA4C,CAAC;AAC7M,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AACpE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AACrE,OAAO,EAA6C,KAAK,0BAA0B,EAAE,MAAM,+CAA+C,CAAC;AAE3I;;;;GAIG;AACH,eAAO,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAUhC,oDAAoD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAEpD,CAAC;AAEH,2EAA2E;AAC3E,eAAO,MAAM,2BAA2B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAUtC,CAAC;AAEH,0EAA0E;AAC1E,eAAO,MAAM,0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAUrC,CAAC;AAEH,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAEpE,mFAAmF;AACnF,eAAO,MAAM,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EASnC,CAAC;AAEH,MAAM,MAAM,kBAAkB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,wBAAwB,CAAC,CAAC;AAE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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAeH;;;;;;;OAOG;;IAMH,+EAA+E;;IAM/E,6EAA6E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAc7E,CAAC"}
@@ -175,6 +175,11 @@ export const NegotiationGraphState = Annotation.Root({
175
175
  reducer: (curr, next) => next ?? curr,
176
176
  default: () => undefined,
177
177
  }),
178
+ /** Server-only IND-508 category recovered from the exact prior task binding. */
179
+ consultationPolicyReason: Annotation({
180
+ reducer: (curr, next) => next ?? curr,
181
+ default: () => undefined,
182
+ }),
178
183
  conversationId: Annotation({
179
184
  reducer: (curr, next) => next ?? curr,
180
185
  default: () => "",
@@ -1 +1 @@
1
- {"version":3,"file":"negotiation.state.js","sourceRoot":"/","sources":["negotiation/negotiation.state.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAKxB,OAAO,EAAE,oBAAoB,EAAE,mBAAmB,EAAmC,MAAM,+CAA+C,CAAC;AAE3I;;;;GAIG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,CAAC,MAAM,CAAC;IAC5C,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,mBAAmB,CAAC;IACnC,UAAU,EAAE,CAAC,CAAC,MAAM,CAAC;QACnB,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE;QACrB,cAAc,EAAE,CAAC,CAAC,MAAM,CAAC;YACvB,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;YAC7C,SAAS,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;SAChD,CAAC;KACH,CAAC;IACF,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE;IACzC,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ACrC,OAAO,EAAE,GAAG,EAAE,CAAC,QAAiB;KACjC,CAAC;IAEF,+EAA+E;IAC/E,cAAc,EAAE,UAAU,CAAS;QACjC,OAAO,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,IAAI,IAAI;QACrC,OAAO,EAAE,GAAG,EAAE,CAAC,CAAC;KACjB,CAAC;IAEF,6EAA6E;IAC7E,WAAW,EAAE,UAAU,CAA0B;QAC/C,OAAO,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,IAAI,IAAI;QACrC,OAAO,EAAE,GAAG,EAAE,CAAC,EAAE;KAClB,CAAC;IAEF,OAAO,EAAE,UAAU,CAA4B;QAC7C,OAAO,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,IAAI,IAAI;QACrC,OAAO,EAAE,GAAG,EAAE,CAAC,IAAI;KACpB,CAAC;IACF,KAAK,EAAE,UAAU,CAAgB;QAC/B,OAAO,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,IAAI,IAAI;QACrC,OAAO,EAAE,GAAG,EAAE,CAAC,IAAI;KACpB,CAAC;CACH,CAAC,CAAC","sourcesContent":["import { Annotation } from \"@langchain/langgraph\";\nimport { z } from \"zod\";\nimport type { NegotiationContinuationExecution, NegotiationContinuationReceipt, NegotiationPrivateConsultation, NegotiationUserAnswer, OpportunityStatus } from \"../shared/interfaces/database.interface.js\";\nimport type { ScreenDecisionRecord } from \"./negotiation.screen.js\";\nimport type { DeadlockShiftRecord } from \"./negotiation.deadlock.js\";\nimport type { NegotiatorMemoryEntry } from \"./negotiation.memory.js\";\nimport { AskUserPayloadSchema, NEGOTIATION_ACTIONS, type NegotiationProtocolVersion } from \"../shared/schemas/negotiation-state.schema.js\";\n\n/**\n * Zod schema for a single negotiation turn (DataPart payload in A2A message).\n * Accepts the full v1+v2 action union — which subset is valid for a given turn\n * is enforced by the seat-scoped schemas in `negotiation.protocol.ts`.\n */\nexport const NegotiationTurnSchema = z.object({\n action: z.enum(NEGOTIATION_ACTIONS),\n assessment: z.object({\n reasoning: z.string(),\n suggestedRoles: z.object({\n ownUser: z.enum([\"agent\", \"patient\", \"peer\"]),\n otherUser: z.enum([\"agent\", \"patient\", \"peer\"]),\n }),\n }),\n message: z.string().nullable().optional(),\n /** Present when action is `ask_user` (v2, P3.2). */\n askUser: AskUserPayloadSchema.nullable().optional(),\n});\n\n/** Restricted v1 turn schema for the system agent (no question action). */\nexport const SystemNegotiationTurnSchema = z.object({\n action: z.enum([\"propose\", \"accept\", \"reject\", \"counter\"]),\n assessment: z.object({\n reasoning: z.string(),\n suggestedRoles: z.object({\n ownUser: z.enum([\"agent\", \"patient\", \"peer\"]),\n otherUser: z.enum([\"agent\", \"patient\", \"peer\"]),\n }),\n }),\n message: z.string().nullable().optional(),\n});\n\n/** v1 turn schema for system agent's final allowed turn (must decide). */\nexport const FinalNegotiationTurnSchema = z.object({\n action: z.enum([\"accept\", \"reject\"]),\n assessment: z.object({\n reasoning: z.string(),\n suggestedRoles: z.object({\n ownUser: z.enum([\"agent\", \"patient\", \"peer\"]),\n otherUser: z.enum([\"agent\", \"patient\", \"peer\"]),\n }),\n }),\n message: z.string().nullable().optional(),\n});\n\nexport type NegotiationTurn = z.infer<typeof NegotiationTurnSchema>;\n\n/** Zod schema for the negotiation outcome (Artifact payload on COMPLETED task). */\nexport const NegotiationOutcomeSchema = z.object({\n hasOpportunity: z.boolean(),\n agreedRoles: z.array(z.object({\n userId: z.string(),\n role: z.enum([\"agent\", \"patient\", \"peer\"]),\n })),\n reasoning: z.string(),\n turnCount: z.number(),\n reason: z.enum([\"turn_cap\", \"timeout\", \"screened_out\"]).optional(),\n});\n\nexport type NegotiationOutcome = z.infer<typeof NegotiationOutcomeSchema>;\n\n/** Context each agent receives about its user. */\nexport interface UserNegotiationContext {\n id: string;\n intents: Array<{ id: string; title: string; description: string; confidence: number }>;\n profile: { name?: string; bio?: string; location?: string; interests?: string[]; skills?: string[] };\n}\n\n/** Seed assessment from the evaluator pre-filter. */\nexport interface SeedAssessment {\n reasoning: string;\n valencyRole: string;\n actors?: Array<{ userId: string; role: string }>;\n}\n\n/** Typed interface for a negotiation graph's invoke signature. */\nexport interface NegotiationGraphLike {\n invoke(input: {\n sourceUser: UserNegotiationContext;\n candidateUser: UserNegotiationContext;\n /** Exact opportunity-actor intent bindings; never inferred from intent array order. */\n sourceIntentId?: string;\n candidateIntentId?: string;\n indexContext: { networkId: string; prompt: string };\n seedAssessment: Omit<SeedAssessment, \"actors\">;\n discoveryQuery?: string;\n opportunityId?: string;\n /** Exact persisted lifecycle state claimed by this negotiation attempt. */\n opportunityStatus?: OpportunityStatus;\n opportunityUpdatedAt?: Date;\n maxTurns?: number;\n timeoutMs?: number;\n /**\n * The user who holds the initiating seat for this match (v2 client-advocate\n * protocol). Stamped into task metadata by the init node. When omitted, the\n * init node resolves it: inherit from the prior task for the same\n * opportunity → conversation-scoped tie-break → fall back to sourceUser.id.\n */\n initiatorUserId?: string;\n /** Exact settled task for a durable ask_user continuation. */\n resumeFromTaskId?: string;\n /** Deterministic durable settlement/outbox identifier. */\n continuationSettlementId?: string;\n /** Current durable lease/fence for the exact successor execution. */\n continuationExecution?: NegotiationContinuationExecution;\n }): Promise<{\n outcome: NegotiationOutcome | null;\n messages?: NegotiationMessage[];\n conversationId?: string;\n isContinuation?: boolean;\n priorTurnCount?: number;\n error?: string | null;\n continuationReceipt?: NegotiationContinuationReceipt;\n }>;\n}\n\n/** A2A message record shape (matches messages table). */\nexport interface NegotiationMessage {\n id: string;\n senderId: string;\n role: \"agent\";\n parts: unknown[];\n createdAt: Date;\n}\n\n/** LangGraph state annotation for the negotiation graph. */\nexport const NegotiationGraphState = Annotation.Root({\n sourceUser: Annotation<UserNegotiationContext>({\n reducer: (curr, next) => next ?? curr,\n default: () => ({ id: \"\", intents: [], profile: {} }),\n }),\n candidateUser: Annotation<UserNegotiationContext>({\n reducer: (curr, next) => next ?? curr,\n default: () => ({ id: \"\", intents: [], profile: {} }),\n }),\n sourceIntentId: Annotation<string | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n candidateIntentId: Annotation<string | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n indexContext: Annotation<{ networkId: string; prompt: string }>({\n reducer: (curr, next) => next ?? curr,\n default: () => ({ networkId: \"\", prompt: \"\" }),\n }),\n seedAssessment: Annotation<SeedAssessment>({\n reducer: (curr, next) => next ?? curr,\n default: () => ({ reasoning: \"\", valencyRole: \"\" }),\n }),\n\n /**\n * Explicit initiator seat for this match (purely additive metadata — no seat\n * rules attach to it yet). Resolution when unset happens in the init node;\n * the resolved value is written back to state and into task metadata.\n */\n initiatorUserId: Annotation<string | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n\n /** The explicit search query that triggered discovery (if any). */\n discoveryQuery: Annotation<string | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n /**\n * Negotiation protocol version for this session's task. Resolved by the\n * init node: inherited from the prior task on the conversation when one\n * exists (never re-stamped — a v1 conversation stays v1 mid-flight), else\n * stamped from `NEGOTIATION_PROTOCOL_VERSION` for genuinely fresh runs.\n */\n protocolVersion: Annotation<NegotiationProtocolVersion>({\n reducer: (curr, next) => next ?? curr,\n default: () => \"v1\" as const,\n }),\n\n /**\n * Screen-gate decision for this fresh run (P2.1 shadow mode). Written by the\n * screen node; null when the gate is off, on continuations, or before the\n * node runs. Mirrors `tasks.metadata.screenDecision`.\n */\n screenDecision: Annotation<ScreenDecisionRecord | null>({\n reducer: (curr, next) => next ?? curr,\n default: () => null,\n }),\n\n /**\n * First applied deadlock→bargaining shift in this session (IND-428).\n * Written by the turn node when the system agent first drafts in the\n * bargaining stance; used to record the shift exactly once per session.\n * Internal analytics only — mirrored to `tasks.metadata.deadlockShift`,\n * never into any turn payload or public projection.\n */\n deadlockShift: Annotation<DeadlockShiftRecord | null>({\n reducer: (curr, next) => next ?? curr,\n default: () => null,\n }),\n\n /**\n * Per-side negotiator-memory cache (P5.3 read path). Populated lazily the\n * first time each side's memory is retrieved (screen node for the client,\n * turn node for the speaker) so a multi-turn session pays for retrieval at\n * most once per side. `undefined` per side = not yet retrieved; `[]` =\n * retrieved and empty (flag off / no rows / retrieval failed).\n */\n memoryBySide: Annotation<Partial<Record<\"source\" | \"candidate\", NegotiatorMemoryEntry[]>>>({\n reducer: (curr, next) => ({ ...curr, ...next }),\n default: () => ({}),\n }),\n\n /** Whether this run is continuing a prior conversation with the same pair. */\n isContinuation: Annotation<boolean>({\n reducer: (curr, next) => next ?? curr,\n default: () => false,\n }),\n opportunityId: Annotation<string>({\n reducer: (curr, next) => next ?? curr,\n default: () => \"\",\n }),\n /** Exact persisted lifecycle state claimed by this negotiation attempt. */\n opportunityStatus: Annotation<OpportunityStatus | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n opportunityUpdatedAt: Annotation<Date | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n /** Exact prior task selected by a durable continuation; bypasses latest-task lookup. */\n resumeFromTaskId: Annotation<string | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n /** Deterministic settlement key used to idempotently reuse a successor task. */\n continuationSettlementId: Annotation<string | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n\n continuationExecution: Annotation<NegotiationContinuationExecution | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n\n continuationReceipt: Annotation<NegotiationContinuationReceipt | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n\n privateConsultation: Annotation<NegotiationPrivateConsultation | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n conversationId: Annotation<string>({\n reducer: (curr, next) => next ?? curr,\n default: () => \"\",\n }),\n taskId: Annotation<string>({\n reducer: (curr, next) => next ?? curr,\n default: () => \"\",\n }),\n messages: Annotation<NegotiationMessage[]>({\n reducer: (curr, next) => [...curr, ...(next || [])],\n default: () => [],\n }),\n turnCount: Annotation<number>({\n reducer: (curr, next) => next ?? curr,\n default: () => 0,\n }),\n maxTurns: Annotation<number | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n /**\n * Park-window budget in milliseconds. Ambient callers pass `AMBIENT_PARK_WINDOW_MS`\n * (5 minutes); orchestrator callers pass a shorter window. This annotation default\n * is a safety net for any caller that omits the field — keep it aligned with\n * `AMBIENT_PARK_WINDOW_MS` in packages/protocol/src/negotiation/negotiation.tools.ts.\n * Inlined rather than imported to avoid a state↔tools cycle.\n */\n timeoutMs: Annotation<number>({\n reducer: (curr, next) => next ?? curr,\n default: () => 5 * 60 * 1000,\n }),\n\n currentSpeaker: Annotation<\"source\" | \"candidate\">({\n reducer: (curr, next) => next ?? curr,\n default: () => \"source\" as const,\n }),\n lastTurn: Annotation<NegotiationTurn | null>({\n reducer: (curr, next) => next ?? curr,\n default: () => null,\n }),\n\n /**\n * Graph status.\n * - `active` — agents are exchanging turns (default)\n * - `waiting_for_agent` — graph suspended; awaiting external agent response or timeout\n * - `input_required` — graph suspended on an `ask_user` pause; awaiting the\n * negotiator's own client (answer or 24 h window expiry resumes it)\n * - `completed` — negotiation finalized (accept/reject/turn-cap/timeout)\n */\n status: Annotation<'active' | 'waiting_for_agent' | 'input_required' | 'completed'>({\n reducer: (curr, next) => next ?? curr,\n default: () => 'active' as const,\n }),\n\n /** Number of turns present in the conversation before this session started. */\n priorTurnCount: Annotation<number>({\n reducer: (curr, next) => next ?? curr,\n default: () => 0,\n }),\n\n /** User answers collected by the questioner between negotiation sessions. */\n userAnswers: Annotation<NegotiationUserAnswer[]>({\n reducer: (curr, next) => next ?? curr,\n default: () => [],\n }),\n\n outcome: Annotation<NegotiationOutcome | null>({\n reducer: (curr, next) => next ?? curr,\n default: () => null,\n }),\n error: Annotation<string | null>({\n reducer: (curr, next) => next ?? curr,\n default: () => null,\n }),\n});\n"]}
1
+ {"version":3,"file":"negotiation.state.js","sourceRoot":"/","sources":["negotiation/negotiation.state.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAKxB,OAAO,EAAE,oBAAoB,EAAE,mBAAmB,EAAmC,MAAM,+CAA+C,CAAC;AAG3I;;;;GAIG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,CAAC,MAAM,CAAC;IAC5C,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,mBAAmB,CAAC;IACnC,UAAU,EAAE,CAAC,CAAC,MAAM,CAAC;QACnB,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE;QACrB,cAAc,EAAE,CAAC,CAAC,MAAM,CAAC;YACvB,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;YAC7C,SAAS,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;SAChD,CAAC;KACH,CAAC;IACF,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE;IACzC,oDAAoD;IACpD,OAAO,EAAE,oBAAoB,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE;CACpD,CAAC,CAAC;AAEH,2EAA2E;AAC3E,MAAM,CAAC,MAAM,2BAA2B,GAAG,CAAC,CAAC,MAAM,CAAC;IAClD,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC;IAC1D,UAAU,EAAE,CAAC,CAAC,MAAM,CAAC;QACnB,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE;QACrB,cAAc,EAAE,CAAC,CAAC,MAAM,CAAC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KACjB,CAAC;IAEF,6EAA6E;IAC7E,WAAW,EAAE,UAAU,CAA0B;QAC/C,OAAO,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,IAAI,IAAI;QACrC,OAAO,EAAE,GAAG,EAAE,CAAC,EAAE;KAClB,CAAC;IAEF,OAAO,EAAE,UAAU,CAA4B;QAC7C,OAAO,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,IAAI,IAAI;QACrC,OAAO,EAAE,GAAG,EAAE,CAAC,IAAI;KACpB,CAAC;IACF,KAAK,EAAE,UAAU,CAAgB;QAC/B,OAAO,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,IAAI,IAAI;QACrC,OAAO,EAAE,GAAG,EAAE,CAAC,IAAI;KACpB,CAAC;CACH,CAAC,CAAC","sourcesContent":["import { Annotation } from \"@langchain/langgraph\";\nimport { z } from \"zod\";\nimport type { NegotiationContinuationExecution, NegotiationContinuationReceipt, NegotiationPrivateConsultation, NegotiationUserAnswer, OpportunityStatus } from \"../shared/interfaces/database.interface.js\";\nimport type { ScreenDecisionRecord } from \"./negotiation.screen.js\";\nimport type { DeadlockShiftRecord } from \"./negotiation.deadlock.js\";\nimport type { NegotiatorMemoryEntry } from \"./negotiation.memory.js\";\nimport { AskUserPayloadSchema, NEGOTIATION_ACTIONS, type NegotiationProtocolVersion } from \"../shared/schemas/negotiation-state.schema.js\";\nimport type { NegotiationConsultationReason } from \"./negotiation.consultation-policy.js\";\n\n/**\n * Zod schema for a single negotiation turn (DataPart payload in A2A message).\n * Accepts the full v1+v2 action union — which subset is valid for a given turn\n * is enforced by the seat-scoped schemas in `negotiation.protocol.ts`.\n */\nexport const NegotiationTurnSchema = z.object({\n action: z.enum(NEGOTIATION_ACTIONS),\n assessment: z.object({\n reasoning: z.string(),\n suggestedRoles: z.object({\n ownUser: z.enum([\"agent\", \"patient\", \"peer\"]),\n otherUser: z.enum([\"agent\", \"patient\", \"peer\"]),\n }),\n }),\n message: z.string().nullable().optional(),\n /** Present when action is `ask_user` (v2, P3.2). */\n askUser: AskUserPayloadSchema.nullable().optional(),\n});\n\n/** Restricted v1 turn schema for the system agent (no question action). */\nexport const SystemNegotiationTurnSchema = z.object({\n action: z.enum([\"propose\", \"accept\", \"reject\", \"counter\"]),\n assessment: z.object({\n reasoning: z.string(),\n suggestedRoles: z.object({\n ownUser: z.enum([\"agent\", \"patient\", \"peer\"]),\n otherUser: z.enum([\"agent\", \"patient\", \"peer\"]),\n }),\n }),\n message: z.string().nullable().optional(),\n});\n\n/** v1 turn schema for system agent's final allowed turn (must decide). */\nexport const FinalNegotiationTurnSchema = z.object({\n action: z.enum([\"accept\", \"reject\"]),\n assessment: z.object({\n reasoning: z.string(),\n suggestedRoles: z.object({\n ownUser: z.enum([\"agent\", \"patient\", \"peer\"]),\n otherUser: z.enum([\"agent\", \"patient\", \"peer\"]),\n }),\n }),\n message: z.string().nullable().optional(),\n});\n\nexport type NegotiationTurn = z.infer<typeof NegotiationTurnSchema>;\n\n/** Zod schema for the negotiation outcome (Artifact payload on COMPLETED task). */\nexport const NegotiationOutcomeSchema = z.object({\n hasOpportunity: z.boolean(),\n agreedRoles: z.array(z.object({\n userId: z.string(),\n role: z.enum([\"agent\", \"patient\", \"peer\"]),\n })),\n reasoning: z.string(),\n turnCount: z.number(),\n reason: z.enum([\"turn_cap\", \"timeout\", \"screened_out\"]).optional(),\n});\n\nexport type NegotiationOutcome = z.infer<typeof NegotiationOutcomeSchema>;\n\n/** Context each agent receives about its user. */\nexport interface UserNegotiationContext {\n id: string;\n intents: Array<{ id: string; title: string; description: string; confidence: number }>;\n profile: { name?: string; bio?: string; location?: string; interests?: string[]; skills?: string[] };\n}\n\n/** Seed assessment from the evaluator pre-filter. */\nexport interface SeedAssessment {\n reasoning: string;\n valencyRole: string;\n actors?: Array<{ userId: string; role: string }>;\n}\n\n/** Typed interface for a negotiation graph's invoke signature. */\nexport interface NegotiationGraphLike {\n invoke(input: {\n sourceUser: UserNegotiationContext;\n candidateUser: UserNegotiationContext;\n /** Exact opportunity-actor intent bindings; never inferred from intent array order. */\n sourceIntentId?: string;\n candidateIntentId?: string;\n indexContext: { networkId: string; prompt: string };\n seedAssessment: Omit<SeedAssessment, \"actors\">;\n discoveryQuery?: string;\n opportunityId?: string;\n /** Exact persisted lifecycle state claimed by this negotiation attempt. */\n opportunityStatus?: OpportunityStatus;\n opportunityUpdatedAt?: Date;\n maxTurns?: number;\n timeoutMs?: number;\n /**\n * The user who holds the initiating seat for this match (v2 client-advocate\n * protocol). Stamped into task metadata by the init node. When omitted, the\n * init node resolves it: inherit from the prior task for the same\n * opportunity → conversation-scoped tie-break → fall back to sourceUser.id.\n */\n initiatorUserId?: string;\n /** Exact settled task for a durable ask_user continuation. */\n resumeFromTaskId?: string;\n /** Deterministic durable settlement/outbox identifier. */\n continuationSettlementId?: string;\n /** Current durable lease/fence for the exact successor execution. */\n continuationExecution?: NegotiationContinuationExecution;\n }): Promise<{\n outcome: NegotiationOutcome | null;\n messages?: NegotiationMessage[];\n conversationId?: string;\n isContinuation?: boolean;\n priorTurnCount?: number;\n error?: string | null;\n continuationReceipt?: NegotiationContinuationReceipt;\n }>;\n}\n\n/** A2A message record shape (matches messages table). */\nexport interface NegotiationMessage {\n id: string;\n senderId: string;\n role: \"agent\";\n parts: unknown[];\n createdAt: Date;\n}\n\n/** LangGraph state annotation for the negotiation graph. */\nexport const NegotiationGraphState = Annotation.Root({\n sourceUser: Annotation<UserNegotiationContext>({\n reducer: (curr, next) => next ?? curr,\n default: () => ({ id: \"\", intents: [], profile: {} }),\n }),\n candidateUser: Annotation<UserNegotiationContext>({\n reducer: (curr, next) => next ?? curr,\n default: () => ({ id: \"\", intents: [], profile: {} }),\n }),\n sourceIntentId: Annotation<string | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n candidateIntentId: Annotation<string | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n indexContext: Annotation<{ networkId: string; prompt: string }>({\n reducer: (curr, next) => next ?? curr,\n default: () => ({ networkId: \"\", prompt: \"\" }),\n }),\n seedAssessment: Annotation<SeedAssessment>({\n reducer: (curr, next) => next ?? curr,\n default: () => ({ reasoning: \"\", valencyRole: \"\" }),\n }),\n\n /**\n * Explicit initiator seat for this match (purely additive metadata — no seat\n * rules attach to it yet). Resolution when unset happens in the init node;\n * the resolved value is written back to state and into task metadata.\n */\n initiatorUserId: Annotation<string | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n\n /** The explicit search query that triggered discovery (if any). */\n discoveryQuery: Annotation<string | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n /**\n * Negotiation protocol version for this session's task. Resolved by the\n * init node: inherited from the prior task on the conversation when one\n * exists (never re-stamped — a v1 conversation stays v1 mid-flight), else\n * stamped from `NEGOTIATION_PROTOCOL_VERSION` for genuinely fresh runs.\n */\n protocolVersion: Annotation<NegotiationProtocolVersion>({\n reducer: (curr, next) => next ?? curr,\n default: () => \"v1\" as const,\n }),\n\n /**\n * Screen-gate decision for this fresh run (P2.1 shadow mode). Written by the\n * screen node; null when the gate is off, on continuations, or before the\n * node runs. Mirrors `tasks.metadata.screenDecision`.\n */\n screenDecision: Annotation<ScreenDecisionRecord | null>({\n reducer: (curr, next) => next ?? curr,\n default: () => null,\n }),\n\n /**\n * First applied deadlock→bargaining shift in this session (IND-428).\n * Written by the turn node when the system agent first drafts in the\n * bargaining stance; used to record the shift exactly once per session.\n * Internal analytics only — mirrored to `tasks.metadata.deadlockShift`,\n * never into any turn payload or public projection.\n */\n deadlockShift: Annotation<DeadlockShiftRecord | null>({\n reducer: (curr, next) => next ?? curr,\n default: () => null,\n }),\n\n /**\n * Per-side negotiator-memory cache (P5.3 read path). Populated lazily the\n * first time each side's memory is retrieved (screen node for the client,\n * turn node for the speaker) so a multi-turn session pays for retrieval at\n * most once per side. `undefined` per side = not yet retrieved; `[]` =\n * retrieved and empty (flag off / no rows / retrieval failed).\n */\n memoryBySide: Annotation<Partial<Record<\"source\" | \"candidate\", NegotiatorMemoryEntry[]>>>({\n reducer: (curr, next) => ({ ...curr, ...next }),\n default: () => ({}),\n }),\n\n /** Whether this run is continuing a prior conversation with the same pair. */\n isContinuation: Annotation<boolean>({\n reducer: (curr, next) => next ?? curr,\n default: () => false,\n }),\n opportunityId: Annotation<string>({\n reducer: (curr, next) => next ?? curr,\n default: () => \"\",\n }),\n /** Exact persisted lifecycle state claimed by this negotiation attempt. */\n opportunityStatus: Annotation<OpportunityStatus | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n opportunityUpdatedAt: Annotation<Date | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n /** Exact prior task selected by a durable continuation; bypasses latest-task lookup. */\n resumeFromTaskId: Annotation<string | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n /** Deterministic settlement key used to idempotently reuse a successor task. */\n continuationSettlementId: Annotation<string | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n\n continuationExecution: Annotation<NegotiationContinuationExecution | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n\n continuationReceipt: Annotation<NegotiationContinuationReceipt | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n\n privateConsultation: Annotation<NegotiationPrivateConsultation | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n /** Server-only IND-508 category recovered from the exact prior task binding. */\n consultationPolicyReason: Annotation<NegotiationConsultationReason | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n conversationId: Annotation<string>({\n reducer: (curr, next) => next ?? curr,\n default: () => \"\",\n }),\n taskId: Annotation<string>({\n reducer: (curr, next) => next ?? curr,\n default: () => \"\",\n }),\n messages: Annotation<NegotiationMessage[]>({\n reducer: (curr, next) => [...curr, ...(next || [])],\n default: () => [],\n }),\n turnCount: Annotation<number>({\n reducer: (curr, next) => next ?? curr,\n default: () => 0,\n }),\n maxTurns: Annotation<number | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n /**\n * Park-window budget in milliseconds. Ambient callers pass `AMBIENT_PARK_WINDOW_MS`\n * (5 minutes); orchestrator callers pass a shorter window. This annotation default\n * is a safety net for any caller that omits the field — keep it aligned with\n * `AMBIENT_PARK_WINDOW_MS` in packages/protocol/src/negotiation/negotiation.tools.ts.\n * Inlined rather than imported to avoid a state↔tools cycle.\n */\n timeoutMs: Annotation<number>({\n reducer: (curr, next) => next ?? curr,\n default: () => 5 * 60 * 1000,\n }),\n\n currentSpeaker: Annotation<\"source\" | \"candidate\">({\n reducer: (curr, next) => next ?? curr,\n default: () => \"source\" as const,\n }),\n lastTurn: Annotation<NegotiationTurn | null>({\n reducer: (curr, next) => next ?? curr,\n default: () => null,\n }),\n\n /**\n * Graph status.\n * - `active` — agents are exchanging turns (default)\n * - `waiting_for_agent` — graph suspended; awaiting external agent response or timeout\n * - `input_required` — graph suspended on an `ask_user` pause; awaiting the\n * negotiator's own client (answer or 24 h window expiry resumes it)\n * - `completed` — negotiation finalized (accept/reject/turn-cap/timeout)\n */\n status: Annotation<'active' | 'waiting_for_agent' | 'input_required' | 'completed'>({\n reducer: (curr, next) => next ?? curr,\n default: () => 'active' as const,\n }),\n\n /** Number of turns present in the conversation before this session started. */\n priorTurnCount: Annotation<number>({\n reducer: (curr, next) => next ?? curr,\n default: () => 0,\n }),\n\n /** User answers collected by the questioner between negotiation sessions. */\n userAnswers: Annotation<NegotiationUserAnswer[]>({\n reducer: (curr, next) => next ?? curr,\n default: () => [],\n }),\n\n outcome: Annotation<NegotiationOutcome | null>({\n reducer: (curr, next) => next ?? curr,\n default: () => null,\n }),\n error: Annotation<string | null>({\n reducer: (curr, next) => next ?? curr,\n default: () => null,\n }),\n});\n"]}
@@ -16,7 +16,7 @@
16
16
  * Surfaces choose *policy* (send a sanitized fallback vs skip entirely) via
17
17
  * `allowFallback`; they no longer choose (or forget) sanitization steps.
18
18
  *
19
- * See `.pi/skills/review-opportunity-presentation/SKILL.md` for the review
19
+ * See `.agents/skills/review-opportunity-presentation/SKILL.md` for the review
20
20
  * checklist this module exists to satisfy.
21
21
  */
22
22
  /** Default max length for fallback summaries (matches presenter internal fallback). */
@@ -16,7 +16,7 @@
16
16
  * Surfaces choose *policy* (send a sanitized fallback vs skip entirely) via
17
17
  * `allowFallback`; they no longer choose (or forget) sanitization steps.
18
18
  *
19
- * See `.pi/skills/review-opportunity-presentation/SKILL.md` for the review
19
+ * See `.agents/skills/review-opportunity-presentation/SKILL.md` for the review
20
20
  * checklist this module exists to satisfy.
21
21
  */
22
22
  import { truncateAtBoundary, viewerCentricCardSummary } from "./opportunity.presentation.js";
@@ -1 +1 @@
1
- {"version":3,"file":"opportunity.safe-presentation.js","sourceRoot":"/","sources":["opportunity/opportunity.safe-presentation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAE,kBAAkB,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAC7F,OAAO,EAAE,iCAAiC,EAAE,MAAM,+BAA+B,CAAC;AAElF,uFAAuF;AACvF,MAAM,CAAC,MAAM,uBAAuB,GAAG,GAAG,CAAC;AAE3C,+DAA+D;AAC/D,MAAM,CAAC,MAAM,2BAA2B,GAAG,yBAAyB,CAAC;AAErE,yFAAyF;AACzF,MAAM,CAAC,MAAM,yBAAyB,GAAG,wBAAwB,CAAC;AAElE,oFAAoF;AACpF,MAAM,CAAC,MAAM,uBAAuB,GAClC,8CAA8C,CAAC;AAejD;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,mBAAmB,CACjC,YAAuC,EACvC,OAA4B,EAAE;IAE9B,MAAM,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,2BAA2B,CAAC;IAChE,MAAM,QAAQ,GAAG,IAAI,C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Ae,CAAC;oBAC5D,uBAAuB;gBACzB,UAAU,EAAE,KAAK;aAClB,CAAC;QACJ,CAAC;IACH,CAAC;IAED,IAAI,IAAI,CAAC,aAAa,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IAE9C,MAAM,YAAY,GAChB,MAAM,CAAC,WAAW,IAAI,MAAM,CAAC,cAAc,EAAE,SAAS,IAAI,EAAE,CAAC;IAC/D,OAAO;QACL,QAAQ,EAAE,yBAAyB;QACnC,OAAO,EAAE,mBAAmB,CAAC,YAAY,EAAE,IAAI,CAAC;QAChD,eAAe,EAAE,uBAAuB;QACxC,UAAU,EAAE,IAAI;KACjB,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Shared safe-presentation primitive for all user-facing opportunity surfaces.\n *\n * Historically every surface (home feed, list/discover cards, minimal chat\n * cards, notification emails/Telegram, chat context, delivery cards) invented\n * its own fallback chain for the case where genuine LLM presenter output is\n * unavailable — some sliced raw `interpretation.reasoning` with no\n * sanitization at all. This module is the single standard:\n *\n * raw reasoning\n * → whitespace-normalize\n * → viewer-centric rewrite (incl. UUID stripping + introducer-mention stripping)\n * → boundary-aware truncation\n * → per-surface empty-text default\n *\n * Surfaces choose *policy* (send a sanitized fallback vs skip entirely) via\n * `allowFallback`; they no longer choose (or forget) sanitization steps.\n *\n * See `.pi/skills/review-opportunity-presentation/SKILL.md` for the review\n * checklist this module exists to satisfy.\n */\n\nimport { truncateAtBoundary, viewerCentricCardSummary } from \"./opportunity.presentation.js\";\nimport { stripUnsupportedOpportunityClaims } from \"./opportunity.claim-safety.js\";\n\n/** Default max length for fallback summaries (matches presenter internal fallback). */\nexport const SAFE_FALLBACK_MAX_CHARS = 300;\n\n/** Default copy when no reasoning text is available at all. */\nexport const DEFAULT_EMPTY_FALLBACK_TEXT = \"A promising connection.\";\n\n/** Default headline for fallback presentations (matches presenter internal fallback). */\nexport const DEFAULT_FALLBACK_HEADLINE = \"A promising connection\";\n\n/** Default CTA for fallback presentations (matches presenter internal fallback). */\nexport const DEFAULT_FALLBACK_ACTION =\n \"Take a look and decide whether to reach out.\";\n\nexport interface SafeFallbackOptions {\n /** Display name of the counterpart shown on the card (enables viewer-centric rewrite). */\n counterpartName?: string;\n /** Display name of the viewer; sentences describing the viewer are skipped/rewritten to \"you\". */\n viewerName?: string;\n /** Introducer display name; introducer mentions are stripped from the summary body. */\n introducerName?: string | null;\n /** Max output length (boundary-aware). Default {@link SAFE_FALLBACK_MAX_CHARS}. */\n maxChars?: number;\n /** Copy returned when reasoning is empty/blank. Default {@link DEFAULT_EMPTY_FALLBACK_TEXT}. */\n emptyText?: string;\n}\n\n/**\n * Produce safe user-facing fallback copy from raw match reasoning.\n *\n * This is the ONE sanitization standard: UUID stripping, introducer-mention\n * stripping, and viewer-centric rewrite (via {@link viewerCentricCardSummary}),\n * followed by whitespace normalization and boundary-aware truncation (via\n * {@link truncateAtBoundary}). Never returns raw reasoning verbatim beyond\n * these guarantees, and never returns an empty string.\n *\n * @param rawReasoning - Raw `interpretation.reasoning` / `matchReason` text (may be null/undefined).\n * @param opts - Per-surface knobs (names for rewrite, max length, empty-text copy).\n */\nexport function safeFallbackSummary(\n rawReasoning: string | null | undefined,\n opts: SafeFallbackOptions = {},\n): string {\n const emptyText = opts.emptyText ?? DEFAULT_EMPTY_FALLBACK_TEXT;\n const maxChars = opts.maxChars ?? SAFE_FALLBACK_MAX_CHARS;\n\n const normalized = (rawReasoning ?? \"\").replace(/\\s+/g, \" \").trim();\n if (!normalized) return emptyText;\n const claimSafeInput = stripUnsupportedOpportunityClaims(normalized);\n if (!claimSafeInput) return emptyText;\n\n // viewerCentricCardSummary handles UUID stripping, introducer-mention\n // stripping, and the viewer-centric rewrite. Pass Infinity so truncation is\n // handled by boundary-aware logic below instead of a mid-word hard slice.\n const rewritten = viewerCentricCardSummary(\n claimSafeInput,\n opts.counterpartName ?? \"\",\n Number.POSITIVE_INFINITY,\n opts.viewerName,\n opts.introducerName ?? undefined,\n );\n\n // Claim validation intentionally runs after viewer-centric rewriting: rewrite\n // heuristics may select or join different source sentences, and the final\n // user-facing sentence set is what must be safe.\n const claimSafe = stripUnsupportedOpportunityClaims(rewritten);\n const truncated = truncateAtBoundary(claimSafe, maxChars);\n return truncated || emptyText;\n}\n\n/** Minimal presenter-output shape the primitive inspects (subset of HomeCardPresentationResult). */\nexport interface SafePresentationCandidate {\n headline?: string;\n personalizedSummary?: string;\n suggestedAction?: string;\n /** Set by OpportunityPresenter when its LLM call failed and it returned fallback-shaped copy. */\n isFallback?: boolean;\n}\n\n/** Opportunity-ish source object accepted by {@link getSafePresentationOrSkip}. */\nexport interface SafePresentationSource {\n /** Presenter output attached to the record, when available. */\n homeCardPresentation?: SafePresentationCandidate | null;\n /** Pre-truncated raw reasoning carried on discovery/list card data. */\n matchReason?: string | null;\n /** Full opportunity interpretation, when the caller holds the record. */\n interpretation?: { reasoning?: string | null } | null;\n}\n\nexport interface SafePresentationOptions extends SafeFallbackOptions {\n /**\n * Policy switch: when false, return null instead of fallback copy so the\n * surface can skip rendering entirely (e.g. scheduled digests where sending\n * degraded copy is worse than sending nothing). Default true.\n */\n allowFallback?: boolean;\n}\n\n/** Resolved safe presentation for a surface to render. */\nexport interface SafePresentation {\n headline: string;\n summary: string;\n suggestedAction: string;\n /** True when copy was derived from raw reasoning rather than genuine LLM presenter output. */\n isFallback: boolean;\n}\n\n/**\n * Resolve the safe user-facing presentation for an opportunity, or signal skip.\n *\n * Resolution order:\n * 1. Genuine presenter output (`homeCardPresentation` present, non-empty, and\n * NOT tagged `isFallback` by the presenter) — claim-validated before return.\n * 2. Otherwise, if `allowFallback` (default true): sanitized fallback copy\n * built from `matchReason` / `interpretation.reasoning` via\n * {@link safeFallbackSummary}.\n * 3. Otherwise `null` — the surface must skip this opportunity.\n *\n * Raw `interpretation.reasoning` / `matchReason` never reaches the caller\n * unsanitized through this function.\n */\nexport function getSafePresentationOrSkip(\n source: SafePresentationSource,\n opts: SafePresentationOptions = {},\n): SafePresentation | null {\n const candidate = source.homeCardPresentation;\n if (candidate?.personalizedSummary?.trim() && !candidate.isFallback) {\n const summary = stripUnsupportedOpportunityClaims(candidate.personalizedSummary);\n if (summary) {\n return {\n headline:\n stripUnsupportedOpportunityClaims(candidate.headline) ||\n DEFAULT_FALLBACK_HEADLINE,\n summary,\n suggestedAction:\n stripUnsupportedOpportunityClaims(candidate.suggestedAction) ||\n DEFAULT_FALLBACK_ACTION,\n isFallback: false,\n };\n }\n }\n\n if (opts.allowFallback === false) return null;\n\n const rawReasoning =\n source.matchReason ?? source.interpretation?.reasoning ?? \"\";\n return {\n headline: DEFAULT_FALLBACK_HEADLINE,\n summary: safeFallbackSummary(rawReasoning, opts),\n suggestedAction: DEFAULT_FALLBACK_ACTION,\n isFallback: true,\n };\n}\n"]}
1
+ {"version":3,"file":"opportunity.safe-presentation.js","sourceRoot":"/","sources":["opportunity/opportunity.safe-presentation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAE,kBAAkB,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAC7F,OAAO,EAAE,iCAAiC,EAAE,MAAM,+BAA+B,CAAC;AAElF,uFAAuF;AACvF,MAAM,CAAC,MAAM,uBAAuB,GAAG,GAAG,CAAC;AAE3C,+DAA+D;AAC/D,MAAM,CAAC,MAAM,2BAA2B,GAAG,yBAAyB,CAAC;AAErE,yFAAyF;AACzF,MAAM,CAAC,MAAM,yBAAyB,GAAG,wBAAwB,CAAC;AAElE,oFAAoF;AACpF,MAAM,CAAC,MAAM,uBAAuB,GAClC,8CAA8C,CAAC;AAejD;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,mBAAmB,CACjC,YAAuC,EACvC,OAA4B,EAAE;IAE9B,MAAM,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,2BAA2B,CAAC;IAChE,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,IAAI,uBAAuB,CAAC;IAE1D,MAAM,UAAU,GAAG,CAAC,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QACJ,CAAC;IACH,CAAC;IAED,IAAI,IAAI,CAAC,aAAa,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IAE9C,MAAM,YAAY,GAChB,MAAM,CAAC,WAAW,IAAI,MAAM,CAAC,cAAc,EAAE,SAAS,IAAI,EAAE,CAAC;IAC/D,OAAO;QACL,QAAQ,EAAE,yBAAyB;QACnC,OAAO,EAAE,mBAAmB,CAAC,YAAY,EAAE,IAAI,CAAC;QAChD,eAAe,EAAE,uBAAuB;QACxC,UAAU,EAAE,IAAI;KACjB,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Shared safe-presentation primitive for all user-facing opportunity surfaces.\n *\n * Historically every surface (home feed, list/discover cards, minimal chat\n * cards, notification emails/Telegram, chat context, delivery cards) invented\n * its own fallback chain for the case where genuine LLM presenter output is\n * unavailable — some sliced raw `interpretation.reasoning` with no\n * sanitization at all. This module is the single standard:\n *\n * raw reasoning\n * → whitespace-normalize\n * → viewer-centric rewrite (incl. UUID stripping + introducer-mention stripping)\n * → boundary-aware truncation\n * → per-surface empty-text default\n *\n * Surfaces choose *policy* (send a sanitized fallback vs skip entirely) via\n * `allowFallback`; they no longer choose (or forget) sanitization steps.\n *\n * See `.agents/skills/review-opportunity-presentation/SKILL.md` for the review\n * checklist this module exists to satisfy.\n */\n\nimport { truncateAtBoundary, viewerCentricCardSummary } from \"./opportunity.presentation.js\";\nimport { stripUnsupportedOpportunityClaims } from \"./opportunity.claim-safety.js\";\n\n/** Default max length for fallback summaries (matches presenter internal fallback). */\nexport const SAFE_FALLBACK_MAX_CHARS = 300;\n\n/** Default copy when no reasoning text is available at all. */\nexport const DEFAULT_EMPTY_FALLBACK_TEXT = \"A promising connection.\";\n\n/** Default headline for fallback presentations (matches presenter internal fallback). */\nexport const DEFAULT_FALLBACK_HEADLINE = \"A promising connection\";\n\n/** Default CTA for fallback presentations (matches presenter internal fallback). */\nexport const DEFAULT_FALLBACK_ACTION =\n \"Take a look and decide whether to reach out.\";\n\nexport interface SafeFallbackOptions {\n /** Display name of the counterpart shown on the card (enables viewer-centric rewrite). */\n counterpartName?: string;\n /** Display name of the viewer; sentences describing the viewer are skipped/rewritten to \"you\". */\n viewerName?: string;\n /** Introducer display name; introducer mentions are stripped from the summary body. */\n introducerName?: string | null;\n /** Max output length (boundary-aware). Default {@link SAFE_FALLBACK_MAX_CHARS}. */\n maxChars?: number;\n /** Copy returned when reasoning is empty/blank. Default {@link DEFAULT_EMPTY_FALLBACK_TEXT}. */\n emptyText?: string;\n}\n\n/**\n * Produce safe user-facing fallback copy from raw match reasoning.\n *\n * This is the ONE sanitization standard: UUID stripping, introducer-mention\n * stripping, and viewer-centric rewrite (via {@link viewerCentricCardSummary}),\n * followed by whitespace normalization and boundary-aware truncation (via\n * {@link truncateAtBoundary}). Never returns raw reasoning verbatim beyond\n * these guarantees, and never returns an empty string.\n *\n * @param rawReasoning - Raw `interpretation.reasoning` / `matchReason` text (may be null/undefined).\n * @param opts - Per-surface knobs (names for rewrite, max length, empty-text copy).\n */\nexport function safeFallbackSummary(\n rawReasoning: string | null | undefined,\n opts: SafeFallbackOptions = {},\n): string {\n const emptyText = opts.emptyText ?? DEFAULT_EMPTY_FALLBACK_TEXT;\n const maxChars = opts.maxChars ?? SAFE_FALLBACK_MAX_CHARS;\n\n const normalized = (rawReasoning ?? \"\").replace(/\\s+/g, \" \").trim();\n if (!normalized) return emptyText;\n const claimSafeInput = stripUnsupportedOpportunityClaims(normalized);\n if (!claimSafeInput) return emptyText;\n\n // viewerCentricCardSummary handles UUID stripping, introducer-mention\n // stripping, and the viewer-centric rewrite. Pass Infinity so truncation is\n // handled by boundary-aware logic below instead of a mid-word hard slice.\n const rewritten = viewerCentricCardSummary(\n claimSafeInput,\n opts.counterpartName ?? \"\",\n Number.POSITIVE_INFINITY,\n opts.viewerName,\n opts.introducerName ?? undefined,\n );\n\n // Claim validation intentionally runs after viewer-centric rewriting: rewrite\n // heuristics may select or join different source sentences, and the final\n // user-facing sentence set is what must be safe.\n const claimSafe = stripUnsupportedOpportunityClaims(rewritten);\n const truncated = truncateAtBoundary(claimSafe, maxChars);\n return truncated || emptyText;\n}\n\n/** Minimal presenter-output shape the primitive inspects (subset of HomeCardPresentationResult). */\nexport interface SafePresentationCandidate {\n headline?: string;\n personalizedSummary?: string;\n suggestedAction?: string;\n /** Set by OpportunityPresenter when its LLM call failed and it returned fallback-shaped copy. */\n isFallback?: boolean;\n}\n\n/** Opportunity-ish source object accepted by {@link getSafePresentationOrSkip}. */\nexport interface SafePresentationSource {\n /** Presenter output attached to the record, when available. */\n homeCardPresentation?: SafePresentationCandidate | null;\n /** Pre-truncated raw reasoning carried on discovery/list card data. */\n matchReason?: string | null;\n /** Full opportunity interpretation, when the caller holds the record. */\n interpretation?: { reasoning?: string | null } | null;\n}\n\nexport interface SafePresentationOptions extends SafeFallbackOptions {\n /**\n * Policy switch: when false, return null instead of fallback copy so the\n * surface can skip rendering entirely (e.g. scheduled digests where sending\n * degraded copy is worse than sending nothing). Default true.\n */\n allowFallback?: boolean;\n}\n\n/** Resolved safe presentation for a surface to render. */\nexport interface SafePresentation {\n headline: string;\n summary: string;\n suggestedAction: string;\n /** True when copy was derived from raw reasoning rather than genuine LLM presenter output. */\n isFallback: boolean;\n}\n\n/**\n * Resolve the safe user-facing presentation for an opportunity, or signal skip.\n *\n * Resolution order:\n * 1. Genuine presenter output (`homeCardPresentation` present, non-empty, and\n * NOT tagged `isFallback` by the presenter) — claim-validated before return.\n * 2. Otherwise, if `allowFallback` (default true): sanitized fallback copy\n * built from `matchReason` / `interpretation.reasoning` via\n * {@link safeFallbackSummary}.\n * 3. Otherwise `null` — the surface must skip this opportunity.\n *\n * Raw `interpretation.reasoning` / `matchReason` never reaches the caller\n * unsanitized through this function.\n */\nexport function getSafePresentationOrSkip(\n source: SafePresentationSource,\n opts: SafePresentationOptions = {},\n): SafePresentation | null {\n const candidate = source.homeCardPresentation;\n if (candidate?.personalizedSummary?.trim() && !candidate.isFallback) {\n const summary = stripUnsupportedOpportunityClaims(candidate.personalizedSummary);\n if (summary) {\n return {\n headline:\n stripUnsupportedOpportunityClaims(candidate.headline) ||\n DEFAULT_FALLBACK_HEADLINE,\n summary,\n suggestedAction:\n stripUnsupportedOpportunityClaims(candidate.suggestedAction) ||\n DEFAULT_FALLBACK_ACTION,\n isFallback: false,\n };\n }\n }\n\n if (opts.allowFallback === false) return null;\n\n const rawReasoning =\n source.matchReason ?? source.interpretation?.reasoning ?? \"\";\n return {\n headline: DEFAULT_FALLBACK_HEADLINE,\n summary: safeFallbackSummary(rawReasoning, opts),\n suggestedAction: DEFAULT_FALLBACK_ACTION,\n isFallback: true,\n };\n}\n"]}
@@ -8,6 +8,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
10
  import type { NegotiationQuestionCandidate, QuestionMode, QuestionPoolDiscriminator } from "../shared/schemas/question.schema.js";
11
+ import type { NegotiationConsultationReason } from "../negotiation/negotiation.consultation-policy.js";
11
12
  /**
12
13
  * Discovery context — wraps the existing DiscoveryQuestionInput wholesale.
13
14
  * The discovery preset's buildPrompt delegates to `questioner.discovery.prompt.ts`.
@@ -77,6 +78,8 @@ export interface NegotiationInflightContext {
77
78
  draftQuestion?: string;
78
79
  /** Community / index context the negotiation runs in. */
79
80
  indexContext: string;
81
+ /** Server-only IND-508 reason; never copied into generated or persisted payloads. */
82
+ consultationPolicyReason?: NegotiationConsultationReason;
80
83
  /** The user's global user_context paragraph (profile-replacing identity text). */
81
84
  userContext?: string;
82
85
  }
@@ -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,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B,CAAC;AAE5B,wFAAwF;AACxF,wBAAgB,8BAA8B,CAAC,KAAK,EAAE,eAAe,GAAG,OAAO,CA8D9E"}
@@ -30,6 +30,11 @@ export function isValidQuestionerInputContract(input) {
30
30
  && context.negotiationId === input.negotiation.taskId
31
31
  && typeof context.disclosureSubject === 'string'
32
32
  && isSafeNegotiationQuestionText(context.disclosureSubject)
33
+ && (context.consultationPolicyReason === undefined
34
+ || context.consultationPolicyReason === 'unresolved_owner_constraint'
35
+ || context.consultationPolicyReason === 'consequential_disclosure_permission'
36
+ || context.consultationPolicyReason === 'repeated_non_convergence'
37
+ || context.consultationPolicyReason === 'insufficient_commitment_authority')
33
38
  && (context.draftQuestion === undefined
34
39
  || (typeof context.draftQuestion === 'string' && isSafeNegotiationQuestionText(context.draftQuestion)));
35
40
  }
@@ -1 +1 @@
1
- {"version":3,"file":"questioner.types.js","sourceRoot":"/","sources":["questioner/questioner.types.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,yCAAyC,EAAE,oCAAoC,EAAE,4CAA4C,EAAE,6BAA6B,EAAE,MAAM,+CAA+C,CAAC;AAwO7N,wFAAwF;AACxF,MAAM,UAAU,8BAA8B,CAAC,KAAsB;IACnE,IAAI,KAAK,CAAC,OAAO,KAAK,UAAU,EAAE,CAAC;QACjC,MAAM,OAAO,GAAG,KAAK,CAAC,OAAgC,CAAC;QACvD,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ;eACzB,KAAK,CAAC,UAAU,KAAK,QAAQ;eAC7B,KAAK,CAAC,mBAAmB,KAAK,KAAK,CAAC,QAAQ;eAC5C,KAAK,CAAC,WAAW,KAAK,SAAS;eAC/B,OAAO,CAAC,OAAO,KAAK,UAAU;eAC9B,OAAO,CAAC,QAAQ,KAAK,KAAK,CAAC,QAAQ,CAAC;IAC3C,CAAC;IACD,IAAI,KAAK,CAAC,IAAI,KAAK,aAAa,IAAI,KAAK,CAAC,IAAI,KAAK,sBAAsB,EAAE,CAAC;QAC1E,OAAO,K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D,KAAK,CAAC,WAAW,CAAC,kBAAkB,CAAC,MAAM,GAAG,CAAC;eAC/C,OAAO,KAAK,CAAC,WAAW,CAAC,oBAAoB,KAAK,QAAQ;eAC1D,KAAK,CAAC,WAAW,CAAC,oBAAoB,CAAC,MAAM,GAAG,CAAC;eACjD,OAAO,KAAK,CAAC,WAAW,CAAC,6BAA6B,KAAK,QAAQ;eACnE,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,WAAW,CAAC,6BAA6B,CAAC;eAChE,OAAO,CAAC,aAAa,KAAK,KAAK,CAAC,QAAQ;eACxC,OAAO,CAAC,OAAO,KAAK,QAAQ;eAC5B,OAAO,CAAC,gBAAgB,KAAK,4CAA4C,CAAC;IACjF,CAAC;IACD,OAAO,KAAK,CAAC,OAAO,KAAK,kBAAkB;WACtC,OAAO,KAAK,CAAC,WAAW,CAAC,MAAM,KAAK,QAAQ;WAC5C,KAAK,CAAC,WAAW,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC;WACnC,OAAO,CAAC,aAAa,KAAK,KAAK,CAAC,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
+ {"version":3,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AC;eAChE,OAAO,CAAC,aAAa,KAAK,KAAK,CAAC,QAAQ;eACxC,OAAO,CAAC,OAAO,KAAK,QAAQ;eAC5B,OAAO,CAAC,gBAAgB,KAAK,4CAA4C,CAAC;IACjF,CAAC;IACD,OAAO,KAAK,CAAC,OAAO,KAAK,kBAAkB;WACtC,OAAO,KAAK,CAAC,WAAW,CAAC,MAAM,KAAK,QAAQ;WAC5C,KAAK,CAAC,WAAW,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC;WACnC,OAAO,CAAC,aAAa,KAAK,KAAK,CAAC,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\";\nimport type { NegotiationConsultationReason } from \"../negotiation/negotiation.consultation-policy.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 /** Server-only IND-508 reason; never copied into generated or persisted payloads. */\n consultationPolicyReason?: NegotiationConsultationReason;\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.consultationPolicyReason === undefined\n || context.consultationPolicyReason === 'unresolved_owner_constraint'\n || context.consultationPolicyReason === 'consequential_disclosure_permission'\n || context.consultationPolicyReason === 'repeated_non_convergence'\n || context.consultationPolicyReason === 'insufficient_commitment_authority')\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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@indexnetwork/protocol",
3
- "version": "6.9.0-rc.396.1",
3
+ "version": "6.10.0-rc.398.1",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",