@postalsys/email-ai-tools 2.2.7 → 2.3.0
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/CHANGELOG.md +19 -0
- package/README.md +1 -1
- package/dist/cjs/index.d.ts +28 -0
- package/dist/cjs/index.js +67 -0
- package/dist/cjs/lib/api-request.d.ts +42 -0
- package/dist/cjs/lib/api-request.js +183 -0
- package/dist/cjs/lib/authentication.d.ts +46 -0
- package/{lib → dist/cjs/lib}/authentication.js +33 -44
- package/dist/cjs/lib/generate-summary.d.ts +143 -0
- package/dist/cjs/lib/generate-summary.js +562 -0
- package/dist/cjs/lib/get-api-url.d.ts +19 -0
- package/dist/cjs/lib/get-api-url.js +37 -0
- package/dist/cjs/lib/list-models.d.ts +46 -0
- package/dist/cjs/lib/list-models.js +125 -0
- package/dist/cjs/lib/signals.d.ts +72 -0
- package/dist/cjs/lib/signals.js +293 -0
- package/dist/cjs/lib/token-estimate.d.ts +46 -0
- package/{lib → dist/cjs/lib}/token-estimate.js +21 -50
- package/dist/cjs/lib/visible-text.d.ts +33 -0
- package/dist/cjs/lib/visible-text.js +182 -0
- package/dist/cjs/package-info.d.ts +2 -0
- package/dist/cjs/package-info.js +6 -0
- package/dist/cjs/package.json +3 -0
- package/dist/esm/index.d.ts +28 -0
- package/dist/esm/index.js +30 -0
- package/dist/esm/lib/api-request.d.ts +42 -0
- package/{lib → dist/esm/lib}/api-request.js +20 -53
- package/dist/esm/lib/authentication.d.ts +46 -0
- package/dist/esm/lib/authentication.js +149 -0
- package/dist/esm/lib/generate-summary.d.ts +143 -0
- package/{lib → dist/esm/lib}/generate-summary.js +59 -155
- package/dist/esm/lib/get-api-url.d.ts +19 -0
- package/{lib → dist/esm/lib}/get-api-url.js +4 -13
- package/dist/esm/lib/list-models.d.ts +46 -0
- package/{lib → dist/esm/lib}/list-models.js +19 -50
- package/dist/esm/lib/signals.d.ts +72 -0
- package/{lib → dist/esm/lib}/signals.js +33 -79
- package/dist/esm/lib/token-estimate.d.ts +46 -0
- package/dist/esm/lib/token-estimate.js +108 -0
- package/dist/esm/lib/visible-text.d.ts +33 -0
- package/{lib → dist/esm/lib}/visible-text.js +14 -40
- package/dist/esm/package-info.d.ts +2 -0
- package/dist/esm/package-info.js +3 -0
- package/dist/esm/package.json +3 -0
- package/package.json +73 -13
- package/.eslintrc +0 -22
- package/.github/VULNERABILITY_REPORT.yml +0 -75
- package/.github/workflows/release.yaml +0 -36
- package/.github/workflows/test.yaml +0 -43
- package/.ncurc.js +0 -18
- package/.prettierignore +0 -3
- package/.prettierrc.js +0 -10
- package/.release-please-manifest.json +0 -3
- package/CLAUDE.md +0 -150
- package/eslint.config.js +0 -39
- package/examples/fixtures/message-1.json +0 -74
- package/examples/list-models.js +0 -14
- package/examples/summary.js +0 -34
- package/index.js +0 -26
- package/release-please-config.json +0 -10
- package/test/api-request.test.js +0 -169
- package/test/authentication.test.js +0 -110
- package/test/dispatcher.test.js +0 -94
- package/test/generate-summary.test.js +0 -795
- package/test/get-api-url.test.js +0 -52
- package/test/helpers/mock-server.js +0 -120
- package/test/index.test.js +0 -57
- package/test/list-models.test.js +0 -302
- package/test/signals.test.js +0 -264
- package/test/token-estimate.test.js +0 -164
- package/test/visible-text.test.js +0 -144
|
@@ -1,18 +1,13 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
const util = require('util');
|
|
7
|
-
const packageData = require('../package.json');
|
|
8
|
-
|
|
1
|
+
import { fetch as fetchCmd, Agent } from 'undici';
|
|
2
|
+
import timers from 'node:timers/promises';
|
|
3
|
+
import crypto from 'node:crypto';
|
|
4
|
+
import util from 'node:util';
|
|
5
|
+
import { name as packageName, version as packageVersion } from '../package-info.js';
|
|
9
6
|
const fetchAgent = new Agent({ connect: { timeout: 90 * 1000 } });
|
|
10
|
-
|
|
11
7
|
// How long one call may take in all, retries included, when the caller sets no deadline of its
|
|
12
8
|
// own. undici bounds each phase of a request but nothing bounds the sum, and a chat completion
|
|
13
9
|
// waits for its headers until the answer is complete
|
|
14
10
|
const DEFAULT_TIMEOUT = 5 * 60 * 1000;
|
|
15
|
-
|
|
16
11
|
const MAX_RETRIES = 5;
|
|
17
12
|
const RETRY_DELAY_MS = 1000;
|
|
18
13
|
// A 429 asking for a longer pause than this fails right away instead of holding the caller
|
|
@@ -20,11 +15,11 @@ const MAX_RETRY_DELAY_MS = 20 * 1000;
|
|
|
20
15
|
// Large enough for a batch of 3072-dimension embeddings, small enough to not buffer anything
|
|
21
16
|
const MAX_RESPONSE_SIZE = 8 * 1024 * 1024;
|
|
22
17
|
const RESPONSE_SNIPPET_LENGTH = 512;
|
|
23
|
-
|
|
24
18
|
async function sleep(ms, signal) {
|
|
25
19
|
try {
|
|
26
|
-
await
|
|
27
|
-
}
|
|
20
|
+
await timers.setTimeout(ms, undefined, { signal });
|
|
21
|
+
}
|
|
22
|
+
catch (err) {
|
|
28
23
|
// report the caller's own abort reason, not the generic AbortError of the timer
|
|
29
24
|
if (err.name === 'AbortError' && signal && signal.aborted) {
|
|
30
25
|
throw signal.reason;
|
|
@@ -32,7 +27,6 @@ async function sleep(ms, signal) {
|
|
|
32
27
|
throw err;
|
|
33
28
|
}
|
|
34
29
|
}
|
|
35
|
-
|
|
36
30
|
// Returns the requested delay in milliseconds, or null if the response does not name one
|
|
37
31
|
function getRetryAfter(headers) {
|
|
38
32
|
// Azure OpenAI sends the millisecond variant
|
|
@@ -40,7 +34,6 @@ function getRetryAfter(headers) {
|
|
|
40
34
|
if (/^\d+(\.\d+)?$/.test(retryAfterMs)) {
|
|
41
35
|
return Number(retryAfterMs);
|
|
42
36
|
}
|
|
43
|
-
|
|
44
37
|
const retryAfter = (headers.get('retry-after') || '').trim();
|
|
45
38
|
if (!retryAfter) {
|
|
46
39
|
return null;
|
|
@@ -54,14 +47,12 @@ function getRetryAfter(headers) {
|
|
|
54
47
|
}
|
|
55
48
|
return null;
|
|
56
49
|
}
|
|
57
|
-
|
|
58
50
|
async function readBody(res, maxSize) {
|
|
59
51
|
const declared = Number(res.headers.get('content-length'));
|
|
60
52
|
if (declared > maxSize) {
|
|
61
53
|
await res.body?.cancel().catch(() => false);
|
|
62
54
|
throw responseTooLarge(res, maxSize);
|
|
63
55
|
}
|
|
64
|
-
|
|
65
56
|
const chunks = [];
|
|
66
57
|
let size = 0;
|
|
67
58
|
if (res.body) {
|
|
@@ -76,14 +67,12 @@ async function readBody(res, maxSize) {
|
|
|
76
67
|
}
|
|
77
68
|
return Buffer.concat(chunks).toString('utf-8');
|
|
78
69
|
}
|
|
79
|
-
|
|
80
70
|
function responseTooLarge(res, maxSize) {
|
|
81
71
|
const error = new Error(`API response exceeds the maximum allowed size of ${maxSize} bytes`);
|
|
82
72
|
error.code = 'ResponseTooLarge';
|
|
83
73
|
error.statusCode = res.status;
|
|
84
74
|
return error;
|
|
85
75
|
}
|
|
86
|
-
|
|
87
76
|
function errorMessage(apiError) {
|
|
88
77
|
if (typeof apiError === 'string') {
|
|
89
78
|
return apiError;
|
|
@@ -93,63 +82,48 @@ function errorMessage(apiError) {
|
|
|
93
82
|
}
|
|
94
83
|
try {
|
|
95
84
|
return JSON.stringify(apiError);
|
|
96
|
-
}
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
97
87
|
return 'Failed to run API request';
|
|
98
88
|
}
|
|
99
89
|
}
|
|
100
|
-
|
|
101
90
|
/**
|
|
102
91
|
* Sends a request to an OpenAI-compatible API and returns the parsed JSON response body
|
|
103
92
|
*
|
|
104
|
-
* @param
|
|
105
|
-
* @
|
|
106
|
-
* @param {string} [opts.method='post']
|
|
107
|
-
* @param {string} opts.apiToken - Sent as a Bearer token
|
|
108
|
-
* @param {Object} [opts.payload] - JSON request body
|
|
109
|
-
* @param {Object} [opts.dispatcher] - undici Dispatcher, the module's own agent when omitted
|
|
110
|
-
* @param {AbortSignal} [opts.signal] - Aborts the request and any retry wait; without one the call is given `timeout` in all
|
|
111
|
-
* @param {number} [opts.timeout=DEFAULT_TIMEOUT] - Deadline in milliseconds for the whole call when no signal is given
|
|
112
|
-
* @param {boolean} [opts.verbose] - Logs the request and the response to stderr
|
|
113
|
-
* @returns {Promise<{data: Object, time: number}>} Parsed response body and the time the request took in milliseconds
|
|
93
|
+
* @param url - Request URL
|
|
94
|
+
* @returns Parsed response body and the time the request took in milliseconds
|
|
114
95
|
*/
|
|
115
96
|
async function apiRequest(url, opts) {
|
|
116
97
|
const { method, apiToken, payload, dispatcher, verbose } = opts;
|
|
117
98
|
const signal = opts.signal || AbortSignal.timeout(opts.timeout || DEFAULT_TIMEOUT);
|
|
118
|
-
|
|
119
99
|
const headers = {
|
|
120
|
-
'User-Agent': `${
|
|
100
|
+
'User-Agent': `${packageName}/${packageVersion}`,
|
|
121
101
|
Authorization: `Bearer ${apiToken}`,
|
|
122
102
|
'Content-Type': 'application/json'
|
|
123
103
|
};
|
|
124
|
-
|
|
125
104
|
const requestId = crypto.randomBytes(8).toString('base64');
|
|
126
105
|
if (verbose) {
|
|
127
106
|
console.error(util.inspect({ requestId, apiUrl: url, payload }, false, 8, true));
|
|
128
107
|
}
|
|
129
|
-
|
|
130
108
|
const startTime = Date.now();
|
|
131
|
-
|
|
132
|
-
for (let attempt = 1; ; attempt++) {
|
|
109
|
+
for (let attempt = 1;; attempt++) {
|
|
133
110
|
const res = await fetchCmd(url, {
|
|
134
111
|
method: method || 'post',
|
|
135
112
|
headers,
|
|
136
|
-
body: payload ? JSON.stringify(payload) :
|
|
113
|
+
body: payload ? JSON.stringify(payload) : null,
|
|
137
114
|
dispatcher: dispatcher || fetchAgent,
|
|
138
115
|
signal
|
|
139
116
|
});
|
|
140
|
-
|
|
141
117
|
const text = await readBody(res, MAX_RESPONSE_SIZE);
|
|
142
|
-
|
|
143
118
|
let data = null;
|
|
144
119
|
try {
|
|
145
120
|
data = JSON.parse(text);
|
|
146
|
-
}
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
147
123
|
// handled below, an HTML error page from a proxy is the usual case
|
|
148
124
|
}
|
|
149
|
-
|
|
150
125
|
if (!res.ok) {
|
|
151
126
|
const retryAfter = res.status === 429 ? getRetryAfter(res.headers) : null;
|
|
152
|
-
|
|
153
127
|
if (res.status === 429 && attempt < MAX_RETRIES) {
|
|
154
128
|
const wait = retryAfter !== null ? retryAfter : RETRY_DELAY_MS * 2 ** (attempt - 1);
|
|
155
129
|
if (wait <= MAX_RETRY_DELAY_MS) {
|
|
@@ -157,7 +131,6 @@ async function apiRequest(url, opts) {
|
|
|
157
131
|
continue;
|
|
158
132
|
}
|
|
159
133
|
}
|
|
160
|
-
|
|
161
134
|
let error;
|
|
162
135
|
if (data && data.error) {
|
|
163
136
|
error = new Error(errorMessage(data.error));
|
|
@@ -171,21 +144,19 @@ async function apiRequest(url, opts) {
|
|
|
171
144
|
if (typeof data.error.type === 'string' && data.error.type) {
|
|
172
145
|
error.type = data.error.type;
|
|
173
146
|
}
|
|
174
|
-
}
|
|
147
|
+
}
|
|
148
|
+
else {
|
|
175
149
|
error = new Error('Failed to run API request');
|
|
176
150
|
}
|
|
177
151
|
error.statusCode = res.status;
|
|
178
|
-
|
|
179
152
|
if (retryAfter !== null) {
|
|
180
153
|
error.retryAfter = Math.ceil(retryAfter / 1000);
|
|
181
154
|
}
|
|
182
|
-
|
|
183
155
|
if (!data && text) {
|
|
184
156
|
error.responseText = text.substring(0, RESPONSE_SNIPPET_LENGTH);
|
|
185
157
|
}
|
|
186
158
|
throw error;
|
|
187
159
|
}
|
|
188
|
-
|
|
189
160
|
if (!data) {
|
|
190
161
|
// not JSON at all, or a JSON null
|
|
191
162
|
const error = new Error('Invalid JSON in API response');
|
|
@@ -194,15 +165,11 @@ async function apiRequest(url, opts) {
|
|
|
194
165
|
error.responseText = text.substring(0, RESPONSE_SNIPPET_LENGTH);
|
|
195
166
|
throw error;
|
|
196
167
|
}
|
|
197
|
-
|
|
198
168
|
const time = Date.now() - startTime;
|
|
199
|
-
|
|
200
169
|
if (verbose) {
|
|
201
170
|
console.error(util.inspect({ requestId, output: data }, false, 8, true));
|
|
202
171
|
}
|
|
203
|
-
|
|
204
172
|
return { data, time };
|
|
205
173
|
}
|
|
206
174
|
}
|
|
207
|
-
|
|
208
|
-
module.exports = { apiRequest, MAX_RESPONSE_SIZE, DEFAULT_TIMEOUT };
|
|
175
|
+
export { apiRequest, MAX_RESPONSE_SIZE, DEFAULT_TIMEOUT };
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/** The parsed results, the first one per method */
|
|
2
|
+
export type AuthenticationResults = Partial<Record<'spf' | 'dkim' | 'dmarc' | 'arc', string>>;
|
|
3
|
+
/** The authentication block of the model's input */
|
|
4
|
+
export interface AuthenticationBlock extends AuthenticationResults {
|
|
5
|
+
verified: boolean;
|
|
6
|
+
authservId?: string | undefined;
|
|
7
|
+
}
|
|
8
|
+
/** Which authserv-ids count as the receiving server */
|
|
9
|
+
export interface AuthenticationTrust {
|
|
10
|
+
/** Lower-case names */
|
|
11
|
+
trustedAuthservIds: string[];
|
|
12
|
+
acceptUnnamedAuthentication: boolean;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Parses one Authentication-Results header value
|
|
16
|
+
*
|
|
17
|
+
* @param value - Header value, unfolded
|
|
18
|
+
* @returns The authserv-id (null when the header carries none, as Microsoft's do) and the first result per method
|
|
19
|
+
*/
|
|
20
|
+
declare function parseAuthenticationResults(value: unknown): {
|
|
21
|
+
authservId: string | null;
|
|
22
|
+
results: AuthenticationResults;
|
|
23
|
+
} | null;
|
|
24
|
+
/**
|
|
25
|
+
* Tells whether an authserv-id names a server the caller trusts: the name itself or a host
|
|
26
|
+
* under it
|
|
27
|
+
*
|
|
28
|
+
* @param trusted - Trusted names, lower case
|
|
29
|
+
* @param acceptUnnamed - Whether a header without an authserv-id counts, for providers that write none
|
|
30
|
+
*/
|
|
31
|
+
declare function isTrustedAuthservId(authservId: string | null | undefined, trusted: string[] | string | null | undefined, acceptUnnamed?: boolean): boolean;
|
|
32
|
+
/**
|
|
33
|
+
* The authentication block of the model's input: the receiving server's verdict, marked as
|
|
34
|
+
* verified when the server that wrote it is one the caller trusts
|
|
35
|
+
*
|
|
36
|
+
* @param value - The topmost Authentication-Results header value
|
|
37
|
+
*/
|
|
38
|
+
declare function authenticationBlock(value: unknown, trust: AuthenticationTrust): AuthenticationBlock | null;
|
|
39
|
+
/**
|
|
40
|
+
* Whether a verified verdict says the sender failed: DMARC failed outright, or both SPF and
|
|
41
|
+
* DKIM did without DMARC saying otherwise
|
|
42
|
+
*
|
|
43
|
+
* @param authentication - As returned by authenticationBlock()
|
|
44
|
+
*/
|
|
45
|
+
declare function authenticationFailed(authentication: AuthenticationBlock | null | undefined): boolean;
|
|
46
|
+
export { parseAuthenticationResults, isTrustedAuthservId, authenticationBlock, authenticationFailed };
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
// The Authentication-Results header (RFC 8601) is where the receiving server records what it
|
|
2
|
+
// verified about the sender. A sender can add one of its own, so only a header the receiving
|
|
3
|
+
// server added counts, and that is told by its authserv-id: the name of the server that wrote
|
|
4
|
+
// it. The caller says which names it trusts for the mailbox at hand
|
|
5
|
+
const METHODS = ['spf', 'dkim', 'dmarc', 'arc'];
|
|
6
|
+
// Splits a header value on the semicolons outside comments and quoted strings, which may carry
|
|
7
|
+
// semicolons of their own and whose content a trusted server copies from the message. Comments
|
|
8
|
+
// nest, and both are dropped from the pieces, since the grammar needs neither
|
|
9
|
+
function splitResinfo(value) {
|
|
10
|
+
const segments = [];
|
|
11
|
+
let current = '';
|
|
12
|
+
let depth = 0;
|
|
13
|
+
let quoted = false;
|
|
14
|
+
for (let i = 0; i < value.length; i++) {
|
|
15
|
+
const char = value[i];
|
|
16
|
+
if (quoted) {
|
|
17
|
+
if (char === '\\') {
|
|
18
|
+
i++;
|
|
19
|
+
}
|
|
20
|
+
else if (char === '"') {
|
|
21
|
+
quoted = false;
|
|
22
|
+
}
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
if (depth) {
|
|
26
|
+
// a quote inside a comment is not a quoted string by the grammar, but a server that
|
|
27
|
+
// echoes an address into a comment may write one, and a parenthesis in it must not
|
|
28
|
+
// end the comment
|
|
29
|
+
if (char === '\\') {
|
|
30
|
+
i++;
|
|
31
|
+
}
|
|
32
|
+
else if (char === '"') {
|
|
33
|
+
quoted = true;
|
|
34
|
+
}
|
|
35
|
+
else if (char === '(') {
|
|
36
|
+
depth++;
|
|
37
|
+
}
|
|
38
|
+
else if (char === ')') {
|
|
39
|
+
depth--;
|
|
40
|
+
}
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
if (char === '"') {
|
|
44
|
+
quoted = true;
|
|
45
|
+
}
|
|
46
|
+
else if (char === '(') {
|
|
47
|
+
depth = 1;
|
|
48
|
+
}
|
|
49
|
+
else if (char === ';') {
|
|
50
|
+
segments.push(current.trim());
|
|
51
|
+
current = '';
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
current += char;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
segments.push(current.trim());
|
|
58
|
+
return segments.filter(Boolean);
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Parses one Authentication-Results header value
|
|
62
|
+
*
|
|
63
|
+
* @param value - Header value, unfolded
|
|
64
|
+
* @returns The authserv-id (null when the header carries none, as Microsoft's do) and the first result per method
|
|
65
|
+
*/
|
|
66
|
+
function parseAuthenticationResults(value) {
|
|
67
|
+
const segments = splitResinfo(String(value ?? ''));
|
|
68
|
+
if (!segments.length) {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
let authservId = null;
|
|
72
|
+
const first = segments[0];
|
|
73
|
+
const firstToken = first.split(/\s+/)[0];
|
|
74
|
+
if (!first.includes('=')) {
|
|
75
|
+
// "authserv-id" or "authserv-id version"
|
|
76
|
+
authservId = firstToken.toLowerCase();
|
|
77
|
+
segments.shift();
|
|
78
|
+
}
|
|
79
|
+
else if (!firstToken.includes('=') && /\s[a-z0-9-]+\s*=/i.test(first)) {
|
|
80
|
+
// "authserv-id method=result" in one segment, which some servers write
|
|
81
|
+
authservId = firstToken.toLowerCase();
|
|
82
|
+
segments[0] = first.substring(firstToken.length).trim();
|
|
83
|
+
}
|
|
84
|
+
const results = {};
|
|
85
|
+
for (const segment of segments) {
|
|
86
|
+
const match = /^([a-z0-9-]+)\s*=\s*([a-z0-9-]+)/i.exec(segment);
|
|
87
|
+
if (!match) {
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
const method = match[1].toLowerCase();
|
|
91
|
+
const result = match[2].toLowerCase();
|
|
92
|
+
if (!METHODS.includes(method)) {
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
// the first result per method: a second DKIM entry is another signature on the message,
|
|
96
|
+
// a mailing list's broken one as often as not, and not a verdict on the first
|
|
97
|
+
if (!(method in results)) {
|
|
98
|
+
results[method] = result;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return { authservId, results };
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Tells whether an authserv-id names a server the caller trusts: the name itself or a host
|
|
105
|
+
* under it
|
|
106
|
+
*
|
|
107
|
+
* @param trusted - Trusted names, lower case
|
|
108
|
+
* @param acceptUnnamed - Whether a header without an authserv-id counts, for providers that write none
|
|
109
|
+
*/
|
|
110
|
+
function isTrustedAuthservId(authservId, trusted, acceptUnnamed) {
|
|
111
|
+
if (!authservId) {
|
|
112
|
+
return !!acceptUnnamed;
|
|
113
|
+
}
|
|
114
|
+
const id = authservId.toLowerCase();
|
|
115
|
+
return [].concat(trusted || []).some(name => name && (id === name || id.endsWith(`.${name}`)));
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* The authentication block of the model's input: the receiving server's verdict, marked as
|
|
119
|
+
* verified when the server that wrote it is one the caller trusts
|
|
120
|
+
*
|
|
121
|
+
* @param value - The topmost Authentication-Results header value
|
|
122
|
+
*/
|
|
123
|
+
function authenticationBlock(value, trust) {
|
|
124
|
+
const parsed = parseAuthenticationResults(value);
|
|
125
|
+
if (!parsed) {
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
return Object.assign({
|
|
129
|
+
verified: isTrustedAuthservId(parsed.authservId, trust.trustedAuthservIds, trust.acceptUnnamedAuthentication),
|
|
130
|
+
authservId: parsed.authservId || undefined
|
|
131
|
+
}, parsed.results);
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Whether a verified verdict says the sender failed: DMARC failed outright, or both SPF and
|
|
135
|
+
* DKIM did without DMARC saying otherwise
|
|
136
|
+
*
|
|
137
|
+
* @param authentication - As returned by authenticationBlock()
|
|
138
|
+
*/
|
|
139
|
+
function authenticationFailed(authentication) {
|
|
140
|
+
if (!authentication || !authentication.verified) {
|
|
141
|
+
return false;
|
|
142
|
+
}
|
|
143
|
+
if (authentication.dmarc === 'fail') {
|
|
144
|
+
return true;
|
|
145
|
+
}
|
|
146
|
+
const failed = (result) => ['fail', 'softfail', 'permerror'].includes(result);
|
|
147
|
+
return !authentication.dmarc && failed(authentication.spf) && failed(authentication.dkim);
|
|
148
|
+
}
|
|
149
|
+
export { parseAuthenticationResults, isTrustedAuthservId, authenticationBlock, authenticationFailed };
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import type { Dispatcher } from 'undici';
|
|
2
|
+
import type { ApiRequestError } from './api-request.js';
|
|
3
|
+
import type { Signal } from './signals.js';
|
|
4
|
+
/** An address as {name, address} */
|
|
5
|
+
export interface SummaryAddress {
|
|
6
|
+
name?: string | null | undefined;
|
|
7
|
+
address?: string | null | undefined;
|
|
8
|
+
}
|
|
9
|
+
/** The email message to analyze */
|
|
10
|
+
export interface SummaryMessage {
|
|
11
|
+
/** Header objects; a value may be a string or a list of strings, encoded words are decoded */
|
|
12
|
+
headers?: Array<{
|
|
13
|
+
key?: string | null | undefined;
|
|
14
|
+
value?: unknown;
|
|
15
|
+
} | null | undefined> | null | undefined;
|
|
16
|
+
/** Decoded subject, used over the subject header */
|
|
17
|
+
subject?: string | null | undefined;
|
|
18
|
+
/** Sender, as a string or as {name, address}, used over the from header */
|
|
19
|
+
from?: string | SummaryAddress | null | undefined;
|
|
20
|
+
/** Message date, used over the date header */
|
|
21
|
+
date?: string | Date | null | undefined;
|
|
22
|
+
/** Attachment objects with {filename, contentType} */
|
|
23
|
+
attachments?: Array<{
|
|
24
|
+
filename?: string | null | undefined;
|
|
25
|
+
contentType?: string | null | undefined;
|
|
26
|
+
[key: string]: unknown;
|
|
27
|
+
} | null | undefined> | null | undefined;
|
|
28
|
+
/** Plain text content */
|
|
29
|
+
text?: string | null | undefined;
|
|
30
|
+
/** HTML content, converted to text when it is the fuller version */
|
|
31
|
+
html?: string | null | undefined;
|
|
32
|
+
}
|
|
33
|
+
export interface GenerateSummaryOptions {
|
|
34
|
+
/** Custom API base URL (default: OpenAI API) */
|
|
35
|
+
baseApiUrl?: string | null | undefined;
|
|
36
|
+
/** Model to use (default: DEFAULT_MODEL) */
|
|
37
|
+
gptModel?: string | null | undefined;
|
|
38
|
+
/** Replaces the role and trust rules at the top of the system message */
|
|
39
|
+
systemPrompt?: string | null | undefined;
|
|
40
|
+
/** Replaces the analysis instructions, including the output properties */
|
|
41
|
+
instructions?: string | null | undefined;
|
|
42
|
+
/** Maximum estimated tokens for the prompt (default 30000, a character-based estimate that errs high) */
|
|
43
|
+
maxTokens?: number | null | undefined;
|
|
44
|
+
/** Sampling temperature (0-2), not sent to a model that is reasoning */
|
|
45
|
+
temperature?: number | string | null | undefined;
|
|
46
|
+
/** Nucleus sampling parameter (0-1), not sent to a model that is reasoning */
|
|
47
|
+
topP?: number | string | null | undefined;
|
|
48
|
+
/** Reasoning effort for reasoning models ("low" when unset for one) */
|
|
49
|
+
reasoningEffort?: string | null | undefined;
|
|
50
|
+
/** Ask for a JSON object response (default true), dropped when the model refuses it */
|
|
51
|
+
jsonMode?: boolean | undefined;
|
|
52
|
+
/** End-user identifier passed to the API */
|
|
53
|
+
user?: string | null | undefined;
|
|
54
|
+
/** Additional headers to include (merged with defaults) */
|
|
55
|
+
allowedHeaders?: string[] | string | null | undefined;
|
|
56
|
+
/** Names of the servers whose Authentication-Results header counts as verified, hosts under them included */
|
|
57
|
+
trustedAuthservIds?: string[] | string | null | undefined;
|
|
58
|
+
/** Whether an Authentication-Results header without an authserv-id counts as verified (Microsoft writes none) */
|
|
59
|
+
acceptUnnamedAuthentication?: boolean | undefined;
|
|
60
|
+
/** Log requests to stderr and include the prompt text in the usage */
|
|
61
|
+
verbose?: boolean | undefined;
|
|
62
|
+
/** undici Dispatcher (for example a ProxyAgent) the API request is sent through */
|
|
63
|
+
dispatcher?: Dispatcher | undefined;
|
|
64
|
+
/** Aborts the API request and any rate limit retry wait */
|
|
65
|
+
signal?: AbortSignal | undefined;
|
|
66
|
+
}
|
|
67
|
+
/** What the model returned, with the documented properties normalized */
|
|
68
|
+
export interface SummaryResult {
|
|
69
|
+
summary?: string;
|
|
70
|
+
sentiment?: 'positive' | 'neutral' | 'negative';
|
|
71
|
+
shouldReply?: boolean;
|
|
72
|
+
riskAssessment?: {
|
|
73
|
+
risk?: number;
|
|
74
|
+
assessment?: string;
|
|
75
|
+
signals?: string[];
|
|
76
|
+
[key: string]: unknown;
|
|
77
|
+
};
|
|
78
|
+
events?: Array<Record<string, string | number | boolean>>;
|
|
79
|
+
actions?: Array<Record<string, string | number | boolean>>;
|
|
80
|
+
[key: string]: unknown;
|
|
81
|
+
}
|
|
82
|
+
export interface SummaryUsage {
|
|
83
|
+
id: string | null;
|
|
84
|
+
model: string;
|
|
85
|
+
servedModel: string | null;
|
|
86
|
+
tokens: number | null;
|
|
87
|
+
promptTokens: number | null;
|
|
88
|
+
completionTokens: number | null;
|
|
89
|
+
time: number;
|
|
90
|
+
charactersRemoved: number;
|
|
91
|
+
/** The prompt text, with `verbose` */
|
|
92
|
+
text?: string;
|
|
93
|
+
}
|
|
94
|
+
/** An error from generateSummary(), carrying the signals found before it */
|
|
95
|
+
export interface SummaryError extends ApiRequestError {
|
|
96
|
+
signals?: Signal[];
|
|
97
|
+
textContent?: string;
|
|
98
|
+
finishReason?: string;
|
|
99
|
+
}
|
|
100
|
+
declare const DEFAULT_MODEL = "gpt-6-luna";
|
|
101
|
+
declare const REASONING_EFFORTS: string[];
|
|
102
|
+
declare const DEFAULT_REASONING_EFFORT = "low";
|
|
103
|
+
declare const DEFAULT_MAX_TOKENS = 30000;
|
|
104
|
+
declare const DEFAULT_SYSTEM_PROMPT: string;
|
|
105
|
+
declare const DEFAULT_INSTRUCTIONS: string;
|
|
106
|
+
/**
|
|
107
|
+
* Tells whether a model name belongs to a family that takes a reasoning effort and, while
|
|
108
|
+
* reasoning, refuses sampling parameters: GPT-5 and later, the open-weight gpt-oss models and
|
|
109
|
+
* the o-series. The "chat" variants of those families are ordinary chat models. A name this does
|
|
110
|
+
* not recognize (an Azure deployment, a prefixed name) is still handled: the backend's refusal
|
|
111
|
+
* of a parameter is honored either way, this only saves the request that learns it
|
|
112
|
+
*
|
|
113
|
+
* @param input - Model name as sent to the API
|
|
114
|
+
*/
|
|
115
|
+
declare function isReasoningModel(input: unknown): boolean;
|
|
116
|
+
/**
|
|
117
|
+
* Forgets which parameters a backend refused. Meant for tests
|
|
118
|
+
*/
|
|
119
|
+
declare function resetParameterCache(): void;
|
|
120
|
+
/**
|
|
121
|
+
* Analyzes an email message with a chat model and returns what the model reported, untouched
|
|
122
|
+
* except for normalization of the documented properties, beside the request usage
|
|
123
|
+
*
|
|
124
|
+
* @param message - The email message to analyze
|
|
125
|
+
* @param apiToken - API authentication token
|
|
126
|
+
* @param opts - Configuration options
|
|
127
|
+
*
|
|
128
|
+
* @returns The model's JSON object (`result`: sentiment, summary, shouldReply, riskAssessment and
|
|
129
|
+
* so on, with the risk score held at the signals' floor and the signal codes listed under
|
|
130
|
+
* riskAssessment.signals), the request usage and the signals found in code, each with its code,
|
|
131
|
+
* detail and floor
|
|
132
|
+
*
|
|
133
|
+
* @throws Error if the prompt is too long even without any text (code PROMPT_TOO_LONG)
|
|
134
|
+
* @throws Error if the API request fails
|
|
135
|
+
* @throws Error if the response holds no JSON object
|
|
136
|
+
*/
|
|
137
|
+
declare function generateSummary(message: SummaryMessage | null | undefined, apiToken: string, opts?: GenerateSummaryOptions | null): Promise<{
|
|
138
|
+
result: SummaryResult;
|
|
139
|
+
usage: SummaryUsage;
|
|
140
|
+
signals: Signal[];
|
|
141
|
+
}>;
|
|
142
|
+
declare const ALLOWED_HEADERS: readonly string[];
|
|
143
|
+
export { generateSummary, isReasoningModel, resetParameterCache, DEFAULT_MODEL, DEFAULT_REASONING_EFFORT, DEFAULT_MAX_TOKENS, DEFAULT_SYSTEM_PROMPT, DEFAULT_INSTRUCTIONS, REASONING_EFFORTS, ALLOWED_HEADERS };
|