@postalsys/email-ai-tools 2.2.8 → 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.
Files changed (71) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/cjs/index.d.ts +28 -0
  4. package/dist/cjs/index.js +67 -0
  5. package/dist/cjs/lib/api-request.d.ts +42 -0
  6. package/dist/cjs/lib/api-request.js +183 -0
  7. package/dist/cjs/lib/authentication.d.ts +46 -0
  8. package/{lib → dist/cjs/lib}/authentication.js +33 -44
  9. package/dist/cjs/lib/generate-summary.d.ts +143 -0
  10. package/dist/cjs/lib/generate-summary.js +562 -0
  11. package/dist/cjs/lib/get-api-url.d.ts +19 -0
  12. package/dist/cjs/lib/get-api-url.js +37 -0
  13. package/dist/cjs/lib/list-models.d.ts +46 -0
  14. package/dist/cjs/lib/list-models.js +125 -0
  15. package/dist/cjs/lib/signals.d.ts +72 -0
  16. package/dist/cjs/lib/signals.js +293 -0
  17. package/dist/cjs/lib/token-estimate.d.ts +46 -0
  18. package/{lib → dist/cjs/lib}/token-estimate.js +21 -50
  19. package/dist/cjs/lib/visible-text.d.ts +33 -0
  20. package/dist/cjs/lib/visible-text.js +182 -0
  21. package/dist/cjs/package-info.d.ts +2 -0
  22. package/dist/cjs/package-info.js +6 -0
  23. package/dist/cjs/package.json +3 -0
  24. package/dist/esm/index.d.ts +28 -0
  25. package/dist/esm/index.js +30 -0
  26. package/dist/esm/lib/api-request.d.ts +42 -0
  27. package/{lib → dist/esm/lib}/api-request.js +20 -53
  28. package/dist/esm/lib/authentication.d.ts +46 -0
  29. package/dist/esm/lib/authentication.js +149 -0
  30. package/dist/esm/lib/generate-summary.d.ts +143 -0
  31. package/{lib → dist/esm/lib}/generate-summary.js +59 -155
  32. package/dist/esm/lib/get-api-url.d.ts +19 -0
  33. package/{lib → dist/esm/lib}/get-api-url.js +4 -13
  34. package/dist/esm/lib/list-models.d.ts +46 -0
  35. package/{lib → dist/esm/lib}/list-models.js +19 -50
  36. package/dist/esm/lib/signals.d.ts +72 -0
  37. package/{lib → dist/esm/lib}/signals.js +33 -79
  38. package/dist/esm/lib/token-estimate.d.ts +46 -0
  39. package/dist/esm/lib/token-estimate.js +108 -0
  40. package/dist/esm/lib/visible-text.d.ts +33 -0
  41. package/{lib → dist/esm/lib}/visible-text.js +14 -40
  42. package/dist/esm/package-info.d.ts +2 -0
  43. package/dist/esm/package-info.js +3 -0
  44. package/dist/esm/package.json +3 -0
  45. package/package.json +63 -10
  46. package/.github/VULNERABILITY_REPORT.yml +0 -75
  47. package/.github/workflows/release.yaml +0 -37
  48. package/.github/workflows/test.yaml +0 -35
  49. package/.ncurc.js +0 -23
  50. package/.prettierignore +0 -5
  51. package/.prettierrc.js +0 -10
  52. package/.release-please-manifest.json +0 -3
  53. package/CLAUDE.md +0 -185
  54. package/eslint.config.js +0 -70
  55. package/examples/fixtures/message-1.json +0 -74
  56. package/examples/list-models.js +0 -14
  57. package/examples/summary.js +0 -34
  58. package/index.js +0 -26
  59. package/release-please-config.json +0 -10
  60. package/test/api-request.test.js +0 -169
  61. package/test/authentication.test.js +0 -110
  62. package/test/commonjs-graph.test.js +0 -21
  63. package/test/dispatcher.test.js +0 -94
  64. package/test/generate-summary.test.js +0 -795
  65. package/test/get-api-url.test.js +0 -52
  66. package/test/helpers/mock-server.js +0 -120
  67. package/test/index.test.js +0 -57
  68. package/test/list-models.test.js +0 -302
  69. package/test/signals.test.js +0 -264
  70. package/test/token-estimate.test.js +0 -164
  71. package/test/visible-text.test.js +0 -144
package/CLAUDE.md DELETED
@@ -1,185 +0,0 @@
1
- # Claude Development Guidelines
2
-
3
- ## Project Overview
4
-
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.
11
-
12
- It is published to npm and consumed by other Postal Systems projects - most
13
- notably EmailEngine (`../emailengine`), where it ships inside a standalone binary
14
- built with `@yao-pkg/pkg`. See **Platform constraints** below; it constrains
15
- which dependencies this library may use.
16
-
17
- ## Project Structure
18
-
19
- - `index.js` - Public entry point; re-exports the functions listed below
20
- - `/lib` - Implementation modules (one feature per file)
21
- - `/test` - Tests using the Node.js native test runner (`*.test.js`)
22
- - `/test/helpers/mock-server.js` - Local mock of the OpenAI-compatible API used by tests
23
- - `/examples` - Standalone usage examples (excluded from lint and CodeQL)
24
-
25
- ### Library Modules
26
-
27
- - `lib/generate-summary.js` - `generateSummary()` plus `DEFAULT_SYSTEM_PROMPT` /
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/visible-text.js` - drops hidden elements, scripts, styles and comments
38
- from HTML and invisible characters from text, so the model reads what the
39
- recipient sees.
40
- - `lib/signals.js` - checks run in code before the model sees the email
41
- (executable attachments, link text naming another host than its target,
42
- lookalike domains, display name and reply address mismatches, verified
43
- authentication failures, removed hidden content), passed to the model as
44
- `signals` and applied afterwards as a floor on `riskAssessment.risk`.
45
- - `lib/authentication.js` - parses the topmost Authentication-Results header
46
- into an `authentication` block marked verified when its authserv-id is one
47
- the caller trusts (`trustedAuthservIds`, `acceptUnnamedAuthentication`).
48
- - `lib/list-models.js` - `listModels()`; lists the chat models an endpoint
49
- serves, newest family first (`chatOnly: false` keeps the rest), each with a
50
- description and a recommended flag (`describeModel()`).
51
- - `lib/api-request.js` - shared HTTP request helper (size cap, JSON parsing, 429
52
- retry with Retry-After, error shaping) used by every API call.
53
- - `lib/token-estimate.js` - character-based token estimate and prompt fitting against
54
- a budget that covers the fixed parts of the prompt too.
55
-
56
- ## Technology Stack
57
-
58
- - **Runtime**: Node.js >= 20 (CI tests on 20, 22 and 24). No build step - plain CommonJS.
59
- - **Module system**: CommonJS (`'use strict';`, `require`/`module.exports`).
60
- - **HTTP**: `undici` (`fetch` + `Agent`) for all outbound API calls.
61
- - **Token budgeting**: a character-based estimate in `lib/token-estimate.js` (no
62
- tokenizer dependency); the model's own context-length error is the backstop.
63
- - **Email/text helpers**: `@postalsys/email-text-tools` (HTML to text),
64
- `libmime` (decoding encoded words in header values), `htmlparser2` with
65
- `domutils` and `dom-serializer` (hidden element removal and link extraction,
66
- pinned to their last CommonJS majors) and `tldts` (registrable domains).
67
-
68
- ## Development Commands
69
-
70
- ```
71
- npm test # Run the test suite (node --test test/*.test.js)
72
- npm run test:cjs # The suite with require(esm) disabled (CommonJS graph guard)
73
- npm run test:coverage # Run the suite under c8 coverage
74
- npm run lint # eslint .
75
- npm run lint:fix # eslint . --fix
76
- npm run format # prettier --write .
77
- npm run format:check # prettier --check .
78
- npm run update # Refresh deps: remove node_modules + lockfile, ncu -u, npm install
79
- ```
80
-
81
- Run a single test file, or a single test by name:
82
-
83
- ```
84
- node --test test/signals.test.js
85
- node --test --test-name-pattern="lookalike" test/*.test.js
86
- ```
87
-
88
- ESLint uses the shared Postal Systems flat config (`eslint.config.js`, kept
89
- identical across repos except its "Repo-specific" block, which here turns off
90
- `no-await-in-loop` for the intentional sequential retry loops). Prettier options
91
- live in `.prettierrc.js`. CI (`.github/workflows/test.yaml`) runs lint,
92
- format:check and the tests on every matrix job, plus `npm run test:cjs` on 22
93
- and 24.
94
-
95
- ## Testing
96
-
97
- - Uses the Node.js native test runner with the native `assert` module.
98
- - Tests live in `/test` and must be named `*.test.js` - the runner glob only
99
- matches that pattern, so helpers (e.g. `test/helpers/mock-server.js`) are never
100
- picked up as test files.
101
- - Tests are hermetic: they run against the in-process mock server in
102
- `test/helpers/mock-server.js` rather than calling real OpenAI endpoints. Do not
103
- add tests that require live API credentials or network access.
104
- - Run `npm test` before committing and make sure it passes.
105
-
106
- ## Platform constraints (important)
107
-
108
- - **Node.js 20 is the minimum supported version** (`engines.node` is
109
- `>=20.0.0`). Runtime code, tests and tooling must work on Node 20, 22 and 24.
110
- - **Everything that reaches runtime must be genuinely CommonJS-loadable.**
111
- EmailEngine bundles this library into a single executable with
112
- `@yao-pkg/pkg`, which snapshots the CommonJS `require` graph at build time and
113
- cannot load ES modules. `require()` of this package and of every runtime
114
- dependency must work with `--no-experimental-require-module`: Node 22+ (and
115
- 20.19) enable require(esm) by default, which hides an ESM-only dependency
116
- until the pkg binary fails. A CommonJS entry that only wraps a dynamic
117
- `import()` of ESM code does not count.
118
- - **How to check:** `npm run test:cjs` runs the whole suite under
119
- `NODE_OPTIONS=--no-experimental-require-module`; CI runs it on Node 22 and 24.
120
- `test/commonjs-graph.test.js` requires every runtime dependency, including the
121
- jsdom-backed `mimeHtml` of `@postalsys/email-text-tools` that the summary code
122
- never loads, so the guard sees the whole graph.
123
- - **Pins:** never add or upgrade to an ESM-only dependency. Hold the last
124
- CommonJS major in `.ncurc.js` (`reject` or `target`) with a one-line comment
125
- explaining why; `npm run update` honors it. `nanoid`, `htmlparser2` (10.x),
126
- `domutils` (3.x), `dom-serializer` (2.x) and `@asamuzakjp/css-color` are
127
- rejected; `undici` is held to the 7.x line by `target` (8.x requires
128
- Node >= 22.19). When `npm run update` proposes an upgrade, confirm
129
- `npm run test:cjs` still passes before accepting it.
130
- - **The jsdom chain:** `@postalsys/email-text-tools` -> jsdom -> cssstyle ->
131
- `@asamuzakjp/css-color` >=4.1.2 pulls in `@csstools/*` v4, which are pure
132
- ESM. `package.json` `"overrides"` holds `@asamuzakjp/css-color` at 4.1.1 so
133
- this repo's own tests and CI exercise the CommonJS graph. Overrides do not
134
- propagate to consumers: an app installing this package resolves css-color
135
- itself, and EmailEngine carries its own identical override and `.ncurc.js`
136
- reject.
137
-
138
- ## Dependency Management
139
-
140
- - Use `npm run update` to bump dependencies (it runs `ncu -u` then a clean
141
- install). Respect the `reject` list in `.ncurc.js`.
142
- - After updating, run `npm test`, `npm run lint`, and `npm run format:check`
143
- to confirm nothing broke.
144
- - Keep `package.json` versions exact (no `^`/`~` ranges), dev dependencies
145
- included, to match the existing convention and keep `pkg` builds reproducible.
146
-
147
- ## Versioning & Releases
148
-
149
- - Releases are automated with **release-please** (`.github/workflows/release.yaml`).
150
- Merging Conventional Commit messages to `master` opens/updates a release PR;
151
- merging that PR tags the version, updates `CHANGELOG.md`, and publishes to npm
152
- with provenance.
153
- - Commit prefixes drive the version bump: `fix:` -> patch, `feat:` -> minor,
154
- `feat!:` / `BREAKING CHANGE:` -> major.
155
-
156
- ## Code Style Rules
157
-
158
- - CommonJS only - every module starts with `'use strict';` and uses
159
- `require`/`module.exports`. No `import`/`export`.
160
- - Never use emojis in code or documentation; printable ASCII characters only.
161
- - Use a single hyphen-minus (`-`) as a dash in user-facing strings and docs.
162
- Never use double hyphens (`--`), em dashes, or en dashes.
163
- - Formatting is owned by Prettier and linting by ESLint - run both before
164
- committing; do not hand-format against them.
165
- - **Git commit messages: do not list Claude (or any AI) as a co-author or
166
- contributor.** Write commit messages in the project's own voice.
167
- - Use Conventional Commit prefixes so release-please works (`fix:`, `feat:`,
168
- `chore:`, `docs:`, `test:`, `ci:`, `refactor:`).
169
- - For commits that do not change runtime behavior (docs, comments, CI/workflow
170
- tweaks, formatting), append `[skip ci]` to the commit message to avoid
171
- triggering the GitHub Actions workflows. Exception: do not add `[skip ci]` to
172
- commits using a `fix:` or `feat:` prefix - those must run so the release action
173
- is triggered.
174
-
175
- ## Workflow After Making Changes
176
-
177
- 1. Run `npm run format` and `npm run lint`.
178
- 2. Run `npm test` and confirm it passes.
179
- 3. Review changed code for reuse, quality, and efficiency (`/simplify`), and run
180
- `/security-review` for anything touching parsing, prompts, or outbound HTTP.
181
- 4. After pushing, check the GitHub Actions runs (e.g. `gh run list --branch master`)
182
- and report their status, including the CodeQL ("code quality") results. If a
183
- run fails for an unrelated infrastructure reason (checkout reporting "account
184
- suspended", HTTP 403, other auth errors), check https://www.githubstatus.com/
185
- for an active GitHub incident before assuming the code is at fault.
package/eslint.config.js DELETED
@@ -1,70 +0,0 @@
1
- 'use strict';
2
-
3
- // Shared lint baseline for the Postal Systems / Nodemailer packages: eslint:recommended
4
- // plus the rules of the retired eslint-config-nodemailer, with formatting left to Prettier.
5
- // Keep this file identical across repos except for the "Repo-specific" block at the end.
6
-
7
- const js = require('@eslint/js');
8
- const prettier = require('eslint-config-prettier');
9
- const globals = require('globals');
10
-
11
- module.exports = [
12
- {
13
- ignores: ['node_modules/**', 'coverage/**', 'dist/**']
14
- },
15
- js.configs.recommended,
16
- {
17
- files: ['**/*.js', '**/*.cjs'],
18
- languageOptions: {
19
- ecmaVersion: 2022,
20
- sourceType: 'commonjs',
21
- globals: { ...globals.node }
22
- },
23
- rules: {
24
- 'no-await-in-loop': 'error',
25
- 'no-div-regex': 'error',
26
- strict: ['error', 'global'],
27
- eqeqeq: 'error',
28
- 'dot-notation': 'error',
29
- curly: 'error',
30
- 'no-unused-expressions': ['error', { allowShortCircuit: true }],
31
- 'no-unused-vars': ['error', { varsIgnorePattern: '^_', argsIgnorePattern: '^_', caughtErrorsIgnorePattern: '^_' }],
32
- 'handle-callback-err': 'error',
33
- 'no-new': 'error',
34
- 'new-cap': 'error',
35
- 'no-eval': 'error',
36
- 'no-invalid-this': 'error',
37
- radix: ['error', 'always'],
38
- 'no-use-before-define': ['error', 'nofunc'],
39
- 'callback-return': ['error', ['callback', 'cb', 'done']],
40
- 'no-redeclare': 'error',
41
- 'block-scoped-var': 'error',
42
- 'no-sequences': 'error',
43
- 'no-throw-literal': 'error',
44
- 'no-useless-call': 'error',
45
- 'no-useless-concat': 'error',
46
- 'no-void': 'error',
47
- yoda: 'error',
48
- 'no-var': 'error',
49
- 'no-bitwise': 'error',
50
- 'no-lonely-if': 'error',
51
- 'arrow-body-style': ['error', 'as-needed'],
52
- 'prefer-arrow-callback': 'error',
53
- 'object-shorthand': 'error',
54
- 'prefer-spread': 'error',
55
- 'no-prototype-builtins': 'off'
56
- }
57
- },
58
- {
59
- files: ['test/**'],
60
- languageOptions: {
61
- globals: { ...globals.node, ...globals.mocha }
62
- }
63
- },
64
- // Repo-specific: overrides go here, each with a one-line reason
65
- {
66
- // Retry loops (429 backoff in api-request.js, refused-parameter retry in generate-summary.js) await sequentially on purpose, 4 sites
67
- rules: { 'no-await-in-loop': 'off' }
68
- },
69
- prettier
70
- ];
@@ -1,74 +0,0 @@
1
- {
2
- "id": "AAAADQAABlw",
3
- "uid": 1628,
4
- "path": "INBOX",
5
- "date": "2022-07-06T14:12:30.000Z",
6
- "flags": ["\\Seen"],
7
- "size": 4400,
8
- "subject": "Re: proovikiri",
9
- "from": {
10
- "name": "Andris Reinman",
11
- "address": "andris.reinman@gmail.com"
12
- },
13
- "replyTo": [
14
- {
15
- "name": "Andris Reinman",
16
- "address": "andris.reinman@gmail.com"
17
- }
18
- ],
19
- "sender": {
20
- "name": "Andris Reinman",
21
- "address": "andris.reinman@gmail.com"
22
- },
23
- "to": [
24
- {
25
- "name": "andris",
26
- "address": "andris@ekiri.ee"
27
- }
28
- ],
29
- "messageId": "<A768E075-1C9F-4483-A04A-943FA920BFC5@gmail.com>",
30
- "inReplyTo": "<CAPFU5tRb4fM+4d74kkb5bjGuFr7n3kFF_TNXK=67ki93CLzGFw@mail.gmail.com>",
31
- "headers": {
32
- "return-path": ["<andris.reinman@gmail.com>"],
33
- "delivered-to": ["andris@ekiri.ee"],
34
- "received": [
35
- "from mail-lj1-f179.google.com (mail-lj1-f179.google.com [209.85.208.179]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by uvn-67-33.tll01.zonevs.eu (Postfix) with ESMTPS id 44342821FF for <andris@ekiri.ee>; Wed, 6 Jul 2022 17:12:33 +0300 (EEST)",
36
- "by mail-lj1-f179.google.com with SMTP id w2so2284874ljj.7 for <andris@ekiri.ee>; Wed, 06 Jul 2022 07:12:33 -0700 (PDT)",
37
- "from smtpclient.apple (39-152-191-90.dyn.estpak.ee. [90.191.152.39]) by smtp.gmail.com with ESMTPSA id z8-20020a05651c022800b0025d37955bc7sm947119ljn.74.2022.07.06.07.12.30 for <andris@ekiri.ee> (version=TLS1_2 cipher=ECDHE-ECDSA-AES128-GCM-SHA256 bits=128/128); Wed, 06 Jul 2022 07:12:31 -0700 (PDT)"
38
- ],
39
- "authentication-results": [
40
- "uvn-67-33.tll01.zonevs.eu; dkim=pass reason=\"2048-bit key; insecure key\" header.d=gmail.com header.i=@gmail.com header.b=E9nmrfaB; dkim-adsp=pass; dkim-atps=neutral"
41
- ],
42
- "dkim-signature": [
43
- "v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20210112; h=from:mime-version:subject:date:references:to:in-reply-to:message-id; bh=us7LzUXeWkaVy96MNsqMB7vDjhaZ9hRrGPgxXc9icYc=; b=E9nmrfaBGUMEisRJCJy674YfEQyu2oXIF/1E7AcyGAit26CPU+vfpL3XGXmMzwWKTd S+EjMUwCc4xn4wkmxYl3nxcd3EQr1XpIpp42fK4wEfaAt7Nb3Wp+uV1pBej6Slh2TgBf j7NWyea3gyh/m09OqKAijYesJYw9YGmo+6Y7lgiNFFuIeuJRUrg5htvc6eNzoSQfnIIl QiUptLnrFFfgMRsaBkIsd4ie1/1HnLoa7ngopIRVARKRrrCNRhTqkiM93BUf8nBUDjb7 QPh8PBzzGrVvA9nDLjlSsF8t0s8Nwk9f7HApzFKAra3dzv8VnFY6zQxBm26yCjnrCxbH 8dyA=="
44
- ],
45
- "x-google-dkim-signature": [
46
- "v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=x-gm-message-state:from:mime-version:subject:date:references:to :in-reply-to:message-id; bh=us7LzUXeWkaVy96MNsqMB7vDjhaZ9hRrGPgxXc9icYc=; b=0hw1EbIluZO7ZAuzBIRNVqHtNAHviTJ0RXDtefUWxyfjaaTnKkmnwPum49KIf5gGu+ J7r9tw4rGvQKLjmM1runJiZFZHq7afV3MmR4wGjjvLRA62MAdIcpAT5u8ElxjHf0nhhM OO7Yf+mYwqsB6KDeZQ5JF9LCNBvpe+TQpSXMlHANyWvh5Ofp6ugH+gLEx+8QIJHIcGBi 6cXu+pPb1GsE+M3bWY7DEiYeTDy6QQfxRZSdi9vSHFb4h/R8K6Z1/heJN+RlEGmUU2M7 fQbEuCcHfObhWMe5AmLfDXIlrx+wKxVyVxpafkLSiMQnRSvqhxVSWcUKjzr20TlHT/qH ca9g=="
47
- ],
48
- "x-gm-message-state": ["AJIora/2p0hYvgtQ3eBu7h9wBVVfY6UdVx4BO6QA32p0fTru+yWtItsi GdXLS5baocCqlr3JhbHd4ORKCa46iqRbZA=="],
49
- "x-google-smtp-source": ["AGRyM1s3m/T3Exsg6pXn6DGV9dmrrt5GV7nTjah/wAyWp+fel/88cNszkKiPBCE/I3u1VEiSO1zJMw=="],
50
- "x-received": [
51
- "by 2002:a05:651c:1032:b0:25a:780b:7140 with SMTP id w18-20020a05651c103200b0025a780b7140mr23860776ljm.319.1657116752521; Wed, 06 Jul 2022 07:12:32 -0700 (PDT)"
52
- ],
53
- "from": ["Andris Reinman <andris.reinman@gmail.com>"],
54
- "content-type": ["multipart/alternative; boundary=\"Apple-Mail=_650C0B0C-FF20-4BA0-B542-9025E8199E24\""],
55
- "mime-version": ["1.0 (Mac OS X Mail 16.0 \\(3696.100.31\\))"],
56
- "subject": ["Re: proovikiri"],
57
- "date": ["Wed, 6 Jul 2022 17:12:30 +0300"],
58
- "references": ["<CAPFU5tRb4fM+4d74kkb5bjGuFr7n3kFF_TNXK=67ki93CLzGFw@mail.gmail.com>"],
59
- "to": ["andris <andris@ekiri.ee>"],
60
- "in-reply-to": ["<CAPFU5tRb4fM+4d74kkb5bjGuFr7n3kFF_TNXK=67ki93CLzGFw@mail.gmail.com>"],
61
- "message-id": ["<A768E075-1C9F-4483-A04A-943FA920BFC5@gmail.com>"],
62
- "x-mailer": ["Apple Mail (2.3696.100.31)"]
63
- },
64
- "text": {
65
- "id": "AAAADQAABlyTkaExkaEykA",
66
- "encodedSize": {
67
- "plain": 123,
68
- "html": 590
69
- },
70
- "plain": "multi pultiu 3\n\n> On 6. Jul 2022, at 16:34, Andris Reinman <andris@postalsys.com> wrote:\n> \n> See on lihtsalt proov\n\n",
71
- "html": "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=us-ascii\"></head><body style=\"word-wrap: break-word; -webkit-nbsp-mode: space; line-break: after-white-space;\" class=\"\">multi <b class=\"\">pultiu 3</b><br class=\"\"><div><br class=\"\"><blockquote type=\"cite\" class=\"\"><div class=\"\">On 6. Jul 2022, at 16:34, Andris Reinman &lt;<a href=\"mailto:andris@postalsys.com\" class=\"\">andris@postalsys.com</a>&gt; wrote:</div><br class=\"Apple-interchange-newline\"><div class=\"\"><div dir=\"ltr\" class=\"\">See on lihtsalt proov</div>\n</div></blockquote></div><br class=\"\"></body></html>",
72
- "hasMore": false
73
- }
74
- }
@@ -1,14 +0,0 @@
1
- 'use strict';
2
-
3
- const { listModels } = require('../lib/list-models');
4
- const util = require('util');
5
-
6
- async function main() {
7
- const result = await listModels(process.env.OPENAI_API_KEY, {
8
- verbose: true
9
- });
10
-
11
- console.log(util.inspect(result, false, 22, true));
12
- }
13
-
14
- main();
@@ -1,34 +0,0 @@
1
- 'use strict';
2
-
3
- const fs = require('fs').promises;
4
- const { generateSummary } = require('../lib/generate-summary');
5
- const simpleParser = require('mailparser').simpleParser;
6
- const libmime = require('libmime');
7
- const util = require('util');
8
-
9
- async function main() {
10
- const eml = await fs.readFile(process.argv[2]);
11
-
12
- const parsed = await simpleParser(eml);
13
-
14
- const { result, usage } = await generateSummary(
15
- {
16
- headers: parsed.headerLines.map(header => libmime.decodeHeader(header.line)),
17
- attachments: parsed.attachments,
18
- html: parsed.html,
19
- text: parsed.text,
20
- subject: parsed.subject,
21
- from: parsed.from && parsed.from.value && parsed.from.value[0],
22
- date: parsed.date
23
- },
24
- process.env.OPENAI_API_KEY,
25
- {
26
- gptModel: process.env.OPENAI_MODEL,
27
- verbose: true
28
- }
29
- );
30
-
31
- console.log(util.inspect({ result, usage }, false, 22, true));
32
- }
33
-
34
- main();
package/index.js DELETED
@@ -1,26 +0,0 @@
1
- 'use strict';
2
-
3
- const {
4
- generateSummary,
5
- DEFAULT_MODEL,
6
- DEFAULT_REASONING_EFFORT,
7
- DEFAULT_MAX_TOKENS,
8
- DEFAULT_SYSTEM_PROMPT,
9
- DEFAULT_INSTRUCTIONS,
10
- REASONING_EFFORTS,
11
- ALLOWED_HEADERS
12
- } = require('./lib/generate-summary');
13
- const { listModels, describeModel } = require('./lib/list-models');
14
-
15
- module.exports = {
16
- generateSummary,
17
- listModels,
18
- describeModel,
19
- DEFAULT_MODEL,
20
- DEFAULT_REASONING_EFFORT,
21
- DEFAULT_MAX_TOKENS,
22
- DEFAULT_SYSTEM_PROMPT,
23
- DEFAULT_INSTRUCTIONS,
24
- REASONING_EFFORTS,
25
- ALLOWED_HEADERS
26
- };
@@ -1,10 +0,0 @@
1
- {
2
- "packages": {
3
- ".": {
4
- "release-type": "node",
5
- "package-name": "@postalsys/email-ai-tools",
6
- "include-component-in-tag": false,
7
- "pull-request-title-pattern": "chore${scope}: release ${version} [skip-ci]"
8
- }
9
- }
10
- }
@@ -1,169 +0,0 @@
1
- 'use strict';
2
-
3
- const { describe, it, before, after, beforeEach } = require('node:test');
4
- const assert = require('node:assert/strict');
5
- const { createMockServer, modelsResponse } = require('./helpers/mock-server');
6
- const { apiRequest, MAX_RESPONSE_SIZE, DEFAULT_TIMEOUT } = require('../lib/api-request');
7
-
8
- const HTML_502 = '<html><head><title>502 Bad Gateway</title></head><body><center><h1>502 Bad Gateway</h1></center></body></html>';
9
-
10
- // A short per-test timeout catches a regression that waits for a long Retry-After instead of failing
11
- const TIMEOUT = { timeout: 5000 };
12
-
13
- describe('apiRequest', () => {
14
- let mock;
15
- let url;
16
-
17
- before(async () => {
18
- mock = await createMockServer();
19
- url = `${mock.url}/v1/models`;
20
- });
21
-
22
- after(async () => {
23
- await mock.close();
24
- });
25
-
26
- beforeEach(() => {
27
- mock.clearRequests();
28
- });
29
-
30
- it('sends the token, user agent and JSON payload and returns the parsed body', TIMEOUT, async () => {
31
- mock.setHandler(() => modelsResponse());
32
-
33
- const { data, time } = await apiRequest(url, { apiToken: 'secret', payload: { a: 1 } });
34
-
35
- assert.ok(Array.isArray(data.data));
36
- assert.equal(typeof time, 'number');
37
- assert.equal(mock.requests.length, 1);
38
- assert.equal(mock.requests[0].method, 'POST');
39
- assert.equal(mock.requests[0].headers.authorization, 'Bearer secret');
40
- assert.equal(mock.requests[0].headers['content-type'], 'application/json');
41
- assert.ok(/^@postalsys\/email-ai-tools\//.test(mock.requests[0].headers['user-agent']));
42
- assert.deepEqual(mock.requests[0].body, { a: 1 });
43
- });
44
-
45
- it('reports an HTML 502 with its status code instead of a JSON SyntaxError', TIMEOUT, async () => {
46
- mock.setHandler(() => ({ status: 502, raw: HTML_502 }));
47
-
48
- await assert.rejects(
49
- () => apiRequest(url, { apiToken: 'token' }),
50
- err => {
51
- assert.notEqual(err.name, 'SyntaxError');
52
- assert.equal(err.message, 'Failed to run API request');
53
- assert.equal(err.statusCode, 502);
54
- assert.ok(err.responseText.includes('502 Bad Gateway'));
55
- return true;
56
- }
57
- );
58
- assert.equal(mock.requests.length, 1);
59
- });
60
-
61
- it('retries an HTML 429 after the Retry-After delay', TIMEOUT, async () => {
62
- let calls = 0;
63
- mock.setHandler(() => {
64
- calls++;
65
- if (calls === 1) {
66
- return { status: 429, raw: '<html>Too Many Requests</html>', headers: { 'retry-after-ms': '50' } };
67
- }
68
- return modelsResponse();
69
- });
70
-
71
- const { data } = await apiRequest(url, { apiToken: 'token' });
72
-
73
- assert.equal(calls, 2);
74
- assert.ok(Array.isArray(data.data));
75
- });
76
-
77
- it('fails right away when Retry-After is longer than it is willing to wait', TIMEOUT, async () => {
78
- mock.setHandler(() => ({ status: 429, raw: '<html>Too Many Requests</html>', headers: { 'Retry-After': '3600' } }));
79
-
80
- await assert.rejects(
81
- () => apiRequest(url, { apiToken: 'token' }),
82
- err => {
83
- assert.equal(err.statusCode, 429);
84
- assert.equal(err.retryAfter, 3600);
85
- return true;
86
- }
87
- );
88
- assert.equal(mock.requests.length, 1);
89
- });
90
-
91
- it('does not produce "[object Object]" for an error object without a message', TIMEOUT, async () => {
92
- mock.setHandler(() => ({ status: 400, body: { error: { type: 'invalid_request_error', code: 'bad_input' } } }));
93
-
94
- await assert.rejects(
95
- () => apiRequest(url, { apiToken: 'token' }),
96
- err => {
97
- assert.ok(!err.message.includes('[object Object]'), err.message);
98
- assert.ok(err.message.includes('invalid_request_error'));
99
- assert.equal(err.code, 'bad_input');
100
- assert.equal(err.statusCode, 400);
101
- return true;
102
- }
103
- );
104
- });
105
-
106
- it('uses a string error as the message', TIMEOUT, async () => {
107
- mock.setHandler(() => ({ status: 400, body: { error: 'Model not found' } }));
108
-
109
- await assert.rejects(
110
- () => apiRequest(url, { apiToken: 'token' }),
111
- err => {
112
- assert.equal(err.message, 'Model not found');
113
- assert.equal(err.statusCode, 400);
114
- return true;
115
- }
116
- );
117
- });
118
-
119
- it('rejects a 200 response that is not JSON with the status and a snippet', TIMEOUT, async () => {
120
- mock.setHandler(() => ({ status: 200, raw: '<html>Login required</html>' }));
121
-
122
- await assert.rejects(
123
- () => apiRequest(url, { apiToken: 'token' }),
124
- err => {
125
- assert.equal(err.code, 'InvalidResponse');
126
- assert.equal(err.statusCode, 200);
127
- assert.ok(err.responseText.includes('Login required'));
128
- return true;
129
- }
130
- );
131
- });
132
-
133
- it('rejects a 200 response with a JSON null body', TIMEOUT, async () => {
134
- mock.setHandler(() => ({ status: 200, raw: 'null' }));
135
-
136
- await assert.rejects(() => apiRequest(url, { apiToken: 'token' }), { code: 'InvalidResponse', statusCode: 200 });
137
- });
138
-
139
- it('stops reading a response larger than the size cap', TIMEOUT, async () => {
140
- const big = 'x'.repeat(MAX_RESPONSE_SIZE + 1024);
141
- mock.setHandler(() => ({ status: 200, raw: big }));
142
-
143
- await assert.rejects(
144
- () => apiRequest(url, { apiToken: 'token' }),
145
- err => {
146
- assert.equal(err.code, 'ResponseTooLarge');
147
- assert.equal(err.statusCode, 200);
148
- return true;
149
- }
150
- );
151
- });
152
-
153
- it('gives up on a backend that never answers when the caller set no deadline', TIMEOUT, async () => {
154
- mock.setHandler(() => new Promise(resolve => setTimeout(() => resolve(modelsResponse()), 2000).unref()));
155
-
156
- await assert.rejects(() => apiRequest(url, { apiToken: 'token', timeout: 100 }), { name: 'TimeoutError' });
157
- assert.ok(DEFAULT_TIMEOUT > 0 && DEFAULT_TIMEOUT <= 10 * 60 * 1000, 'the default is a few minutes');
158
- });
159
-
160
- it('stops waiting for a 429 retry when the signal is aborted', TIMEOUT, async () => {
161
- mock.setHandler(() => ({ status: 429, raw: '', headers: { 'Retry-After': '10' } }));
162
-
163
- const controller = new AbortController();
164
- setTimeout(() => controller.abort(new Error('stopped')), 100);
165
-
166
- await assert.rejects(() => apiRequest(url, { apiToken: 'token', signal: controller.signal }), { message: 'stopped' });
167
- assert.equal(mock.requests.length, 1);
168
- });
169
- });