@postalsys/email-ai-tools 3.0.4 → 3.0.5
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 +11 -0
- package/README.md +38 -24
- package/dist/cjs/lib/generate-summary.d.ts +5 -2
- package/dist/cjs/lib/generate-summary.js +141 -46
- package/dist/cjs/lib/visible-text.d.ts +2 -2
- package/dist/cjs/lib/visible-text.js +718 -66
- package/dist/cjs/package-info.d.ts +1 -1
- package/dist/cjs/package-info.js +1 -1
- package/dist/esm/lib/generate-summary.d.ts +5 -2
- package/dist/esm/lib/generate-summary.js +140 -46
- package/dist/esm/lib/visible-text.d.ts +2 -2
- package/dist/esm/lib/visible-text.js +718 -67
- package/dist/esm/package-info.d.ts +1 -1
- package/dist/esm/package-info.js +1 -1
- package/package.json +3 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [3.0.5](https://github.com/postalsys/email-ai-tools/compare/v3.0.4...v3.0.5) (2026-11-28)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
### Bug Fixes
|
|
7
|
+
|
|
8
|
+
* harden the summary against content the reader never sees ([f095a74](https://github.com/postalsys/email-ai-tools/commit/f095a746e5f1757fd0365bc967c9ade4e849fc5e))
|
|
9
|
+
* limit the tokens the model may spend on a summary ([fcb3068](https://github.com/postalsys/email-ai-tools/commit/fcb306848f18867536fab52723b7b59e8aeb463c))
|
|
10
|
+
* pass on only the documented summary properties with the default instructions ([e7cbc1b](https://github.com/postalsys/email-ai-tools/commit/e7cbc1b809493ba0c51aaad703cbed69ba051ddc))
|
|
11
|
+
* summarize the HTML part, and leave out text the message's style sheets hide ([2877a45](https://github.com/postalsys/email-ai-tools/commit/2877a4585f954ee150a3736a1a7aa1d2c7c1288f))
|
|
12
|
+
* trust a message's style sheets only when they can be read as a mail client reads them ([43e1d75](https://github.com/postalsys/email-ai-tools/commit/43e1d75292b9b1bf144c1fbdf53b1103dbd98f87))
|
|
13
|
+
|
|
3
14
|
## [3.0.4](https://github.com/postalsys/email-ai-tools/compare/v3.0.3...v3.0.4) (2026-11-26)
|
|
4
15
|
|
|
5
16
|
|
package/README.md
CHANGED
|
@@ -53,38 +53,43 @@ console.log(usage);
|
|
|
53
53
|
| `headers` | Array of `{ key, value }` objects; `value` may be a string or a list of strings. Encoded words are decoded. Only whitelisted headers reach the model |
|
|
54
54
|
| `attachments` | Array of `{ filename, contentType }` objects. Other properties are ignored |
|
|
55
55
|
| `text` | Plain text body |
|
|
56
|
-
| `html` | HTML body
|
|
56
|
+
| `html` | HTML body. Read in place of `text` whenever it has any text, because that is the part a mail client shows |
|
|
57
57
|
|
|
58
|
-
The whitelisted headers are `from`, `reply-to`, `to`, `cc`, `bcc`, `date`, `subject`, `in-reply-to`, `references`, `list-id`, `auto-submitted`, `precedence
|
|
58
|
+
The whitelisted headers are `from`, `reply-to`, `to`, `cc`, `bcc`, `date`, `subject`, `in-reply-to`, `references`, `list-id`, `auto-submitted`, `precedence` and `authentication-results`. Of the authentication results only the topmost value, the one added by the receiving server, is passed on. Add more with `options.allowedHeaders`.
|
|
59
59
|
|
|
60
60
|
### Options
|
|
61
61
|
|
|
62
|
-
| Option | Default
|
|
63
|
-
| ----------------------------- |
|
|
64
|
-
| `baseApiUrl` | `https://api.openai.com`
|
|
65
|
-
| `gptModel` | `DEFAULT_MODEL`
|
|
66
|
-
| `instructions` | `DEFAULT_INSTRUCTIONS`
|
|
67
|
-
| `systemPrompt` | `DEFAULT_SYSTEM_PROMPT`
|
|
68
|
-
| `maxTokens` | `30000`
|
|
69
|
-
| `
|
|
70
|
-
| `
|
|
71
|
-
| `
|
|
72
|
-
| `
|
|
73
|
-
| `
|
|
74
|
-
| `
|
|
75
|
-
| `
|
|
76
|
-
| `
|
|
77
|
-
| `
|
|
78
|
-
| `
|
|
79
|
-
| `
|
|
80
|
-
|
|
81
|
-
|
|
62
|
+
| Option | Default | Description |
|
|
63
|
+
| ----------------------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
64
|
+
| `baseApiUrl` | `https://api.openai.com` | Base URL of an OpenAI-compatible API, including any path prefix the service mounts it under, for example `https://<resource>.openai.azure.com/openai/v1` |
|
|
65
|
+
| `gptModel` | `DEFAULT_MODEL` | Model name |
|
|
66
|
+
| `instructions` | `DEFAULT_INSTRUCTIONS` | The analysis instructions, including the JSON properties to return. Replaces the default block as a whole |
|
|
67
|
+
| `systemPrompt` | `DEFAULT_SYSTEM_PROMPT` | The role and the untrusted-data rule at the top of the system message |
|
|
68
|
+
| `maxTokens` | `30000` | Budget for the whole prompt as an estimated token count. The email text is cut to fit |
|
|
69
|
+
| `maxCompletionTokens` | `4000`, `16000` from `medium` effort | Most tokens the answer may take, reasoning included, sent as `max_completion_tokens`. An answer cut short fails with `finishReason: "length"` |
|
|
70
|
+
| `reasoningEffort` | `low` for reasoning models | Sent as `reasoning_effort`. Reasoning models are GPT-5 and later, gpt-oss and the o-series; others get nothing unless a value is given |
|
|
71
|
+
| `temperature` | | Sampling temperature |
|
|
72
|
+
| `topP` | | Nucleus sampling cutoff |
|
|
73
|
+
| `jsonMode` | `true` | Asks for a JSON object response (`response_format`) |
|
|
74
|
+
| `user` | | End-user identifier passed to the API |
|
|
75
|
+
| `allowedHeaders` | | Header names to pass on in addition to the whitelist |
|
|
76
|
+
| `trustedAuthservIds` | | Names of the servers whose `Authentication-Results` header counts as verified, hosts under them included |
|
|
77
|
+
| `acceptUnnamedAuthentication` | `false` | Whether an `Authentication-Results` header without an authserv-id counts as verified |
|
|
78
|
+
| `dispatcher` | the module's own agent | undici dispatcher the request goes through, for example a `ProxyAgent` |
|
|
79
|
+
| `signal` | | `AbortSignal` that cancels the request and any rate limit wait |
|
|
80
|
+
| `verbose` | `false` | Logs the request and the response to stderr and includes the fitted text as `usage.text` |
|
|
81
|
+
|
|
82
|
+
A parameter the backend refuses with a 400 that names it (`response_format`, `reasoning_effort`, `temperature`, `top_p`, `max_completion_tokens`, `max_tokens`) is dropped, the request is repeated, and the refusal is remembered for that endpoint and model. A refused `max_completion_tokens` is sent as `max_tokens` first, so a server that predates the newer name still limits the answer. That is what makes one configuration work across OpenAI's reasoning models, its chat models, which reject `reasoning_effort`, and compatible servers that know neither. The sampling parameters are not even sent to a model that is reasoning, since every such model refuses them; with the effort set to `none` they are sent again.
|
|
82
83
|
|
|
83
84
|
### What the model sees, and what code checks first
|
|
84
85
|
|
|
85
86
|
The email is untrusted input, and the library does not leave its verdict to the model alone:
|
|
86
87
|
|
|
87
|
-
- **
|
|
88
|
+
- **The model reads the part the recipient sees.** When a message has an HTML part, that is what is read, however long the plain text beside it: a sender writes both, and a plain part no mail client shows is where text meant only for the model would go. The plain text is read only when there is no HTML, or the HTML has no text at all.
|
|
89
|
+
- **Hidden text is removed.** Elements a mail client does not render (`display:none`, `visibility:hidden`, a font size below a pixel, an opacity below a tenth, a far negative text indent, a block-level box of no height that clips its content, the `hidden` attribute, scripts, styles, comments) are dropped before the HTML is converted, and zero-width, soft-hyphen and bidirectional control characters are removed from the text. The model reads what the recipient sees. An element hidden only by an inherited property (visibility, font size, text indent) is kept when something inside it sets that property again, as email templates do with a `font-size:0` wrapper.
|
|
90
|
+
- **Style sheets count only when they can be read faithfully.** The message's own `<style>` rules are weighed with the `style` attributes the way a mail client weighs them: by specificity, then by their place in the sheet, the attribute after the rules, and `!important` declarations after all of those. A leading `html` or `body` before a descendant combinator matches as if both were present. Removing text a reader sees would be worse than leaving in text they do not, so the sheets count for nothing, and only `style` attributes do, whenever a rule that could show an element again cannot be read: a pseudo-class or a sibling combinator, a media query that does not hold for every reader, another at-rule, an `@import` or a linked style sheet, a sheet in a conditional comment, an escaped property name, more than 100 such rules, or matching them all would cost more than a fixed budget. The same happens where the parser here and a browser could disagree about which style elements exist: inside SVG or MathML, inside an element a browser reads as text (`noframes`, `noembed`, `iframe`, `noscript`, after `plaintext`), or after a comment a browser ends earlier (`--!>`, a CDATA section), and when the document is cut short.
|
|
91
|
+
- **Conditional comments are read as the clients read them.** Outlook-only content (`<!--[if mso]>...<![endif]-->`) is kept, and the downlevel-revealed form email builders write (`<!--[if !mso]><!-->...<!--<![endif]-->`) keeps the content between its two comments. Comments end where a browser ends them.
|
|
92
|
+
- **The work is bounded.** At most 1 MB of HTML and 128 KB of style sheets is read, elements nested more than 500 deep are left out (as the text converter would leave them out), and the style sheet rules are applied only while the estimated cost of matching them stays under a fixed budget. A hostile message costs about as much as an ordinary large one.
|
|
88
93
|
- **Signals are collected in code**, on the full message and before anything is removed, and the ones that carry a floor are passed to the model as `signals`: an executable or double-extension attachment (by extension or content type, after the name is normalised), an attachment a browser runs code from (HTML, SVG), a link whose text names a different host than its target (links read the way a browser does, hidden links included, image alt text counted as link text), a lookalike domain mixing scripts (a Cyrillic letter inside `paypal.com`, in unicode, punycode or percent encoding), a display name that reads as an address on another domain, a reply address on another domain, and a verified authentication failure. Each carries a quoted, cleaned detail.
|
|
89
94
|
- **The risk score has a floor.** After the model answers, `riskAssessment.risk` is raised to the floor of the signals found (4 for an executable attachment or a lookalike domain, 3 for a link mismatch, a scriptable attachment, a display name address or a failed authentication, 2 for a reply address elsewhere), the assessment says what was found, and `riskAssessment.signals` lists the codes. That list is always what the code found, an empty one when nothing was, whatever the model wrote there. A model talked into "risk 1" by text inside the message still delivers a 4 when the attachment is an executable. When the model's answer cannot be parsed, or the prompt cannot be fitted into the token budget, the error carries the signals.
|
|
90
95
|
- **Authentication results are parsed, and trusted only when the server that wrote them is.** The topmost `Authentication-Results` header becomes an `authentication` block with the SPF, DKIM, DMARC and ARC results and a `verified` flag, and is kept out of `headers` so the model never reads it as text a sender could have written; the ARC results header is not passed on at all. The parser handles nested comments and quoted strings, and lets a failure win when a method is repeated. `verified` is true when the header's authserv-id is one of `options.trustedAuthservIds` or a host under one, or when the header carries no authserv-id and `options.acceptUnnamedAuthentication` is set (Microsoft 365 writes such headers). The default instructions tell the model that an unverified or missing verdict means unknown, not failed. The library sees headers by name, not by position, so it cannot tell whether the topmost header was written by the receiving server or arrived with the message: the caller decides what to trust accordingly, and should not trust a name a sender could guess.
|
|
@@ -97,7 +102,16 @@ The system message carries the role, the rule that the email is untrusted data,
|
|
|
97
102
|
|
|
98
103
|
### Result
|
|
99
104
|
|
|
100
|
-
`result` is the JSON object the model returned, with `null` and empty values removed. The properties the default instructions ask for are normalized: `sentiment` is lower-cased and must be one of `positive`, `neutral` or `negative`, `shouldReply` is a boolean, `riskAssessment.risk` is an integer from 1 to 5, `summary` and `riskAssessment.assessment` are cut at 1000 characters, and `events` and `actions` are arrays of at most 50 objects whose values are strings (cut the same way), numbers or booleans. A value that cannot be made to fit is dropped.
|
|
105
|
+
`result` is the JSON object the model returned, with `null` and empty values removed. The properties the default instructions ask for are normalized: `sentiment` is lower-cased and must be one of `positive`, `neutral` or `negative`, `shouldReply` is a boolean, `riskAssessment.risk` is an integer from 1 to 5, `summary` and `riskAssessment.assessment` are cut at 1000 characters, and `events` and `actions` are arrays of at most 50 objects whose values are strings (cut the same way), numbers or booleans. A value that cannot be made to fit is dropped.
|
|
106
|
+
|
|
107
|
+
With the default instructions, only the documented properties are passed on: `summary`, `sentiment`, `shouldReply`, `riskAssessment` with `risk`, `assessment` and `signals`, `events` with `description`, `type`, `startTime`, `endTime` and `location`, and `actions` with `description` and `dueDate`. A property the model was not asked for is one the message asked it to write, and a consumer cannot tell it from a checked fact. Properties that custom `instructions` ask for are passed on, within bounds at every level: strings cut at 1000 characters, lists at 50 entries, objects at 50 properties and nesting at four levels.
|
|
108
|
+
|
|
109
|
+
### Using the result safely
|
|
110
|
+
|
|
111
|
+
Text in the email can steer what the model writes. Treat the result as a hint about the message, never as a decision:
|
|
112
|
+
|
|
113
|
+
- `riskAssessment.risk` is advisory. The floors make a low score impossible when code found something, but a message with no signal can still talk the model into a 1. Never use a low score to let a message through a check you would otherwise apply
|
|
114
|
+
- `summary`, `assessment` and the text of `events` and `actions` contain words the sender chose. Escape them before you render them as HTML, and do not pass them to another model as instructions
|
|
101
115
|
|
|
102
116
|
`usage` holds the request id, the model name requested and the one the API reports it served, the token counts, the request time in milliseconds and how many characters were cut from the text to fit the budget.
|
|
103
117
|
|
|
@@ -27,7 +27,7 @@ export interface SummaryMessage {
|
|
|
27
27
|
} | null | undefined> | null | undefined;
|
|
28
28
|
/** Plain text content */
|
|
29
29
|
text?: string | null | undefined;
|
|
30
|
-
/** HTML content,
|
|
30
|
+
/** HTML content, read in place of the plain text whenever it carries any text */
|
|
31
31
|
html?: string | null | undefined;
|
|
32
32
|
}
|
|
33
33
|
export interface GenerateSummaryOptions {
|
|
@@ -47,6 +47,8 @@ export interface GenerateSummaryOptions {
|
|
|
47
47
|
topP?: number | string | null | undefined;
|
|
48
48
|
/** Reasoning effort for reasoning models ("low" when unset for one) */
|
|
49
49
|
reasoningEffort?: string | null | undefined;
|
|
50
|
+
/** Most tokens the model may spend on its answer, reasoning included (default 4000, 16000 from a "medium" effort up) */
|
|
51
|
+
maxCompletionTokens?: number | string | null | undefined;
|
|
50
52
|
/** Ask for a JSON object response (default true), dropped when the model refuses it */
|
|
51
53
|
jsonMode?: boolean | undefined;
|
|
52
54
|
/** End-user identifier passed to the API */
|
|
@@ -101,6 +103,7 @@ declare const DEFAULT_MODEL = "gpt-6-luna";
|
|
|
101
103
|
declare const REASONING_EFFORTS: string[];
|
|
102
104
|
declare const DEFAULT_REASONING_EFFORT = "low";
|
|
103
105
|
declare const DEFAULT_MAX_TOKENS = 30000;
|
|
106
|
+
declare const DEFAULT_MAX_COMPLETION_TOKENS = 4000;
|
|
104
107
|
declare const DEFAULT_SYSTEM_PROMPT: string;
|
|
105
108
|
declare const DEFAULT_INSTRUCTIONS: string;
|
|
106
109
|
/**
|
|
@@ -140,4 +143,4 @@ declare function generateSummary(message: SummaryMessage | null | undefined, api
|
|
|
140
143
|
signals: Signal[];
|
|
141
144
|
}>;
|
|
142
145
|
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 };
|
|
146
|
+
export { generateSummary, isReasoningModel, resetParameterCache, DEFAULT_MODEL, DEFAULT_REASONING_EFFORT, DEFAULT_MAX_TOKENS, DEFAULT_MAX_COMPLETION_TOKENS, DEFAULT_SYSTEM_PROMPT, DEFAULT_INSTRUCTIONS, REASONING_EFFORTS, ALLOWED_HEADERS };
|
|
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.ALLOWED_HEADERS = exports.REASONING_EFFORTS = exports.DEFAULT_INSTRUCTIONS = exports.DEFAULT_SYSTEM_PROMPT = exports.DEFAULT_MAX_TOKENS = exports.DEFAULT_REASONING_EFFORT = exports.DEFAULT_MODEL = void 0;
|
|
6
|
+
exports.ALLOWED_HEADERS = exports.REASONING_EFFORTS = exports.DEFAULT_INSTRUCTIONS = exports.DEFAULT_SYSTEM_PROMPT = exports.DEFAULT_MAX_COMPLETION_TOKENS = exports.DEFAULT_MAX_TOKENS = exports.DEFAULT_REASONING_EFFORT = exports.DEFAULT_MODEL = void 0;
|
|
7
7
|
exports.generateSummary = generateSummary;
|
|
8
8
|
exports.isReasoningModel = isReasoningModel;
|
|
9
9
|
exports.resetParameterCache = resetParameterCache;
|
|
@@ -71,11 +71,40 @@ const RISK_MAX = 5;
|
|
|
71
71
|
// for more. The events and actions are what one message mentions
|
|
72
72
|
const MAX_TEXT_LENGTH = 1000;
|
|
73
73
|
const MAX_LIST_LENGTH = 50;
|
|
74
|
+
// What a custom instruction set adds to the answer is bounded the same way at every level, and
|
|
75
|
+
// in how far it nests and how many properties an object has: text in the message can ask the
|
|
76
|
+
// model for more of anything
|
|
77
|
+
const MAX_DEPTH = 4;
|
|
78
|
+
const MAX_KEYS = 50;
|
|
79
|
+
// The properties the default instructions ask for. With those instructions nothing else is
|
|
80
|
+
// passed on: a property the model was not asked for is one the message asked for, and a
|
|
81
|
+
// consumer reading "verified": true beside the risk score cannot tell who wrote it. Each property
|
|
82
|
+
// lists the keys of the object it holds, or of every entry of the list it holds, and null when it
|
|
83
|
+
// holds a single value. The risk signals are written by code after this, never by the model
|
|
84
|
+
const DOCUMENTED = {
|
|
85
|
+
summary: null,
|
|
86
|
+
sentiment: null,
|
|
87
|
+
shouldReply: null,
|
|
88
|
+
riskAssessment: ['risk', 'assessment'],
|
|
89
|
+
events: ['description', 'type', 'startTime', 'endTime', 'location'],
|
|
90
|
+
actions: ['description', 'dueDate']
|
|
91
|
+
};
|
|
92
|
+
// The answer is paid for by the token and nothing in the request bounded it: the documented
|
|
93
|
+
// object takes a few hundred tokens, and text in the message can ask for an essay. Reasoning
|
|
94
|
+
// tokens count against the same limit, so a model told to reason harder gets more room
|
|
95
|
+
const DEFAULT_MAX_COMPLETION_TOKENS = 4000;
|
|
96
|
+
exports.DEFAULT_MAX_COMPLETION_TOKENS = DEFAULT_MAX_COMPLETION_TOKENS;
|
|
97
|
+
const REASONING_MAX_COMPLETION_TOKENS = 16000;
|
|
98
|
+
const DEEP_REASONING_EFFORT = 'medium';
|
|
74
99
|
// Request parameters a backend may refuse with a 400 that names them. Such a parameter is
|
|
75
100
|
// dropped and the request repeated, and the refusal is remembered per endpoint and model so the
|
|
76
101
|
// next call does not pay for it again. OpenAI's reasoning models reject the sampling parameters,
|
|
77
|
-
// its chat models reject reasoning_effort, and a compatible server may know none of them
|
|
78
|
-
|
|
102
|
+
// its chat models reject reasoning_effort, and a compatible server may know none of them, the
|
|
103
|
+
// newer name of the answer limit included
|
|
104
|
+
const OPTIONAL_PARAMS = ['response_format', 'reasoning_effort', 'temperature', 'top_p', 'max_completion_tokens', 'max_tokens'];
|
|
105
|
+
// A refused parameter that has an older name is tried under that name before it goes: a server
|
|
106
|
+
// that predates max_completion_tokens still bounds the answer with max_tokens
|
|
107
|
+
const PARAM_FALLBACKS = { max_completion_tokens: 'max_tokens' };
|
|
79
108
|
const unsupportedParams = new Map();
|
|
80
109
|
const DEFAULT_SYSTEM_PROMPT = `
|
|
81
110
|
You are an email triage assistant. You analyze one incoming email at a time and report what you find as a JSON object for an automated pipeline. No person reads your output directly.
|
|
@@ -249,25 +278,6 @@ function parseJsonObject(output) {
|
|
|
249
278
|
}
|
|
250
279
|
return value;
|
|
251
280
|
}
|
|
252
|
-
function walkAndRemoveNull(branch) {
|
|
253
|
-
if (typeof branch !== 'object' || !branch) {
|
|
254
|
-
return;
|
|
255
|
-
}
|
|
256
|
-
for (const key of Object.keys(branch)) {
|
|
257
|
-
const subBranch = branch[key];
|
|
258
|
-
if (Array.isArray(subBranch)) {
|
|
259
|
-
for (const entry of subBranch) {
|
|
260
|
-
walkAndRemoveNull(entry);
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
else if (subBranch && typeof subBranch === 'object') {
|
|
264
|
-
walkAndRemoveNull(subBranch);
|
|
265
|
-
}
|
|
266
|
-
else if (!['boolean', 'string', 'number'].includes(typeof subBranch) || subBranch === '') {
|
|
267
|
-
delete branch[key];
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
281
|
function setOrDelete(obj, key, value) {
|
|
272
282
|
if (value === undefined || value === null || value === '') {
|
|
273
283
|
delete obj[key];
|
|
@@ -306,16 +316,75 @@ function toBoolean(value) {
|
|
|
306
316
|
}
|
|
307
317
|
return null;
|
|
308
318
|
}
|
|
319
|
+
function keepKeys(obj, keys) {
|
|
320
|
+
for (const key of Object.keys(obj)) {
|
|
321
|
+
if (!keys.includes(key)) {
|
|
322
|
+
delete obj[key];
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
// Drops everything DOCUMENTED does not list, at every level it describes
|
|
327
|
+
function keepDocumented(values) {
|
|
328
|
+
keepKeys(values, Object.keys(DOCUMENTED));
|
|
329
|
+
for (const [key, keys] of Object.entries(DOCUMENTED)) {
|
|
330
|
+
if (keys && values[key] && typeof values[key] === 'object') {
|
|
331
|
+
for (const entry of [].concat(values[key])) {
|
|
332
|
+
keepKeys(entry, keys);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* Bounds a parsed value in place: text is trimmed and cut, a list and the properties of an object
|
|
339
|
+
* are held to a count, and whatever nests deeper than a consumer would read is dropped without
|
|
340
|
+
* being walked. A property that is null or empty goes, and so does "__proto__" at every level, so
|
|
341
|
+
* the result is safe to merge
|
|
342
|
+
*
|
|
343
|
+
* @returns The value, or undefined for one that nests too deep
|
|
344
|
+
*/
|
|
345
|
+
function boundValue(value, depth) {
|
|
346
|
+
if (typeof value === 'string') {
|
|
347
|
+
return freeText(value);
|
|
348
|
+
}
|
|
349
|
+
if (!value || typeof value !== 'object') {
|
|
350
|
+
return value;
|
|
351
|
+
}
|
|
352
|
+
if (depth >= MAX_DEPTH) {
|
|
353
|
+
return undefined;
|
|
354
|
+
}
|
|
355
|
+
if (Array.isArray(value)) {
|
|
356
|
+
value.length = Math.min(value.length, MAX_LIST_LENGTH);
|
|
357
|
+
for (let i = 0; i < value.length; i++) {
|
|
358
|
+
value[i] = boundValue(value[i], depth + 1);
|
|
359
|
+
}
|
|
360
|
+
return value;
|
|
361
|
+
}
|
|
362
|
+
const obj = value;
|
|
363
|
+
let kept = 0;
|
|
364
|
+
for (const key of Object.keys(obj)) {
|
|
365
|
+
const bounded = key === '__proto__' || kept >= MAX_KEYS ? undefined : boundValue(obj[key], depth + 1);
|
|
366
|
+
if (bounded === undefined || bounded === null || bounded === '') {
|
|
367
|
+
delete obj[key];
|
|
368
|
+
}
|
|
369
|
+
else {
|
|
370
|
+
obj[key] = bounded;
|
|
371
|
+
kept++;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
return obj;
|
|
375
|
+
}
|
|
309
376
|
/**
|
|
310
377
|
* Brings the properties the default instructions ask for into their documented shape, and drops
|
|
311
378
|
* a value that cannot be made to fit. Properties a custom instruction set adds are passed on as
|
|
312
|
-
* they came, less null and empty values
|
|
379
|
+
* they came, less null and empty values and within the bounds of boundValue(). With the default
|
|
380
|
+
* instructions there are no such properties, and anything undocumented is dropped
|
|
313
381
|
*
|
|
314
382
|
* @param values - Parsed model output
|
|
383
|
+
* @param documentedOnly - Whether the default instructions were used
|
|
315
384
|
* @returns The same object, normalized in place
|
|
316
385
|
*/
|
|
317
|
-
function normalizeResult(values) {
|
|
318
|
-
|
|
386
|
+
function normalizeResult(values, documentedOnly) {
|
|
387
|
+
boundValue(values, 0);
|
|
319
388
|
if ('sentiment' in values) {
|
|
320
389
|
const sentiment = asText(values.sentiment).trim().toLowerCase();
|
|
321
390
|
setOrDelete(values, 'sentiment', SENTIMENTS.includes(sentiment) ? sentiment : '');
|
|
@@ -348,12 +417,20 @@ function normalizeResult(values) {
|
|
|
348
417
|
const list = []
|
|
349
418
|
.concat(values[key])
|
|
350
419
|
.filter(entry => entry && typeof entry === 'object' && !Array.isArray(entry))
|
|
351
|
-
.
|
|
352
|
-
|
|
420
|
+
.map(entry => {
|
|
421
|
+
normalizeEntry(entry);
|
|
422
|
+
if (documentedOnly) {
|
|
423
|
+
keepKeys(entry, DOCUMENTED[key]);
|
|
424
|
+
}
|
|
425
|
+
return entry;
|
|
426
|
+
})
|
|
353
427
|
.filter(entry => Object.keys(entry).length);
|
|
354
428
|
setOrDelete(values, key, list.length ? list : null);
|
|
355
429
|
}
|
|
356
430
|
}
|
|
431
|
+
if (documentedOnly) {
|
|
432
|
+
keepDocumented(values);
|
|
433
|
+
}
|
|
357
434
|
return values;
|
|
358
435
|
}
|
|
359
436
|
/**
|
|
@@ -364,6 +441,10 @@ async function requestChat(url, payload, requestOpts) {
|
|
|
364
441
|
const cacheKey = `${url}|${payload.model}`;
|
|
365
442
|
const dropped = unsupportedParams.get(cacheKey) || new Set();
|
|
366
443
|
for (const name of dropped) {
|
|
444
|
+
const fallback = PARAM_FALLBACKS[name];
|
|
445
|
+
if (fallback && name in payload && !dropped.has(fallback)) {
|
|
446
|
+
payload[fallback] = payload[name];
|
|
447
|
+
}
|
|
367
448
|
delete payload[name];
|
|
368
449
|
}
|
|
369
450
|
const startTime = Date.now();
|
|
@@ -381,8 +462,13 @@ async function requestChat(url, payload, requestOpts) {
|
|
|
381
462
|
if (!refused.length) {
|
|
382
463
|
throw err;
|
|
383
464
|
}
|
|
384
|
-
// every retry removes a key, so the loop ends with the optional parameters
|
|
465
|
+
// every retry removes a key, so the loop ends with the optional parameters. A fallback
|
|
466
|
+
// name is one of them, so it is tried once at most
|
|
385
467
|
for (const name of refused) {
|
|
468
|
+
const fallback = PARAM_FALLBACKS[name];
|
|
469
|
+
if (fallback && !dropped.has(fallback) && !(fallback in payload)) {
|
|
470
|
+
payload[fallback] = payload[name];
|
|
471
|
+
}
|
|
386
472
|
delete payload[name];
|
|
387
473
|
dropped.add(name);
|
|
388
474
|
}
|
|
@@ -399,6 +485,19 @@ async function requestChat(url, payload, requestOpts) {
|
|
|
399
485
|
function resetParameterCache() {
|
|
400
486
|
unsupportedParams.clear();
|
|
401
487
|
}
|
|
488
|
+
/**
|
|
489
|
+
* The body as the reader sees it, with what was found on the way. The parsed HTML stays in here,
|
|
490
|
+
* so it is not kept alive for the length of the API request
|
|
491
|
+
*/
|
|
492
|
+
function readBody(message) {
|
|
493
|
+
const html = message.html ? (0, visible_text_js_1.visibleHtml)(message.html) : null;
|
|
494
|
+
if (!html) {
|
|
495
|
+
return Object.assign((0, visible_text_js_1.visibleText)(message.text), { links: null, hiddenElements: 0 });
|
|
496
|
+
}
|
|
497
|
+
const htmlText = (0, email_text_tools_1.htmlToText)(html.html());
|
|
498
|
+
const read = htmlText.trim() || html.hiddenElements ? { text: htmlText, invisibleCharacters: html.invisibleCharacters } : (0, visible_text_js_1.visibleText)(message.text);
|
|
499
|
+
return Object.assign(read, { links: html.links, hiddenElements: html.hiddenElements });
|
|
500
|
+
}
|
|
402
501
|
/**
|
|
403
502
|
* Analyzes an email message with a chat model and returns what the model reported, untouched
|
|
404
503
|
* except for normalization of the documented properties, beside the request usage
|
|
@@ -424,21 +523,13 @@ async function generateSummary(message, apiToken, opts) {
|
|
|
424
523
|
const systemPrompt = asText(opts.systemPrompt).trim() || DEFAULT_SYSTEM_PROMPT;
|
|
425
524
|
const instructions = asText(opts.instructions).trim() || DEFAULT_INSTRUCTIONS;
|
|
426
525
|
const system = systemContent(systemPrompt, instructions);
|
|
427
|
-
// the model reads what the recipient sees: hidden elements and invisible characters go.
|
|
428
|
-
// HTML
|
|
429
|
-
//
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
text = (0, email_text_tools_1.htmlToText)(html.html());
|
|
435
|
-
invisibleCharacters = html.invisibleCharacters;
|
|
436
|
-
}
|
|
437
|
-
else {
|
|
438
|
-
const visible = (0, visible_text_js_1.visibleText)(text);
|
|
439
|
-
text = visible.text;
|
|
440
|
-
invisibleCharacters = visible.invisibleCharacters;
|
|
441
|
-
}
|
|
526
|
+
// the model reads what the recipient sees: hidden elements and invisible characters go. A
|
|
527
|
+
// mail client shows the HTML part whenever there is one, so that is the part read, however
|
|
528
|
+
// long the plain text beside it: a sender picks both, and a plain part nobody is shown is
|
|
529
|
+
// where text meant for the model alone would go. The plain part is read only for a message
|
|
530
|
+
// without HTML, or with HTML that carries no text at all: when the only text of the HTML was
|
|
531
|
+
// hidden, the reader is shown nothing, and the plain part is not what they see either
|
|
532
|
+
const { text, invisibleCharacters, links, hiddenElements } = readBody(message);
|
|
442
533
|
const trust = {
|
|
443
534
|
trustedAuthservIds: []
|
|
444
535
|
.concat(opts.trustedAuthservIds || [])
|
|
@@ -456,10 +547,10 @@ async function generateSummary(message, apiToken, opts) {
|
|
|
456
547
|
from: input.from,
|
|
457
548
|
replyTo: input.headers['reply-to'],
|
|
458
549
|
attachments: message.attachments,
|
|
459
|
-
links
|
|
550
|
+
links,
|
|
460
551
|
text,
|
|
461
552
|
authentication: input.authentication,
|
|
462
|
-
hiddenElements
|
|
553
|
+
hiddenElements,
|
|
463
554
|
invisibleCharacters
|
|
464
555
|
});
|
|
465
556
|
const shownSignals = (0, signals_js_1.modelSignals)(signals);
|
|
@@ -500,6 +591,10 @@ async function generateSummary(message, apiToken, opts) {
|
|
|
500
591
|
if (reasoningEffort) {
|
|
501
592
|
payload.reasoning_effort = reasoningEffort;
|
|
502
593
|
}
|
|
594
|
+
const maxCompletionTokens = optionalNumber(opts.maxCompletionTokens) ?? 0;
|
|
595
|
+
const deepReasoning = REASONING_EFFORTS.indexOf(reasoningEffort) >= REASONING_EFFORTS.indexOf(DEEP_REASONING_EFFORT);
|
|
596
|
+
payload.max_completion_tokens =
|
|
597
|
+
maxCompletionTokens >= 1 ? Math.floor(maxCompletionTokens) : deepReasoning ? REASONING_MAX_COMPLETION_TOKENS : DEFAULT_MAX_COMPLETION_TOKENS;
|
|
503
598
|
// A reasoning model refuses the sampling parameters while it reasons; with the effort
|
|
504
599
|
// switched off (GPT-5.1 and later) it takes them again, and the refusal fallback decides
|
|
505
600
|
if (!reasoning || !reasoningEffort || reasoningEffort === 'none') {
|
|
@@ -527,7 +622,7 @@ async function generateSummary(message, apiToken, opts) {
|
|
|
527
622
|
.trim();
|
|
528
623
|
let result;
|
|
529
624
|
try {
|
|
530
|
-
result = normalizeResult(parseJsonObject(output));
|
|
625
|
+
result = normalizeResult(parseJsonObject(output), instructions === DEFAULT_INSTRUCTIONS);
|
|
531
626
|
}
|
|
532
627
|
catch (err) {
|
|
533
628
|
const error = new Error('Failed to parse output from OpenAI API', { cause: err });
|
|
@@ -16,6 +16,7 @@ export interface VisibleHtml {
|
|
|
16
16
|
}
|
|
17
17
|
declare const MAX_HTML_LENGTH: number;
|
|
18
18
|
declare const MAX_LINK_TEXT_LENGTH = 1024;
|
|
19
|
+
declare const MAX_NESTING = 500;
|
|
19
20
|
declare const INVISIBLE_CHARS: RegExp;
|
|
20
21
|
/**
|
|
21
22
|
* Parses an HTML message once: every link it carries, for the checks, and the document as the
|
|
@@ -24,10 +25,9 @@ declare const INVISIBLE_CHARS: RegExp;
|
|
|
24
25
|
declare function visibleHtml(html: string): VisibleHtml;
|
|
25
26
|
/**
|
|
26
27
|
* Removes the characters that take no space on screen
|
|
27
|
-
*
|
|
28
28
|
*/
|
|
29
29
|
declare function visibleText(input: unknown): {
|
|
30
30
|
text: string;
|
|
31
31
|
invisibleCharacters: number;
|
|
32
32
|
};
|
|
33
|
-
export { visibleHtml, visibleText, INVISIBLE_CHARS, MAX_HTML_LENGTH, MAX_LINK_TEXT_LENGTH };
|
|
33
|
+
export { visibleHtml, visibleText, INVISIBLE_CHARS, MAX_HTML_LENGTH, MAX_LINK_TEXT_LENGTH, MAX_NESTING };
|