@postalsys/email-ai-tools 1.14.14 → 2.0.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/.ncurc.js CHANGED
@@ -7,11 +7,6 @@ module.exports = {
7
7
  target: name => (name === 'undici' ? 'minor' : 'latest'),
8
8
  reject: [
9
9
  // Block package upgrades that moved to ESM
10
- 'nanoid',
11
- // linkify-it 6.0.0 changed the CommonJS export shape (named bindings instead of
12
- // the constructor) and stopped linkifying bare domains such as example.com by
13
- // default, which silently breaks autolinking in plain text content. Stay on 5.x,
14
- // matching mailparser and @postalsys/email-text-tools so consumers dedupe on one copy.
15
- 'linkify-it'
10
+ 'nanoid'
16
11
  ]
17
12
  };
@@ -1,3 +1,3 @@
1
1
  {
2
- ".": "1.14.14"
2
+ ".": "2.0.0"
3
3
  }
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.0.0](https://github.com/postalsys/email-ai-tools/compare/v1.14.14...v2.0.0) (2026-10-01)
4
+
5
+
6
+ ### ⚠ BREAKING CHANGES
7
+
8
+ * generateSummary() returns { result, usage } instead of the model output with id, tokens and model merged in; options.userPrompt and DEFAULT_USER_PROMPT are options.instructions and DEFAULT_INSTRUCTIONS; the completions endpoint branch for gpt-3.5-turbo-instruct is gone; riskAnalysis(), generateEmbeddings(), getChunkEmbeddings(), embeddingsQuery() and questionQuery() are removed along with the linkify-it, nodemailer, punycode.js and tlds dependencies.
9
+
10
+ ### Features
11
+
12
+ * return the model output and the request usage apart, trim the library to the summary ([12ab1be](https://github.com/postalsys/email-ai-tools/commit/12ab1be751554fd5f1fe9d040ab6f654b520ffd6))
13
+
3
14
  ## [1.14.14](https://github.com/postalsys/email-ai-tools/compare/v1.14.13...v1.14.14) (2026-09-30)
4
15
 
5
16
 
package/CLAUDE.md CHANGED
@@ -2,10 +2,12 @@
2
2
 
3
3
  ## Project Overview
4
4
 
5
- `@postalsys/email-ai-tools` is a Node.js library that adds AI/LLM features on top
6
- of parsed email data. It talks to OpenAI-compatible HTTP APIs (chat completions,
7
- text completions, embeddings, model listing) to summarize messages, score them
8
- for risk, generate vector embeddings, and answer questions over stored email.
5
+ `@postalsys/email-ai-tools` is a Node.js library that analyzes one parsed email
6
+ at a time with an OpenAI-compatible chat model: a summary, the sentiment, whether
7
+ a reply is expected, a fraud risk score, and the events and actions the message
8
+ mentions. It also lists the models an endpoint serves. Version 2.0 dropped the
9
+ risk-only analysis, the embeddings and the question answering over stored email,
10
+ which lost their only consumer when EmailEngine removed its Document Store.
9
11
 
10
12
  It is published to npm and consumed by other Postal Systems projects - most
11
13
  notably EmailEngine (`../emailengine`), where it ships inside a standalone binary
@@ -23,13 +25,17 @@ which dependencies this library may use.
23
25
  ### Library Modules
24
26
 
25
27
  - `lib/generate-summary.js` - `generateSummary()` plus `DEFAULT_SYSTEM_PROMPT` /
26
- `DEFAULT_USER_PROMPT`; produces a natural-language summary of a message.
27
- - `lib/risk-analysis.js` - `riskAnalysis()`; flags suspicious/risky email content.
28
- - `lib/generate-embeddings.js` - `generateEmbeddings()` / `getChunkEmbeddings()`;
29
- splits message text into chunks and returns vector embeddings.
30
- - `lib/embeddings-query.js` - `embeddingsQuery()` / `questionQuery()`; answers
31
- questions over a set of emails using embeddings and chat completions.
32
- - `lib/list-models.js` - `listModels()`; lists models exposed by the API endpoint.
28
+ `DEFAULT_INSTRUCTIONS` / `DEFAULT_MODEL`; returns `{ result, usage }`, where
29
+ `result` is the model's JSON object (documented properties normalized, custom
30
+ ones passed through) and `usage` the request id, model, token counts and time.
31
+ The instructions and the input format description go in the system message,
32
+ the email alone goes in the user message as one JSON object with decoded
33
+ headers. A parameter the backend refuses with a 400 naming it
34
+ (`response_format`, `reasoning_effort`, `temperature`, `top_p`) is dropped,
35
+ retried and remembered per endpoint and model; reasoning models
36
+ (`isReasoningModel()`) get `reasoning_effort: "low"` unless told otherwise.
37
+ - `lib/list-models.js` - `listModels()`; lists the chat models an endpoint
38
+ serves, newest family first (`chatOnly: false` keeps the rest).
33
39
  - `lib/api-request.js` - shared HTTP request helper (size cap, JSON parsing, 429
34
40
  retry with Retry-After, error shaping) used by every API call.
35
41
  - `lib/token-estimate.js` - character-based token estimate, prompt fitting and chunking.
@@ -41,8 +47,8 @@ which dependencies this library may use.
41
47
  - **HTTP**: `undici` (`fetch` + `Agent`) for all outbound API calls.
42
48
  - **Token budgeting**: a character-based estimate in `lib/token-estimate.js` (no
43
49
  tokenizer dependency); the model's own context-length error is the backstop.
44
- - **Email/text helpers**: `@postalsys/email-text-tools`, `libmime`,
45
- `nodemailer/lib/addressparser`, `linkify-it`, `tlds`, `punycode.js`.
50
+ - **Email/text helpers**: `@postalsys/email-text-tools` (HTML to text) and
51
+ `libmime` (decoding encoded words in header values).
46
52
 
47
53
  ## Development Commands
48
54
 
package/README.md CHANGED
@@ -1,3 +1,122 @@
1
1
  # email-ai-tools
2
2
 
3
- Email AI tools extracted from email-text-tools
3
+ Summarize and risk-score email messages with an OpenAI-compatible chat model. This is the library behind the AI processing feature of [EmailEngine](https://emailengine.app/).
4
+
5
+ ## Install
6
+
7
+ ```
8
+ npm install @postalsys/email-ai-tools
9
+ ```
10
+
11
+ Node.js 20 or later. Plain CommonJS with no build step and no native dependencies.
12
+
13
+ ## generateSummary(message, apiToken, options)
14
+
15
+ Sends one email to the chat completions endpoint and returns what the model reported about it.
16
+
17
+ ```js
18
+ const { generateSummary } = require('@postalsys/email-ai-tools');
19
+
20
+ const { result, usage } = await generateSummary(
21
+ {
22
+ subject: 'Meeting tomorrow at 2pm',
23
+ from: { name: 'Jane Doe', address: 'jane@example.com' },
24
+ date: 'Mon, 17 Oct 2022 09:42:07 +0300',
25
+ headers: [{ key: 'authentication-results', value: 'mx.example.com; spf=pass; dkim=pass; dmarc=pass' }],
26
+ attachments: [{ filename: 'agenda.pdf', contentType: 'application/pdf' }],
27
+ text: 'Can we go through the Q4 roadmap tomorrow at 2pm in room A?'
28
+ },
29
+ process.env.OPENAI_API_KEY
30
+ );
31
+
32
+ console.log(result);
33
+ // {
34
+ // summary: 'Jane asks to review the Q4 roadmap tomorrow at 2pm in room A.',
35
+ // sentiment: 'positive',
36
+ // shouldReply: true,
37
+ // riskAssessment: { risk: 1 },
38
+ // events: [{ description: 'Q4 roadmap review', type: 'meeting', startTime: '2022-10-18T14:00:00', location: 'room A' }],
39
+ // actions: [{ description: 'Confirm the meeting' }]
40
+ // }
41
+
42
+ console.log(usage);
43
+ // { id: 'chatcmpl-...', model: 'gpt-6-luna', servedModel: 'gpt-6-luna-2026-09-22', tokens: 812, promptTokens: 790, completionTokens: 22, time: 1430, charactersRemoved: 0 }
44
+ ```
45
+
46
+ ### Message
47
+
48
+ | Property | Description |
49
+ | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
50
+ | `subject` | Decoded subject line. Falls back to the `subject` header |
51
+ | `from` | Sender, as a string or as `{ name, address }`. Falls back to the `from` header |
52
+ | `date` | `Date` object or the raw header value. Falls back to the `date` header |
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
+ | `attachments` | Array of `{ filename, contentType }` objects. Other properties are ignored |
55
+ | `text` | Plain text body |
56
+ | `html` | HTML body, converted to text when it is at least as long as `text` |
57
+
58
+ The whitelisted headers are `from`, `reply-to`, `to`, `cc`, `bcc`, `date`, `subject`, `in-reply-to`, `references`, `list-id`, `auto-submitted`, `precedence`, `authentication-results` and `arc-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
+
60
+ ### Options
61
+
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
+ | `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 |
70
+ | `temperature` | | Sampling temperature |
71
+ | `topP` | | Nucleus sampling cutoff |
72
+ | `jsonMode` | `true` | Asks for a JSON object response (`response_format`) |
73
+ | `user` | | End-user identifier passed to the API |
74
+ | `allowedHeaders` | | Header names to pass on in addition to the whitelist |
75
+ | `dispatcher` | the module's own agent | undici dispatcher the request goes through, for example a `ProxyAgent` |
76
+ | `signal` | | `AbortSignal` that cancels the request and any rate limit wait |
77
+ | `verbose` | `false` | Logs the request and the response to stderr and includes the fitted text as `usage.text` |
78
+
79
+ A parameter the backend refuses with a 400 that names it (`response_format`, `reasoning_effort`, `temperature`, `top_p`) is dropped, the request is repeated, and the refusal is remembered for that endpoint and model. 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.
80
+
81
+ ### Prompt layout
82
+
83
+ The system message carries the role, the rule that the email is untrusted data, the instructions and a description of the input format. The user message is a single JSON object with the email: `subject`, `from`, `date`, `headers`, `attachments` and `text`. Nothing of the email is mixed into the instructions.
84
+
85
+ ### Result
86
+
87
+ `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, and `events` and `actions` are arrays of objects. A value that cannot be made to fit is dropped. Properties that custom instructions ask for are passed on as they came.
88
+
89
+ `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.
90
+
91
+ ### Errors
92
+
93
+ The promise rejects with an `Error` carrying `statusCode` and, when the API gave one, `code`. A 429 is retried up to five times honoring `Retry-After`. A response without a JSON object fails with `Failed to parse output from OpenAI API`, `textContent` holding the output and `finishReason` the reason the model stopped. A prompt that does not fit the budget even without any text fails with the code `PROMPT_TOO_LONG` before any request is made.
94
+
95
+ ## listModels(apiToken, options)
96
+
97
+ Lists the models the endpoint serves, newest family first, each with a display name.
98
+
99
+ ```js
100
+ const { listModels } = require('@postalsys/email-ai-tools');
101
+
102
+ const { models } = await listModels(process.env.OPENAI_API_KEY);
103
+ // [{ id: 'gpt-6-astra', name: 'GPT-6 Astra', ... }, { id: 'gpt-6-luna', name: 'GPT-6 Luna', ... }, ...]
104
+ ```
105
+
106
+ Models that are not chat models are left out unless `chatOnly: false` is set. On OpenAI's own endpoint the names are known, so embeddings, speech, images, video, moderation, the legacy completion models and specialised variants such as codex or search are all dropped; on another endpoint the names are whatever the operator pulled, so only embeddings, speech and reranking models are. `baseApiUrl`, `dispatcher`, `signal` and `verbose` work as above.
107
+
108
+ ## Other exports
109
+
110
+ `DEFAULT_MODEL`, `DEFAULT_REASONING_EFFORT`, `DEFAULT_SYSTEM_PROMPT` and `DEFAULT_INSTRUCTIONS`, for a UI that lets the operator edit the instructions or pick the model.
111
+
112
+ ## Upgrading from 1.x
113
+
114
+ - `generateSummary()` returns `{ result, usage }`. The request id, token count and model name are no longer merged into the model's own output; read them from `usage`
115
+ - The analysis instructions live in the system message and are overridden with `options.instructions`. `options.userPrompt` and `DEFAULT_USER_PROMPT` are gone
116
+ - Header values are decoded and lists are flattened, and `subject`, `from` and `date` are passed to the model as their own properties
117
+ - The default model is `gpt-6-luna`, the default instructions no longer ask for `replyText`, and reasoning models get `reasoning_effort: "low"`
118
+ - `riskAnalysis()`, `generateEmbeddings()`, `getChunkEmbeddings()`, `embeddingsQuery()` and `questionQuery()` were removed, along with the completions endpoint branch for `gpt-3.5-turbo-instruct`
119
+
120
+ ## License
121
+
122
+ MIT
@@ -11,23 +11,24 @@ async function main() {
11
11
 
12
12
  const parsed = await simpleParser(eml);
13
13
 
14
- const summary = await generateSummary(
14
+ const { result, usage } = await generateSummary(
15
15
  {
16
16
  headers: parsed.headerLines.map(header => libmime.decodeHeader(header.line)),
17
17
  attachments: parsed.attachments,
18
18
  html: parsed.html,
19
19
  text: parsed.text,
20
- subject: parsed.subject
20
+ subject: parsed.subject,
21
+ from: parsed.from && parsed.from.value && parsed.from.value[0],
22
+ date: parsed.date
21
23
  },
22
24
  process.env.OPENAI_API_KEY,
23
25
  {
24
- gptModel: 'gpt-5-mini',
25
- maxTokens: 30000,
26
+ gptModel: process.env.OPENAI_MODEL,
26
27
  verbose: true
27
28
  }
28
29
  );
29
30
 
30
- console.log(util.inspect(summary, false, 22, true));
31
+ console.log(util.inspect({ result, usage }, false, 22, true));
31
32
  }
32
33
 
33
34
  main();
package/index.js CHANGED
@@ -1,19 +1,13 @@
1
1
  'use strict';
2
2
 
3
- const { generateSummary, DEFAULT_SYSTEM_PROMPT, DEFAULT_USER_PROMPT } = require('./lib/generate-summary');
4
- const riskAnalysis = require('./lib/risk-analysis');
5
- const { generateEmbeddings, getChunkEmbeddings } = require('./lib/generate-embeddings');
6
- const { embeddingsQuery, questionQuery } = require('./lib/embeddings-query');
3
+ const { generateSummary, DEFAULT_MODEL, DEFAULT_REASONING_EFFORT, DEFAULT_SYSTEM_PROMPT, DEFAULT_INSTRUCTIONS } = require('./lib/generate-summary');
7
4
  const { listModels } = require('./lib/list-models');
8
5
 
9
6
  module.exports = {
10
7
  generateSummary,
11
- generateEmbeddings,
12
- getChunkEmbeddings,
13
- embeddingsQuery,
14
- questionQuery,
15
- riskAnalysis,
16
8
  listModels,
9
+ DEFAULT_MODEL,
10
+ DEFAULT_REASONING_EFFORT,
17
11
  DEFAULT_SYSTEM_PROMPT,
18
- DEFAULT_USER_PROMPT
12
+ DEFAULT_INSTRUCTIONS
19
13
  };
@@ -157,6 +157,13 @@ async function apiRequest(url, opts) {
157
157
  if (data.error.code) {
158
158
  error.code = data.error.code;
159
159
  }
160
+ // which request parameter a 400 is about, when the API says
161
+ if (typeof data.error.param === 'string' && data.error.param) {
162
+ error.param = data.error.param;
163
+ }
164
+ if (typeof data.error.type === 'string' && data.error.type) {
165
+ error.type = data.error.type;
166
+ }
160
167
  } else {
161
168
  error = new Error('Failed to run API request');
162
169
  }