@postalsys/email-ai-tools 3.0.3 → 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.
@@ -1,2 +1,2 @@
1
1
  export declare const name = "@postalsys/email-ai-tools";
2
- export declare const version = "3.0.3";
2
+ export declare const version = "3.0.5";
@@ -3,4 +3,4 @@
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.version = exports.name = void 0;
5
5
  exports.name = "@postalsys/email-ai-tools";
6
- exports.version = "3.0.3";
6
+ exports.version = "3.0.5";
@@ -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, converted to text when it is the fuller version */
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 };
@@ -58,11 +58,39 @@ const RISK_MAX = 5;
58
58
  // for more. The events and actions are what one message mentions
59
59
  const MAX_TEXT_LENGTH = 1000;
60
60
  const MAX_LIST_LENGTH = 50;
61
+ // What a custom instruction set adds to the answer is bounded the same way at every level, and
62
+ // in how far it nests and how many properties an object has: text in the message can ask the
63
+ // model for more of anything
64
+ const MAX_DEPTH = 4;
65
+ const MAX_KEYS = 50;
66
+ // The properties the default instructions ask for. With those instructions nothing else is
67
+ // passed on: a property the model was not asked for is one the message asked for, and a
68
+ // consumer reading "verified": true beside the risk score cannot tell who wrote it. Each property
69
+ // lists the keys of the object it holds, or of every entry of the list it holds, and null when it
70
+ // holds a single value. The risk signals are written by code after this, never by the model
71
+ const DOCUMENTED = {
72
+ summary: null,
73
+ sentiment: null,
74
+ shouldReply: null,
75
+ riskAssessment: ['risk', 'assessment'],
76
+ events: ['description', 'type', 'startTime', 'endTime', 'location'],
77
+ actions: ['description', 'dueDate']
78
+ };
79
+ // The answer is paid for by the token and nothing in the request bounded it: the documented
80
+ // object takes a few hundred tokens, and text in the message can ask for an essay. Reasoning
81
+ // tokens count against the same limit, so a model told to reason harder gets more room
82
+ const DEFAULT_MAX_COMPLETION_TOKENS = 4000;
83
+ const REASONING_MAX_COMPLETION_TOKENS = 16000;
84
+ const DEEP_REASONING_EFFORT = 'medium';
61
85
  // Request parameters a backend may refuse with a 400 that names them. Such a parameter is
62
86
  // dropped and the request repeated, and the refusal is remembered per endpoint and model so the
63
87
  // next call does not pay for it again. OpenAI's reasoning models reject the sampling parameters,
64
- // its chat models reject reasoning_effort, and a compatible server may know none of them
65
- const OPTIONAL_PARAMS = ['response_format', 'reasoning_effort', 'temperature', 'top_p'];
88
+ // its chat models reject reasoning_effort, and a compatible server may know none of them, the
89
+ // newer name of the answer limit included
90
+ const OPTIONAL_PARAMS = ['response_format', 'reasoning_effort', 'temperature', 'top_p', 'max_completion_tokens', 'max_tokens'];
91
+ // A refused parameter that has an older name is tried under that name before it goes: a server
92
+ // that predates max_completion_tokens still bounds the answer with max_tokens
93
+ const PARAM_FALLBACKS = { max_completion_tokens: 'max_tokens' };
66
94
  const unsupportedParams = new Map();
67
95
  const DEFAULT_SYSTEM_PROMPT = `
68
96
  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.
@@ -234,25 +262,6 @@ function parseJsonObject(output) {
234
262
  }
235
263
  return value;
236
264
  }
237
- function walkAndRemoveNull(branch) {
238
- if (typeof branch !== 'object' || !branch) {
239
- return;
240
- }
241
- for (const key of Object.keys(branch)) {
242
- const subBranch = branch[key];
243
- if (Array.isArray(subBranch)) {
244
- for (const entry of subBranch) {
245
- walkAndRemoveNull(entry);
246
- }
247
- }
248
- else if (subBranch && typeof subBranch === 'object') {
249
- walkAndRemoveNull(subBranch);
250
- }
251
- else if (!['boolean', 'string', 'number'].includes(typeof subBranch) || subBranch === '') {
252
- delete branch[key];
253
- }
254
- }
255
- }
256
265
  function setOrDelete(obj, key, value) {
257
266
  if (value === undefined || value === null || value === '') {
258
267
  delete obj[key];
@@ -291,16 +300,75 @@ function toBoolean(value) {
291
300
  }
292
301
  return null;
293
302
  }
303
+ function keepKeys(obj, keys) {
304
+ for (const key of Object.keys(obj)) {
305
+ if (!keys.includes(key)) {
306
+ delete obj[key];
307
+ }
308
+ }
309
+ }
310
+ // Drops everything DOCUMENTED does not list, at every level it describes
311
+ function keepDocumented(values) {
312
+ keepKeys(values, Object.keys(DOCUMENTED));
313
+ for (const [key, keys] of Object.entries(DOCUMENTED)) {
314
+ if (keys && values[key] && typeof values[key] === 'object') {
315
+ for (const entry of [].concat(values[key])) {
316
+ keepKeys(entry, keys);
317
+ }
318
+ }
319
+ }
320
+ }
321
+ /**
322
+ * Bounds a parsed value in place: text is trimmed and cut, a list and the properties of an object
323
+ * are held to a count, and whatever nests deeper than a consumer would read is dropped without
324
+ * being walked. A property that is null or empty goes, and so does "__proto__" at every level, so
325
+ * the result is safe to merge
326
+ *
327
+ * @returns The value, or undefined for one that nests too deep
328
+ */
329
+ function boundValue(value, depth) {
330
+ if (typeof value === 'string') {
331
+ return freeText(value);
332
+ }
333
+ if (!value || typeof value !== 'object') {
334
+ return value;
335
+ }
336
+ if (depth >= MAX_DEPTH) {
337
+ return undefined;
338
+ }
339
+ if (Array.isArray(value)) {
340
+ value.length = Math.min(value.length, MAX_LIST_LENGTH);
341
+ for (let i = 0; i < value.length; i++) {
342
+ value[i] = boundValue(value[i], depth + 1);
343
+ }
344
+ return value;
345
+ }
346
+ const obj = value;
347
+ let kept = 0;
348
+ for (const key of Object.keys(obj)) {
349
+ const bounded = key === '__proto__' || kept >= MAX_KEYS ? undefined : boundValue(obj[key], depth + 1);
350
+ if (bounded === undefined || bounded === null || bounded === '') {
351
+ delete obj[key];
352
+ }
353
+ else {
354
+ obj[key] = bounded;
355
+ kept++;
356
+ }
357
+ }
358
+ return obj;
359
+ }
294
360
  /**
295
361
  * Brings the properties the default instructions ask for into their documented shape, and drops
296
362
  * a value that cannot be made to fit. Properties a custom instruction set adds are passed on as
297
- * they came, less null and empty values
363
+ * they came, less null and empty values and within the bounds of boundValue(). With the default
364
+ * instructions there are no such properties, and anything undocumented is dropped
298
365
  *
299
366
  * @param values - Parsed model output
367
+ * @param documentedOnly - Whether the default instructions were used
300
368
  * @returns The same object, normalized in place
301
369
  */
302
- function normalizeResult(values) {
303
- walkAndRemoveNull(values);
370
+ function normalizeResult(values, documentedOnly) {
371
+ boundValue(values, 0);
304
372
  if ('sentiment' in values) {
305
373
  const sentiment = asText(values.sentiment).trim().toLowerCase();
306
374
  setOrDelete(values, 'sentiment', SENTIMENTS.includes(sentiment) ? sentiment : '');
@@ -333,12 +401,20 @@ function normalizeResult(values) {
333
401
  const list = []
334
402
  .concat(values[key])
335
403
  .filter(entry => entry && typeof entry === 'object' && !Array.isArray(entry))
336
- .slice(0, MAX_LIST_LENGTH)
337
- .map(normalizeEntry)
404
+ .map(entry => {
405
+ normalizeEntry(entry);
406
+ if (documentedOnly) {
407
+ keepKeys(entry, DOCUMENTED[key]);
408
+ }
409
+ return entry;
410
+ })
338
411
  .filter(entry => Object.keys(entry).length);
339
412
  setOrDelete(values, key, list.length ? list : null);
340
413
  }
341
414
  }
415
+ if (documentedOnly) {
416
+ keepDocumented(values);
417
+ }
342
418
  return values;
343
419
  }
344
420
  /**
@@ -349,6 +425,10 @@ async function requestChat(url, payload, requestOpts) {
349
425
  const cacheKey = `${url}|${payload.model}`;
350
426
  const dropped = unsupportedParams.get(cacheKey) || new Set();
351
427
  for (const name of dropped) {
428
+ const fallback = PARAM_FALLBACKS[name];
429
+ if (fallback && name in payload && !dropped.has(fallback)) {
430
+ payload[fallback] = payload[name];
431
+ }
352
432
  delete payload[name];
353
433
  }
354
434
  const startTime = Date.now();
@@ -366,8 +446,13 @@ async function requestChat(url, payload, requestOpts) {
366
446
  if (!refused.length) {
367
447
  throw err;
368
448
  }
369
- // every retry removes a key, so the loop ends with the optional parameters
449
+ // every retry removes a key, so the loop ends with the optional parameters. A fallback
450
+ // name is one of them, so it is tried once at most
370
451
  for (const name of refused) {
452
+ const fallback = PARAM_FALLBACKS[name];
453
+ if (fallback && !dropped.has(fallback) && !(fallback in payload)) {
454
+ payload[fallback] = payload[name];
455
+ }
371
456
  delete payload[name];
372
457
  dropped.add(name);
373
458
  }
@@ -384,6 +469,19 @@ async function requestChat(url, payload, requestOpts) {
384
469
  function resetParameterCache() {
385
470
  unsupportedParams.clear();
386
471
  }
472
+ /**
473
+ * The body as the reader sees it, with what was found on the way. The parsed HTML stays in here,
474
+ * so it is not kept alive for the length of the API request
475
+ */
476
+ function readBody(message) {
477
+ const html = message.html ? visibleHtml(message.html) : null;
478
+ if (!html) {
479
+ return Object.assign(visibleText(message.text), { links: null, hiddenElements: 0 });
480
+ }
481
+ const htmlText = htmlToText(html.html());
482
+ const read = htmlText.trim() || html.hiddenElements ? { text: htmlText, invisibleCharacters: html.invisibleCharacters } : visibleText(message.text);
483
+ return Object.assign(read, { links: html.links, hiddenElements: html.hiddenElements });
484
+ }
387
485
  /**
388
486
  * Analyzes an email message with a chat model and returns what the model reported, untouched
389
487
  * except for normalization of the documented properties, beside the request usage
@@ -409,21 +507,13 @@ async function generateSummary(message, apiToken, opts) {
409
507
  const systemPrompt = asText(opts.systemPrompt).trim() || DEFAULT_SYSTEM_PROMPT;
410
508
  const instructions = asText(opts.instructions).trim() || DEFAULT_INSTRUCTIONS;
411
509
  const system = systemContent(systemPrompt, instructions);
412
- // the model reads what the recipient sees: hidden elements and invisible characters go. The
413
- // HTML is parsed whenever there is one, since its links are checked either way, and
414
- // converted only when it is the fuller version of the body
415
- const html = message.html ? visibleHtml(message.html) : null;
416
- let text = asText(message.text);
417
- let invisibleCharacters;
418
- if (html && message.html.length >= text.length) {
419
- text = htmlToText(html.html());
420
- invisibleCharacters = html.invisibleCharacters;
421
- }
422
- else {
423
- const visible = visibleText(text);
424
- text = visible.text;
425
- invisibleCharacters = visible.invisibleCharacters;
426
- }
510
+ // the model reads what the recipient sees: hidden elements and invisible characters go. A
511
+ // mail client shows the HTML part whenever there is one, so that is the part read, however
512
+ // long the plain text beside it: a sender picks both, and a plain part nobody is shown is
513
+ // where text meant for the model alone would go. The plain part is read only for a message
514
+ // without HTML, or with HTML that carries no text at all: when the only text of the HTML was
515
+ // hidden, the reader is shown nothing, and the plain part is not what they see either
516
+ const { text, invisibleCharacters, links, hiddenElements } = readBody(message);
427
517
  const trust = {
428
518
  trustedAuthservIds: []
429
519
  .concat(opts.trustedAuthservIds || [])
@@ -441,10 +531,10 @@ async function generateSummary(message, apiToken, opts) {
441
531
  from: input.from,
442
532
  replyTo: input.headers['reply-to'],
443
533
  attachments: message.attachments,
444
- links: html ? html.links : null,
534
+ links,
445
535
  text,
446
536
  authentication: input.authentication,
447
- hiddenElements: html ? html.hiddenElements : 0,
537
+ hiddenElements,
448
538
  invisibleCharacters
449
539
  });
450
540
  const shownSignals = modelSignals(signals);
@@ -485,6 +575,10 @@ async function generateSummary(message, apiToken, opts) {
485
575
  if (reasoningEffort) {
486
576
  payload.reasoning_effort = reasoningEffort;
487
577
  }
578
+ const maxCompletionTokens = optionalNumber(opts.maxCompletionTokens) ?? 0;
579
+ const deepReasoning = REASONING_EFFORTS.indexOf(reasoningEffort) >= REASONING_EFFORTS.indexOf(DEEP_REASONING_EFFORT);
580
+ payload.max_completion_tokens =
581
+ maxCompletionTokens >= 1 ? Math.floor(maxCompletionTokens) : deepReasoning ? REASONING_MAX_COMPLETION_TOKENS : DEFAULT_MAX_COMPLETION_TOKENS;
488
582
  // A reasoning model refuses the sampling parameters while it reasons; with the effort
489
583
  // switched off (GPT-5.1 and later) it takes them again, and the refusal fallback decides
490
584
  if (!reasoning || !reasoningEffort || reasoningEffort === 'none') {
@@ -512,7 +606,7 @@ async function generateSummary(message, apiToken, opts) {
512
606
  .trim();
513
607
  let result;
514
608
  try {
515
- result = normalizeResult(parseJsonObject(output));
609
+ result = normalizeResult(parseJsonObject(output), instructions === DEFAULT_INSTRUCTIONS);
516
610
  }
517
611
  catch (err) {
518
612
  const error = new Error('Failed to parse output from OpenAI API', { cause: err });
@@ -544,4 +638,4 @@ async function generateSummary(message, apiToken, opts) {
544
638
  }
545
639
  // a copy: the headers the model gets to see, for a caller that decides what to fetch
546
640
  const ALLOWED_HEADERS = Object.freeze([...DEFAULT_ALLOWED_HEADERS]);
547
- export { generateSummary, isReasoningModel, resetParameterCache, DEFAULT_MODEL, DEFAULT_REASONING_EFFORT, DEFAULT_MAX_TOKENS, DEFAULT_SYSTEM_PROMPT, DEFAULT_INSTRUCTIONS, REASONING_EFFORTS, ALLOWED_HEADERS };
641
+ 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 };
@@ -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 };