emailengine-app 2.81.2 → 2.82.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/.ncurc.js +33 -10
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +71 -0
- package/DOCKER_DEPLOYMENT.md +13 -12
- package/Dockerfile +2 -0
- package/bin/emailengine.js +105 -25
- package/config/default.toml +0 -5
- package/config/test.toml +0 -5
- package/data/google-crawlers.json +1 -1
- package/encrypt.js +70 -42
- package/getswagger.sh +0 -4
- package/lib/account/account-state.js +2 -110
- package/lib/account/expected-identity.js +1 -1
- package/lib/account-assignment.js +138 -1
- package/lib/account.js +289 -869
- package/lib/api-reference/index.js +2 -3
- package/lib/api-reference/schema-tree.js +53 -3
- package/lib/api-routes/account-binding.js +58 -0
- package/lib/api-routes/account-routes.js +65 -37
- package/lib/api-routes/behavior-notes.js +4 -0
- package/lib/api-routes/blocklist-routes.js +2 -2
- package/lib/api-routes/bull-board-routes.js +1 -6
- package/lib/api-routes/export-routes.js +2 -22
- package/lib/api-routes/gateway-routes.js +15 -16
- package/lib/api-routes/index.js +1 -13
- package/lib/api-routes/mailbox-routes.js +2 -7
- package/lib/api-routes/mcp-oauth-routes.js +2 -1
- package/lib/api-routes/mcp-routes.js +7 -7
- package/lib/api-routes/message-routes.js +50 -238
- package/lib/api-routes/mint-bounds.js +110 -0
- package/lib/api-routes/oauth2-app-routes.js +23 -32
- package/lib/api-routes/operation-impact.js +1 -1
- package/lib/api-routes/outbox-routes.js +3 -3
- package/lib/api-routes/permission-map.js +1 -7
- package/lib/api-routes/route-helpers.js +11 -5
- package/lib/api-routes/settings-routes.js +20 -21
- package/lib/api-routes/stats-routes.js +1 -1
- package/lib/api-routes/submit-routes.js +17 -18
- package/lib/api-routes/template-routes.js +4 -9
- package/lib/api-routes/token-routes.js +28 -6
- package/lib/api-token-scheme.js +71 -0
- package/lib/arf-detect.js +33 -6
- package/lib/auth-token.js +44 -24
- package/lib/autodetect-imap-settings.js +305 -123
- package/lib/bounce-detect.js +25 -16
- package/lib/calendar-event.js +78 -0
- package/lib/consts.js +54 -5
- package/lib/create-imap-client.js +24 -0
- package/lib/db.js +77 -30
- package/lib/delivery-error.js +70 -2
- package/lib/egress-fetch.js +54 -3
- package/lib/egress-filter.js +11 -0
- package/lib/email-client/api-retry.js +147 -0
- package/lib/email-client/base-client.js +383 -536
- package/lib/email-client/credential-errors.js +21 -5
- package/lib/email-client/gmail/gmail-api.js +38 -125
- package/lib/email-client/gmail/send-request.js +1 -1
- package/lib/email-client/gmail-client.js +77 -51
- package/lib/email-client/imap/mailbox.js +158 -324
- package/lib/email-client/imap/stale-view.js +109 -0
- package/lib/email-client/imap/subconnection.js +46 -9
- package/lib/email-client/imap/sync-operations.js +5 -37
- package/lib/email-client/imap-client.js +190 -65
- package/lib/email-client/message-builder.js +50 -25
- package/lib/email-client/notification-handler.js +5 -219
- package/lib/email-client/outlook/graph-api.js +147 -126
- package/lib/email-client/outlook/send-request.js +10 -4
- package/lib/email-client/outlook-client.js +389 -463
- package/lib/email-client/smtp-pool-manager.js +3 -2
- package/lib/encrypt.js +184 -19
- package/lib/enum-descriptions.js +6 -3
- package/lib/export.js +141 -41
- package/lib/gateway.js +25 -6
- package/lib/get-raw-email.js +26 -44
- package/lib/get-secret.js +1 -21
- package/lib/handlebars-helpers.js +31 -10
- package/lib/imap-proxy-auth.js +13 -29
- package/lib/imapproxy/imap-core/README.md +1 -0
- package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
- package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
- package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
- package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
- package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
- package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
- package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
- package/lib/imapproxy/imap-server.js +17 -177
- package/lib/imapproxy/proxy-handoff.js +235 -0
- package/lib/imapproxy/response-error.js +33 -0
- package/lib/imapproxy/upstream-client.js +2 -2
- package/lib/license-beacon.js +3 -9
- package/lib/llm-pre-process.js +182 -43
- package/lib/logger.js +1 -1
- package/lib/lua/ee-export-queue-add.lua +39 -0
- package/lib/lua/ee-get-idempotency.lua +15 -3
- package/lib/lua/ee-release-attempts.lua +23 -0
- package/lib/lua/ee-reserve-attempts.lua +42 -0
- package/lib/lua/h-set-bigger.lua +12 -2
- package/lib/lua/s-list-accounts.lua +6 -3
- package/lib/mcp/index.js +1 -2
- package/lib/mcp/listen.js +221 -18
- package/lib/mcp/oauth.js +44 -5
- package/lib/mcp/resources.js +8 -2
- package/lib/mcp/tools.js +108 -36
- package/lib/message-port-stream.js +64 -6
- package/lib/oauth/external-account-signer.js +16 -13
- package/lib/oauth/gmail.js +64 -32
- package/lib/oauth/mail-ru.js +24 -17
- package/lib/oauth/outlook.js +53 -40
- package/lib/oauth/pubsub/google.js +38 -2
- package/lib/oauth/scope-checker.js +39 -8
- package/lib/oauth/scope-list.js +55 -0
- package/lib/oauth/token-fetch.js +47 -0
- package/lib/oauth/verify-app.js +2 -2
- package/lib/oauth2-apps.js +154 -90
- package/lib/openapi/build-document.js +1 -1
- package/lib/openapi/joi-schema.js +78 -9
- package/lib/outbox.js +2 -7
- package/lib/parse-message.js +21 -0
- package/lib/payload-examples-webhooks.json +4 -7
- package/lib/pbkdf2-phc.js +101 -0
- package/lib/privileged-settings.js +0 -14
- package/lib/queue-retention.js +4 -2
- package/lib/rate-limit.js +54 -15
- package/lib/read-env-value.js +33 -2
- package/lib/redis-scan-delete.js +56 -29
- package/lib/redis-url.js +3 -1
- package/lib/respawn-backoff.js +5 -4
- package/lib/response-stream.js +25 -4
- package/lib/rewrite-text-nodes.js +27 -40
- package/lib/routes-ui.js +0 -5
- package/lib/schemas.js +180 -253
- package/lib/sentry.js +21 -5
- package/lib/settings.js +58 -59
- package/lib/smtp-auth.js +6 -2
- package/lib/smtp-message-processor.js +28 -7
- package/lib/sso.js +7 -3
- package/lib/stream-encrypt.js +14 -13
- package/lib/swagger-options.js +3 -1
- package/lib/tls/provision.js +69 -3
- package/lib/tls/store.js +14 -1
- package/lib/token-audit-log.js +3 -2
- package/lib/tools.js +114 -53
- package/lib/totp.js +16 -1
- package/lib/ui-routes/account-routes.js +67 -70
- package/lib/ui-routes/admin-config-routes.js +111 -134
- package/lib/ui-routes/admin-entities-routes.js +101 -191
- package/lib/ui-routes/ai-options.js +104 -0
- package/lib/ui-routes/auth-routes.js +98 -18
- package/lib/ui-routes/export-routes.js +3 -23
- package/lib/ui-routes/internals-routes.js +12 -9
- package/lib/ui-routes/network-config-routes.js +8 -18
- package/lib/ui-routes/oauth-config-routes.js +83 -228
- package/lib/ui-routes/route-helpers.js +63 -67
- package/lib/ui-routes/special-use-paths.js +33 -0
- package/lib/ui-routes/unsubscribe-routes.js +2 -2
- package/lib/utils/decode-headers.js +32 -5
- package/lib/utils/header-map.js +62 -1
- package/lib/utils/network.js +11 -17
- package/lib/web-safe-html.js +77 -4
- package/lib/webhook-request.js +9 -1
- package/lib/webhook-routing.js +27 -1
- package/lib/webhooks.js +120 -43
- package/lib/worker-rpc-error.js +43 -2
- package/list-generate.js +13 -2
- package/package.json +38 -46
- package/sbom.json +1 -1
- package/scripts/refresh-test-tokens.js +42 -14
- package/server.js +338 -292
- package/setup-production.sh +16 -7
- package/static/css/flyonui.css +1 -1
- package/static/css/src/app.tailwind.css +7 -8
- package/static/js/ee-client.js +145 -70
- package/static/js/ui.js +350 -154
- package/static/licenses.html +349 -1740
- package/translations/messages.pot +129 -111
- package/views/account-workspace-error.hbs +30 -0
- package/views/accounts/account.hbs +9 -4
- package/views/accounts/browse.hbs +10 -4
- package/views/accounts/edit.hbs +11 -2
- package/views/config/ai.hbs +49 -41
- package/views/config/oauth/app.hbs +2 -1
- package/views/dashboard.hbs +18 -16
- package/views/internals/index.hbs +1 -1
- package/views/layout/app.hbs +0 -22
- package/views/layout/login.hbs +2 -1
- package/views/partials/filter_editor_js.hbs +4 -3
- package/views/partials/gmail_api_scopes.hbs +16 -0
- package/views/partials/oauth_form.hbs +67 -94
- package/views/partials/oauth_pubsub_app_select.hbs +43 -0
- package/views/partials/scope_info.hbs +14 -23
- package/views/partials/side_menu.hbs +0 -4
- package/views/partials/ui/account-picker.hbs +6 -32
- package/views/partials/ui/model-picker.hbs +31 -0
- package/views/partials/ui/pagination.hbs +6 -1
- package/views/partials/ui/picker.hbs +47 -0
- package/views/unsubscribe.hbs +1 -1
- package/workers/api.js +82 -47
- package/workers/export.js +55 -60
- package/workers/imap.js +132 -49
- package/workers/submit.js +5 -6
- package/workers/webhooks.js +46 -27
- package/.githooks/pre-commit +0 -80
- package/.github/CODE_OF_CONDUCT.md +0 -76
- package/.github/contributing.md +0 -17
- package/.github/dependabot.yml +0 -22
- package/.github/docker-smoke-test.sh +0 -61
- package/.github/workflows/deploy.yml +0 -215
- package/.github/workflows/e2e.yml +0 -55
- package/.github/workflows/release.yaml +0 -217
- package/.github/workflows/test.yml +0 -307
- package/lib/api-routes/chat-routes.js +0 -535
- package/lib/document-store.js +0 -75
- package/lib/es.js +0 -757
- package/lib/generate-text-preview.js +0 -61
- package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
- package/lib/pre-process.js +0 -196
- package/lib/threads.js +0 -155
- package/lib/ui-routes/document-store-routes.js +0 -806
- package/playwright.config.js +0 -47
- package/views/config/document-store/chat.hbs +0 -286
- package/views/config/document-store/index.hbs +0 -146
- package/views/config/document-store/mappings/index.hbs +0 -108
- package/views/config/document-store/mappings/new.hbs +0 -68
- package/views/config/document-store/pre-processing/index.hbs +0 -103
- package/views/partials/document_store_header.hbs +0 -30
- package/workers/documents.js +0 -1128
|
@@ -1,535 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
const { redis } = require('../db');
|
|
4
|
-
const { Account } = require('../account');
|
|
5
|
-
const getSecret = require('../get-secret');
|
|
6
|
-
const Boom = require('@hapi/boom');
|
|
7
|
-
const Joi = require('joi');
|
|
8
|
-
const { failAction, getBoolean } = require('../tools');
|
|
9
|
-
const { logApiError } = require('./route-helpers');
|
|
10
|
-
const settings = require('../settings');
|
|
11
|
-
|
|
12
|
-
const LOG_VERBOSE = getBoolean(process.env.EE_OPENAPI_VERBOSE);
|
|
13
|
-
|
|
14
|
-
const { accountIdSchema, messageSpecialUseSchema, responseAddressSchema, responseFromAddressSchema, apiResponses } = require('../schemas');
|
|
15
|
-
|
|
16
|
-
function getDateValue(str) {
|
|
17
|
-
try {
|
|
18
|
-
let date;
|
|
19
|
-
if (/^\d{4}-\d{1,2}-\d{1,2}(\s+\d{1,2}:\d{1,2}(:\d{1,2})?)?$/.test(str)) {
|
|
20
|
-
let parts = str.split(/[^\d]+/).map(v => Number(v));
|
|
21
|
-
parts[1]--;
|
|
22
|
-
date = new Date(Date.UTC(...parts));
|
|
23
|
-
} else {
|
|
24
|
-
date = new Date(str);
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
if (date.toString() === 'Invalid Date') {
|
|
28
|
-
return false;
|
|
29
|
-
}
|
|
30
|
-
return date;
|
|
31
|
-
} catch (err) {
|
|
32
|
-
return false;
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
async function init(args) {
|
|
37
|
-
const { server, call, CORS_CONFIG } = args;
|
|
38
|
-
|
|
39
|
-
async function processChatRequest(opts) {
|
|
40
|
-
let { account, question, index, client, logger } = opts;
|
|
41
|
-
|
|
42
|
-
// throws if account does not exist
|
|
43
|
-
let accountObject = new Account({ redis, account, call, secret: await getSecret() });
|
|
44
|
-
let accountData = await accountObject.loadAccountData();
|
|
45
|
-
|
|
46
|
-
let documentStoreEnabled = await settings.get('documentStoreEnabled');
|
|
47
|
-
let documentStoreGenerateEmbeddings = (await settings.get('documentStoreGenerateEmbeddings')) || false;
|
|
48
|
-
let hasOpenAiAPIKey = !!(await settings.get('openAiAPIKey'));
|
|
49
|
-
|
|
50
|
-
if (!documentStoreEnabled) {
|
|
51
|
-
let error = Boom.boomify(new Error('Document store is not enabled'), { statusCode: 403 });
|
|
52
|
-
error.output.payload.code = 'DocumentStoreDisabled';
|
|
53
|
-
throw error;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
if (!documentStoreGenerateEmbeddings) {
|
|
57
|
-
let error = Boom.boomify(new Error('Chat is not enabled'), { statusCode: 403 });
|
|
58
|
-
error.output.payload.code = 'ChatDisabled';
|
|
59
|
-
throw error;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
if (!hasOpenAiAPIKey) {
|
|
63
|
-
let error = Boom.boomify(new Error('OpenAI API key not set'), { statusCode: 403 });
|
|
64
|
-
error.output.payload.code = 'ApiKeyNotSet';
|
|
65
|
-
throw error;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
let processPipeline = [];
|
|
69
|
-
|
|
70
|
-
processPipeline.push({
|
|
71
|
-
timestamp: new Date().toISOString(),
|
|
72
|
-
message: 'Received a question',
|
|
73
|
-
question
|
|
74
|
-
});
|
|
75
|
-
|
|
76
|
-
// Step 1. define sorting options
|
|
77
|
-
|
|
78
|
-
let sortingResponse;
|
|
79
|
-
try {
|
|
80
|
-
sortingResponse = await call({
|
|
81
|
-
cmd: 'questionQuery',
|
|
82
|
-
data: {
|
|
83
|
-
question,
|
|
84
|
-
account
|
|
85
|
-
},
|
|
86
|
-
timeout: 3 * 60 * 1000
|
|
87
|
-
});
|
|
88
|
-
} catch (err) {
|
|
89
|
-
err.processPipeline = processPipeline;
|
|
90
|
-
throw err;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
processPipeline.push({
|
|
94
|
-
timestamp: new Date().toISOString(),
|
|
95
|
-
message: 'Retrieved the sorting options',
|
|
96
|
-
ordering: sortingResponse?.ordering,
|
|
97
|
-
startTime: sortingResponse?.start_time,
|
|
98
|
-
endTime: sortingResponse?.end_time,
|
|
99
|
-
model: sortingResponse?.model,
|
|
100
|
-
tokens: sortingResponse?.tokens
|
|
101
|
-
});
|
|
102
|
-
|
|
103
|
-
// Step 2. Embeddings for the request
|
|
104
|
-
|
|
105
|
-
let embeddingsResult;
|
|
106
|
-
try {
|
|
107
|
-
embeddingsResult = await call({
|
|
108
|
-
cmd: 'generateChunkEmbeddings',
|
|
109
|
-
data: {
|
|
110
|
-
message: `${sortingResponse?.topic || question}`,
|
|
111
|
-
account
|
|
112
|
-
}
|
|
113
|
-
});
|
|
114
|
-
} catch (err) {
|
|
115
|
-
err.processPipeline = processPipeline;
|
|
116
|
-
throw err;
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
if (!embeddingsResult || !embeddingsResult.embedding) {
|
|
120
|
-
let error = new Error('Failed to generate embeddings for query');
|
|
121
|
-
error.processPipeline = processPipeline;
|
|
122
|
-
throw error;
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
processPipeline.push({
|
|
126
|
-
timestamp: new Date().toISOString(),
|
|
127
|
-
message: 'Generated embeddings for vector search',
|
|
128
|
-
model: embeddingsResult?.model,
|
|
129
|
-
tokens: embeddingsResult?.usage?.total_tokens
|
|
130
|
-
});
|
|
131
|
-
|
|
132
|
-
// Step 3. find matching vectors
|
|
133
|
-
|
|
134
|
-
const vectorsFilter = {
|
|
135
|
-
bool: {
|
|
136
|
-
must: [
|
|
137
|
-
{
|
|
138
|
-
term: {
|
|
139
|
-
account
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
]
|
|
143
|
-
}
|
|
144
|
-
};
|
|
145
|
-
|
|
146
|
-
let startDate, endDate;
|
|
147
|
-
if (sortingResponse?.start_time) {
|
|
148
|
-
startDate = getDateValue(sortingResponse?.start_time);
|
|
149
|
-
}
|
|
150
|
-
if (sortingResponse?.end_time) {
|
|
151
|
-
endDate = getDateValue(sortingResponse?.end_time);
|
|
152
|
-
}
|
|
153
|
-
if (startDate && endDate && startDate.getTime() === endDate.getTime()) {
|
|
154
|
-
// use next day value
|
|
155
|
-
endDate = new Date(endDate.getTime() + 24 * 3600 * 1000);
|
|
156
|
-
}
|
|
157
|
-
let dateMatch = {};
|
|
158
|
-
if (startDate) {
|
|
159
|
-
dateMatch.gte = startDate;
|
|
160
|
-
}
|
|
161
|
-
if (endDate) {
|
|
162
|
-
dateMatch.lte = endDate;
|
|
163
|
-
}
|
|
164
|
-
if (Object.keys(dateMatch).length) {
|
|
165
|
-
vectorsFilter.bool.must.push({
|
|
166
|
-
range: { date: dateMatch }
|
|
167
|
-
});
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
let knnResult;
|
|
171
|
-
try {
|
|
172
|
-
knnResult = await client.knnSearch({
|
|
173
|
-
index: `${index}.embeddings`,
|
|
174
|
-
knn: {
|
|
175
|
-
field: 'embeddings',
|
|
176
|
-
|
|
177
|
-
query_vector: embeddingsResult.embedding,
|
|
178
|
-
k: 10,
|
|
179
|
-
num_candidates: 100
|
|
180
|
-
},
|
|
181
|
-
|
|
182
|
-
filter: vectorsFilter,
|
|
183
|
-
|
|
184
|
-
fields: ['id', 'account', 'chunk', 'messageId', 'chunkNr', 'date', 'created']
|
|
185
|
-
});
|
|
186
|
-
} catch (err) {
|
|
187
|
-
err.processPipeline = processPipeline;
|
|
188
|
-
throw err;
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
if (!knnResult?.hits?.hits?.length) {
|
|
192
|
-
processPipeline.push({
|
|
193
|
-
timestamp: new Date().toISOString(),
|
|
194
|
-
message: 'No matching vectors found from the database',
|
|
195
|
-
filter: vectorsFilter?.bool?.must
|
|
196
|
-
});
|
|
197
|
-
return {
|
|
198
|
-
success: false,
|
|
199
|
-
answer: null,
|
|
200
|
-
processPipeline
|
|
201
|
-
};
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
processPipeline.push({
|
|
205
|
-
timestamp: new Date().toISOString(),
|
|
206
|
-
message: 'Retrieved matching vectors from the database',
|
|
207
|
-
matches: knnResult?.hits?.hits?.length || 0,
|
|
208
|
-
filter: vectorsFilter?.bool?.must
|
|
209
|
-
});
|
|
210
|
-
|
|
211
|
-
let results = [];
|
|
212
|
-
knnResult.hits.hits
|
|
213
|
-
.map(entry => {
|
|
214
|
-
let headerPos = entry._source.chunk.indexOf('\n\n');
|
|
215
|
-
return {
|
|
216
|
-
account: entry._source.account,
|
|
217
|
-
messageId: entry._source.messageId,
|
|
218
|
-
chunkNr: entry._source.chunkNr,
|
|
219
|
-
header: entry._source.chunk.substring(0, headerPos),
|
|
220
|
-
body: entry._source.chunk.substring(headerPos + 2),
|
|
221
|
-
date: entry._source.date,
|
|
222
|
-
created: entry._source.created
|
|
223
|
-
};
|
|
224
|
-
})
|
|
225
|
-
.forEach(entry => {
|
|
226
|
-
let existing = results.find(elm => elm.messageId === entry.messageId);
|
|
227
|
-
if (!existing) {
|
|
228
|
-
results.push({
|
|
229
|
-
messageId: entry.messageId,
|
|
230
|
-
header: `${entry.header}\nMessage-ID: ${entry.messageId}`,
|
|
231
|
-
chunks: [{ chunkNr: entry.chunkNr, body: entry.body }],
|
|
232
|
-
date: new Date(entry.date || entry.created)
|
|
233
|
-
});
|
|
234
|
-
} else {
|
|
235
|
-
existing.chunks.push({ chunkNr: entry.chunkNr, body: entry.body });
|
|
236
|
-
}
|
|
237
|
-
});
|
|
238
|
-
|
|
239
|
-
// sort and slice
|
|
240
|
-
switch (sortingResponse?.ordering) {
|
|
241
|
-
case 'newer_first':
|
|
242
|
-
results = results.sort((a, b) => b.date - a.date);
|
|
243
|
-
break;
|
|
244
|
-
case 'older_first':
|
|
245
|
-
results = results.sort((a, b) => a.date - b.date);
|
|
246
|
-
break;
|
|
247
|
-
}
|
|
248
|
-
results = results.slice(0, 6);
|
|
249
|
-
|
|
250
|
-
let payloadData = results.map((entry, nr) => {
|
|
251
|
-
entry.chunks.sort((a, b) => a.chunkNr - b.chunkNr);
|
|
252
|
-
return `- EMAIL #${nr + 1}:\n${entry.header}\n\n${entry.chunks
|
|
253
|
-
.slice(0, 3) // limit chunks for a single email
|
|
254
|
-
.map(chunk => chunk.body)
|
|
255
|
-
.join('\n')}`;
|
|
256
|
-
});
|
|
257
|
-
|
|
258
|
-
// Step 4. Send the question with context emails
|
|
259
|
-
|
|
260
|
-
let responseData = {};
|
|
261
|
-
|
|
262
|
-
let queryResponse;
|
|
263
|
-
try {
|
|
264
|
-
queryResponse = await call({
|
|
265
|
-
cmd: 'embeddingsQuery',
|
|
266
|
-
data: {
|
|
267
|
-
question,
|
|
268
|
-
contextChunks: payloadData.join('\n\n'),
|
|
269
|
-
account,
|
|
270
|
-
userData: { name: accountData.name, email: accountData.email }
|
|
271
|
-
},
|
|
272
|
-
timeout: 3 * 60 * 1000
|
|
273
|
-
});
|
|
274
|
-
} catch (err) {
|
|
275
|
-
err.processPipeline = processPipeline;
|
|
276
|
-
throw err;
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
processPipeline.push({
|
|
280
|
-
timestamp: new Date().toISOString(),
|
|
281
|
-
message: 'Retrieved the answer',
|
|
282
|
-
messages: queryResponse?.messageId?.length || 0,
|
|
283
|
-
model: queryResponse?.model,
|
|
284
|
-
tokens: queryResponse?.tokens
|
|
285
|
-
});
|
|
286
|
-
|
|
287
|
-
if (queryResponse?.answer) {
|
|
288
|
-
responseData.answer = queryResponse?.answer;
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
if (queryResponse?.messageId) {
|
|
292
|
-
let searchQuery = {
|
|
293
|
-
bool: {
|
|
294
|
-
must: [
|
|
295
|
-
{
|
|
296
|
-
term: {
|
|
297
|
-
account
|
|
298
|
-
}
|
|
299
|
-
},
|
|
300
|
-
{
|
|
301
|
-
terms: {
|
|
302
|
-
messageId: queryResponse.messageId
|
|
303
|
-
}
|
|
304
|
-
}
|
|
305
|
-
]
|
|
306
|
-
}
|
|
307
|
-
};
|
|
308
|
-
|
|
309
|
-
// find the originating message this bounce applies for
|
|
310
|
-
let searchResult;
|
|
311
|
-
try {
|
|
312
|
-
searchResult = await client.search({
|
|
313
|
-
index,
|
|
314
|
-
size: 20,
|
|
315
|
-
from: 0,
|
|
316
|
-
query: searchQuery,
|
|
317
|
-
sort: { uid: 'desc' },
|
|
318
|
-
_source_excludes: 'headers,text'
|
|
319
|
-
});
|
|
320
|
-
} catch (err) {
|
|
321
|
-
err.processPipeline = processPipeline;
|
|
322
|
-
throw err;
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
if (LOG_VERBOSE) {
|
|
326
|
-
logger.trace({ msg: 'Chat search result', searchQuery, searchResult });
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
if (searchResult && searchResult.hits && searchResult.hits.hits && searchResult.hits.hits.length) {
|
|
330
|
-
let seenIds = new Set();
|
|
331
|
-
responseData.messages = searchResult.hits.hits
|
|
332
|
-
.map(message => message._source)
|
|
333
|
-
.sort((a, b) => {
|
|
334
|
-
if (a.messageSpecialUse === '\\Inbox') {
|
|
335
|
-
return -1;
|
|
336
|
-
}
|
|
337
|
-
if (b.messageSpecialUse === '\\Inbox') {
|
|
338
|
-
return 1;
|
|
339
|
-
}
|
|
340
|
-
return new Date(a.date || a.created) - new Date(b.date || b.created);
|
|
341
|
-
})
|
|
342
|
-
.filter(message => {
|
|
343
|
-
if (seenIds.has(message.messageId)) {
|
|
344
|
-
return false;
|
|
345
|
-
}
|
|
346
|
-
seenIds.add(message.messageId);
|
|
347
|
-
return true;
|
|
348
|
-
})
|
|
349
|
-
.sort((a, b) => new Date(b.date) - new Date(a.date))
|
|
350
|
-
.map(message => {
|
|
351
|
-
let responseData = {};
|
|
352
|
-
for (let key of ['id', 'path', 'date', 'from', 'to', 'cc', 'bcc', 'subject', 'messageSpecialUse']) {
|
|
353
|
-
if (message[key]) {
|
|
354
|
-
responseData[key] = message[key];
|
|
355
|
-
}
|
|
356
|
-
}
|
|
357
|
-
return responseData;
|
|
358
|
-
});
|
|
359
|
-
}
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
return {
|
|
363
|
-
success: !!responseData.answer,
|
|
364
|
-
...responseData,
|
|
365
|
-
processPipeline
|
|
366
|
-
};
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
server.route({
|
|
370
|
-
method: 'POST',
|
|
371
|
-
path: '/v1/chat/{account}',
|
|
372
|
-
|
|
373
|
-
async handler(request, h) {
|
|
374
|
-
try {
|
|
375
|
-
const esClient = await h.getESClient(request.logger);
|
|
376
|
-
const { index, client } = esClient;
|
|
377
|
-
return await processChatRequest({
|
|
378
|
-
account: request.params.account,
|
|
379
|
-
question: request.payload.question,
|
|
380
|
-
index,
|
|
381
|
-
client,
|
|
382
|
-
logger: request.logger
|
|
383
|
-
});
|
|
384
|
-
} catch (err) {
|
|
385
|
-
let statusCode = logApiError(request, err);
|
|
386
|
-
if (Boom.isBoom(err)) {
|
|
387
|
-
throw err;
|
|
388
|
-
}
|
|
389
|
-
let error = Boom.boomify(err, { statusCode });
|
|
390
|
-
if (err.code) {
|
|
391
|
-
error.output.payload.code = err.code;
|
|
392
|
-
}
|
|
393
|
-
if (err.processPipeline) {
|
|
394
|
-
error.output.payload.processPipeline = err.processPipeline;
|
|
395
|
-
}
|
|
396
|
-
throw error;
|
|
397
|
-
}
|
|
398
|
-
},
|
|
399
|
-
|
|
400
|
-
options: {
|
|
401
|
-
description: 'Chat with emails',
|
|
402
|
-
notes: 'Use OpenAI API and embeddings stored in the Document Store to "chat" with account emails. Requires Document Store indexing and the "Chat with emails" feature to be enabled.',
|
|
403
|
-
tags: ['api', 'Deprecated endpoints (Document Store)'],
|
|
404
|
-
|
|
405
|
-
plugins: {
|
|
406
|
-
openapi: {
|
|
407
|
-
responses: apiResponses('Returns the generated answer and the messages it was drawn from.', 400, 401, 403, 404, 429, 500)
|
|
408
|
-
}
|
|
409
|
-
},
|
|
410
|
-
|
|
411
|
-
auth: {
|
|
412
|
-
strategy: 'api-token',
|
|
413
|
-
mode: 'required'
|
|
414
|
-
},
|
|
415
|
-
cors: CORS_CONFIG,
|
|
416
|
-
|
|
417
|
-
validate: {
|
|
418
|
-
options: {
|
|
419
|
-
stripUnknown: false,
|
|
420
|
-
abortEarly: false,
|
|
421
|
-
convert: true
|
|
422
|
-
},
|
|
423
|
-
failAction,
|
|
424
|
-
|
|
425
|
-
params: Joi.object({
|
|
426
|
-
account: accountIdSchema.required()
|
|
427
|
-
}),
|
|
428
|
-
|
|
429
|
-
payload: Joi.object({
|
|
430
|
-
question: Joi.string()
|
|
431
|
-
.trim()
|
|
432
|
-
.max(1024)
|
|
433
|
-
.example('When did Jason last message me?')
|
|
434
|
-
.description('Chat message to use')
|
|
435
|
-
.label('ChatMessage')
|
|
436
|
-
.required()
|
|
437
|
-
}).label('RequestChat')
|
|
438
|
-
},
|
|
439
|
-
|
|
440
|
-
response: {
|
|
441
|
-
schema: Joi.object({
|
|
442
|
-
success: Joi.boolean()
|
|
443
|
-
.example(true)
|
|
444
|
-
.description('Whether the LLM produced an answer. Can be false on a 200 response when no answer was found')
|
|
445
|
-
.label('ReturnChatResponseSuccess'),
|
|
446
|
-
answer: Joi.string()
|
|
447
|
-
.trim()
|
|
448
|
-
.allow(null)
|
|
449
|
-
.example('Last tuesday')
|
|
450
|
-
.description('Chat response. Not present (or null) when no answer was produced')
|
|
451
|
-
.label('ChatResponse'),
|
|
452
|
-
messages: Joi.array()
|
|
453
|
-
.items(
|
|
454
|
-
Joi.object({
|
|
455
|
-
id: Joi.string().example('AAAAAgAACrI').description('Unique identifier for the message').label('ChatMessageId'),
|
|
456
|
-
path: Joi.string().example('INBOX').description('Folder this message was found from').label('ChatMessagePath'),
|
|
457
|
-
date: Joi.date().iso().example('2023-09-29T10:03:49.000Z').description('Date of the email'),
|
|
458
|
-
from: responseFromAddressSchema,
|
|
459
|
-
|
|
460
|
-
to: Joi.array()
|
|
461
|
-
.items(responseAddressSchema)
|
|
462
|
-
.single()
|
|
463
|
-
.description('List of addresses')
|
|
464
|
-
.example([{ address: 'recipient@example.com' }])
|
|
465
|
-
.label('ChatToAddressList'),
|
|
466
|
-
cc: Joi.array().items(responseAddressSchema).single().description('List of CC addresses').label('ChatCcAddressList'),
|
|
467
|
-
bcc: Joi.array().items(responseAddressSchema).single().description('List of BCC addresses').label('ChatBccAddressList'),
|
|
468
|
-
subject: Joi.string().example('What a wonderful message').description('Message subject'),
|
|
469
|
-
messageSpecialUse: messageSpecialUseSchema
|
|
470
|
-
})
|
|
471
|
-
.description('Email that best matched the question')
|
|
472
|
-
.label('ChatResponseMessage')
|
|
473
|
-
)
|
|
474
|
-
.description('Emails that best matched the question')
|
|
475
|
-
.label('ChatResponseMessages'),
|
|
476
|
-
processPipeline: Joi.array()
|
|
477
|
-
.items(Joi.object().unknown().label('ChatProcessPipelineStep'))
|
|
478
|
-
.description('Diagnostic information about the chat processing steps, including timings and token usage')
|
|
479
|
-
.label('ChatProcessPipeline')
|
|
480
|
-
}).label('ReturnChatResponse'),
|
|
481
|
-
failAction: 'log'
|
|
482
|
-
}
|
|
483
|
-
}
|
|
484
|
-
});
|
|
485
|
-
|
|
486
|
-
server.route({
|
|
487
|
-
method: 'POST',
|
|
488
|
-
path: '/admin/config/document-store/chat/test',
|
|
489
|
-
async handler(request, h) {
|
|
490
|
-
try {
|
|
491
|
-
const esClient = await h.getESClient(request.logger);
|
|
492
|
-
const { index, client } = esClient;
|
|
493
|
-
|
|
494
|
-
return await processChatRequest({
|
|
495
|
-
account: request.payload.account,
|
|
496
|
-
question: request.payload.question,
|
|
497
|
-
index,
|
|
498
|
-
client,
|
|
499
|
-
logger: request.logger
|
|
500
|
-
});
|
|
501
|
-
} catch (err) {
|
|
502
|
-
request.logger.error({ msg: 'Failed to run chat test', err });
|
|
503
|
-
return {
|
|
504
|
-
success: false,
|
|
505
|
-
error: err.message
|
|
506
|
-
};
|
|
507
|
-
}
|
|
508
|
-
},
|
|
509
|
-
options: {
|
|
510
|
-
tags: ['test'],
|
|
511
|
-
validate: {
|
|
512
|
-
options: {
|
|
513
|
-
stripUnknown: true,
|
|
514
|
-
abortEarly: false,
|
|
515
|
-
convert: true
|
|
516
|
-
},
|
|
517
|
-
|
|
518
|
-
failAction,
|
|
519
|
-
|
|
520
|
-
payload: Joi.object({
|
|
521
|
-
account: accountIdSchema.required(),
|
|
522
|
-
question: Joi.string()
|
|
523
|
-
.trim()
|
|
524
|
-
.max(1024)
|
|
525
|
-
.example('When did Jason last message me?')
|
|
526
|
-
.description('Chat message to use')
|
|
527
|
-
.label('ChatMessage')
|
|
528
|
-
.required()
|
|
529
|
-
}).label('ChatTestPayload')
|
|
530
|
-
}
|
|
531
|
-
}
|
|
532
|
-
});
|
|
533
|
-
}
|
|
534
|
-
|
|
535
|
-
module.exports = init;
|
package/lib/document-store.js
DELETED
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
const config = require('@zone-eu/wild-config');
|
|
4
|
-
const settings = require('./settings');
|
|
5
|
-
const { Client: ElasticSearch } = require('@elastic/elasticsearch');
|
|
6
|
-
const { ensureIndex } = require('./es');
|
|
7
|
-
const { hasEnvValue, readEnvValue, getBoolean } = require('./tools');
|
|
8
|
-
|
|
9
|
-
// Deployment-level gate for the deprecated Document Store feature. When this is false the
|
|
10
|
-
// "documents" worker is not spawned, document-store-only endpoints are not registered, and
|
|
11
|
-
// all runtime document-store code takes its existing "disabled" path. Set via the
|
|
12
|
-
// --documentStore.enabled CLI flag / [documentStore] enabled config or EENGINE_DOCUMENT_STORE_ENABLED.
|
|
13
|
-
const documentStoreFeatureEnabled = hasEnvValue('EENGINE_DOCUMENT_STORE_ENABLED')
|
|
14
|
-
? getBoolean(readEnvValue('EENGINE_DOCUMENT_STORE_ENABLED'))
|
|
15
|
-
: getBoolean(config.documentStore && config.documentStore.enabled);
|
|
16
|
-
|
|
17
|
-
// Effective runtime state: the feature must be available (gate) AND enabled in settings.
|
|
18
|
-
// When the gate is off this is always false, so callers reuse the already-tested
|
|
19
|
-
// "documentStoreEnabled is false" code paths.
|
|
20
|
-
const isDocumentStoreEnabled = async () => documentStoreFeatureEnabled && !!(await settings.get('documentStoreEnabled'));
|
|
21
|
-
|
|
22
|
-
const clientCache = { version: -1, config: false, client: false, index: false };
|
|
23
|
-
|
|
24
|
-
const getESClient = async logger => {
|
|
25
|
-
// Feature gate is off: behave exactly as a disabled document store. Checked before any
|
|
26
|
-
// Redis access so disabled deployments do not pay a round-trip on every getESClient call.
|
|
27
|
-
if (!documentStoreFeatureEnabled) {
|
|
28
|
-
return clientCache;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
const documentStoreVersion = (await settings.get('documentStoreVersion')) || 0;
|
|
32
|
-
if (clientCache.version === documentStoreVersion) {
|
|
33
|
-
return clientCache;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
let documentStoreEnabled = await settings.get('documentStoreEnabled');
|
|
37
|
-
let documentStoreUrl = await settings.get('documentStoreUrl');
|
|
38
|
-
|
|
39
|
-
if (!documentStoreEnabled || !documentStoreUrl) {
|
|
40
|
-
clientCache.version = documentStoreVersion;
|
|
41
|
-
clientCache.client = false;
|
|
42
|
-
clientCache.index = false;
|
|
43
|
-
return clientCache;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
clientCache.index = (await settings.get('documentStoreIndex')) || 'emailengine';
|
|
47
|
-
|
|
48
|
-
let documentStoreAuthEnabled = await settings.get('documentStoreAuthEnabled');
|
|
49
|
-
let documentStoreUsername = await settings.get('documentStoreUsername');
|
|
50
|
-
let documentStorePassword = await settings.get('documentStorePassword');
|
|
51
|
-
|
|
52
|
-
clientCache.config = {
|
|
53
|
-
node: { url: new URL(documentStoreUrl), tls: { rejectUnauthorized: false } },
|
|
54
|
-
auth:
|
|
55
|
-
documentStoreAuthEnabled && documentStoreUsername
|
|
56
|
-
? {
|
|
57
|
-
username: documentStoreUsername,
|
|
58
|
-
password: documentStorePassword
|
|
59
|
-
}
|
|
60
|
-
: false
|
|
61
|
-
};
|
|
62
|
-
|
|
63
|
-
clientCache.version = documentStoreVersion;
|
|
64
|
-
clientCache.client = new ElasticSearch(clientCache.config);
|
|
65
|
-
|
|
66
|
-
// ensure proper index settings
|
|
67
|
-
let indexResult = await ensureIndex(clientCache.client, clientCache.index);
|
|
68
|
-
if (!indexResult || !indexResult.exists) {
|
|
69
|
-
logger.info({ msg: 'Updated document index', index: clientCache.index, result: indexResult });
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
return clientCache;
|
|
73
|
-
};
|
|
74
|
-
|
|
75
|
-
module.exports = { getESClient, documentStoreFeatureEnabled, isDocumentStoreEnabled };
|