@indexnetwork/protocol 4.3.2 → 4.3.4-rc.309.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chat/chat.agent.d.ts.map +1 -1
- package/dist/chat/chat.agent.js +11 -1
- package/dist/chat/chat.agent.js.map +1 -1
- package/dist/chat/chat.graph.d.ts +16 -0
- package/dist/chat/chat.graph.d.ts.map +1 -1
- package/dist/chat/chat.graph.js +5 -2
- package/dist/chat/chat.graph.js.map +1 -1
- package/dist/chat/chat.prompt.d.ts.map +1 -1
- package/dist/chat/chat.prompt.js +20 -13
- package/dist/chat/chat.prompt.js.map +1 -1
- package/dist/chat/chat.state.d.ts +6 -3
- package/dist/chat/chat.state.d.ts.map +1 -1
- package/dist/chat/chat.state.js +12 -3
- package/dist/chat/chat.state.js.map +1 -1
- package/dist/chat/chat.streamer.d.ts +5 -0
- package/dist/chat/chat.streamer.d.ts.map +1 -1
- package/dist/chat/chat.streamer.js +13 -4
- package/dist/chat/chat.streamer.js.map +1 -1
- package/dist/enrichment/enrichment.tools.d.ts.map +1 -1
- package/dist/enrichment/enrichment.tools.js +16 -19
- package/dist/enrichment/enrichment.tools.js.map +1 -1
- package/dist/index.d.ts +5 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/intent/intent.graph.d.ts +10 -0
- package/dist/intent/intent.graph.d.ts.map +1 -1
- package/dist/intent/intent.graph.js +6 -2
- package/dist/intent/intent.graph.js.map +1 -1
- package/dist/intent/intent.state.d.ts +5 -1
- package/dist/intent/intent.state.d.ts.map +1 -1
- package/dist/intent/intent.state.js +11 -1
- package/dist/intent/intent.state.js.map +1 -1
- package/dist/intent/intent.tools.d.ts.map +1 -1
- package/dist/intent/intent.tools.js +63 -39
- package/dist/intent/intent.tools.js.map +1 -1
- package/dist/mcp/mcp.server.d.ts +45 -18
- package/dist/mcp/mcp.server.d.ts.map +1 -1
- package/dist/mcp/mcp.server.js +86 -45
- package/dist/mcp/mcp.server.js.map +1 -1
- package/dist/negotiation/negotiation.tools.d.ts.map +1 -1
- package/dist/negotiation/negotiation.tools.js +11 -7
- package/dist/negotiation/negotiation.tools.js.map +1 -1
- package/dist/network/network.graph.js +2 -2
- package/dist/network/network.graph.js.map +1 -1
- package/dist/network/network.tools.d.ts.map +1 -1
- package/dist/network/network.tools.js +50 -38
- package/dist/network/network.tools.js.map +1 -1
- package/dist/opportunity/opportunity.discover.d.ts +5 -0
- package/dist/opportunity/opportunity.discover.d.ts.map +1 -1
- package/dist/opportunity/opportunity.discover.js +3 -0
- package/dist/opportunity/opportunity.discover.js.map +1 -1
- package/dist/opportunity/opportunity.graph.d.ts +6 -6
- package/dist/opportunity/opportunity.graph.js +1 -1
- package/dist/opportunity/opportunity.graph.js.map +1 -1
- package/dist/opportunity/opportunity.pending-questions.d.ts +3 -0
- package/dist/opportunity/opportunity.pending-questions.d.ts.map +1 -1
- package/dist/opportunity/opportunity.pending-questions.js +7 -2
- package/dist/opportunity/opportunity.pending-questions.js.map +1 -1
- package/dist/opportunity/opportunity.state.d.ts +1 -1
- package/dist/opportunity/opportunity.tools.d.ts.map +1 -1
- package/dist/opportunity/opportunity.tools.js +46 -36
- package/dist/opportunity/opportunity.tools.js.map +1 -1
- package/dist/premise/premise.graph.d.ts +13 -1
- package/dist/premise/premise.graph.d.ts.map +1 -1
- package/dist/premise/premise.graph.js +11 -6
- package/dist/premise/premise.graph.js.map +1 -1
- package/dist/premise/premise.state.d.ts +5 -0
- package/dist/premise/premise.state.d.ts.map +1 -1
- package/dist/premise/premise.state.js +11 -0
- package/dist/premise/premise.state.js.map +1 -1
- package/dist/premise/premise.tools.d.ts.map +1 -1
- package/dist/premise/premise.tools.js +5 -0
- package/dist/premise/premise.tools.js.map +1 -1
- package/dist/questioner/questioner.tools.d.ts +1 -1
- package/dist/questioner/questioner.tools.d.ts.map +1 -1
- package/dist/questioner/questioner.tools.js +24 -13
- package/dist/questioner/questioner.tools.js.map +1 -1
- package/dist/questioner/questioner.types.d.ts +5 -0
- package/dist/questioner/questioner.types.d.ts.map +1 -1
- package/dist/questioner/questioner.types.js.map +1 -1
- package/dist/shared/agent/tool.factory.d.ts.map +1 -1
- package/dist/shared/agent/tool.factory.js +25 -16
- package/dist/shared/agent/tool.factory.js.map +1 -1
- package/dist/shared/agent/tool.helpers.d.ts +17 -18
- package/dist/shared/agent/tool.helpers.d.ts.map +1 -1
- package/dist/shared/agent/tool.helpers.js +10 -11
- package/dist/shared/agent/tool.helpers.js.map +1 -1
- package/dist/shared/agent/tool.registry.js +1 -1
- package/dist/shared/agent/tool.registry.js.map +1 -1
- package/dist/shared/agent/tool.scope.d.ts +39 -0
- package/dist/shared/agent/tool.scope.d.ts.map +1 -0
- package/dist/shared/agent/tool.scope.js +41 -0
- package/dist/shared/agent/tool.scope.js.map +1 -0
- package/dist/shared/assignment/network-assignment.policy.d.ts +8 -5
- package/dist/shared/assignment/network-assignment.policy.d.ts.map +1 -1
- package/dist/shared/assignment/network-assignment.policy.js +11 -6
- package/dist/shared/assignment/network-assignment.policy.js.map +1 -1
- package/dist/shared/hyde/hyde.graph.d.ts +6 -6
- package/dist/shared/hyde/hyde.state.d.ts +2 -2
- package/dist/shared/interfaces/auth.interface.d.ts +3 -3
- package/dist/shared/interfaces/auth.interface.js.map +1 -1
- package/dist/shared/interfaces/database.interface.d.ts +15 -3
- package/dist/shared/interfaces/database.interface.d.ts.map +1 -1
- package/dist/shared/interfaces/database.interface.js.map +1 -1
- package/dist/shared/interfaces/discovery-run.interface.d.ts +1 -1
- package/dist/shared/interfaces/discovery-run.interface.d.ts.map +1 -1
- package/dist/shared/interfaces/discovery-run.interface.js.map +1 -1
- package/dist/shared/interfaces/enrichment-run.interface.d.ts +1 -1
- package/dist/shared/interfaces/enrichment-run.interface.d.ts.map +1 -1
- package/dist/shared/interfaces/enrichment-run.interface.js.map +1 -1
- package/dist/shared/interfaces/queue.interface.d.ts +8 -2
- package/dist/shared/interfaces/queue.interface.d.ts.map +1 -1
- package/dist/shared/interfaces/queue.interface.js.map +1 -1
- package/dist/shared/schemas/network-assignment.schema.d.ts +2 -2
- package/dist/shared/schemas/pending-question.schema.d.ts +5 -0
- package/dist/shared/schemas/pending-question.schema.d.ts.map +1 -1
- package/dist/shared/schemas/pending-question.schema.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { PremiseAnalyzerOutput } from "./premise.analyzer.js";
|
|
1
2
|
import { PremiseIndexer } from "./premise.indexer.js";
|
|
2
3
|
import type { PremiseGraphDatabase, PremiseAnalysis } from "../shared/interfaces/database.interface.js";
|
|
3
4
|
import type { Embedder } from "../shared/interfaces/embedder.interface.js";
|
|
@@ -9,7 +10,10 @@ export declare class PremiseGraphFactory {
|
|
|
9
10
|
private database;
|
|
10
11
|
private embedder;
|
|
11
12
|
private premiseIndexer;
|
|
12
|
-
|
|
13
|
+
private premiseAnalyzer;
|
|
14
|
+
constructor(database: PremiseGraphDatabase, embedder: Embedder, premiseIndexer?: PremiseIndexer, premiseAnalyzer?: {
|
|
15
|
+
invoke(premiseText: string, profileContext?: string): Promise<PremiseAnalyzerOutput>;
|
|
16
|
+
});
|
|
13
17
|
/**
|
|
14
18
|
* Compiles and returns the premise lifecycle graph.
|
|
15
19
|
*
|
|
@@ -26,6 +30,8 @@ export declare class PremiseGraphFactory {
|
|
|
26
30
|
provenanceSourceId: string | undefined;
|
|
27
31
|
provenanceConfidence: number | undefined;
|
|
28
32
|
operationMode: "query" | "update" | "create";
|
|
33
|
+
scopeType: "network" | undefined;
|
|
34
|
+
scopeId: string | undefined;
|
|
29
35
|
networkScopeId: string | undefined;
|
|
30
36
|
targetPremiseId: string | undefined;
|
|
31
37
|
analysis: PremiseAnalysis | undefined;
|
|
@@ -58,6 +64,8 @@ export declare class PremiseGraphFactory {
|
|
|
58
64
|
provenanceSourceId?: string | import("@langchain/langgraph").OverwriteValue<string | undefined> | undefined;
|
|
59
65
|
provenanceConfidence?: number | import("@langchain/langgraph").OverwriteValue<number | undefined> | undefined;
|
|
60
66
|
operationMode?: "query" | "update" | "create" | import("@langchain/langgraph").OverwriteValue<"query" | "update" | "create"> | undefined;
|
|
67
|
+
scopeType?: "network" | import("@langchain/langgraph").OverwriteValue<"network" | undefined> | undefined;
|
|
68
|
+
scopeId?: string | import("@langchain/langgraph").OverwriteValue<string | undefined> | undefined;
|
|
61
69
|
networkScopeId?: string | import("@langchain/langgraph").OverwriteValue<string | undefined> | undefined;
|
|
62
70
|
targetPremiseId?: string | import("@langchain/langgraph").OverwriteValue<string | undefined> | undefined;
|
|
63
71
|
analysis?: PremiseAnalysis | import("@langchain/langgraph").OverwriteValue<PremiseAnalysis | undefined> | undefined;
|
|
@@ -105,6 +113,8 @@ export declare class PremiseGraphFactory {
|
|
|
105
113
|
provenanceSourceId: import("@langchain/langgraph").BaseChannel<string | undefined, string | import("@langchain/langgraph").OverwriteValue<string | undefined> | undefined, unknown>;
|
|
106
114
|
provenanceConfidence: import("@langchain/langgraph").BaseChannel<number | undefined, number | import("@langchain/langgraph").OverwriteValue<number | undefined> | undefined, unknown>;
|
|
107
115
|
operationMode: import("@langchain/langgraph").BaseChannel<"query" | "update" | "create", "query" | "update" | "create" | import("@langchain/langgraph").OverwriteValue<"query" | "update" | "create">, unknown>;
|
|
116
|
+
scopeType: import("@langchain/langgraph").BaseChannel<"network" | undefined, "network" | import("@langchain/langgraph").OverwriteValue<"network" | undefined> | undefined, unknown>;
|
|
117
|
+
scopeId: import("@langchain/langgraph").BaseChannel<string | undefined, string | import("@langchain/langgraph").OverwriteValue<string | undefined> | undefined, unknown>;
|
|
108
118
|
networkScopeId: import("@langchain/langgraph").BaseChannel<string | undefined, string | import("@langchain/langgraph").OverwriteValue<string | undefined> | undefined, unknown>;
|
|
109
119
|
targetPremiseId: import("@langchain/langgraph").BaseChannel<string | undefined, string | import("@langchain/langgraph").OverwriteValue<string | undefined> | undefined, unknown>;
|
|
110
120
|
analysis: import("@langchain/langgraph").BaseChannel<PremiseAnalysis | undefined, PremiseAnalysis | import("@langchain/langgraph").OverwriteValue<PremiseAnalysis | undefined> | undefined, unknown>;
|
|
@@ -163,6 +173,8 @@ export declare class PremiseGraphFactory {
|
|
|
163
173
|
provenanceSourceId: import("@langchain/langgraph").BaseChannel<string | undefined, string | import("@langchain/langgraph").OverwriteValue<string | undefined> | undefined, unknown>;
|
|
164
174
|
provenanceConfidence: import("@langchain/langgraph").BaseChannel<number | undefined, number | import("@langchain/langgraph").OverwriteValue<number | undefined> | undefined, unknown>;
|
|
165
175
|
operationMode: import("@langchain/langgraph").BaseChannel<"query" | "update" | "create", "query" | "update" | "create" | import("@langchain/langgraph").OverwriteValue<"query" | "update" | "create">, unknown>;
|
|
176
|
+
scopeType: import("@langchain/langgraph").BaseChannel<"network" | undefined, "network" | import("@langchain/langgraph").OverwriteValue<"network" | undefined> | undefined, unknown>;
|
|
177
|
+
scopeId: import("@langchain/langgraph").BaseChannel<string | undefined, string | import("@langchain/langgraph").OverwriteValue<string | undefined> | undefined, unknown>;
|
|
166
178
|
networkScopeId: import("@langchain/langgraph").BaseChannel<string | undefined, string | import("@langchain/langgraph").OverwriteValue<string | undefined> | undefined, unknown>;
|
|
167
179
|
targetPremiseId: import("@langchain/langgraph").BaseChannel<string | undefined, string | import("@langchain/langgraph").OverwriteValue<string | undefined> | undefined, unknown>;
|
|
168
180
|
analysis: import("@langchain/langgraph").BaseChannel<PremiseAnalysis | undefined, PremiseAnalysis | import("@langchain/langgraph").OverwriteValue<PremiseAnalysis | undefined> | undefined, unknown>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"premise.graph.d.ts","sourceRoot":"/","sources":["premise/premise.graph.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;
|
|
1
|
+
{"version":3,"file":"premise.graph.d.ts","sourceRoot":"/","sources":["premise/premise.graph.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AACnE,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAKtD,OAAO,KAAK,EAAE,oBAAoB,EAAE,eAAe,EAAE,MAAM,4CAA4C,CAAC;AACxG,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,4CAA4C,CAAC;AAG3E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AA6BtE;;GAEG;AACH,qBAAa,mBAAmB;IAE5B,OAAO,CAAC,QAAQ;IAChB,OAAO,CAAC,QAAQ;IAChB,OAAO,CAAC,cAAc;IACtB,OAAO,CAAC,eAAe;gBAHf,QAAQ,EAAE,oBAAoB,EAC9B,QAAQ,EAAE,QAAQ,EAClB,cAAc,GAAE,cAAqC,EACrD,eAAe,GAAE;QAAE,MAAM,CAAC,WAAW,EAAE,MAAM,EAAE,cAAc,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,qBAAqB,CAAC,CAAA;KAA0B;IAG3I;;;;OAIG;IACI,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2BAmK0B,MAAM;gCAAkB,MAAM;;;;;CA6F3E"}
|
|
@@ -4,6 +4,7 @@ import { PremiseAnalyzer } from "./premise.analyzer.js";
|
|
|
4
4
|
import { PremiseIndexer } from "./premise.indexer.js";
|
|
5
5
|
import { buildNetworkAssignmentDecision, resolveAssignmentNetworkScope } from "../shared/assignment/network-assignment.policy.js";
|
|
6
6
|
import { getAbortSignalConfig } from "../shared/agent/model-signal.js";
|
|
7
|
+
import { scopeFromNetworkId } from "../shared/agent/tool.scope.js";
|
|
7
8
|
import { protocolLogger } from "../shared/observability/protocol.logger.js";
|
|
8
9
|
import { timed } from "../shared/observability/performance.js";
|
|
9
10
|
const logger = protocolLogger("PremiseGraphFactory");
|
|
@@ -36,10 +37,11 @@ function deriveProvenanceConfidence(analysis) {
|
|
|
36
37
|
* Graph factory for premise lifecycle: create, update, and query modes.
|
|
37
38
|
*/
|
|
38
39
|
export class PremiseGraphFactory {
|
|
39
|
-
constructor(database, embedder, premiseIndexer = new PremiseIndexer()) {
|
|
40
|
+
constructor(database, embedder, premiseIndexer = new PremiseIndexer(), premiseAnalyzer = new PremiseAnalyzer()) {
|
|
40
41
|
this.database = database;
|
|
41
42
|
this.embedder = embedder;
|
|
42
43
|
this.premiseIndexer = premiseIndexer;
|
|
44
|
+
this.premiseAnalyzer = premiseAnalyzer;
|
|
43
45
|
}
|
|
44
46
|
/**
|
|
45
47
|
* Compiles and returns the premise lifecycle graph.
|
|
@@ -47,7 +49,7 @@ export class PremiseGraphFactory {
|
|
|
47
49
|
* @returns A compiled LangGraph graph handling create, update, and query modes.
|
|
48
50
|
*/
|
|
49
51
|
createGraph() {
|
|
50
|
-
const analyzer =
|
|
52
|
+
const analyzer = this.premiseAnalyzer;
|
|
51
53
|
const indexer = this.premiseIndexer;
|
|
52
54
|
const queryNode = async (state) => {
|
|
53
55
|
return timed("PremiseGraph.query", async () => {
|
|
@@ -183,12 +185,15 @@ export class PremiseGraphFactory {
|
|
|
183
185
|
if (!state.premise)
|
|
184
186
|
return {};
|
|
185
187
|
logger.verbose(`[PremiseGraph.index] Scoring premise against user networks`);
|
|
186
|
-
const
|
|
188
|
+
const assignmentMemberships = await this.database.getAssignmentNetworkMembershipsForUser(state.userId);
|
|
189
|
+
const requestScope = state.scopeType && state.scopeId
|
|
190
|
+
? { scopeType: state.scopeType, scopeId: state.scopeId }
|
|
191
|
+
: scopeFromNetworkId(state.networkScopeId);
|
|
187
192
|
const indexIds = resolveAssignmentNetworkScope({
|
|
188
|
-
memberships:
|
|
189
|
-
|
|
193
|
+
memberships: assignmentMemberships,
|
|
194
|
+
...requestScope,
|
|
190
195
|
});
|
|
191
|
-
const scope =
|
|
196
|
+
const scope = requestScope.scopeType ? "network" : "global";
|
|
192
197
|
const assignments = [];
|
|
193
198
|
const agentTimings = [];
|
|
194
199
|
for (const networkId of indexIds) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"premise.graph.js","sourceRoot":"/","sources":["premise/premise.graph.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAE9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAEtD,OAAO,EAAE,8BAA8B,EAAE,6BAA6B,EAAE,MAAM,mDAAmD,CAAC;AAClI,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AAGvE,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAG/D,MAAM,MAAM,GAAG,cAAc,CAAC,qBAAqB,CAAC,CAAC;AAErD;;;;;;GAMG;AACH,MAAM,0BAA0B,GAAG,CAAC,GAAG,EAAE;IACvC,MAAM,GAAG,GAAG,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC;IACzD,OAAO,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC;AAClE,CAAC,CAAC,EAAE,CAAC;AAEL;;;;GAIG;AACH,SAAS,0BAA0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AAC;QACnB,CAAC,CAAC;QAEF,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,iBAAiB,CAAC;aAC5C,OAAO,CAAC,OAAO,EAAE,SAAS,CAAC;aAC3B,OAAO,CAAC,SAAS,EAAE,WAAW,CAAC;aAC/B,OAAO,CAAC,OAAO,EAAE,SAAS,CAAC;aAC3B,OAAO,CAAC,QAAQ,EAAE,UAAU,CAAC;aAC7B,OAAO,CAAC,SAAS,EAAE,WAAW,CAAC;aAC/B,OAAO,CAAC,OAAO,EAAE,SAAS,CAAC;aAC3B,mBAAmB,CAAC,KAAK,EAAE,WAAW,EAAE;YACvC,KAAK,EAAE,OAAO;YACd,OAAO,EAAE,SAAS;YAClB,GAAG,EAAE,GAAG;SACT,CAAC;aACD,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC;aACrB,OAAO,CAAC,SAAS,EAAE,OAAO,CAAC;aAC3B,OAAO,CAAC,OAAO,EAAE,QAAQ,CAAC;YAC3B,0EAA0E;aACzE,mBAAmB,CAAC,QAAQ,EAAE,CAAC,KAAqC,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,EAAE;YACjH,OAAO,EAAE,SAAS;YAClB,GAAG,EAAE,GAAG;SACT,CAAC;aACD,OAAO,CAAC,SAAS,EAAE,OAAO,CAAC;aAC3B,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;QAEzB,OAAO,KAAK,CAAC,OAAO,EAAE,CAAC;IACzB,CAAC;CACF","sourcesContent":["import { StateGraph, START, END } from \"@langchain/langgraph\";\n\nimport { PremiseGraphState } from \"./premise.state.js\";\nimport { PremiseAnalyzer } from \"./premise.analyzer.js\";\nimport { PremiseIndexer } from \"./premise.indexer.js\";\n\nimport { buildNetworkAssignmentDecision, resolveAssignmentNetworkScope } from \"../shared/assignment/network-assignment.policy.js\";\nimport { getAbortSignalConfig } from \"../shared/agent/model-signal.js\";\nimport type { PremiseGraphDatabase, PremiseAnalysis } from \"../shared/interfaces/database.interface.js\";\nimport type { Embedder } from \"../shared/interfaces/embedder.interface.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport { timed } from \"../shared/observability/performance.js\";\nimport type { DebugMetaAgent } from \"../chat/chat-streaming.types.js\";\n\nconst logger = protocolLogger(\"PremiseGraphFactory\");\n\n/**\n * Minimum cosine similarity (0-1) at which a freshly-decomposed premise is treated\n * as a near-duplicate of an existing ACTIVE premise for the same user and skipped\n * on create. Tuned high so genuine paraphrases collapse while distinct facts (e.g.\n * \"I work at Google\" vs \"I worked at Google\") still persist. Override with\n * PREMISE_DEDUP_SIMILARITY.\n */\nconst DEDUP_SIMILARITY_THRESHOLD = (() => {\n const raw = Number(process.env.PREMISE_DEDUP_SIMILARITY);\n return Number.isFinite(raw) && raw > 0 && raw <= 1 ? raw : 0.93;\n})();\n\n/**\n * Derive a premise provenance confidence (0-1) from the analyzer's felicity scores.\n * Averages authority, sincerity, and clarity — the dimensions that speak to how\n * trustworthy the self-assertion is. Falls back to 1.0 when no analysis is present.\n */\nfunction deriveProvenanceConfidence(analysis: PremiseAnalysis | undefined): number {\n if (!analysis) return 1.0;\n const { felicityAuthority, felicitySincerity, felicityClarity } = analysis;\n const mean = (felicityAuthority + felicitySincerity + felicityClarity) / 3;\n if (!Number.isFinite(mean)) return 1.0;\n return Math.min(1, Math.max(0, mean));\n}\n\n/**\n * Graph factory for premise lifecycle: create, update, and query modes.\n */\nexport class PremiseGraphFactory {\n constructor(\n private database: PremiseGraphDatabase,\n private embedder: Embedder,\n private premiseIndexer: PremiseIndexer = new PremiseIndexer(),\n ) {}\n\n /**\n * Compiles and returns the premise lifecycle graph.\n *\n * @returns A compiled LangGraph graph handling create, update, and query modes.\n */\n public createGraph() {\n const analyzer = new PremiseAnalyzer();\n const indexer = this.premiseIndexer;\n\n const queryNode = async (state: typeof PremiseGraphState.State) => {\n return timed(\"PremiseGraph.query\", async () => {\n logger.verbose(`[PremiseGraph.query] Fetching premises for user ${state.userId}`);\n const premises = await this.database.getPremisesForUser(state.userId, 'ACTIVE');\n return {\n readResult: {\n premises,\n count: premises.length,\n },\n };\n });\n };\n\n const analyzeNode = async (state: typeof PremiseGraphState.State) => {\n return timed(\"PremiseGraph.analyze\", async () => {\n if (!state.assertionText) {\n return { error: \"assertionText is required for create/update mode\" };\n }\n\n logger.verbose(`[PremiseGraph.analyze] Analyzing: \"${state.assertionText.substring(0, 50)}...\"`);\n\n const start = Date.now();\n const result = await analyzer.invoke(state.assertionText);\n const timing: DebugMetaAgent = {\n name: \"premise-analyzer\",\n durationMs: Date.now() - start,\n };\n\n const analysis: PremiseAnalysis = {\n speechActType: result.speechActType,\n felicityAuthority: result.felicityAuthority,\n felicitySincerity: result.felicitySincerity,\n felicityClarity: result.felicityClarity,\n semanticEntropy: result.semanticEntropy,\n };\n\n return { analysis, agentTimings: [timing] };\n });\n };\n\n const embedNode = async (state: typeof PremiseGraphState.State) => {\n return timed(\"PremiseGraph.embed\", async () => {\n if (state.error) return {};\n\n if (!state.assertionText) {\n return { error: \"assertionText is required for embedding\" };\n }\n\n logger.verbose(`[PremiseGraph.embed] Generating embedding for premise`);\n\n // Embedder.generate returns number[] | number[][], cast for single string input\n const embedding = await this.embedder.generate(state.assertionText, undefined, getAbortSignalConfig()) as number[];\n return { embedding };\n });\n };\n\n // ─────────────────────────────────────────────────────────\n // NODE: Dedupe (create mode only)\n // Skips persisting a near-duplicate of an existing ACTIVE premise for the same\n // user. Re-running similar input (e.g. repeated enrichment) therefore does not\n // accumulate near-identical premises. No-op for update mode, when no embedding\n // is available, or when the adapter does not implement findSimilarActivePremise.\n // ─────────────────────────────────────────────────────────\n const dedupeNode = async (state: typeof PremiseGraphState.State) => {\n return timed(\"PremiseGraph.dedupe\", async () => {\n if (state.error) return {};\n if (state.operationMode === 'update') return {};\n if (!state.embedding || state.embedding.length === 0) return {};\n if (typeof this.database.findSimilarActivePremise !== 'function') return {};\n\n const match = await this.database.findSimilarActivePremise({\n userId: state.userId,\n embedding: state.embedding,\n threshold: DEDUP_SIMILARITY_THRESHOLD,\n });\n\n if (match) {\n logger.verbose(\n `[PremiseGraph.dedupe] Skipping near-duplicate (similarity=${match.similarity.toFixed(3)} >= ${DEDUP_SIMILARITY_THRESHOLD}) of premise ${match.premiseId}`,\n );\n return { duplicateOf: match };\n }\n return {};\n });\n };\n\n const persistNode = async (state: typeof PremiseGraphState.State) => {\n return timed(\"PremiseGraph.persist\", async () => {\n if (state.error) return {};\n\n if (state.operationMode === 'update' && !state.targetPremiseId) {\n return { error: \"targetPremiseId is required for update mode\" };\n }\n\n if (state.operationMode === 'update' && state.targetPremiseId) {\n logger.verbose(`[PremiseGraph.persist] Updating premise ${state.targetPremiseId}`);\n\n const updated = await this.database.updatePremise(state.targetPremiseId, {\n assertion: {\n text: state.assertionText!,\n tier: state.tier,\n },\n analysis: state.analysis ?? undefined,\n validity: {\n validFrom: state.validFrom,\n validUntil: state.validUntil,\n volatile: state.volatile,\n },\n embedding: state.embedding,\n });\n return { premise: updated };\n }\n\n logger.verbose(`[PremiseGraph.persist] Creating new premise for user ${state.userId}`);\n\n // Provenance confidence: prefer an explicit caller-supplied value; otherwise\n // derive it from the analyzer's felicity scores (how authoritative, sincere,\n // and clear the assertion is) rather than a blanket 1.0, so the stored\n // provenance reflects per-premise signal quality.\n const derivedConfidence = deriveProvenanceConfidence(state.analysis);\n const premise = await this.database.createPremise({\n userId: state.userId,\n assertion: {\n text: state.assertionText!,\n tier: state.tier,\n },\n provenance: {\n source: state.provenanceSource ?? 'explicit',\n sourceId: state.provenanceSourceId,\n confidence: state.provenanceConfidence ?? derivedConfidence,\n timestamp: new Date().toISOString(),\n },\n analysis: state.analysis ?? undefined,\n validity: {\n validFrom: state.validFrom,\n validUntil: state.validUntil,\n volatile: state.volatile,\n },\n embedding: state.embedding,\n });\n return { premise };\n });\n };\n\n const indexNode = async (state: typeof PremiseGraphState.State) => {\n return timed(\"PremiseGraph.index\", async () => {\n if (!state.premise) return {};\n\n logger.verbose(`[PremiseGraph.index] Scoring premise against user networks`);\n\n const membershipNetworkIds = await this.database.getAssignmentNetworkIdsForUser(state.userId);\n const indexIds = resolveAssignmentNetworkScope({\n memberships: membershipNetworkIds,\n networkScopeId: state.networkScopeId,\n });\n const scope = state.networkScopeId ? \"network\" : \"global\";\n const assignments: Array<{ networkId: string; relevancyScore: number }> = [];\n const agentTimings: DebugMetaAgent[] = [];\n\n for (const networkId of indexIds) {\n try {\n const assignmentContext = await this.database.getNetworkAssignmentContext(networkId, state.userId);\n if (!assignmentContext) continue;\n const indexPrompt = assignmentContext.indexPrompt;\n const memberPrompt = assignmentContext.memberPrompt;\n const hasPrompts = !!indexPrompt?.trim() || !!memberPrompt?.trim();\n let rawScores: { indexScore?: number; memberScore?: number } | undefined;\n let reason: string | undefined;\n\n if (hasPrompts) {\n const start = Date.now();\n const result = await indexer.invoke({\n premiseText: state.assertionText!,\n indexPrompt: indexPrompt ?? \"\",\n memberPrompt: memberPrompt ?? undefined,\n });\n const timing: DebugMetaAgent = {\n name: \"premise-indexer\",\n durationMs: Date.now() - start,\n };\n rawScores = { indexScore: result.indexScore, memberScore: result.memberScore };\n reason = result.reasoning;\n agentTimings.push(timing);\n }\n\n const decision = buildNetworkAssignmentDecision({\n resourceType: \"premise\",\n mode: \"automatic\",\n scope,\n indexPrompt,\n memberPrompt,\n rawScores,\n evaluator: \"premise-indexer\",\n source: \"premise-graph\",\n reason,\n createdAt: new Date().toISOString(),\n });\n\n if (decision.assigned) {\n await this.database.assignPremiseToNetwork(\n state.premise.id,\n networkId,\n decision.finalScore,\n decision.metadata,\n );\n assignments.push({ networkId, relevancyScore: decision.finalScore });\n }\n } catch (err) {\n logger.verbose(`[PremiseGraph.index] Failed to score network ${networkId}, skipping: ${err}`);\n }\n }\n\n logger.verbose(`[PremiseGraph.index] Assigned to ${assignments.length} networks`);\n\n return { networkAssignments: assignments, agentTimings };\n });\n };\n\n const routeByMode = (state: typeof PremiseGraphState.State) => {\n if (state.error) return \"end\";\n if (state.operationMode === 'query') return \"query\";\n return \"analyze\";\n };\n\n const graph = new StateGraph(PremiseGraphState)\n .addNode(\"query\", queryNode)\n .addNode(\"analyze\", analyzeNode)\n .addNode(\"embed\", embedNode)\n .addNode(\"dedupe\", dedupeNode)\n .addNode(\"persist\", persistNode)\n .addNode(\"index\", indexNode)\n .addConditionalEdges(START, routeByMode, {\n query: \"query\",\n analyze: \"analyze\",\n end: END,\n })\n .addEdge(\"query\", END)\n .addEdge(\"analyze\", \"embed\")\n .addEdge(\"embed\", \"dedupe\")\n // A near-duplicate short-circuits straight to END (no persist, no index).\n .addConditionalEdges(\"dedupe\", (state: typeof PremiseGraphState.State) => (state.duplicateOf ? \"end\" : \"persist\"), {\n persist: \"persist\",\n end: END,\n })\n .addEdge(\"persist\", \"index\")\n .addEdge(\"index\", END);\n\n return graph.compile();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"premise.graph.js","sourceRoot":"/","sources":["premise/premise.graph.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAE9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExD,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAEtD,OAAO,EAAE,8BAA8B,EAAE,6BAA6B,EAAE,MAAM,mDAAmD,CAAC;AAClI,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AACvE,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAGnE,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAC5E,OAAO,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAG/D,MAAM,MAAM,GAAG,cAAc,CAAC,qBAAqB,CAAC,CAAC;AAErD;;;;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aACzE,mBAAmB,CAAC,QAAQ,EAAE,CAAC,KAAqC,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,EAAE;YACjH,OAAO,EAAE,SAAS;YAClB,GAAG,EAAE,GAAG;SACT,CAAC;aACD,OAAO,CAAC,SAAS,EAAE,OAAO,CAAC;aAC3B,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;QAEzB,OAAO,KAAK,CAAC,OAAO,EAAE,CAAC;IACzB,CAAC;CACF","sourcesContent":["import { StateGraph, START, END } from \"@langchain/langgraph\";\n\nimport { PremiseGraphState } from \"./premise.state.js\";\nimport { PremiseAnalyzer } from \"./premise.analyzer.js\";\nimport type { PremiseAnalyzerOutput } from \"./premise.analyzer.js\";\nimport { PremiseIndexer } from \"./premise.indexer.js\";\n\nimport { buildNetworkAssignmentDecision, resolveAssignmentNetworkScope } from \"../shared/assignment/network-assignment.policy.js\";\nimport { getAbortSignalConfig } from \"../shared/agent/model-signal.js\";\nimport { scopeFromNetworkId } from \"../shared/agent/tool.scope.js\";\nimport type { PremiseGraphDatabase, PremiseAnalysis } from \"../shared/interfaces/database.interface.js\";\nimport type { Embedder } from \"../shared/interfaces/embedder.interface.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport { timed } from \"../shared/observability/performance.js\";\nimport type { DebugMetaAgent } from \"../chat/chat-streaming.types.js\";\n\nconst logger = protocolLogger(\"PremiseGraphFactory\");\n\n/**\n * Minimum cosine similarity (0-1) at which a freshly-decomposed premise is treated\n * as a near-duplicate of an existing ACTIVE premise for the same user and skipped\n * on create. Tuned high so genuine paraphrases collapse while distinct facts (e.g.\n * \"I work at Google\" vs \"I worked at Google\") still persist. Override with\n * PREMISE_DEDUP_SIMILARITY.\n */\nconst DEDUP_SIMILARITY_THRESHOLD = (() => {\n const raw = Number(process.env.PREMISE_DEDUP_SIMILARITY);\n return Number.isFinite(raw) && raw > 0 && raw <= 1 ? raw : 0.93;\n})();\n\n/**\n * Derive a premise provenance confidence (0-1) from the analyzer's felicity scores.\n * Averages authority, sincerity, and clarity — the dimensions that speak to how\n * trustworthy the self-assertion is. Falls back to 1.0 when no analysis is present.\n */\nfunction deriveProvenanceConfidence(analysis: PremiseAnalysis | undefined): number {\n if (!analysis) return 1.0;\n const { felicityAuthority, felicitySincerity, felicityClarity } = analysis;\n const mean = (felicityAuthority + felicitySincerity + felicityClarity) / 3;\n if (!Number.isFinite(mean)) return 1.0;\n return Math.min(1, Math.max(0, mean));\n}\n\n/**\n * Graph factory for premise lifecycle: create, update, and query modes.\n */\nexport class PremiseGraphFactory {\n constructor(\n private database: PremiseGraphDatabase,\n private embedder: Embedder,\n private premiseIndexer: PremiseIndexer = new PremiseIndexer(),\n private premiseAnalyzer: { invoke(premiseText: string, profileContext?: string): Promise<PremiseAnalyzerOutput> } = new PremiseAnalyzer(),\n ) {}\n\n /**\n * Compiles and returns the premise lifecycle graph.\n *\n * @returns A compiled LangGraph graph handling create, update, and query modes.\n */\n public createGraph() {\n const analyzer = this.premiseAnalyzer;\n const indexer = this.premiseIndexer;\n\n const queryNode = async (state: typeof PremiseGraphState.State) => {\n return timed(\"PremiseGraph.query\", async () => {\n logger.verbose(`[PremiseGraph.query] Fetching premises for user ${state.userId}`);\n const premises = await this.database.getPremisesForUser(state.userId, 'ACTIVE');\n return {\n readResult: {\n premises,\n count: premises.length,\n },\n };\n });\n };\n\n const analyzeNode = async (state: typeof PremiseGraphState.State) => {\n return timed(\"PremiseGraph.analyze\", async () => {\n if (!state.assertionText) {\n return { error: \"assertionText is required for create/update mode\" };\n }\n\n logger.verbose(`[PremiseGraph.analyze] Analyzing: \"${state.assertionText.substring(0, 50)}...\"`);\n\n const start = Date.now();\n const result = await analyzer.invoke(state.assertionText);\n const timing: DebugMetaAgent = {\n name: \"premise-analyzer\",\n durationMs: Date.now() - start,\n };\n\n const analysis: PremiseAnalysis = {\n speechActType: result.speechActType,\n felicityAuthority: result.felicityAuthority,\n felicitySincerity: result.felicitySincerity,\n felicityClarity: result.felicityClarity,\n semanticEntropy: result.semanticEntropy,\n };\n\n return { analysis, agentTimings: [timing] };\n });\n };\n\n const embedNode = async (state: typeof PremiseGraphState.State) => {\n return timed(\"PremiseGraph.embed\", async () => {\n if (state.error) return {};\n\n if (!state.assertionText) {\n return { error: \"assertionText is required for embedding\" };\n }\n\n logger.verbose(`[PremiseGraph.embed] Generating embedding for premise`);\n\n // Embedder.generate returns number[] | number[][], cast for single string input\n const embedding = await this.embedder.generate(state.assertionText, undefined, getAbortSignalConfig()) as number[];\n return { embedding };\n });\n };\n\n // ─────────────────────────────────────────────────────────\n // NODE: Dedupe (create mode only)\n // Skips persisting a near-duplicate of an existing ACTIVE premise for the same\n // user. Re-running similar input (e.g. repeated enrichment) therefore does not\n // accumulate near-identical premises. No-op for update mode, when no embedding\n // is available, or when the adapter does not implement findSimilarActivePremise.\n // ─────────────────────────────────────────────────────────\n const dedupeNode = async (state: typeof PremiseGraphState.State) => {\n return timed(\"PremiseGraph.dedupe\", async () => {\n if (state.error) return {};\n if (state.operationMode === 'update') return {};\n if (!state.embedding || state.embedding.length === 0) return {};\n if (typeof this.database.findSimilarActivePremise !== 'function') return {};\n\n const match = await this.database.findSimilarActivePremise({\n userId: state.userId,\n embedding: state.embedding,\n threshold: DEDUP_SIMILARITY_THRESHOLD,\n });\n\n if (match) {\n logger.verbose(\n `[PremiseGraph.dedupe] Skipping near-duplicate (similarity=${match.similarity.toFixed(3)} >= ${DEDUP_SIMILARITY_THRESHOLD}) of premise ${match.premiseId}`,\n );\n return { duplicateOf: match };\n }\n return {};\n });\n };\n\n const persistNode = async (state: typeof PremiseGraphState.State) => {\n return timed(\"PremiseGraph.persist\", async () => {\n if (state.error) return {};\n\n if (state.operationMode === 'update' && !state.targetPremiseId) {\n return { error: \"targetPremiseId is required for update mode\" };\n }\n\n if (state.operationMode === 'update' && state.targetPremiseId) {\n logger.verbose(`[PremiseGraph.persist] Updating premise ${state.targetPremiseId}`);\n\n const updated = await this.database.updatePremise(state.targetPremiseId, {\n assertion: {\n text: state.assertionText!,\n tier: state.tier,\n },\n analysis: state.analysis ?? undefined,\n validity: {\n validFrom: state.validFrom,\n validUntil: state.validUntil,\n volatile: state.volatile,\n },\n embedding: state.embedding,\n });\n return { premise: updated };\n }\n\n logger.verbose(`[PremiseGraph.persist] Creating new premise for user ${state.userId}`);\n\n // Provenance confidence: prefer an explicit caller-supplied value; otherwise\n // derive it from the analyzer's felicity scores (how authoritative, sincere,\n // and clear the assertion is) rather than a blanket 1.0, so the stored\n // provenance reflects per-premise signal quality.\n const derivedConfidence = deriveProvenanceConfidence(state.analysis);\n const premise = await this.database.createPremise({\n userId: state.userId,\n assertion: {\n text: state.assertionText!,\n tier: state.tier,\n },\n provenance: {\n source: state.provenanceSource ?? 'explicit',\n sourceId: state.provenanceSourceId,\n confidence: state.provenanceConfidence ?? derivedConfidence,\n timestamp: new Date().toISOString(),\n },\n analysis: state.analysis ?? undefined,\n validity: {\n validFrom: state.validFrom,\n validUntil: state.validUntil,\n volatile: state.volatile,\n },\n embedding: state.embedding,\n });\n return { premise };\n });\n };\n\n const indexNode = async (state: typeof PremiseGraphState.State) => {\n return timed(\"PremiseGraph.index\", async () => {\n if (!state.premise) return {};\n\n logger.verbose(`[PremiseGraph.index] Scoring premise against user networks`);\n\n const assignmentMemberships = await this.database.getAssignmentNetworkMembershipsForUser(state.userId);\n const requestScope = state.scopeType && state.scopeId\n ? { scopeType: state.scopeType, scopeId: state.scopeId }\n : scopeFromNetworkId(state.networkScopeId);\n const indexIds = resolveAssignmentNetworkScope({\n memberships: assignmentMemberships,\n ...requestScope,\n });\n const scope = requestScope.scopeType ? \"network\" : \"global\";\n const assignments: Array<{ networkId: string; relevancyScore: number }> = [];\n const agentTimings: DebugMetaAgent[] = [];\n\n for (const networkId of indexIds) {\n try {\n const assignmentContext = await this.database.getNetworkAssignmentContext(networkId, state.userId);\n if (!assignmentContext) continue;\n const indexPrompt = assignmentContext.indexPrompt;\n const memberPrompt = assignmentContext.memberPrompt;\n const hasPrompts = !!indexPrompt?.trim() || !!memberPrompt?.trim();\n let rawScores: { indexScore?: number; memberScore?: number } | undefined;\n let reason: string | undefined;\n\n if (hasPrompts) {\n const start = Date.now();\n const result = await indexer.invoke({\n premiseText: state.assertionText!,\n indexPrompt: indexPrompt ?? \"\",\n memberPrompt: memberPrompt ?? undefined,\n });\n const timing: DebugMetaAgent = {\n name: \"premise-indexer\",\n durationMs: Date.now() - start,\n };\n rawScores = { indexScore: result.indexScore, memberScore: result.memberScore };\n reason = result.reasoning;\n agentTimings.push(timing);\n }\n\n const decision = buildNetworkAssignmentDecision({\n resourceType: \"premise\",\n mode: \"automatic\",\n scope,\n indexPrompt,\n memberPrompt,\n rawScores,\n evaluator: \"premise-indexer\",\n source: \"premise-graph\",\n reason,\n createdAt: new Date().toISOString(),\n });\n\n if (decision.assigned) {\n await this.database.assignPremiseToNetwork(\n state.premise.id,\n networkId,\n decision.finalScore,\n decision.metadata,\n );\n assignments.push({ networkId, relevancyScore: decision.finalScore });\n }\n } catch (err) {\n logger.verbose(`[PremiseGraph.index] Failed to score network ${networkId}, skipping: ${err}`);\n }\n }\n\n logger.verbose(`[PremiseGraph.index] Assigned to ${assignments.length} networks`);\n\n return { networkAssignments: assignments, agentTimings };\n });\n };\n\n const routeByMode = (state: typeof PremiseGraphState.State) => {\n if (state.error) return \"end\";\n if (state.operationMode === 'query') return \"query\";\n return \"analyze\";\n };\n\n const graph = new StateGraph(PremiseGraphState)\n .addNode(\"query\", queryNode)\n .addNode(\"analyze\", analyzeNode)\n .addNode(\"embed\", embedNode)\n .addNode(\"dedupe\", dedupeNode)\n .addNode(\"persist\", persistNode)\n .addNode(\"index\", indexNode)\n .addConditionalEdges(START, routeByMode, {\n query: \"query\",\n analyze: \"analyze\",\n end: END,\n })\n .addEdge(\"query\", END)\n .addEdge(\"analyze\", \"embed\")\n .addEdge(\"embed\", \"dedupe\")\n // A near-duplicate short-circuits straight to END (no persist, no index).\n .addConditionalEdges(\"dedupe\", (state: typeof PremiseGraphState.State) => (state.duplicateOf ? \"end\" : \"persist\"), {\n persist: \"persist\",\n end: END,\n })\n .addEdge(\"persist\", \"index\")\n .addEdge(\"index\", END);\n\n return graph.compile();\n }\n}\n"]}
|
|
@@ -15,6 +15,11 @@ export declare const PremiseGraphState: import("@langchain/langgraph").Annotatio
|
|
|
15
15
|
provenanceSourceId: import("@langchain/langgraph").BaseChannel<string | undefined, string | import("@langchain/langgraph").OverwriteValue<string | undefined> | undefined, unknown>;
|
|
16
16
|
provenanceConfidence: import("@langchain/langgraph").BaseChannel<number | undefined, number | import("@langchain/langgraph").OverwriteValue<number | undefined> | undefined, unknown>;
|
|
17
17
|
operationMode: import("@langchain/langgraph").BaseChannel<"query" | "update" | "create", "query" | "update" | "create" | import("@langchain/langgraph").OverwriteValue<"query" | "update" | "create">, unknown>;
|
|
18
|
+
/** Focused request scope type for assignment writes. */
|
|
19
|
+
scopeType: import("@langchain/langgraph").BaseChannel<"network" | undefined, "network" | import("@langchain/langgraph").OverwriteValue<"network" | undefined> | undefined, unknown>;
|
|
20
|
+
/** Focused request scope id. When scopeType is `network`, this is the focused network id. */
|
|
21
|
+
scopeId: import("@langchain/langgraph").BaseChannel<string | undefined, string | import("@langchain/langgraph").OverwriteValue<string | undefined> | undefined, unknown>;
|
|
22
|
+
/** @deprecated Use scopeType/scopeId. Retained temporarily for older enqueue handlers. */
|
|
18
23
|
networkScopeId: import("@langchain/langgraph").BaseChannel<string | undefined, string | import("@langchain/langgraph").OverwriteValue<string | undefined> | undefined, unknown>;
|
|
19
24
|
targetPremiseId: import("@langchain/langgraph").BaseChannel<string | undefined, string | import("@langchain/langgraph").OverwriteValue<string | undefined> | undefined, unknown>;
|
|
20
25
|
analysis: import("@langchain/langgraph").BaseChannel<PremiseAnalysis | undefined, PremiseAnalysis | import("@langchain/langgraph").OverwriteValue<PremiseAnalysis | undefined> | undefined, unknown>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"premise.state.d.ts","sourceRoot":"/","sources":["premise/premise.state.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAqB,aAAa,EAAE,MAAM,4CAA4C,CAAC;AACpH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;
|
|
1
|
+
{"version":3,"file":"premise.state.d.ts","sourceRoot":"/","sources":["premise/premise.state.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAqB,aAAa,EAAE,MAAM,4CAA4C,CAAC;AACpH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAGtE,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;;;IAgD5B,wDAAwD;;IAMxD,6FAA6F;;IAM7F,0FAA0F;;;;;;;mBA6BrD,MAAM;uBAAiB,MAAM;oBAAc,MAAM;;mBAAjD,MAAM;uBAAiB,MAAM;oBAAc,MAAM;;mBAAjD,MAAM;uBAAiB,MAAM;oBAAc,MAAM;;;mBAKpC,MAAM;wBAAkB,MAAM;;mBAA9B,MAAM;wBAAkB,MAAM;;mBAA9B,MAAM;wBAAkB,MAAM;;;;kBAWpE,aAAa,EAAE;eAClB,MAAM;kBACH,MAAM;;kBAFN,aAAa,EAAE;eAClB,MAAM;kBACH,MAAM;;kBAFN,aAAa,EAAE;eAClB,MAAM;kBACH,MAAM;;;EAUlB,CAAC"}
|
|
@@ -37,6 +37,17 @@ export const PremiseGraphState = Annotation.Root({
|
|
|
37
37
|
reducer: (curr, next) => next ?? curr,
|
|
38
38
|
default: () => 'create',
|
|
39
39
|
}),
|
|
40
|
+
/** Focused request scope type for assignment writes. */
|
|
41
|
+
scopeType: Annotation({
|
|
42
|
+
reducer: (curr, next) => next ?? curr,
|
|
43
|
+
default: () => undefined,
|
|
44
|
+
}),
|
|
45
|
+
/** Focused request scope id. When scopeType is `network`, this is the focused network id. */
|
|
46
|
+
scopeId: Annotation({
|
|
47
|
+
reducer: (curr, next) => next ?? curr,
|
|
48
|
+
default: () => undefined,
|
|
49
|
+
}),
|
|
50
|
+
/** @deprecated Use scopeType/scopeId. Retained temporarily for older enqueue handlers. */
|
|
40
51
|
networkScopeId: Annotation({
|
|
41
52
|
reducer: (curr, next) => next ?? curr,
|
|
42
53
|
default: () => undefined,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"premise.state.js","sourceRoot":"/","sources":["premise/premise.state.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;
|
|
1
|
+
{"version":3,"file":"premise.state.js","sourceRoot":"/","sources":["premise/premise.state.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAKlD,MAAM,CAAC,MAAM,iBAAiB,GAAG,UAAU,CAAC,IAAI,CAAC;IAC/C,MAAM,EAAE,CAAA,UAAkB,CAAA;IAE1B,aAAa,EAAE,UAAU,CAAqB;QAC5C,OAAO,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,IAAI,IAAI;QACrC,OAAO,EAAE,GAAG,EAAE,CAAC,SAAS;KACzB,CAAC;IAEF,IAAI,EAAE,UAAU,CAA6B;QAC3C,OAAO,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,IAAI,IAAI;QACrC,OAAO,EAAE,GAAG,EAAE,CAAC,WAAW;KAC3B,CAAC;IAEF,SAAS,EAAE,UAAU,CAAqB;QACxC,OAAO,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI;QAC7B,OAAO,EAAE,GAAG,EAAE,CAAC,SAAS;KACzB,CAAC;IAEF,UAAU,EAAE,UAAU,CAAqB;QACzC,OAAO,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI;QAC7B,OAAO,EAAE,GAAG,EAAE,C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I,IAAI,IAAI;QACrC,OAAO,EAAE,GAAG,EAAE,CAAC,SAAS;KACzB,CAAC;IAEF,UAAU,EAAE,UAAU,CAIP;QACb,OAAO,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI;QAC7B,OAAO,EAAE,GAAG,EAAE,CAAC,SAAS;KACzB,CAAC;IAEF,YAAY,EAAE,UAAU,CAAmB;QACzC,OAAO,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,GAAG,GAAG,EAAE,GAAG,GAAG,CAAC;QACvC,OAAO,EAAE,GAAG,EAAE,CAAC,EAAE;KAClB,CAAC;CACH,CAAC,CAAC","sourcesContent":["import { Annotation } from \"@langchain/langgraph\";\nimport type { PremiseAnalysis, PremiseProvenance, PremiseRecord } from \"../shared/interfaces/database.interface.js\";\nimport type { DebugMetaAgent } from '../chat/chat-streaming.types.js';\nimport type { ToolScopeType } from '../shared/agent/tool.scope.js';\n\nexport const PremiseGraphState = Annotation.Root({\n userId: Annotation<string>,\n\n assertionText: Annotation<string | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n\n tier: Annotation<'assertive' | 'contextual'>({\n reducer: (curr, next) => next ?? curr,\n default: () => 'assertive',\n }),\n\n validFrom: Annotation<string | undefined>({\n reducer: (curr, next) => next,\n default: () => undefined,\n }),\n\n validUntil: Annotation<string | undefined>({\n reducer: (curr, next) => next,\n default: () => undefined,\n }),\n\n volatile: Annotation<boolean>({\n reducer: (curr, next) => next ?? curr,\n default: () => false,\n }),\n\n provenanceSource: Annotation<PremiseProvenance['source'] | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n\n provenanceSourceId: Annotation<string | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n\n provenanceConfidence: Annotation<number | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n\n operationMode: Annotation<'create' | 'update' | 'query'>({\n reducer: (curr, next) => next ?? curr,\n default: () => 'create',\n }),\n\n /** Focused request scope type for assignment writes. */\n scopeType: Annotation<ToolScopeType | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n\n /** Focused request scope id. When scopeType is `network`, this is the focused network id. */\n scopeId: Annotation<string | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n\n /** @deprecated Use scopeType/scopeId. Retained temporarily for older enqueue handlers. */\n networkScopeId: Annotation<string | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n\n targetPremiseId: Annotation<string | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n\n analysis: Annotation<PremiseAnalysis | undefined>({\n reducer: (curr, next) => next,\n default: () => undefined,\n }),\n\n embedding: Annotation<number[] | undefined>({\n reducer: (curr, next) => next,\n default: () => undefined,\n }),\n\n premise: Annotation<PremiseRecord | undefined>({\n reducer: (curr, next) => next,\n default: () => undefined,\n }),\n\n // Set by the dedupe node when a near-duplicate ACTIVE premise already exists for\n // the user (create mode only). When present, persist/index are skipped — the\n // candidate is treated as already represented by `duplicateOf`.\n duplicateOf: Annotation<{ premiseId: string; assertionText: string; similarity: number } | undefined>({\n reducer: (curr, next) => next,\n default: () => undefined,\n }),\n\n networkAssignments: Annotation<Array<{ networkId: string; relevancyScore: number }>>({\n reducer: (curr, next) => next,\n default: () => [],\n }),\n\n error: Annotation<string | undefined>({\n reducer: (curr, next) => next ?? curr,\n default: () => undefined,\n }),\n\n readResult: Annotation<{\n premises: PremiseRecord[];\n count: number;\n message?: string;\n } | undefined>({\n reducer: (curr, next) => next,\n default: () => undefined,\n }),\n\n agentTimings: Annotation<DebugMetaAgent[]>({\n reducer: (acc, val) => [...acc, ...val],\n default: () => [],\n }),\n});\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"premise.tools.d.ts","sourceRoot":"/","sources":["premise/premise.tools.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AAQ5E,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,
|
|
1
|
+
{"version":3,"file":"premise.tools.d.ts","sourceRoot":"/","sources":["premise/premise.tools.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AAQ5E,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,SA+RxE"}
|
|
@@ -35,6 +35,9 @@ export function createPremiseTools(defineTool, deps) {
|
|
|
35
35
|
return error("Premise graph not available.");
|
|
36
36
|
}
|
|
37
37
|
const effectiveVolatile = query.volatile ?? (query.tier === "contextual" ? true : false);
|
|
38
|
+
const scopeEnvelope = context.scopeType && context.scopeId
|
|
39
|
+
? { scopeType: context.scopeType, scopeId: context.scopeId }
|
|
40
|
+
: {};
|
|
38
41
|
logger.verbose(`[createPremise] Creating premise for user ${context.userId}: "${query.text.substring(0, 60)}..."`);
|
|
39
42
|
const result = await invokeWithAbortSignal(premiseGraph, {
|
|
40
43
|
userId: context.userId,
|
|
@@ -44,6 +47,7 @@ export function createPremiseTools(defineTool, deps) {
|
|
|
44
47
|
validUntil: query.validUntil,
|
|
45
48
|
volatile: effectiveVolatile,
|
|
46
49
|
operationMode: "create",
|
|
50
|
+
...scopeEnvelope,
|
|
47
51
|
});
|
|
48
52
|
if (result.error) {
|
|
49
53
|
return error(result.error);
|
|
@@ -193,6 +197,7 @@ export function createPremiseTools(defineTool, deps) {
|
|
|
193
197
|
volatile: query.volatile ?? existing.validity.volatile,
|
|
194
198
|
operationMode: "update",
|
|
195
199
|
targetPremiseId: query.premiseId,
|
|
200
|
+
...(context.scopeType && context.scopeId ? { scopeType: context.scopeType, scopeId: context.scopeId } : {}),
|
|
196
201
|
});
|
|
197
202
|
if (result.error) {
|
|
198
203
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AC,CAAC;YACH,IAAI,CAAC;gBAAC,IAAI,CAAC,aAAa,EAAE,WAAW,EAAE,CAAC,KAAK,CAAC,SAAS,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;YAAC,CAAC;YAC3E,OAAO,CAAC,EAAE,CAAC;gBAAC,MAAM,CAAC,KAAK,CAAC,mDAAmD,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;YAAC,CAAC;YAC9F,OAAO,aAAa,CAAC;QACvB,CAAC;KACF,CAAC,CAAC;IAEH,OAAO,CAAC,aAAa,EAAE,YAAY,EAAE,aAAa,EAAE,cAAc,CAAC,CAAC;AACtE,CAAC","sourcesContent":["import { z } from \"zod\";\n\nimport type { DefineTool, ToolDeps } from \"../shared/agent/tool.helpers.js\";\nimport { success, error, UUID_REGEX } from \"../shared/agent/tool.helpers.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport type { PremiseRecord, PremiseValidity } from \"../shared/interfaces/database.interface.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\n\nconst logger = protocolLogger(\"ChatTools:Premise\");\n\nexport function createPremiseTools(defineTool: DefineTool, deps: ToolDeps) {\n const database = deps.database;\n const premiseGraph = deps.graphs.premise;\n\n // ─────────────────────────────────────────────────────────────────────────────\n // PREMISE CRUD\n // ─────────────────────────────────────────────────────────────────────────────\n\n const createPremise = defineTool({\n name: \"create_premise\",\n description:\n \"Creates a premise — a self-descriptive proposition the user asserts about themselves. \" +\n \"Premises are the foundational facts that shape how the system understands who you are \" +\n \"and what contexts you inhabit.\\n\\n\" +\n \"**Tiers:**\\n\" +\n \"- `assertive` (default): stable identity facts (e.g. 'I am a software engineer', 'I live in Berlin'). \" +\n \"Use for things that are durably true and not time-bound.\\n\" +\n \"- `contextual`: temporal or situational facts (e.g. 'I am attending DevCon this week', \" +\n \"'I am fundraising for my Series A right now'). Use when the user shares something time-bound \" +\n \"or context-specific. These default to `volatile: true`.\\n\\n\" +\n \"**When to use:** Call this whenever the user shares a fact about themselves in first person \" +\n \"('I am', 'I work at', 'I just joined', 'I am currently'). Do not infer premises from vague \" +\n \"statements — only create them when the user is clearly asserting something about themselves.\",\n querySchema: z.object({\n text: z.string().trim().min(1).describe(\"The premise text — a self-descriptive proposition in first person, e.g. 'I am a machine learning researcher at MIT'.\"),\n tier: z.enum([\"assertive\", \"contextual\"]).default(\"assertive\").describe(\"Tier of the premise. 'assertive' = stable identity fact. 'contextual' = temporal/situational. Defaults to 'assertive'.\"),\n validFrom: z.string().datetime().optional().describe(\"ISO 8601 date-time string for when this premise becomes valid. Omit for immediate.\"),\n validUntil: z.string().datetime().optional().describe(\"ISO 8601 date-time string for when this premise expires. Recommended for contextual premises with a known end date; omit if open-ended.\"),\n volatile: z.boolean().optional().describe(\"Whether this premise should be automatically retracted when it expires. Defaults to true for contextual tier, false for assertive.\"),\n }),\n handler: async ({ context, query }) => {\n if (!premiseGraph) {\n return error(\"Premise graph not available.\");\n }\n\n const effectiveVolatile = query.volatile ?? (query.tier === \"contextual\" ? true : false);\n\n logger.verbose(`[createPremise] Creating premise for user ${context.userId}: \"${query.text.substring(0, 60)}...\"`);\n\n const result = await invokeWithAbortSignal(premiseGraph, {\n userId: context.userId,\n assertionText: query.text,\n tier: query.tier,\n validFrom: query.validFrom,\n validUntil: query.validUntil,\n volatile: effectiveVolatile,\n operationMode: \"create\",\n });\n\n if (result.error) {\n return error(result.error);\n }\n\n if (!result.premise) {\n return error(\"Premise creation failed — no premise returned.\");\n }\n\n const premise = result.premise;\n const indexesAssigned = result.networkAssignments?.length ?? 0;\n const analysisSummary = premise.analysis\n ? `speechActType: ${premise.analysis.speechActType}, clarity: ${premise.analysis.felicityClarity?.toFixed(2) ?? \"n/a\"}`\n : \"no analysis\";\n\n const createResult = success({\n id: premise.id,\n assertion: premise.assertion.text,\n tier: premise.assertion.tier,\n analysisSummary,\n indexesAssigned,\n message: `Premise created and assigned to ${indexesAssigned} index${indexesAssigned === 1 ? \"\" : \"es\"}.`,\n });\n try { deps.premiseEvents?.onCreated?.(premise.id, context.userId); }\n catch (e) { logger.error('[createPremise] premiseEvents.onCreated failed', { error: e }); }\n return createResult;\n },\n });\n\n const readPremises = defineTool({\n name: \"read_premises\",\n description:\n \"Retrieves premises — the self-descriptive propositions a user has asserted about themselves. \" +\n \"Premises represent stable identity facts (assertive) and temporal context (contextual).\\n\\n\" +\n \"**Usage modes:**\\n\" +\n \"- No parameters: returns the caller's own active premises.\\n\" +\n \"- With `userId`: returns that user's premises (use when reviewing another member's context).\\n\" +\n \"- With `includeRetracted: true`: returns all premises regardless of status (active, retracted, expired) for history review.\\n\\n\" +\n \"**When to use:** Call before creating a premise to check if it already exists. \" +\n \"Call when the user asks what they have shared about themselves, or to review their current context. \" +\n \"Each premise includes: id, text, tier, status, analysis summary, and validity range.\",\n querySchema: z.object({\n userId: z.string().optional().describe(\"User ID to fetch premises for. Omit to fetch the current user's own premises.\"),\n includeRetracted: z.boolean().default(false).describe(\"When true, returns all premises regardless of status (active, retracted, expired). Defaults to false (active only).\"),\n }),\n handler: async ({ context, query }) => {\n const targetUserId = query.userId?.trim() || context.userId;\n\n if (query.userId?.trim() && !UUID_REGEX.test(query.userId.trim())) {\n return error(\"Invalid userId format.\");\n }\n\n logger.verbose(`[readPremises] Fetching premises for user ${targetUserId}`);\n\n // Query DB directly (bypassing graph) to support status filtering.\n // The graph's query node hardcodes ACTIVE status, so includeRetracted\n // would be dead code if we routed through it.\n const statusFilter = query.includeRetracted ? undefined : \"ACTIVE\" as const;\n const premises = await database.getPremisesForUser(targetUserId, statusFilter);\n\n const mapped = premises.map((p: PremiseRecord) => ({\n id: p.id,\n text: p.assertion.text,\n tier: p.assertion.tier,\n status: p.status,\n analysisSummary: p.analysis\n ? `speechActType: ${p.analysis.speechActType ?? \"n/a\"}, clarity: ${p.analysis.felicityClarity?.toFixed(2) ?? \"n/a\"}`\n : \"no analysis\",\n validFrom: p.validity.validFrom ?? null,\n validUntil: p.validity.validUntil ?? null,\n volatile: p.validity.volatile ?? false,\n }));\n\n return success({\n premises: mapped,\n count: mapped.length,\n });\n },\n });\n\n const updatePremise = defineTool({\n name: \"update_premise\",\n description:\n \"Modifies an existing premise. Updating the text triggers re-analysis and re-embedding, \" +\n \"which may change how it influences opportunity discovery. \" +\n \"Use when the user corrects or refines something they previously stated about themselves, \" +\n \"or when validity dates need adjustment.\\n\\n\" +\n \"**When to use:** When the user says 'actually, I meant...', 'update my premise about...', \" +\n \"or provides a corrected version of a previously stated fact. \" +\n \"Requires the premise ID — call read_premises first if you don't have it.\",\n querySchema: z.object({\n premiseId: z.string().describe(\"UUID of the premise to update. Get from read_premises.\"),\n text: z.string().trim().min(1).optional().describe(\"New assertion text. Triggers re-analysis and re-embedding when provided.\"),\n validFrom: z.string().datetime().optional().describe(\"New ISO 8601 valid-from date-time.\"),\n validUntil: z.string().datetime().optional().describe(\"New ISO 8601 valid-until date-time.\"),\n volatile: z.boolean().optional().describe(\"Update the volatile flag.\"),\n }),\n handler: async ({ context, query }) => {\n if (!UUID_REGEX.test(query.premiseId)) {\n return error(\"Invalid premiseId format.\");\n }\n\n const existing = await database.getPremise(query.premiseId);\n if (!existing) {\n return error(\"Premise not found.\");\n }\n if (existing.userId !== context.userId) {\n return error(\"You can only update your own premises.\");\n }\n if (existing.status === \"RETRACTED\") {\n return error(\"Cannot update a retracted premise. Retracted premises are immutable.\");\n }\n\n logger.verbose(`[updatePremise] Updating premise ${query.premiseId} for user ${context.userId}`);\n\n // When text is unchanged, skip the graph (avoids unnecessary LLM\n // re-analysis and non-deterministic re-embedding). Only route through\n // the graph when the assertion text actually changes.\n if (query.text === undefined) {\n const hasValidityChange =\n query.validFrom !== undefined ||\n query.validUntil !== undefined ||\n query.volatile !== undefined;\n\n if (!hasValidityChange) {\n return error(\"No fields to update. Provide text, validFrom, validUntil, or volatile.\");\n }\n\n const mergedValidity: PremiseValidity = {\n ...existing.validity,\n ...(query.validFrom !== undefined && { validFrom: query.validFrom }),\n ...(query.validUntil !== undefined && { validUntil: query.validUntil }),\n ...(query.volatile !== undefined && { volatile: query.volatile }),\n };\n\n const updated = await database.updatePremise(query.premiseId, { validity: mergedValidity });\n\n const metadataResult = success({\n id: updated.id,\n assertion: updated.assertion.text,\n tier: updated.assertion.tier,\n status: updated.status,\n message: \"Premise updated successfully (metadata only, no re-analysis).\",\n });\n try { deps.premiseEvents?.onUpdated?.(query.premiseId, context.userId); }\n catch (e) { logger.error('[updatePremise] premiseEvents.onUpdated failed', { error: e }); }\n return metadataResult;\n }\n\n // Text change requires the graph for re-analysis and re-embedding\n if (!premiseGraph) {\n return error(\"Premise graph not available.\");\n }\n\n const result = await invokeWithAbortSignal(premiseGraph, {\n userId: context.userId,\n assertionText: query.text,\n tier: existing.assertion.tier,\n validFrom: query.validFrom ?? existing.validity.validFrom ?? undefined,\n validUntil: query.validUntil ?? existing.validity.validUntil ?? undefined,\n volatile: query.volatile ?? existing.validity.volatile,\n operationMode: \"update\",\n targetPremiseId: query.premiseId,\n });\n\n if (result.error) {\n return error(result.error);\n }\n\n if (!result.premise) {\n return error(\"Premise update failed — no updated premise returned.\");\n }\n\n const updated = result.premise;\n\n const updateResult = success({\n id: updated.id,\n assertion: updated.assertion.text,\n tier: updated.assertion.tier,\n status: updated.status,\n message: \"Premise updated successfully.\",\n });\n try { deps.premiseEvents?.onUpdated?.(query.premiseId, context.userId); }\n catch (e) { logger.error('[updatePremise] premiseEvents.onUpdated failed', { error: e }); }\n return updateResult;\n },\n });\n\n const retractPremise = defineTool({\n name: \"retract_premise\",\n description:\n \"Retracts a premise — a soft delete that preserves the history of what was asserted. \" +\n \"Retracted premises are no longer active but remain in the audit trail. \" +\n \"Use when the user explicitly wants to remove something they previously stated about themselves, \" +\n \"or when a contextual premise is no longer true.\\n\\n\" +\n \"**When to use:** When the user says 'remove my premise about...', 'I no longer...', \" +\n \"or 'that's not true anymore'. Do not retract premises proactively — only on explicit user instruction.\",\n querySchema: z.object({\n premiseId: z.string().describe(\"UUID of the premise to retract. Get from read_premises.\"),\n }),\n handler: async ({ context, query }) => {\n if (!UUID_REGEX.test(query.premiseId)) {\n return error(\"Invalid premiseId format.\");\n }\n\n const existing = await database.getPremise(query.premiseId);\n if (!existing) {\n return error(\"Premise not found.\");\n }\n if (existing.userId !== context.userId) {\n return error(\"You can only retract your own premises.\");\n }\n if (existing.status === \"RETRACTED\") {\n return error(\"Premise is already retracted.\");\n }\n\n logger.verbose(`[retractPremise] Retracting premise ${query.premiseId} for user ${context.userId}`);\n\n await database.updatePremise(query.premiseId, {\n status: \"RETRACTED\",\n retractedAt: new Date(),\n });\n\n const retractResult = success({\n id: query.premiseId,\n message: \"Premise retracted successfully.\",\n });\n try { deps.premiseEvents?.onRetracted?.(query.premiseId, context.userId); }\n catch (e) { logger.error('[retractPremise] premiseEvents.onRetracted failed', { error: e }); }\n return retractResult;\n },\n });\n\n return [createPremise, readPremises, updatePremise, retractPremise];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"premise.tools.js","sourceRoot":"/","sources":["premise/premise.tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAC7E,OAAO,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAE5E,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAExE,MAAM,MAAM,GAAG,cAAc,CAAC,mBAAmB,CAAC,CAAC;AAEnD,MAAM,UAAU,kBAAkB,CAAC,UAAsB,EAAE,IAAc;IACvE,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;IAC/B,MAAM,YAAY,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC;IAEzC,gFAAgF;IAChF,eAAe;IACf,gFAAgF;IAEhF,MAAM,aAAa,GAAG,UAAU,CAAC;QAC/B,IAAI,EAAE,gBAAgB;QACtB,WAAW,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,OAAO,aAAa,CAAC;QACvB,CAAC;KACF,CAAC,CAAC;IAEH,OAAO,CAAC,aAAa,EAAE,YAAY,EAAE,aAAa,EAAE,cAAc,CAAC,CAAC;AACtE,CAAC","sourcesContent":["import { z } from \"zod\";\n\nimport type { DefineTool, ToolDeps } from \"../shared/agent/tool.helpers.js\";\nimport { success, error, UUID_REGEX } from \"../shared/agent/tool.helpers.js\";\nimport { protocolLogger } from \"../shared/observability/protocol.logger.js\";\nimport type { PremiseRecord, PremiseValidity } from \"../shared/interfaces/database.interface.js\";\nimport { invokeWithAbortSignal } from \"../shared/agent/model-signal.js\";\n\nconst logger = protocolLogger(\"ChatTools:Premise\");\n\nexport function createPremiseTools(defineTool: DefineTool, deps: ToolDeps) {\n const database = deps.database;\n const premiseGraph = deps.graphs.premise;\n\n // ─────────────────────────────────────────────────────────────────────────────\n // PREMISE CRUD\n // ─────────────────────────────────────────────────────────────────────────────\n\n const createPremise = defineTool({\n name: \"create_premise\",\n description:\n \"Creates a premise — a self-descriptive proposition the user asserts about themselves. \" +\n \"Premises are the foundational facts that shape how the system understands who you are \" +\n \"and what contexts you inhabit.\\n\\n\" +\n \"**Tiers:**\\n\" +\n \"- `assertive` (default): stable identity facts (e.g. 'I am a software engineer', 'I live in Berlin'). \" +\n \"Use for things that are durably true and not time-bound.\\n\" +\n \"- `contextual`: temporal or situational facts (e.g. 'I am attending DevCon this week', \" +\n \"'I am fundraising for my Series A right now'). Use when the user shares something time-bound \" +\n \"or context-specific. These default to `volatile: true`.\\n\\n\" +\n \"**When to use:** Call this whenever the user shares a fact about themselves in first person \" +\n \"('I am', 'I work at', 'I just joined', 'I am currently'). Do not infer premises from vague \" +\n \"statements — only create them when the user is clearly asserting something about themselves.\",\n querySchema: z.object({\n text: z.string().trim().min(1).describe(\"The premise text — a self-descriptive proposition in first person, e.g. 'I am a machine learning researcher at MIT'.\"),\n tier: z.enum([\"assertive\", \"contextual\"]).default(\"assertive\").describe(\"Tier of the premise. 'assertive' = stable identity fact. 'contextual' = temporal/situational. Defaults to 'assertive'.\"),\n validFrom: z.string().datetime().optional().describe(\"ISO 8601 date-time string for when this premise becomes valid. Omit for immediate.\"),\n validUntil: z.string().datetime().optional().describe(\"ISO 8601 date-time string for when this premise expires. Recommended for contextual premises with a known end date; omit if open-ended.\"),\n volatile: z.boolean().optional().describe(\"Whether this premise should be automatically retracted when it expires. Defaults to true for contextual tier, false for assertive.\"),\n }),\n handler: async ({ context, query }) => {\n if (!premiseGraph) {\n return error(\"Premise graph not available.\");\n }\n\n const effectiveVolatile = query.volatile ?? (query.tier === \"contextual\" ? true : false);\n const scopeEnvelope = context.scopeType && context.scopeId\n ? { scopeType: context.scopeType, scopeId: context.scopeId }\n : {};\n\n logger.verbose(`[createPremise] Creating premise for user ${context.userId}: \"${query.text.substring(0, 60)}...\"`);\n\n const result = await invokeWithAbortSignal(premiseGraph, {\n userId: context.userId,\n assertionText: query.text,\n tier: query.tier,\n validFrom: query.validFrom,\n validUntil: query.validUntil,\n volatile: effectiveVolatile,\n operationMode: \"create\",\n ...scopeEnvelope,\n });\n\n if (result.error) {\n return error(result.error);\n }\n\n if (!result.premise) {\n return error(\"Premise creation failed — no premise returned.\");\n }\n\n const premise = result.premise;\n const indexesAssigned = result.networkAssignments?.length ?? 0;\n const analysisSummary = premise.analysis\n ? `speechActType: ${premise.analysis.speechActType}, clarity: ${premise.analysis.felicityClarity?.toFixed(2) ?? \"n/a\"}`\n : \"no analysis\";\n\n const createResult = success({\n id: premise.id,\n assertion: premise.assertion.text,\n tier: premise.assertion.tier,\n analysisSummary,\n indexesAssigned,\n message: `Premise created and assigned to ${indexesAssigned} index${indexesAssigned === 1 ? \"\" : \"es\"}.`,\n });\n try { deps.premiseEvents?.onCreated?.(premise.id, context.userId); }\n catch (e) { logger.error('[createPremise] premiseEvents.onCreated failed', { error: e }); }\n return createResult;\n },\n });\n\n const readPremises = defineTool({\n name: \"read_premises\",\n description:\n \"Retrieves premises — the self-descriptive propositions a user has asserted about themselves. \" +\n \"Premises represent stable identity facts (assertive) and temporal context (contextual).\\n\\n\" +\n \"**Usage modes:**\\n\" +\n \"- No parameters: returns the caller's own active premises.\\n\" +\n \"- With `userId`: returns that user's premises (use when reviewing another member's context).\\n\" +\n \"- With `includeRetracted: true`: returns all premises regardless of status (active, retracted, expired) for history review.\\n\\n\" +\n \"**When to use:** Call before creating a premise to check if it already exists. \" +\n \"Call when the user asks what they have shared about themselves, or to review their current context. \" +\n \"Each premise includes: id, text, tier, status, analysis summary, and validity range.\",\n querySchema: z.object({\n userId: z.string().optional().describe(\"User ID to fetch premises for. Omit to fetch the current user's own premises.\"),\n includeRetracted: z.boolean().default(false).describe(\"When true, returns all premises regardless of status (active, retracted, expired). Defaults to false (active only).\"),\n }),\n handler: async ({ context, query }) => {\n const targetUserId = query.userId?.trim() || context.userId;\n\n if (query.userId?.trim() && !UUID_REGEX.test(query.userId.trim())) {\n return error(\"Invalid userId format.\");\n }\n\n logger.verbose(`[readPremises] Fetching premises for user ${targetUserId}`);\n\n // Query DB directly (bypassing graph) to support status filtering.\n // The graph's query node hardcodes ACTIVE status, so includeRetracted\n // would be dead code if we routed through it.\n const statusFilter = query.includeRetracted ? undefined : \"ACTIVE\" as const;\n const premises = await database.getPremisesForUser(targetUserId, statusFilter);\n\n const mapped = premises.map((p: PremiseRecord) => ({\n id: p.id,\n text: p.assertion.text,\n tier: p.assertion.tier,\n status: p.status,\n analysisSummary: p.analysis\n ? `speechActType: ${p.analysis.speechActType ?? \"n/a\"}, clarity: ${p.analysis.felicityClarity?.toFixed(2) ?? \"n/a\"}`\n : \"no analysis\",\n validFrom: p.validity.validFrom ?? null,\n validUntil: p.validity.validUntil ?? null,\n volatile: p.validity.volatile ?? false,\n }));\n\n return success({\n premises: mapped,\n count: mapped.length,\n });\n },\n });\n\n const updatePremise = defineTool({\n name: \"update_premise\",\n description:\n \"Modifies an existing premise. Updating the text triggers re-analysis and re-embedding, \" +\n \"which may change how it influences opportunity discovery. \" +\n \"Use when the user corrects or refines something they previously stated about themselves, \" +\n \"or when validity dates need adjustment.\\n\\n\" +\n \"**When to use:** When the user says 'actually, I meant...', 'update my premise about...', \" +\n \"or provides a corrected version of a previously stated fact. \" +\n \"Requires the premise ID — call read_premises first if you don't have it.\",\n querySchema: z.object({\n premiseId: z.string().describe(\"UUID of the premise to update. Get from read_premises.\"),\n text: z.string().trim().min(1).optional().describe(\"New assertion text. Triggers re-analysis and re-embedding when provided.\"),\n validFrom: z.string().datetime().optional().describe(\"New ISO 8601 valid-from date-time.\"),\n validUntil: z.string().datetime().optional().describe(\"New ISO 8601 valid-until date-time.\"),\n volatile: z.boolean().optional().describe(\"Update the volatile flag.\"),\n }),\n handler: async ({ context, query }) => {\n if (!UUID_REGEX.test(query.premiseId)) {\n return error(\"Invalid premiseId format.\");\n }\n\n const existing = await database.getPremise(query.premiseId);\n if (!existing) {\n return error(\"Premise not found.\");\n }\n if (existing.userId !== context.userId) {\n return error(\"You can only update your own premises.\");\n }\n if (existing.status === \"RETRACTED\") {\n return error(\"Cannot update a retracted premise. Retracted premises are immutable.\");\n }\n\n logger.verbose(`[updatePremise] Updating premise ${query.premiseId} for user ${context.userId}`);\n\n // When text is unchanged, skip the graph (avoids unnecessary LLM\n // re-analysis and non-deterministic re-embedding). Only route through\n // the graph when the assertion text actually changes.\n if (query.text === undefined) {\n const hasValidityChange =\n query.validFrom !== undefined ||\n query.validUntil !== undefined ||\n query.volatile !== undefined;\n\n if (!hasValidityChange) {\n return error(\"No fields to update. Provide text, validFrom, validUntil, or volatile.\");\n }\n\n const mergedValidity: PremiseValidity = {\n ...existing.validity,\n ...(query.validFrom !== undefined && { validFrom: query.validFrom }),\n ...(query.validUntil !== undefined && { validUntil: query.validUntil }),\n ...(query.volatile !== undefined && { volatile: query.volatile }),\n };\n\n const updated = await database.updatePremise(query.premiseId, { validity: mergedValidity });\n\n const metadataResult = success({\n id: updated.id,\n assertion: updated.assertion.text,\n tier: updated.assertion.tier,\n status: updated.status,\n message: \"Premise updated successfully (metadata only, no re-analysis).\",\n });\n try { deps.premiseEvents?.onUpdated?.(query.premiseId, context.userId); }\n catch (e) { logger.error('[updatePremise] premiseEvents.onUpdated failed', { error: e }); }\n return metadataResult;\n }\n\n // Text change requires the graph for re-analysis and re-embedding\n if (!premiseGraph) {\n return error(\"Premise graph not available.\");\n }\n\n const result = await invokeWithAbortSignal(premiseGraph, {\n userId: context.userId,\n assertionText: query.text,\n tier: existing.assertion.tier,\n validFrom: query.validFrom ?? existing.validity.validFrom ?? undefined,\n validUntil: query.validUntil ?? existing.validity.validUntil ?? undefined,\n volatile: query.volatile ?? existing.validity.volatile,\n operationMode: \"update\",\n targetPremiseId: query.premiseId,\n ...(context.scopeType && context.scopeId ? { scopeType: context.scopeType, scopeId: context.scopeId } : {}),\n });\n\n if (result.error) {\n return error(result.error);\n }\n\n if (!result.premise) {\n return error(\"Premise update failed — no updated premise returned.\");\n }\n\n const updated = result.premise;\n\n const updateResult = success({\n id: updated.id,\n assertion: updated.assertion.text,\n tier: updated.assertion.tier,\n status: updated.status,\n message: \"Premise updated successfully.\",\n });\n try { deps.premiseEvents?.onUpdated?.(query.premiseId, context.userId); }\n catch (e) { logger.error('[updatePremise] premiseEvents.onUpdated failed', { error: e }); }\n return updateResult;\n },\n });\n\n const retractPremise = defineTool({\n name: \"retract_premise\",\n description:\n \"Retracts a premise — a soft delete that preserves the history of what was asserted. \" +\n \"Retracted premises are no longer active but remain in the audit trail. \" +\n \"Use when the user explicitly wants to remove something they previously stated about themselves, \" +\n \"or when a contextual premise is no longer true.\\n\\n\" +\n \"**When to use:** When the user says 'remove my premise about...', 'I no longer...', \" +\n \"or 'that's not true anymore'. Do not retract premises proactively — only on explicit user instruction.\",\n querySchema: z.object({\n premiseId: z.string().describe(\"UUID of the premise to retract. Get from read_premises.\"),\n }),\n handler: async ({ context, query }) => {\n if (!UUID_REGEX.test(query.premiseId)) {\n return error(\"Invalid premiseId format.\");\n }\n\n const existing = await database.getPremise(query.premiseId);\n if (!existing) {\n return error(\"Premise not found.\");\n }\n if (existing.userId !== context.userId) {\n return error(\"You can only retract your own premises.\");\n }\n if (existing.status === \"RETRACTED\") {\n return error(\"Premise is already retracted.\");\n }\n\n logger.verbose(`[retractPremise] Retracting premise ${query.premiseId} for user ${context.userId}`);\n\n await database.updatePremise(query.premiseId, {\n status: \"RETRACTED\",\n retractedAt: new Date(),\n });\n\n const retractResult = success({\n id: query.premiseId,\n message: \"Premise retracted successfully.\",\n });\n try { deps.premiseEvents?.onRetracted?.(query.premiseId, context.userId); }\n catch (e) { logger.error('[retractPremise] premiseEvents.onRetracted failed', { error: e }); }\n return retractResult;\n },\n });\n\n return [createPremise, readPremises, updatePremise, retractPremise];\n}\n"]}
|
|
@@ -4,7 +4,7 @@ import type { DefineTool, ToolDeps } from "../shared/agent/tool.helpers.js";
|
|
|
4
4
|
* Exposes `read_pending_questions` for retrieving the caller's pending
|
|
5
5
|
* questions generated by QuestionerAgent (enrichment, intent, negotiation, discovery modes).
|
|
6
6
|
*
|
|
7
|
-
* Network-scoped agent keys (context.
|
|
7
|
+
* Network-scoped agent keys (context.scopeType/scopeId set via applyNetworkScopeToContext)
|
|
8
8
|
* are clamped to self-owned modes; the result then carries a `scopeRestriction`
|
|
9
9
|
* block mirroring the network-tools convention.
|
|
10
10
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"questioner.tools.d.ts","sourceRoot":"/","sources":["questioner/questioner.tools.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAC;
|
|
1
|
+
{"version":3,"file":"questioner.tools.d.ts","sourceRoot":"/","sources":["questioner/questioner.tools.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AAwB5E;;;;;;;;;;;;GAYG;AACH,wBAAgB,qBAAqB,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,kBA6E3E"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import { error, success } from "../shared/agent/tool.helpers.js";
|
|
3
|
+
import { focusedNetworkId, focusedNetworkLabel } from "../shared/agent/tool.scope.js";
|
|
3
4
|
/**
|
|
4
5
|
* Detection modes whose questions derive solely from the caller's own data
|
|
5
6
|
* (profile gaps, own intents, own discovery sessions). Negotiation-mode
|
|
@@ -8,12 +9,19 @@ import { error, success } from "../shared/agent/tool.helpers.js";
|
|
|
8
9
|
* other users' content (same leak class as the getOpportunitiesForUser fix).
|
|
9
10
|
*/
|
|
10
11
|
const SELF_OWNED_MODES = ["enrichment", "intent", "discovery"];
|
|
12
|
+
function isVisibleInScopedNetwork(question, userId, networkId) {
|
|
13
|
+
return question.actors?.some((actor) => actor.userId === userId && actor.networkId === networkId) === true;
|
|
14
|
+
}
|
|
15
|
+
function stripInternalActors(question) {
|
|
16
|
+
const { actors: _actors, ...publicQuestion } = question;
|
|
17
|
+
return publicQuestion;
|
|
18
|
+
}
|
|
11
19
|
/**
|
|
12
20
|
* Creates MCP tool definitions for the questioner domain.
|
|
13
21
|
* Exposes `read_pending_questions` for retrieving the caller's pending
|
|
14
22
|
* questions generated by QuestionerAgent (enrichment, intent, negotiation, discovery modes).
|
|
15
23
|
*
|
|
16
|
-
* Network-scoped agent keys (context.
|
|
24
|
+
* Network-scoped agent keys (context.scopeType/scopeId set via applyNetworkScopeToContext)
|
|
17
25
|
* are clamped to self-owned modes; the result then carries a `scopeRestriction`
|
|
18
26
|
* block mirroring the network-tools convention.
|
|
19
27
|
*
|
|
@@ -29,7 +37,7 @@ export function createQuestionerTools(defineTool, deps) {
|
|
|
29
37
|
"system to help surface missing signals, refine intents, or capture engagement context.\n\n" +
|
|
30
38
|
"**Returns:** List of pending questions, each with `id`, `title`, `prompt`, `options`, " +
|
|
31
39
|
"`multiSelect`, `mode`, `sourceType`, `sourceId`, `createdAt`, and optional `expiresAt`. " +
|
|
32
|
-
"Network-scoped agents receive only profile/intent/discovery questions plus a " +
|
|
40
|
+
"Network-scoped agents receive only profile/intent/discovery questions for the scoped network plus a " +
|
|
33
41
|
"`scopeRestriction` note.\n\n" +
|
|
34
42
|
"**Use:** Call with no arguments to get all pending questions, or pass `limit` to cap the " +
|
|
35
43
|
"count. For the daily brief the script calls with a small `limit` and renders the first " +
|
|
@@ -48,28 +56,31 @@ export function createQuestionerTools(defineTool, deps) {
|
|
|
48
56
|
return error("Question lookup is not available.");
|
|
49
57
|
}
|
|
50
58
|
const limit = query.limit ?? 10;
|
|
51
|
-
// Scoped-key discriminator:
|
|
52
|
-
|
|
53
|
-
const isScoped = Boolean(
|
|
59
|
+
// Scoped-key discriminator: scoped contexts carry a network scope envelope.
|
|
60
|
+
const scopedNetworkId = focusedNetworkId(context);
|
|
61
|
+
const isScoped = Boolean(scopedNetworkId);
|
|
54
62
|
try {
|
|
55
63
|
const fetched = await deps.findPendingQuestions(context.userId, {
|
|
56
|
-
...(isScoped ? { modes: SELF_OWNED_MODES } : {}),
|
|
64
|
+
...(isScoped ? { modes: SELF_OWNED_MODES, networkId: scopedNetworkId } : {}),
|
|
57
65
|
limit,
|
|
58
66
|
});
|
|
59
|
-
// Defense-in-depth: hosts apply `modes`/`limit` SQL-side;
|
|
60
|
-
// here so the clamp holds even when a custom dep
|
|
67
|
+
// Defense-in-depth: hosts apply `modes`/`networkId`/`limit` SQL-side;
|
|
68
|
+
// re-apply all three here so the clamp holds even when a custom dep
|
|
69
|
+
// ignores the filters. Scoped rows without actor network metadata are
|
|
70
|
+
// hidden fail-closed because they cannot prove membership in this scope.
|
|
61
71
|
const visible = isScoped
|
|
62
|
-
? fetched.filter((q) => SELF_OWNED_MODES.includes(q.mode)
|
|
72
|
+
? fetched.filter((q) => SELF_OWNED_MODES.includes(q.mode) &&
|
|
73
|
+
isVisibleInScopedNetwork(q, context.userId, scopedNetworkId))
|
|
63
74
|
: fetched;
|
|
64
|
-
const limited = visible.slice(0, limit);
|
|
75
|
+
const limited = visible.slice(0, limit).map(stripInternalActors);
|
|
65
76
|
if (isScoped) {
|
|
66
77
|
return success({
|
|
67
78
|
questions: limited,
|
|
68
79
|
scopeRestriction: {
|
|
69
80
|
isScoped: true,
|
|
70
|
-
scopedToIndex: context
|
|
71
|
-
message: `Results
|
|
72
|
-
`
|
|
81
|
+
scopedToIndex: focusedNetworkLabel(context),
|
|
82
|
+
message: `Results are restricted to "${context.indexName ?? "this index"}" and ` +
|
|
83
|
+
`exclude negotiation questions because this agent is scoped to that index.`,
|
|
73
84
|
},
|
|
74
85
|
});
|
|
75
86
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"questioner.tools.js","sourceRoot":"/","sources":["questioner/questioner.tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,iCAAiC,CAAC;
|
|
1
|
+
{"version":3,"file":"questioner.tools.js","sourceRoot":"/","sources":["questioner/questioner.tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAItF;;;;;;GAMG;AACH,MAAM,gBAAgB,GAAmB,CAAC,YAAY,EAAE,QAAQ,EAAE,WAAW,CAAC,CAAC;AAE/E,SAAS,wBAAwB,CAAC,QAAgC,EAAE,MAAc,EAAE,SAAiB;IACnG,OAAO,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,KAAK,MAAM,IAAI,KAAK,CAAC,SAAS,KAAK,SAAS,CAAC,KAAK,IAAI,CAAC;AAC7G,CAAC;AAED,SAAS,mBAAmB,CAA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, ToolDeps } from \"../shared/agent/tool.helpers.js\";\nimport { error, success } from \"../shared/agent/tool.helpers.js\";\nimport { focusedNetworkId, focusedNetworkLabel } from \"../shared/agent/tool.scope.js\";\nimport type { PendingQuestionSummary } from \"../shared/schemas/pending-question.schema.js\";\nimport type { QuestionMode } from \"../shared/schemas/question.schema.js\";\n\n/**\n * Detection modes whose questions derive solely from the caller's own data\n * (profile gaps, own intents, own discovery sessions). Negotiation-mode\n * questions are excluded for network-scoped agents: their prompts are seeded\n * from opportunity metadata that can reference out-of-scope networks and\n * other users' content (same leak class as the getOpportunitiesForUser fix).\n */\nconst SELF_OWNED_MODES: QuestionMode[] = [\"enrichment\", \"intent\", \"discovery\"];\n\nfunction isVisibleInScopedNetwork(question: PendingQuestionSummary, userId: string, networkId: string): boolean {\n return question.actors?.some((actor) => actor.userId === userId && actor.networkId === networkId) === true;\n}\n\nfunction stripInternalActors(question: PendingQuestionSummary): Omit<PendingQuestionSummary, \"actors\"> {\n const { actors: _actors, ...publicQuestion } = question;\n return publicQuestion;\n}\n\n/**\n * Creates MCP tool definitions for the questioner domain.\n * Exposes `read_pending_questions` for retrieving the caller's pending\n * questions generated by QuestionerAgent (enrichment, intent, negotiation, discovery modes).\n *\n * Network-scoped agent keys (context.scopeType/scopeId set via applyNetworkScopeToContext)\n * are clamped to self-owned modes; the result then carries a `scopeRestriction`\n * block mirroring the network-tools convention.\n *\n * @param defineTool - Tool factory provided by the composition root.\n * @param deps - Shared tool dependencies; `findPendingQuestions` is optional\n * and the tool fails gracefully when absent.\n */\nexport function createQuestionerTools(defineTool: DefineTool, deps: ToolDeps) {\n const readPendingQuestions = defineTool({\n name: \"read_pending_questions\",\n description:\n \"Returns pending questions generated for the authenticated user across all modes \" +\n \"(profile, intent, negotiation, discovery). These are questions generated by the \" +\n \"system to help surface missing signals, refine intents, or capture engagement context.\\n\\n\" +\n \"**Returns:** List of pending questions, each with `id`, `title`, `prompt`, `options`, \" +\n \"`multiSelect`, `mode`, `sourceType`, `sourceId`, `createdAt`, and optional `expiresAt`. \" +\n \"Network-scoped agents receive only profile/intent/discovery questions for the scoped network plus a \" +\n \"`scopeRestriction` note.\\n\\n\" +\n \"**Use:** Call with no arguments to get all pending questions, or pass `limit` to cap the \" +\n \"count. For the daily brief the script calls with a small `limit` and renders the first \" +\n \"question that has not been delivered yet.\",\n querySchema: z.object({\n limit: z\n .number()\n .int()\n .min(1)\n .max(10)\n .optional()\n .describe(\"Maximum number of questions to return (1-10, default 10).\"),\n }),\n handler: async ({ context, query }) => {\n if (!deps.findPendingQuestions) {\n return error(\"Question lookup is not available.\");\n }\n\n const limit = query.limit ?? 10;\n // Scoped-key discriminator: scoped contexts carry a network scope envelope.\n const scopedNetworkId = focusedNetworkId(context);\n const isScoped = Boolean(scopedNetworkId);\n\n try {\n const fetched = await deps.findPendingQuestions(context.userId, {\n ...(isScoped ? { modes: SELF_OWNED_MODES, networkId: scopedNetworkId } : {}),\n limit,\n });\n // Defense-in-depth: hosts apply `modes`/`networkId`/`limit` SQL-side;\n // re-apply all three here so the clamp holds even when a custom dep\n // ignores the filters. Scoped rows without actor network metadata are\n // hidden fail-closed because they cannot prove membership in this scope.\n const visible = isScoped\n ? fetched.filter(\n (q) =>\n (SELF_OWNED_MODES as string[]).includes(q.mode) &&\n isVisibleInScopedNetwork(q, context.userId, scopedNetworkId!),\n )\n : fetched;\n const limited = visible.slice(0, limit).map(stripInternalActors);\n\n if (isScoped) {\n return success({\n questions: limited,\n scopeRestriction: {\n isScoped: true,\n scopedToIndex: focusedNetworkLabel(context),\n message:\n `Results are restricted to \"${context.indexName ?? \"this index\"}\" and ` +\n `exclude negotiation questions because this agent is scoped to that index.`,\n },\n });\n }\n\n return success({ questions: limited });\n } catch (err) {\n deps.reportToolError?.(err, {\n operation: \"read-pending-questions\",\n toolName: \"read_pending_questions\",\n userId: context.userId,\n });\n return error(\"Failed to read pending questions.\");\n }\n },\n });\n\n return [readPendingQuestions] as const;\n}\n"]}
|