@indexnetwork/protocol 4.5.0-rc.336.1 → 4.5.0-rc.338.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 (40) hide show
  1. package/dist/chat/negotiator.prompt.d.ts +8 -0
  2. package/dist/chat/negotiator.prompt.d.ts.map +1 -1
  3. package/dist/chat/negotiator.prompt.js +3 -1
  4. package/dist/chat/negotiator.prompt.js.map +1 -1
  5. package/dist/index.d.ts +4 -0
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +2 -0
  8. package/dist/index.js.map +1 -1
  9. package/dist/negotiation/negotiation.agent.d.ts +7 -0
  10. package/dist/negotiation/negotiation.agent.d.ts.map +1 -1
  11. package/dist/negotiation/negotiation.agent.js +4 -2
  12. package/dist/negotiation/negotiation.agent.js.map +1 -1
  13. package/dist/negotiation/negotiation.graph.d.ts +23 -3
  14. package/dist/negotiation/negotiation.graph.d.ts.map +1 -1
  15. package/dist/negotiation/negotiation.graph.js +78 -3
  16. package/dist/negotiation/negotiation.graph.js.map +1 -1
  17. package/dist/negotiation/negotiation.memory.d.ts +58 -0
  18. package/dist/negotiation/negotiation.memory.d.ts.map +1 -0
  19. package/dist/negotiation/negotiation.memory.js +71 -0
  20. package/dist/negotiation/negotiation.memory.js.map +1 -0
  21. package/dist/negotiation/negotiation.reflect.d.ts +199 -0
  22. package/dist/negotiation/negotiation.reflect.d.ts.map +1 -0
  23. package/dist/negotiation/negotiation.reflect.js +153 -0
  24. package/dist/negotiation/negotiation.reflect.js.map +1 -0
  25. package/dist/negotiation/negotiation.screen.d.ts +8 -1
  26. package/dist/negotiation/negotiation.screen.d.ts.map +1 -1
  27. package/dist/negotiation/negotiation.screen.js +5 -3
  28. package/dist/negotiation/negotiation.screen.js.map +1 -1
  29. package/dist/negotiation/negotiation.state.d.ts +9 -0
  30. package/dist/negotiation/negotiation.state.d.ts.map +1 -1
  31. package/dist/negotiation/negotiation.state.js +11 -0
  32. package/dist/negotiation/negotiation.state.js.map +1 -1
  33. package/dist/shared/agent/model.config.d.ts +5 -0
  34. package/dist/shared/agent/model.config.d.ts.map +1 -1
  35. package/dist/shared/agent/model.config.js +1 -0
  36. package/dist/shared/agent/model.config.js.map +1 -1
  37. package/dist/shared/interfaces/agent-dispatcher.interface.d.ts +8 -0
  38. package/dist/shared/interfaces/agent-dispatcher.interface.d.ts.map +1 -1
  39. package/dist/shared/interfaces/agent-dispatcher.interface.js.map +1 -1
  40. package/package.json +1 -1
@@ -0,0 +1,199 @@
1
+ import { z } from "zod";
2
+ import { createStructuredModel } from "../shared/agent/model.config.js";
3
+ /**
4
+ * Memory kinds a reflection pass may distill (P5.1 `negotiator_memories.kind`).
5
+ * Plain text at the DB level (55P04 lesson) — adding kinds is code-only.
6
+ */
7
+ export declare const NEGOTIATOR_MEMORY_KINDS: readonly ["playbook", "disclosure_rule", "counterparty_dossier", "threshold"];
8
+ export type DistilledMemoryKind = (typeof NEGOTIATOR_MEMORY_KINDS)[number];
9
+ /** Hard ceiling on entries distilled per reflection pass (per side). */
10
+ export declare const MAX_DISTILLED_MEMORIES = 3;
11
+ /**
12
+ * One distilled memory entry as produced by the reflection LLM. The caller
13
+ * owns persistence: it resolves `aboutCounterparty` to a `subjectUserId`,
14
+ * computes the embedding, and attaches provenance `sourceRefs`.
15
+ */
16
+ export declare const DistilledMemorySchema: z.ZodObject<{
17
+ kind: z.ZodEnum<["playbook", "disclosure_rule", "counterparty_dossier", "threshold"]>;
18
+ /** Self-contained operational statement, useful without the transcript. */
19
+ content: z.ZodString;
20
+ /** Evidence strength, 0..1. Explicit client statements score high. */
21
+ confidence: z.ZodNumber;
22
+ /**
23
+ * True when the entry is about the counterparty (kind should be
24
+ * `counterparty_dossier`); false for client-side rules and playbooks.
25
+ */
26
+ aboutCounterparty: z.ZodBoolean;
27
+ /** Turn indexes (0-based, into the provided transcript) evidencing this entry. */
28
+ turnIndexes: z.ZodDefault<z.ZodArray<z.ZodNumber, "many">>;
29
+ }, "strip", z.ZodTypeAny, {
30
+ kind: "threshold" | "playbook" | "disclosure_rule" | "counterparty_dossier";
31
+ confidence: number;
32
+ content: string;
33
+ aboutCounterparty: boolean;
34
+ turnIndexes: number[];
35
+ }, {
36
+ kind: "threshold" | "playbook" | "disclosure_rule" | "counterparty_dossier";
37
+ confidence: number;
38
+ content: string;
39
+ aboutCounterparty: boolean;
40
+ turnIndexes?: number[] | undefined;
41
+ }>;
42
+ export type DistilledMemory = z.infer<typeof DistilledMemorySchema>;
43
+ export declare const ReflectionResultSchema: z.ZodObject<{
44
+ memories: z.ZodArray<z.ZodObject<{
45
+ kind: z.ZodEnum<["playbook", "disclosure_rule", "counterparty_dossier", "threshold"]>;
46
+ /** Self-contained operational statement, useful without the transcript. */
47
+ content: z.ZodString;
48
+ /** Evidence strength, 0..1. Explicit client statements score high. */
49
+ confidence: z.ZodNumber;
50
+ /**
51
+ * True when the entry is about the counterparty (kind should be
52
+ * `counterparty_dossier`); false for client-side rules and playbooks.
53
+ */
54
+ aboutCounterparty: z.ZodBoolean;
55
+ /** Turn indexes (0-based, into the provided transcript) evidencing this entry. */
56
+ turnIndexes: z.ZodDefault<z.ZodArray<z.ZodNumber, "many">>;
57
+ }, "strip", z.ZodTypeAny, {
58
+ kind: "threshold" | "playbook" | "disclosure_rule" | "counterparty_dossier";
59
+ confidence: number;
60
+ content: string;
61
+ aboutCounterparty: boolean;
62
+ turnIndexes: number[];
63
+ }, {
64
+ kind: "threshold" | "playbook" | "disclosure_rule" | "counterparty_dossier";
65
+ confidence: number;
66
+ content: string;
67
+ aboutCounterparty: boolean;
68
+ turnIndexes?: number[] | undefined;
69
+ }>, "many">;
70
+ }, "strip", z.ZodTypeAny, {
71
+ memories: {
72
+ kind: "threshold" | "playbook" | "disclosure_rule" | "counterparty_dossier";
73
+ confidence: number;
74
+ content: string;
75
+ aboutCounterparty: boolean;
76
+ turnIndexes: number[];
77
+ }[];
78
+ }, {
79
+ memories: {
80
+ kind: "threshold" | "playbook" | "disclosure_rule" | "counterparty_dossier";
81
+ confidence: number;
82
+ content: string;
83
+ aboutCounterparty: boolean;
84
+ turnIndexes?: number[] | undefined;
85
+ }[];
86
+ }>;
87
+ export type ReflectionResult = z.infer<typeof ReflectionResultSchema>;
88
+ /** A transcript row projected into the reflecting client's perspective. */
89
+ export interface ReflectionTranscriptEntry {
90
+ index: number;
91
+ speaker: "client" | "counterparty";
92
+ action: string;
93
+ message?: string;
94
+ reasoning?: string;
95
+ }
96
+ export interface NegotiationReflectionInput {
97
+ /** The user whose negotiator is reflecting (memories land on their agent). */
98
+ clientUser: {
99
+ id: string;
100
+ name?: string;
101
+ bio?: string;
102
+ };
103
+ counterpartyUser: {
104
+ id: string;
105
+ name?: string;
106
+ bio?: string;
107
+ };
108
+ /** The client's seat in this negotiation. */
109
+ seat: "initiator" | "counterparty";
110
+ outcome: {
111
+ hasOpportunity: boolean;
112
+ reasoning: string;
113
+ turnCount: number;
114
+ };
115
+ transcript: ReflectionTranscriptEntry[];
116
+ /** Network prompt for context (optional). */
117
+ indexContext?: string;
118
+ }
119
+ export interface ChatReflectionInput {
120
+ clientUser: {
121
+ id: string;
122
+ name?: string;
123
+ };
124
+ /** The negotiator DM messages, oldest first. */
125
+ messages: Array<{
126
+ role: "user" | "assistant";
127
+ content: string;
128
+ }>;
129
+ }
130
+ /**
131
+ * Payload the finalize node hands to the injected {@link ReflectEnqueueFn}.
132
+ * Carries user display context so the reflect worker never re-loads profiles;
133
+ * turn history is loaded from the conversation by the worker (payloads stay
134
+ * small in Redis).
135
+ */
136
+ export interface NegotiationReflectJobData {
137
+ negotiationId: string;
138
+ conversationId: string;
139
+ opportunityId?: string;
140
+ sourceUser: {
141
+ id: string;
142
+ name?: string;
143
+ bio?: string;
144
+ };
145
+ candidateUser: {
146
+ id: string;
147
+ name?: string;
148
+ bio?: string;
149
+ };
150
+ initiatorUserId: string;
151
+ outcome: {
152
+ hasOpportunity: boolean;
153
+ reasoning: string;
154
+ turnCount: number;
155
+ };
156
+ }
157
+ /**
158
+ * Injected enqueue callback for post-negotiation reflection (P5.2). The
159
+ * protocol package has no BullMQ access — services/api wires this at its
160
+ * composition roots, exactly like `QuestionerEnqueueFn`. Called fire-and-
161
+ * forget from the finalize node: a reflection failure must never affect the
162
+ * negotiation outcome.
163
+ */
164
+ export type ReflectEnqueueFn = (job: NegotiationReflectJobData) => Promise<void>;
165
+ export interface NegotiationReflectorConfig {
166
+ /** Hard ceiling on the reflection LLM round-trip, in ms (default 20000). */
167
+ timeoutMs?: number;
168
+ }
169
+ /**
170
+ * The memory distiller (P5.2). One structured LLM call per reflection pass,
171
+ * producing ≤ {@link MAX_DISTILLED_MEMORIES} private memory entries for one
172
+ * client's negotiator. Throws on LLM/validation failure — callers (the reflect
173
+ * queue worker) own the swallow-and-log policy, since reflection must never
174
+ * affect a negotiation outcome.
175
+ */
176
+ export declare class NegotiationReflector {
177
+ private readonly timeoutMs;
178
+ constructor(config?: NegotiationReflectorConfig);
179
+ /**
180
+ * Distill memories from a finished negotiation, from one side's perspective.
181
+ * @throws When the LLM call times out or returns schema-invalid output.
182
+ */
183
+ reflectNegotiation(input: NegotiationReflectionInput): Promise<DistilledMemory[]>;
184
+ /**
185
+ * Distill stated preferences/corrections from a client ↔ negotiator chat.
186
+ * @throws When the LLM call times out or returns schema-invalid output.
187
+ */
188
+ reflectChat(input: ChatReflectionInput): Promise<DistilledMemory[]>;
189
+ private distill;
190
+ /**
191
+ * Raw structured-model round trip. Split out as a seam so tests can drive
192
+ * the schema-validation path without a live provider.
193
+ */
194
+ protected callModel(model: ReturnType<typeof createStructuredModel>, chatMessages: Array<{
195
+ role: string;
196
+ content: string;
197
+ }>): Promise<unknown>;
198
+ }
199
+ //# sourceMappingURL=negotiation.reflect.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"negotiation.reflect.d.ts","sourceRoot":"/","sources":["negotiation/negotiation.reflect.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAA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W,0BAA0B;IACzC,4EAA4E;IAC5E,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED;;;;;;GAMG;AACH,qBAAa,oBAAoB;IAC/B,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;gBAEvB,MAAM,CAAC,EAAE,0BAA0B;IAM/C;;;OAGG;IACG,kBAAkB,CAAC,KAAK,EAAE,0BAA0B,GAAG,OAAO,CAAC,eAAe,EAAE,CAAC;IA8BvF;;;OAGG;IACG,WAAW,CAAC,KAAK,EAAE,mBAAmB,GAAG,OAAO,CAAC,eAAe,EAAE,CAAC;YAgB3D,OAAO;IAkBrB;;;OAGG;cACa,SAAS,CACvB,KAAK,EAAE,UAAU,CAAC,OAAO,qBAAqB,CAAC,EAC/C,YAAY,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,GACrD,OAAO,CAAC,OAAO,CAAC;CAGpB"}
@@ -0,0 +1,153 @@
1
+ import { z } from "zod";
2
+ import { createStructuredModel } from "../shared/agent/model.config.js";
3
+ import { invokeWithAbortSignal } from "../shared/agent/model-signal.js";
4
+ import { protocolLogger } from "../shared/observability/protocol.logger.js";
5
+ const reflectLog = protocolLogger("NegotiationReflector");
6
+ /**
7
+ * Memory kinds a reflection pass may distill (P5.1 `negotiator_memories.kind`).
8
+ * Plain text at the DB level (55P04 lesson) — adding kinds is code-only.
9
+ */
10
+ export const NEGOTIATOR_MEMORY_KINDS = [
11
+ "playbook",
12
+ "disclosure_rule",
13
+ "counterparty_dossier",
14
+ "threshold",
15
+ ];
16
+ /** Hard ceiling on entries distilled per reflection pass (per side). */
17
+ export const MAX_DISTILLED_MEMORIES = 3;
18
+ /**
19
+ * One distilled memory entry as produced by the reflection LLM. The caller
20
+ * owns persistence: it resolves `aboutCounterparty` to a `subjectUserId`,
21
+ * computes the embedding, and attaches provenance `sourceRefs`.
22
+ */
23
+ export const DistilledMemorySchema = z.object({
24
+ kind: z.enum(NEGOTIATOR_MEMORY_KINDS),
25
+ /** Self-contained operational statement, useful without the transcript. */
26
+ content: z.string().min(1),
27
+ /** Evidence strength, 0..1. Explicit client statements score high. */
28
+ confidence: z.number().min(0).max(1),
29
+ /**
30
+ * True when the entry is about the counterparty (kind should be
31
+ * `counterparty_dossier`); false for client-side rules and playbooks.
32
+ */
33
+ aboutCounterparty: z.boolean(),
34
+ /** Turn indexes (0-based, into the provided transcript) evidencing this entry. */
35
+ turnIndexes: z.array(z.number().int().min(0)).default([]),
36
+ });
37
+ export const ReflectionResultSchema = z.object({
38
+ memories: z.array(DistilledMemorySchema).max(MAX_DISTILLED_MEMORIES),
39
+ });
40
+ const NEGOTIATION_SYSTEM_PROMPT = `You are the private post-negotiation reflection process for {clientName}'s negotiator agent. The negotiation is over; your job is to distill AT MOST ${MAX_DISTILLED_MEMORIES} durable operational memory entries that will make {clientName}'s negotiator better in FUTURE negotiations. These memories are private to {clientName}'s agent — the counterparty never sees them.
41
+
42
+ Memory kinds:
43
+ - "playbook": a tactic or pattern that worked or failed (e.g. "Opening with the specific shared-interest angle got engagement; generic intros stalled").
44
+ - "disclosure_rule": what {clientName} is or is not willing to share/commit (only when the transcript actually evidences it).
45
+ - "counterparty_dossier": a durable fact about the counterparty useful in future dealings with THEM specifically (set aboutCounterparty=true).
46
+ - "threshold": a concrete boundary observed (e.g. minimum scope, timing constraints, deal-breakers).
47
+
48
+ Rules:
49
+ - Record ONLY what future negotiations need. No summaries, no play-by-play, no identity facts about {clientName} (their profile already covers those).
50
+ - Every entry MUST cite the transcript turn indexes that evidence it in turnIndexes.
51
+ - Each content string must be self-contained and actionable without the transcript.
52
+ - Set confidence by evidence strength: explicit statements ≈ 0.8-0.9, inferred patterns ≈ 0.4-0.6.
53
+ - aboutCounterparty=true ONLY for counterparty_dossier entries.
54
+ - Return an empty memories array when nothing durable was learned — most short or failed negotiations teach nothing. Do not force entries.`;
55
+ const CHAT_SYSTEM_PROMPT = `You are the private reflection process for {clientName}'s negotiator agent, reviewing a direct chat between {clientName} (the client) and their negotiator. Distill AT MOST ${MAX_DISTILLED_MEMORIES} durable operational memory entries capturing the client's STATED preferences, corrections, and instructions.
56
+
57
+ Memory kinds:
58
+ - "playbook": how the client wants negotiations approached (style, priorities).
59
+ - "disclosure_rule": what the client said they will or won't share/commit.
60
+ - "threshold": concrete boundaries the client stated (rates, scope, timing, deal-breakers).
61
+
62
+ Rules:
63
+ - Only distill what the CLIENT stated or clearly confirmed — never invent preferences from the negotiator's own suggestions.
64
+ - Do NOT produce counterparty_dossier entries; this is a client-side conversation. Always set aboutCounterparty=false.
65
+ - Each content string must be self-contained and actionable.
66
+ - turnIndexes cite 0-based indexes into the provided message list.
67
+ - Set confidence by how explicit the client was (direct instruction ≈ 0.9, implied preference ≈ 0.5).
68
+ - Return an empty memories array when the chat contains no durable guidance — casual Q&A usually doesn't.`;
69
+ const DEFAULT_REFLECT_TIMEOUT_MS = 20000;
70
+ /**
71
+ * The memory distiller (P5.2). One structured LLM call per reflection pass,
72
+ * producing ≤ {@link MAX_DISTILLED_MEMORIES} private memory entries for one
73
+ * client's negotiator. Throws on LLM/validation failure — callers (the reflect
74
+ * queue worker) own the swallow-and-log policy, since reflection must never
75
+ * affect a negotiation outcome.
76
+ */
77
+ export class NegotiationReflector {
78
+ constructor(config) {
79
+ this.timeoutMs = config?.timeoutMs && Number.isFinite(config.timeoutMs) && config.timeoutMs > 0
80
+ ? config.timeoutMs
81
+ : DEFAULT_REFLECT_TIMEOUT_MS;
82
+ }
83
+ /**
84
+ * Distill memories from a finished negotiation, from one side's perspective.
85
+ * @throws When the LLM call times out or returns schema-invalid output.
86
+ */
87
+ async reflectNegotiation(input) {
88
+ const clientName = input.clientUser.name ?? "the client";
89
+ const counterpartyName = input.counterpartyUser.name ?? "the counterparty";
90
+ const systemPrompt = NEGOTIATION_SYSTEM_PROMPT.replace(/{clientName}/g, clientName);
91
+ const transcriptText = input.transcript.length > 0
92
+ ? input.transcript.map((t) => {
93
+ const who = t.speaker === "client" ? `${clientName}'s negotiator` : `${counterpartyName}'s negotiator`;
94
+ const parts = [`[${t.index}] ${who} → ${t.action}`];
95
+ if (t.message)
96
+ parts.push(`message: ${t.message}`);
97
+ if (t.reasoning)
98
+ parts.push(`reasoning: ${t.reasoning}`);
99
+ return parts.join("\n ");
100
+ }).join("\n")
101
+ : "(no turns)";
102
+ const userMessage = `CLIENT: ${clientName}${input.clientUser.bio ? ` — ${input.clientUser.bio}` : ""}
103
+ SEAT: ${input.seat === "initiator" ? "initiator (client's negotiator reached out)" : "counterparty (client's negotiator was reached)"}
104
+ COUNTERPARTY: ${counterpartyName}${input.counterpartyUser.bio ? ` — ${input.counterpartyUser.bio}` : ""}
105
+ ${input.indexContext ? `NETWORK CONTEXT: ${input.indexContext}\n` : ""}
106
+ OUTCOME: ${input.outcome.hasOpportunity ? "accepted" : "not accepted"} after ${input.outcome.turnCount} turn(s) — ${input.outcome.reasoning}
107
+
108
+ TRANSCRIPT:
109
+ ${transcriptText}
110
+
111
+ Distill the durable memories (or return an empty array).`;
112
+ return this.distill(systemPrompt, userMessage);
113
+ }
114
+ /**
115
+ * Distill stated preferences/corrections from a client ↔ negotiator chat.
116
+ * @throws When the LLM call times out or returns schema-invalid output.
117
+ */
118
+ async reflectChat(input) {
119
+ const clientName = input.clientUser.name ?? "the client";
120
+ const systemPrompt = CHAT_SYSTEM_PROMPT.replace(/{clientName}/g, clientName);
121
+ const chatText = input.messages
122
+ .map((m, i) => `[${i}] ${m.role === "user" ? clientName : "negotiator"}: ${m.content}`)
123
+ .join("\n");
124
+ const userMessage = `CHAT between ${clientName} and their negotiator (oldest first):
125
+ ${chatText}
126
+
127
+ Distill the client's durable guidance (or return an empty array).`;
128
+ return this.distill(systemPrompt, userMessage);
129
+ }
130
+ async distill(systemPrompt, userMessage) {
131
+ const model = createStructuredModel("negotiationReflector", ReflectionResultSchema, { name: "negotiation_reflector" });
132
+ const result = await this.callModel(model, [
133
+ { role: "system", content: systemPrompt },
134
+ { role: "user", content: userMessage },
135
+ ]);
136
+ const parsed = ReflectionResultSchema.safeParse(result);
137
+ if (!parsed.success) {
138
+ reflectLog.warn("Reflection output failed schema validation", {
139
+ issues: parsed.error.issues.map((i) => i.message).slice(0, 3),
140
+ });
141
+ throw new Error(`Reflection failed validation: ${parsed.error.issues[0]?.message ?? "unknown"}`);
142
+ }
143
+ return parsed.data.memories.slice(0, MAX_DISTILLED_MEMORIES);
144
+ }
145
+ /**
146
+ * Raw structured-model round trip. Split out as a seam so tests can drive
147
+ * the schema-validation path without a live provider.
148
+ */
149
+ async callModel(model, chatMessages) {
150
+ return invokeWithAbortSignal(model, chatMessages, AbortSignal.timeout(this.timeoutMs));
151
+ }
152
+ }
153
+ //# sourceMappingURL=negotiation.reflect.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"negotiation.reflect.js","sourceRoot":"/","sources":["negotiation/negotiation.reflect.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AACxE,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AACxE,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAE5E,MAAM,UAAU,GAAG,cAAc,CAAC,sBAAsB,CAAC,CAAC;AAE1D;;;GAGG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG;IACrC,UAAU;IACV,iBAAiB;IACjB,sBAAsB;IACtB,WAAW;CACH,CAAC;AAIX,wEAAwE;AACxE,MAAM,CAAC,MAAM,sBAAsB,GAAG,CAAC,CAAC;AAExC;;;;GAIG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,CAAC,MAAM,CAAC;IAC5C,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,uBAAuB,CAAC;IACrC,2EAA2E;IAC3E,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,C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AO,EAAE,YAAY,EAAE;YACzC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE;SACvC,CAAC,CAAC;QAEH,MAAM,MAAM,GAAG,sBAAsB,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;QACxD,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;YACpB,UAAU,CAAC,IAAI,CAAC,4CAA4C,EAAE;gBAC5D,MAAM,EAAE,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC;aAC9D,CAAC,CAAC;YACH,MAAM,IAAI,KAAK,CAAC,iCAAiC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,OAAO,IAAI,SAAS,EAAE,CAAC,CAAC;QACnG,CAAC;QACD,OAAO,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,sBAAsB,CAAC,CAAC;IAC/D,CAAC;IAED;;;OAGG;IACO,KAAK,CAAC,SAAS,CACvB,KAA+C,EAC/C,YAAsD;QAEtD,OAAO,qBAAqB,CAAC,KAAK,EAAE,YAAY,EAAE,WAAW,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IACzF,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\n\nimport { createStructuredModel } from \"../shared/agent/model.config.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\n\nconst reflectLog = protocolLogger(\"NegotiationReflector\");\n\n/**\n * Memory kinds a reflection pass may distill (P5.1 `negotiator_memories.kind`).\n * Plain text at the DB level (55P04 lesson) — adding kinds is code-only.\n */\nexport const NEGOTIATOR_MEMORY_KINDS = [\n \"playbook\",\n \"disclosure_rule\",\n \"counterparty_dossier\",\n \"threshold\",\n] as const;\n\nexport type DistilledMemoryKind = (typeof NEGOTIATOR_MEMORY_KINDS)[number];\n\n/** Hard ceiling on entries distilled per reflection pass (per side). */\nexport const MAX_DISTILLED_MEMORIES = 3;\n\n/**\n * One distilled memory entry as produced by the reflection LLM. The caller\n * owns persistence: it resolves `aboutCounterparty` to a `subjectUserId`,\n * computes the embedding, and attaches provenance `sourceRefs`.\n */\nexport const DistilledMemorySchema = z.object({\n kind: z.enum(NEGOTIATOR_MEMORY_KINDS),\n /** Self-contained operational statement, useful without the transcript. */\n content: z.string().min(1),\n /** Evidence strength, 0..1. Explicit client statements score high. */\n confidence: z.number().min(0).max(1),\n /**\n * True when the entry is about the counterparty (kind should be\n * `counterparty_dossier`); false for client-side rules and playbooks.\n */\n aboutCounterparty: z.boolean(),\n /** Turn indexes (0-based, into the provided transcript) evidencing this entry. */\n turnIndexes: z.array(z.number().int().min(0)).default([]),\n});\n\nexport type DistilledMemory = z.infer<typeof DistilledMemorySchema>;\n\nexport const ReflectionResultSchema = z.object({\n memories: z.array(DistilledMemorySchema).max(MAX_DISTILLED_MEMORIES),\n});\n\nexport type ReflectionResult = z.infer<typeof ReflectionResultSchema>;\n\n/** A transcript row projected into the reflecting client's perspective. */\nexport interface ReflectionTranscriptEntry {\n index: number;\n speaker: \"client\" | \"counterparty\";\n action: string;\n message?: string;\n reasoning?: string;\n}\n\nexport interface NegotiationReflectionInput {\n /** The user whose negotiator is reflecting (memories land on their agent). */\n clientUser: { id: string; name?: string; bio?: string };\n counterpartyUser: { id: string; name?: string; bio?: string };\n /** The client's seat in this negotiation. */\n seat: \"initiator\" | \"counterparty\";\n outcome: { hasOpportunity: boolean; reasoning: string; turnCount: number };\n transcript: ReflectionTranscriptEntry[];\n /** Network prompt for context (optional). */\n indexContext?: string;\n}\n\nexport interface ChatReflectionInput {\n clientUser: { id: string; name?: string };\n /** The negotiator DM messages, oldest first. */\n messages: Array<{ role: \"user\" | \"assistant\"; content: string }>;\n}\n\n/**\n * Payload the finalize node hands to the injected {@link ReflectEnqueueFn}.\n * Carries user display context so the reflect worker never re-loads profiles;\n * turn history is loaded from the conversation by the worker (payloads stay\n * small in Redis).\n */\nexport interface NegotiationReflectJobData {\n negotiationId: string;\n conversationId: string;\n opportunityId?: string;\n sourceUser: { id: string; name?: string; bio?: string };\n candidateUser: { id: string; name?: string; bio?: string };\n initiatorUserId: string;\n outcome: { hasOpportunity: boolean; reasoning: string; turnCount: number };\n}\n\n/**\n * Injected enqueue callback for post-negotiation reflection (P5.2). The\n * protocol package has no BullMQ access — services/api wires this at its\n * composition roots, exactly like `QuestionerEnqueueFn`. Called fire-and-\n * forget from the finalize node: a reflection failure must never affect the\n * negotiation outcome.\n */\nexport type ReflectEnqueueFn = (job: NegotiationReflectJobData) => Promise<void>;\n\nconst NEGOTIATION_SYSTEM_PROMPT = `You are the private post-negotiation reflection process for {clientName}'s negotiator agent. The negotiation is over; your job is to distill AT MOST ${MAX_DISTILLED_MEMORIES} durable operational memory entries that will make {clientName}'s negotiator better in FUTURE negotiations. These memories are private to {clientName}'s agent — the counterparty never sees them.\n\nMemory kinds:\n- \"playbook\": a tactic or pattern that worked or failed (e.g. \"Opening with the specific shared-interest angle got engagement; generic intros stalled\").\n- \"disclosure_rule\": what {clientName} is or is not willing to share/commit (only when the transcript actually evidences it).\n- \"counterparty_dossier\": a durable fact about the counterparty useful in future dealings with THEM specifically (set aboutCounterparty=true).\n- \"threshold\": a concrete boundary observed (e.g. minimum scope, timing constraints, deal-breakers).\n\nRules:\n- Record ONLY what future negotiations need. No summaries, no play-by-play, no identity facts about {clientName} (their profile already covers those).\n- Every entry MUST cite the transcript turn indexes that evidence it in turnIndexes.\n- Each content string must be self-contained and actionable without the transcript.\n- Set confidence by evidence strength: explicit statements ≈ 0.8-0.9, inferred patterns ≈ 0.4-0.6.\n- aboutCounterparty=true ONLY for counterparty_dossier entries.\n- Return an empty memories array when nothing durable was learned — most short or failed negotiations teach nothing. Do not force entries.`;\n\nconst CHAT_SYSTEM_PROMPT = `You are the private reflection process for {clientName}'s negotiator agent, reviewing a direct chat between {clientName} (the client) and their negotiator. Distill AT MOST ${MAX_DISTILLED_MEMORIES} durable operational memory entries capturing the client's STATED preferences, corrections, and instructions.\n\nMemory kinds:\n- \"playbook\": how the client wants negotiations approached (style, priorities).\n- \"disclosure_rule\": what the client said they will or won't share/commit.\n- \"threshold\": concrete boundaries the client stated (rates, scope, timing, deal-breakers).\n\nRules:\n- Only distill what the CLIENT stated or clearly confirmed — never invent preferences from the negotiator's own suggestions.\n- Do NOT produce counterparty_dossier entries; this is a client-side conversation. Always set aboutCounterparty=false.\n- Each content string must be self-contained and actionable.\n- turnIndexes cite 0-based indexes into the provided message list.\n- Set confidence by how explicit the client was (direct instruction ≈ 0.9, implied preference ≈ 0.5).\n- Return an empty memories array when the chat contains no durable guidance — casual Q&A usually doesn't.`;\n\nconst DEFAULT_REFLECT_TIMEOUT_MS = 20_000;\n\nexport interface NegotiationReflectorConfig {\n /** Hard ceiling on the reflection LLM round-trip, in ms (default 20000). */\n timeoutMs?: number;\n}\n\n/**\n * The memory distiller (P5.2). One structured LLM call per reflection pass,\n * producing ≤ {@link MAX_DISTILLED_MEMORIES} private memory entries for one\n * client's negotiator. Throws on LLM/validation failure — callers (the reflect\n * queue worker) own the swallow-and-log policy, since reflection must never\n * affect a negotiation outcome.\n */\nexport class NegotiationReflector {\n private readonly timeoutMs: number;\n\n constructor(config?: NegotiationReflectorConfig) {\n this.timeoutMs = config?.timeoutMs && Number.isFinite(config.timeoutMs) && config.timeoutMs > 0\n ? config.timeoutMs\n : DEFAULT_REFLECT_TIMEOUT_MS;\n }\n\n /**\n * Distill memories from a finished negotiation, from one side's perspective.\n * @throws When the LLM call times out or returns schema-invalid output.\n */\n async reflectNegotiation(input: NegotiationReflectionInput): Promise<DistilledMemory[]> {\n const clientName = input.clientUser.name ?? \"the client\";\n const counterpartyName = input.counterpartyUser.name ?? \"the counterparty\";\n\n const systemPrompt = NEGOTIATION_SYSTEM_PROMPT.replace(/{clientName}/g, clientName);\n\n const transcriptText = input.transcript.length > 0\n ? input.transcript.map((t) => {\n const who = t.speaker === \"client\" ? `${clientName}'s negotiator` : `${counterpartyName}'s negotiator`;\n const parts = [`[${t.index}] ${who} → ${t.action}`];\n if (t.message) parts.push(`message: ${t.message}`);\n if (t.reasoning) parts.push(`reasoning: ${t.reasoning}`);\n return parts.join(\"\\n \");\n }).join(\"\\n\")\n : \"(no turns)\";\n\n const userMessage = `CLIENT: ${clientName}${input.clientUser.bio ? ` — ${input.clientUser.bio}` : \"\"}\nSEAT: ${input.seat === \"initiator\" ? \"initiator (client's negotiator reached out)\" : \"counterparty (client's negotiator was reached)\"}\nCOUNTERPARTY: ${counterpartyName}${input.counterpartyUser.bio ? ` — ${input.counterpartyUser.bio}` : \"\"}\n${input.indexContext ? `NETWORK CONTEXT: ${input.indexContext}\\n` : \"\"}\nOUTCOME: ${input.outcome.hasOpportunity ? \"accepted\" : \"not accepted\"} after ${input.outcome.turnCount} turn(s) — ${input.outcome.reasoning}\n\nTRANSCRIPT:\n${transcriptText}\n\nDistill the durable memories (or return an empty array).`;\n\n return this.distill(systemPrompt, userMessage);\n }\n\n /**\n * Distill stated preferences/corrections from a client ↔ negotiator chat.\n * @throws When the LLM call times out or returns schema-invalid output.\n */\n async reflectChat(input: ChatReflectionInput): Promise<DistilledMemory[]> {\n const clientName = input.clientUser.name ?? \"the client\";\n const systemPrompt = CHAT_SYSTEM_PROMPT.replace(/{clientName}/g, clientName);\n\n const chatText = input.messages\n .map((m, i) => `[${i}] ${m.role === \"user\" ? clientName : \"negotiator\"}: ${m.content}`)\n .join(\"\\n\");\n\n const userMessage = `CHAT between ${clientName} and their negotiator (oldest first):\n${chatText}\n\nDistill the client's durable guidance (or return an empty array).`;\n\n return this.distill(systemPrompt, userMessage);\n }\n\n private async distill(systemPrompt: string, userMessage: string): Promise<DistilledMemory[]> {\n const model = createStructuredModel(\"negotiationReflector\", ReflectionResultSchema, { name: \"negotiation_reflector\" });\n\n const result = await this.callModel(model, [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: userMessage },\n ]);\n\n const parsed = ReflectionResultSchema.safeParse(result);\n if (!parsed.success) {\n reflectLog.warn(\"Reflection output failed schema validation\", {\n issues: parsed.error.issues.map((i) => i.message).slice(0, 3),\n });\n throw new Error(`Reflection failed validation: ${parsed.error.issues[0]?.message ?? \"unknown\"}`);\n }\n return parsed.data.memories.slice(0, MAX_DISTILLED_MEMORIES);\n }\n\n /**\n * Raw structured-model round trip. Split out as a seam so tests can drive\n * the schema-validation path without a live provider.\n */\n protected async callModel(\n model: ReturnType<typeof createStructuredModel>,\n chatMessages: Array<{ role: string; content: string }>,\n ): Promise<unknown> {\n return invokeWithAbortSignal(model, chatMessages, AbortSignal.timeout(this.timeoutMs));\n }\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { createStructuredModel } from "../shared/agent/model.config.js";
3
3
  import type { UserNegotiationContext, SeedAssessment } from "../shared/schemas/negotiation-state.schema.js";
4
+ import { type NegotiatorMemoryEntry } from "./negotiation.memory.js";
4
5
  /**
5
6
  * Screen-gate modes (P2.1 — client-advocate protocol).
6
7
  *
@@ -38,7 +39,7 @@ export declare const ScreenDecisionSchema: z.ZodObject<{
38
39
  counterpartyPremiseFit: z.ZodString;
39
40
  /** How the client's intents align with what the counterparty seeks. */
40
41
  intentAlignment: z.ZodString;
41
- /** Prior-negotiation memory signals. Wired in P5.3 — always absent today. */
42
+ /** Prior-negotiation memory signals (P5.3). Filled only when negotiator memory was injected into the screen prompt. */
42
43
  memoryHints: z.ZodOptional<z.ZodNullable<z.ZodString>>;
43
44
  }, "strip", z.ZodTypeAny, {
44
45
  counterpartyPremiseFit: string;
@@ -97,6 +98,12 @@ export interface NegotiationScreenerInput {
97
98
  networkId: string;
98
99
  prompt?: string;
99
100
  };
101
+ /**
102
+ * Retrieved negotiator memories for the client (P5.3 read path). Rendered
103
+ * as a private prompt section with a memoryHints instruction. Absent/empty
104
+ * → the prompt is byte-identical to before.
105
+ */
106
+ memory?: NegotiatorMemoryEntry[];
100
107
  }
101
108
  export interface NegotiationScreenerConfig {
102
109
  /** Hard ceiling on the screen LLM round-trip, in ms (default 15000). */
@@ -1 +1 @@
1
- {"version":3,"file":"negotiation.screen.d.ts","sourceRoot":"/","sources":["negotiation/negotiation.screen.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAExE,OAAO,KAAK,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,+CAA+C,CAAC;AAK5G;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,wBAAwB,uCAAwC,CAAC;AAE9E,MAAM,MAAM,qBAAqB,GAAG,CAAC,OAAO,wBAAwB,CAAC,CAAC,MAAM,CAAC,CAAC;AAE9E;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,IAAI,qBAAqB,CAI5D;AAED;;;GAGG;AACH,eAAO,MAAM,oBAAoB;;;IAG/B,8EAA8E;;;QAG5E,0EAA0E;;QAE1E,uEAAuE;;QAEvE,6EAA6E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAG/E,CAAC;AAEH,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,oBAAoB,CAAC,CAAC;AAElE;;;;GAIG;AACH,MAAM,WAAW,oBAAqB,SAAQ,cAAc;IAC1D,IAAI,EAAE,qBAAqB,CAAC;IAC5B,wEAAwE;IACxE,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,8CAA8C;IAC9C,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,wBAAwB;IACvC,+EAA+E;IAC/E,UAAU,EAAE,sBAAsB,CAAC;IACnC,yEAAyE;IACzE,gBAAgB,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AyB;IAM9C;;;OAGG;IACG,MAAM,CAAC,KAAK,EAAE,wBAAwB,GAAG,OAAO,CAAC,cAAc,CAAC;IAiDtE;;;OAGG;cACa,SAAS,CACvB,KAAK,EAAE,UAAU,CAAC,OAAO,qBAAqB,CAAC,EAC/C,YAAY,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,GACrD,OAAO,CAAC,OAAO,CAAC;CAGpB"}
@@ -2,6 +2,7 @@ import { z } from "zod";
2
2
  import { createStructuredModel } from "../shared/agent/model.config.js";
3
3
  import { invokeWithAbortSignal } from "../shared/agent/model-signal.js";
4
4
  import { protocolLogger } from "../shared/observability/protocol.logger.js";
5
+ import { renderNegotiatorMemorySection } from "./negotiation.memory.js";
5
6
  const screenLog = protocolLogger("NegotiationScreener");
6
7
  /**
7
8
  * Screen-gate modes (P2.1 — client-advocate protocol).
@@ -44,7 +45,7 @@ export const ScreenDecisionSchema = z.object({
44
45
  counterpartyPremiseFit: z.string(),
45
46
  /** How the client's intents align with what the counterparty seeks. */
46
47
  intentAlignment: z.string(),
47
- /** Prior-negotiation memory signals. Wired in P5.3 — always absent today. */
48
+ /** Prior-negotiation memory signals (P5.3). Filled only when negotiator memory was injected into the screen prompt. */
48
49
  memoryHints: z.string().nullable().optional(),
49
50
  }),
50
51
  });
@@ -60,7 +61,7 @@ Rules:
60
61
  {queryRule}
61
62
  - Judge concrete intent alignment, not topical adjacency.
62
63
  - Fill evidence.counterpartyPremiseFit with what (if anything) in the counterparty's context actually fits, and evidence.intentAlignment with how the intents line up. Be specific; cite the strongest signal either way.
63
- - Do NOT reference internal system details like scores, pre-screens, or evaluator outputs in reasoning that could be shown to users.`;
64
+ - Do NOT reference internal system details like scores, pre-screens, or evaluator outputs in reasoning that could be shown to users.{negotiatorMemory}`;
64
65
  const QUERY_RULE = `- {clientName} explicitly searched for "{discoveryQuery}". This query is the PRIMARY criterion: if the counterparty does not satisfy it, pass — background intents cannot rescue a query mismatch.`;
65
66
  const NO_QUERY_RULE = `- No explicit search query: judge against {clientName}'s active intents.`;
66
67
  const DEFAULT_SCREEN_TIMEOUT_MS = 15000;
@@ -91,7 +92,8 @@ export class NegotiationScreener {
91
92
  const systemPrompt = SYSTEM_PROMPT
92
93
  .replace(/{clientName}/g, clientName)
93
94
  .replace("{networkContext}", networkContext)
94
- .replace("{queryRule}", queryRule);
95
+ .replace("{queryRule}", queryRule)
96
+ .replace("{negotiatorMemory}", renderNegotiatorMemorySection(input.memory ?? [], { memoryHintsInstruction: true }));
95
97
  const formatIntents = (intents) => intents.length > 0 ? intents.map((i) => `- ${i.title}: ${i.description}`).join("\n") : "- (none)";
96
98
  const userMessage = `YOUR CLIENT (${clientName}):
97
99
  Bio: ${input.clientUser.profile.bio ?? "N/A"}
@@ -1 +1 @@
1
- {"version":3,"file":"negotiation.screen.js","sourceRoot":"/","sources":["negotiation/negotiation.screen.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AACxE,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAExE,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAE5E,MAAM,SAAS,GAAG,cAAc,CAAC,qBAAqB,CAAC,CAAC;AAExD;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,CAAC,KAAK,EAAE,QAAQ,EAAE,SAAS,CAAU,CAAC;AAI9E;;;;;;;GAOG;AACH,MAAM,UAAU,oBAAoB;IAClC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC;IAChD,IAAI,GAAG,KAAK,QAAQ,IAAI,GAAG,KAAK,SAAS,IAAI,GAAG,KAAK,KAAK;QAAE,OAAO,GAAG,CAAC;IACvE,OAAO,KAAK,CAAC;AACf,CAAC;AAED;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agent/model.config.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\nimport type { UserNegotiationContext, SeedAssessment } from \"../shared/schemas/negotiation-state.schema.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\n\nconst screenLog = protocolLogger(\"NegotiationScreener\");\n\n/**\n * Screen-gate modes (P2.1 — client-advocate protocol).\n *\n * - `off` — the screen node is skipped entirely; no LLM call, no telemetry.\n * - `shadow` — the screen decision is made and recorded (task metadata +\n * trace event + log line) but NEVER blocks: every fresh negotiation still\n * proceeds to the first turn. Used to measure pass rates against observed\n * reject rates before enforcement.\n * - `enforce` — reserved for P2.2. Until enforcement lands, `enforce` runs\n * identically to `shadow` (decision recorded, negotiation proceeds) and the\n * screen node logs a warning that enforcement is not yet implemented.\n */\nexport const NEGOTIATION_SCREEN_MODES = [\"off\", \"shadow\", \"enforce\"] as const;\n\nexport type NegotiationScreenMode = (typeof NEGOTIATION_SCREEN_MODES)[number];\n\n/**\n * Resolve the screen mode from `NEGOTIATION_SCREEN_MODE`.\n *\n * Defaults to `off` when unset or unrecognized — the screen gate is an\n * explicit opt-in flip (same operational pattern as\n * `NEGOTIATION_PROTOCOL_VERSION` / `NEGOTIATOR_CHAT_ENABLED`): code ships\n * inert, the environment turns it on.\n */\nexport function configuredScreenMode(): NegotiationScreenMode {\n const raw = process.env.NEGOTIATION_SCREEN_MODE;\n if (raw === \"shadow\" || raw === \"enforce\" || raw === \"off\") return raw;\n return \"off\";\n}\n\n/**\n * Structured screen decision — the outreach gate's verdict on whether this\n * match is worth the client's name before any turn is exchanged.\n */\nexport const ScreenDecisionSchema = z.object({\n decision: z.enum([\"reach_out\", \"pass\"]),\n reasoning: z.string(),\n /** Suggested opening angle for the outreach turn (only when reaching out). */\n outreachAngle: z.string().nullable().optional(),\n evidence: z.object({\n /** How well the counterparty's context/premises fit the client's need. */\n counterpartyPremiseFit: z.string(),\n /** How the client's intents align with what the counterparty seeks. */\n intentAlignment: z.string(),\n /** Prior-negotiation memory signals. Wired in P5.3 — always absent today. */\n memoryHints: z.string().nullable().optional(),\n }),\n});\n\nexport type ScreenDecision = z.infer<typeof ScreenDecisionSchema>;\n\n/**\n * The record persisted to `tasks.metadata.screenDecision` and returned into\n * graph state. Extends the LLM decision with operational context so pass-rate\n * queries can group by mode and exclude failed-open rows.\n */\nexport interface ScreenDecisionRecord extends ScreenDecision {\n mode: NegotiationScreenMode;\n /** True when the screen LLM call failed and the gate defaulted open. */\n failedOpen?: boolean;\n /** Error message when `failedOpen` is set. */\n error?: string;\n screenedAt: string;\n durationMs: number;\n}\n\nexport interface NegotiationScreenerInput {\n /** The client — the user whose negotiator is deciding whether to reach out. */\n clientUser: UserNegotiationContext;\n /** The counterparty the client's negotiator would be reaching out to. */\n counterpartyUser: UserNegotiationContext;\n /** The counterparty's `user_contexts` paragraph (empty string when absent). */\n counterpartyContext?: string;\n /** The explicit search query that triggered discovery (if any). */\n discoveryQuery?: string;\n seedAssessment: Omit<SeedAssessment, \"actors\">;\n indexContext: { networkId: string; prompt?: string };\n}\n\nconst SYSTEM_PROMPT = `You are the outreach gate for {clientName}'s negotiator agent on a discovery network. Before any negotiation turn is exchanged, you decide whether this match is worth reaching out to on {clientName}'s behalf — their name and attention are spent with every outreach.\n\nNetwork context: {networkContext}\n\nDecide:\n- \"reach_out\" when the counterparty plausibly serves {clientName}'s stated needs and a concrete, honest opening case can be made. When reaching out, set outreachAngle to the strongest specific angle for the opening message.\n- \"pass\" when the match is generic, one-sided, or rests on vague overlap that would waste both parties' attention.\n\nRules:\n{queryRule}\n- Judge concrete intent alignment, not topical adjacency.\n- Fill evidence.counterpartyPremiseFit with what (if anything) in the counterparty's context actually fits, and evidence.intentAlignment with how the intents line up. Be specific; cite the strongest signal either way.\n- Do NOT reference internal system details like scores, pre-screens, or evaluator outputs in reasoning that could be shown to users.`;\n\nconst QUERY_RULE = `- {clientName} explicitly searched for \"{discoveryQuery}\". This query is the PRIMARY criterion: if the counterparty does not satisfy it, pass — background intents cannot rescue a query mismatch.`;\nconst NO_QUERY_RULE = `- No explicit search query: judge against {clientName}'s active intents.`;\n\nconst DEFAULT_SCREEN_TIMEOUT_MS = 15_000;\n\nexport interface NegotiationScreenerConfig {\n /** Hard ceiling on the screen LLM round-trip, in ms (default 15000). */\n timeoutMs?: number;\n}\n\n/**\n * The outreach gate (P2.1). One structured LLM call deciding\n * `reach_out | pass` for a fresh negotiation, from the reaching client's\n * perspective. Throws on LLM/validation failure — the screen graph node owns\n * the fail-open policy (a failed screen never blocks the negotiation).\n */\nexport class NegotiationScreener {\n private readonly timeoutMs: number;\n\n constructor(config?: NegotiationScreenerConfig) {\n this.timeoutMs = config?.timeoutMs && Number.isFinite(config.timeoutMs) && config.timeoutMs > 0\n ? config.timeoutMs\n : DEFAULT_SCREEN_TIMEOUT_MS;\n }\n\n /**\n * Produce a screen decision for a fresh match.\n * @throws When the LLM call times out or returns schema-invalid output.\n */\n async invoke(input: NegotiationScreenerInput): Promise<ScreenDecision> {\n const model = createStructuredModel(\"negotiationScreener\", ScreenDecisionSchema, { name: \"negotiation_screener\" });\n\n const clientName = input.clientUser.profile.name ?? \"your client\";\n const counterpartyName = input.counterpartyUser.profile.name ?? \"the counterparty\";\n const networkContext = input.indexContext.prompt || \"General discovery\";\n const queryRule = (input.discoveryQuery ? QUERY_RULE : NO_QUERY_RULE)\n .replace(/{clientName}/g, clientName)\n .replace(/{discoveryQuery}/g, input.discoveryQuery ?? \"\");\n\n const systemPrompt = SYSTEM_PROMPT\n .replace(/{clientName}/g, clientName)\n .replace(\"{networkContext}\", networkContext)\n .replace(\"{queryRule}\", queryRule);\n\n const formatIntents = (intents: UserNegotiationContext[\"intents\"]): string =>\n intents.length > 0 ? intents.map((i) => `- ${i.title}: ${i.description}`).join(\"\\n\") : \"- (none)\";\n\n const userMessage = `YOUR CLIENT (${clientName}):\nBio: ${input.clientUser.profile.bio ?? \"N/A\"}\n${input.discoveryQuery ? `Search query: \"${input.discoveryQuery}\"\\nBackground intents (secondary to the query):` : \"Active intents:\"}\n${formatIntents(input.clientUser.intents)}\n\nCOUNTERPARTY (${counterpartyName}):\nBio: ${input.counterpartyUser.profile.bio ?? \"N/A\"}\n${input.counterpartyContext ? `Context: ${input.counterpartyContext}\\n` : \"\"}Active intents:\n${formatIntents(input.counterpartyUser.intents)}\n\nWhy this match was suggested: ${input.seedAssessment.reasoning}\n\nDecide whether reaching out serves ${clientName}.`;\n\n const chatMessages = [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: userMessage },\n ];\n\n const result = await this.callModel(model, chatMessages);\n const parsed = ScreenDecisionSchema.safeParse(result);\n if (!parsed.success) {\n screenLog.warn(\"Screen output failed schema validation\", {\n issues: parsed.error.issues.map((i) => i.message).slice(0, 3),\n });\n throw new Error(`Screen decision failed validation: ${parsed.error.issues[0]?.message ?? \"unknown\"}`);\n }\n return parsed.data;\n }\n\n /**\n * Raw structured-model round trip. Split out as a seam so tests can drive\n * the schema-validation and fail-open paths without a live provider.\n */\n protected async callModel(\n model: ReturnType<typeof createStructuredModel>,\n chatMessages: Array<{ role: string; content: string }>,\n ): Promise<unknown> {\n return invokeWithAbortSignal(model, chatMessages, AbortSignal.timeout(this.timeoutMs));\n }\n}\n"]}
1
+ {"version":3,"file":"negotiation.screen.js","sourceRoot":"/","sources":["negotiation/negotiation.screen.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AACxE,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAExE,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,6BAA6B,EAA8B,MAAM,yBAAyB,CAAC;AAEpG,MAAM,SAAS,GAAG,cAAc,CAAC,qBAAqB,CAAC,CAAC;AAExD;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,CAAC,KAAK,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AAI,KAAK,CAAC,sCAAsC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,OAAO,IAAI,SAAS,EAAE,CAAC,CAAC;QACxG,CAAC;QACD,OAAO,MAAM,CAAC,IAAI,CAAC;IACrB,CAAC;IAED;;;OAGG;IACO,KAAK,CAAC,SAAS,CACvB,KAA+C,EAC/C,YAAsD;QAEtD,OAAO,qBAAqB,CAAC,KAAK,EAAE,YAAY,EAAE,WAAW,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IACzF,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\n\nimport { createStructuredModel } from \"../shared/agent/model.config.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\nimport type { UserNegotiationContext, SeedAssessment } from \"../shared/schemas/negotiation-state.schema.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport { renderNegotiatorMemorySection, type NegotiatorMemoryEntry } from \"./negotiation.memory.js\";\n\nconst screenLog = protocolLogger(\"NegotiationScreener\");\n\n/**\n * Screen-gate modes (P2.1 — client-advocate protocol).\n *\n * - `off` — the screen node is skipped entirely; no LLM call, no telemetry.\n * - `shadow` — the screen decision is made and recorded (task metadata +\n * trace event + log line) but NEVER blocks: every fresh negotiation still\n * proceeds to the first turn. Used to measure pass rates against observed\n * reject rates before enforcement.\n * - `enforce` — reserved for P2.2. Until enforcement lands, `enforce` runs\n * identically to `shadow` (decision recorded, negotiation proceeds) and the\n * screen node logs a warning that enforcement is not yet implemented.\n */\nexport const NEGOTIATION_SCREEN_MODES = [\"off\", \"shadow\", \"enforce\"] as const;\n\nexport type NegotiationScreenMode = (typeof NEGOTIATION_SCREEN_MODES)[number];\n\n/**\n * Resolve the screen mode from `NEGOTIATION_SCREEN_MODE`.\n *\n * Defaults to `off` when unset or unrecognized — the screen gate is an\n * explicit opt-in flip (same operational pattern as\n * `NEGOTIATION_PROTOCOL_VERSION` / `NEGOTIATOR_CHAT_ENABLED`): code ships\n * inert, the environment turns it on.\n */\nexport function configuredScreenMode(): NegotiationScreenMode {\n const raw = process.env.NEGOTIATION_SCREEN_MODE;\n if (raw === \"shadow\" || raw === \"enforce\" || raw === \"off\") return raw;\n return \"off\";\n}\n\n/**\n * Structured screen decision — the outreach gate's verdict on whether this\n * match is worth the client's name before any turn is exchanged.\n */\nexport const ScreenDecisionSchema = z.object({\n decision: z.enum([\"reach_out\", \"pass\"]),\n reasoning: z.string(),\n /** Suggested opening angle for the outreach turn (only when reaching out). */\n outreachAngle: z.string().nullable().optional(),\n evidence: z.object({\n /** How well the counterparty's context/premises fit the client's need. */\n counterpartyPremiseFit: z.string(),\n /** How the client's intents align with what the counterparty seeks. */\n intentAlignment: z.string(),\n /** Prior-negotiation memory signals (P5.3). Filled only when negotiator memory was injected into the screen prompt. */\n memoryHints: z.string().nullable().optional(),\n }),\n});\n\nexport type ScreenDecision = z.infer<typeof ScreenDecisionSchema>;\n\n/**\n * The record persisted to `tasks.metadata.screenDecision` and returned into\n * graph state. Extends the LLM decision with operational context so pass-rate\n * queries can group by mode and exclude failed-open rows.\n */\nexport interface ScreenDecisionRecord extends ScreenDecision {\n mode: NegotiationScreenMode;\n /** True when the screen LLM call failed and the gate defaulted open. */\n failedOpen?: boolean;\n /** Error message when `failedOpen` is set. */\n error?: string;\n screenedAt: string;\n durationMs: number;\n}\n\nexport interface NegotiationScreenerInput {\n /** The client — the user whose negotiator is deciding whether to reach out. */\n clientUser: UserNegotiationContext;\n /** The counterparty the client's negotiator would be reaching out to. */\n counterpartyUser: UserNegotiationContext;\n /** The counterparty's `user_contexts` paragraph (empty string when absent). */\n counterpartyContext?: string;\n /** The explicit search query that triggered discovery (if any). */\n discoveryQuery?: string;\n seedAssessment: Omit<SeedAssessment, \"actors\">;\n indexContext: { networkId: string; prompt?: string };\n /**\n * Retrieved negotiator memories for the client (P5.3 read path). Rendered\n * as a private prompt section with a memoryHints instruction. Absent/empty\n * → the prompt is byte-identical to before.\n */\n memory?: NegotiatorMemoryEntry[];\n}\n\nconst SYSTEM_PROMPT = `You are the outreach gate for {clientName}'s negotiator agent on a discovery network. Before any negotiation turn is exchanged, you decide whether this match is worth reaching out to on {clientName}'s behalf — their name and attention are spent with every outreach.\n\nNetwork context: {networkContext}\n\nDecide:\n- \"reach_out\" when the counterparty plausibly serves {clientName}'s stated needs and a concrete, honest opening case can be made. When reaching out, set outreachAngle to the strongest specific angle for the opening message.\n- \"pass\" when the match is generic, one-sided, or rests on vague overlap that would waste both parties' attention.\n\nRules:\n{queryRule}\n- Judge concrete intent alignment, not topical adjacency.\n- Fill evidence.counterpartyPremiseFit with what (if anything) in the counterparty's context actually fits, and evidence.intentAlignment with how the intents line up. Be specific; cite the strongest signal either way.\n- Do NOT reference internal system details like scores, pre-screens, or evaluator outputs in reasoning that could be shown to users.{negotiatorMemory}`;\n\nconst QUERY_RULE = `- {clientName} explicitly searched for \"{discoveryQuery}\". This query is the PRIMARY criterion: if the counterparty does not satisfy it, pass — background intents cannot rescue a query mismatch.`;\nconst NO_QUERY_RULE = `- No explicit search query: judge against {clientName}'s active intents.`;\n\nconst DEFAULT_SCREEN_TIMEOUT_MS = 15_000;\n\nexport interface NegotiationScreenerConfig {\n /** Hard ceiling on the screen LLM round-trip, in ms (default 15000). */\n timeoutMs?: number;\n}\n\n/**\n * The outreach gate (P2.1). One structured LLM call deciding\n * `reach_out | pass` for a fresh negotiation, from the reaching client's\n * perspective. Throws on LLM/validation failure — the screen graph node owns\n * the fail-open policy (a failed screen never blocks the negotiation).\n */\nexport class NegotiationScreener {\n private readonly timeoutMs: number;\n\n constructor(config?: NegotiationScreenerConfig) {\n this.timeoutMs = config?.timeoutMs && Number.isFinite(config.timeoutMs) && config.timeoutMs > 0\n ? config.timeoutMs\n : DEFAULT_SCREEN_TIMEOUT_MS;\n }\n\n /**\n * Produce a screen decision for a fresh match.\n * @throws When the LLM call times out or returns schema-invalid output.\n */\n async invoke(input: NegotiationScreenerInput): Promise<ScreenDecision> {\n const model = createStructuredModel(\"negotiationScreener\", ScreenDecisionSchema, { name: \"negotiation_screener\" });\n\n const clientName = input.clientUser.profile.name ?? \"your client\";\n const counterpartyName = input.counterpartyUser.profile.name ?? \"the counterparty\";\n const networkContext = input.indexContext.prompt || \"General discovery\";\n const queryRule = (input.discoveryQuery ? QUERY_RULE : NO_QUERY_RULE)\n .replace(/{clientName}/g, clientName)\n .replace(/{discoveryQuery}/g, input.discoveryQuery ?? \"\");\n\n const systemPrompt = SYSTEM_PROMPT\n .replace(/{clientName}/g, clientName)\n .replace(\"{networkContext}\", networkContext)\n .replace(\"{queryRule}\", queryRule)\n .replace(\"{negotiatorMemory}\", renderNegotiatorMemorySection(input.memory ?? [], { memoryHintsInstruction: true }));\n\n const formatIntents = (intents: UserNegotiationContext[\"intents\"]): string =>\n intents.length > 0 ? intents.map((i) => `- ${i.title}: ${i.description}`).join(\"\\n\") : \"- (none)\";\n\n const userMessage = `YOUR CLIENT (${clientName}):\nBio: ${input.clientUser.profile.bio ?? \"N/A\"}\n${input.discoveryQuery ? `Search query: \"${input.discoveryQuery}\"\\nBackground intents (secondary to the query):` : \"Active intents:\"}\n${formatIntents(input.clientUser.intents)}\n\nCOUNTERPARTY (${counterpartyName}):\nBio: ${input.counterpartyUser.profile.bio ?? \"N/A\"}\n${input.counterpartyContext ? `Context: ${input.counterpartyContext}\\n` : \"\"}Active intents:\n${formatIntents(input.counterpartyUser.intents)}\n\nWhy this match was suggested: ${input.seedAssessment.reasoning}\n\nDecide whether reaching out serves ${clientName}.`;\n\n const chatMessages = [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: userMessage },\n ];\n\n const result = await this.callModel(model, chatMessages);\n const parsed = ScreenDecisionSchema.safeParse(result);\n if (!parsed.success) {\n screenLog.warn(\"Screen output failed schema validation\", {\n issues: parsed.error.issues.map((i) => i.message).slice(0, 3),\n });\n throw new Error(`Screen decision failed validation: ${parsed.error.issues[0]?.message ?? \"unknown\"}`);\n }\n return parsed.data;\n }\n\n /**\n * Raw structured-model round trip. Split out as a seam so tests can drive\n * the schema-validation and fail-open paths without a live provider.\n */\n protected async callModel(\n model: ReturnType<typeof createStructuredModel>,\n chatMessages: Array<{ role: string; content: string }>,\n ): Promise<unknown> {\n return invokeWithAbortSignal(model, chatMessages, AbortSignal.timeout(this.timeoutMs));\n }\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import type { NegotiationUserAnswer } from "../shared/interfaces/database.interface.js";
3
3
  import type { ScreenDecisionRecord } from "./negotiation.screen.js";
4
+ import type { NegotiatorMemoryEntry } from "./negotiation.memory.js";
4
5
  import { type NegotiationProtocolVersion } from "../shared/schemas/negotiation-state.schema.js";
5
6
  /**
6
7
  * Zod schema for a single negotiation turn (DataPart payload in A2A message).
@@ -311,6 +312,14 @@ export declare const NegotiationGraphState: import("@langchain/langgraph").Annot
311
312
  * node runs. Mirrors `tasks.metadata.screenDecision`.
312
313
  */
313
314
  screenDecision: import("@langchain/langgraph").BaseChannel<ScreenDecisionRecord | null, ScreenDecisionRecord | import("@langchain/langgraph").OverwriteValue<ScreenDecisionRecord | null> | null, unknown>;
315
+ /**
316
+ * Per-side negotiator-memory cache (P5.3 read path). Populated lazily the
317
+ * first time each side's memory is retrieved (screen node for the client,
318
+ * turn node for the speaker) so a multi-turn session pays for retrieval at
319
+ * most once per side. `undefined` per side = not yet retrieved; `[]` =
320
+ * retrieved and empty (flag off / no rows / retrieval failed).
321
+ */
322
+ memoryBySide: import("@langchain/langgraph").BaseChannel<Partial<Record<"source" | "candidate", NegotiatorMemoryEntry[]>>, Partial<Record<"source" | "candidate", NegotiatorMemoryEntry[]>> | import("@langchain/langgraph").OverwriteValue<Partial<Record<"source" | "candidate", NegotiatorMemoryEntry[]>>>, unknown>;
314
323
  /** Whether this run is continuing a prior conversation with the same pair. */
315
324
  isContinuation: import("@langchain/langgraph").BaseChannel<boolean, boolean | import("@langchain/langgraph").OverwriteValue<boolean>, unknown>;
316
325
  opportunityId: import("@langchain/langgraph").BaseChannel<string, string | import("@langchain/langgraph").OverwriteValue<string>, 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,qBAAqB,EAAE,MAAM,4CAA4C,CAAC;AACxF,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AACpE,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;AAE1E,kDAAkD;AAClD,MAAM,WAAW,sBAAsB;IACrC,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,KAAK,CAAC;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM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
107
107
  }),
108
+ /**
109
+ * Per-side negotiator-memory cache (P5.3 read path). Populated lazily the
110
+ * first time each side's memory is retrieved (screen node for the client,
111
+ * turn node for the speaker) so a multi-turn session pays for retrieval at
112
+ * most once per side. `undefined` per side = not yet retrieved; `[]` =
113
+ * retrieved and empty (flag off / no rows / retrieval failed).
114
+ */
115
+ memoryBySide: Annotation({
116
+ reducer: (curr, next) => ({ ...curr, ...next }),
117
+ default: () => ({}),
118
+ }),
108
119
  /** Whether this run is continuing a prior conversation with the same pair. */
109
120
  isContinuation: Annotation({
110
121
  reducer: (curr, next) => next ?? curr,