@postalsys/email-ai-tools 1.14.13 → 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.
@@ -2,8 +2,15 @@
2
2
 
3
3
  const { describe, it, before, after, beforeEach } = require('node:test');
4
4
  const assert = require('node:assert/strict');
5
- const { createMockServer, chatResponse, instructResponse, errorResponse } = require('./helpers/mock-server');
6
- const { generateSummary } = require('../lib/generate-summary');
5
+ const { createMockServer, chatResponse, errorResponse } = require('./helpers/mock-server');
6
+ const {
7
+ generateSummary,
8
+ isReasoningModel,
9
+ resetParameterCache,
10
+ DEFAULT_MODEL,
11
+ DEFAULT_SYSTEM_PROMPT,
12
+ DEFAULT_INSTRUCTIONS
13
+ } = require('../lib/generate-summary');
7
14
 
8
15
  describe('generateSummary', () => {
9
16
  let mock;
@@ -18,6 +25,7 @@ describe('generateSummary', () => {
18
25
 
19
26
  beforeEach(() => {
20
27
  mock.clearRequests();
28
+ resetParameterCache();
21
29
  });
22
30
 
23
31
  const simpleMessage = {
@@ -36,42 +44,103 @@ describe('generateSummary', () => {
36
44
  riskAssessment: { risk: 1, assessment: 'Low risk message.' }
37
45
  };
38
46
 
39
- it('returns structured response from chat API', async () => {
40
- mock.setHandler(() => chatResponse(summaryResult));
47
+ const userObject = req => JSON.parse(req.body.messages[1].content);
41
48
 
42
- const result = await generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url });
49
+ it('returns the model output as the result and the request usage beside it', async () => {
50
+ mock.setHandler(() => chatResponse(summaryResult, { id: 'chatcmpl-abc', tokens: 200, model: 'gpt-6-luna-2026-09-22' }));
43
51
 
44
- assert.equal(result.sentiment, 'neutral');
45
- assert.equal(result.summary, 'A test email greeting.');
46
- assert.equal(result.shouldReply, false);
47
- assert.deepEqual(result.riskAssessment, { risk: 1, assessment: 'Low risk message.' });
48
- assert.equal(result.id, 'chatcmpl-test123');
49
- assert.equal(result.tokens, 150);
50
- assert.equal(result.model, 'gpt-5-mini');
52
+ const { result, usage } = await generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url });
53
+
54
+ assert.deepEqual(result, summaryResult);
55
+ assert.equal(usage.id, 'chatcmpl-abc');
56
+ assert.equal(usage.model, DEFAULT_MODEL);
57
+ assert.equal(usage.servedModel, 'gpt-6-luna-2026-09-22');
58
+ assert.equal(usage.tokens, 200);
59
+ assert.equal(usage.promptTokens, 170);
60
+ assert.equal(usage.completionTokens, 30);
61
+ assert.equal(typeof usage.time, 'number');
62
+ assert.equal(usage.charactersRemoved, 0);
63
+ assert.ok(!('text' in usage));
51
64
  });
52
65
 
53
- it('sends correct request to chat API endpoint', async () => {
66
+ it('puts the instructions in the system message and only the email in the user message', async () => {
54
67
  mock.setHandler(() => chatResponse(summaryResult));
55
68
 
56
- await generateSummary(simpleMessage, 'my-api-key', {
57
- baseApiUrl: mock.url,
58
- user: 'user123',
59
- temperature: 0.7,
60
- topP: 0.9
61
- });
69
+ await generateSummary(simpleMessage, 'my-api-key', { baseApiUrl: mock.url, user: 'user123' });
62
70
 
63
71
  const req = mock.requests[0];
64
72
  assert.equal(req.method, 'POST');
65
73
  assert.equal(req.url, '/v1/chat/completions');
66
74
  assert.ok(req.headers.authorization.includes('Bearer my-api-key'));
67
- assert.equal(req.body.model, 'gpt-5-mini');
75
+ assert.equal(req.body.model, DEFAULT_MODEL);
68
76
  assert.equal(req.body.user, 'user123');
69
- assert.equal(req.body.temperature, 0.7);
70
- assert.equal(req.body.top_p, 0.9);
71
- assert.ok(Array.isArray(req.body.messages));
77
+ assert.deepEqual(req.body.response_format, { type: 'json_object' });
72
78
  assert.equal(req.body.messages.length, 2);
73
- assert.equal(req.body.messages[0].role, 'system');
74
- assert.equal(req.body.messages[1].role, 'user');
79
+
80
+ const [system, user] = req.body.messages;
81
+ assert.equal(system.role, 'system');
82
+ assert.ok(system.content.startsWith(DEFAULT_SYSTEM_PROMPT));
83
+ assert.ok(system.content.includes(DEFAULT_INSTRUCTIONS));
84
+ assert.ok(system.content.includes('JSON'), 'JSON mode needs the word in the prompt');
85
+
86
+ assert.equal(user.role, 'user');
87
+ assert.deepEqual(JSON.parse(user.content), {
88
+ subject: 'Test Subject',
89
+ from: 'sender@example.com',
90
+ date: '',
91
+ headers: { to: 'recipient@example.com' },
92
+ attachments: [],
93
+ text: 'Hello, this is a test email.'
94
+ });
95
+ });
96
+
97
+ it('decodes encoded words and flattens list values in headers', async () => {
98
+ mock.setHandler(() => chatResponse(summaryResult));
99
+
100
+ await generateSummary(
101
+ {
102
+ headers: [
103
+ { key: 'Subject', value: ['=?UTF-8?Q?T=C3=A4na_on_=F0=9F=98=80?='] },
104
+ { key: 'From', value: '=?ISO-8859-1?Q?J=F5gi?= <jogi@example.com>' },
105
+ { key: 'To', value: ['a@example.com', 'b@example.com'] },
106
+ { key: 'Date', value: 'Mon, 17 Oct 2022 09:42:07 +0300' }
107
+ ],
108
+ text: 'Tere'
109
+ },
110
+ 'test-token',
111
+ { baseApiUrl: mock.url }
112
+ );
113
+
114
+ const input = userObject(mock.requests[0]);
115
+ assert.equal(input.subject, 'Täna on \u{1F600}');
116
+ assert.equal(input.from, 'Jõgi <jogi@example.com>');
117
+ assert.equal(input.date, 'Mon, 17 Oct 2022 09:42:07 +0300');
118
+ assert.deepEqual(input.headers, { to: 'a@example.com, b@example.com' });
119
+ });
120
+
121
+ it('prefers the decoded subject, sender object and date over the headers', async () => {
122
+ mock.setHandler(() => chatResponse(summaryResult));
123
+
124
+ await generateSummary(
125
+ {
126
+ subject: 'Decoded subject',
127
+ from: { name: 'Andris', address: 'andris@example.com' },
128
+ date: new Date('2026-10-01T10:00:00.000Z'),
129
+ headers: [
130
+ { key: 'subject', value: '=?UTF-8?Q?Something_else?=' },
131
+ { key: 'from', value: 'other@example.com' }
132
+ ],
133
+ text: 'Hi'
134
+ },
135
+ 'test-token',
136
+ { baseApiUrl: mock.url }
137
+ );
138
+
139
+ const input = userObject(mock.requests[0]);
140
+ assert.equal(input.subject, 'Decoded subject');
141
+ assert.equal(input.from, 'Andris <andris@example.com>');
142
+ assert.equal(input.date, '2026-10-01T10:00:00.000Z');
143
+ assert.deepEqual(input.headers, {});
75
144
  });
76
145
 
77
146
  it('keeps the path prefix of a custom base URL', async () => {
@@ -79,180 +148,297 @@ describe('generateSummary', () => {
79
148
 
80
149
  await generateSummary(simpleMessage, 'my-api-key', { baseApiUrl: `${mock.url}/openai/v1` });
81
150
 
82
- const req = mock.requests[0];
83
- assert.equal(req.url, '/openai/v1/chat/completions');
151
+ assert.equal(mock.requests[0].url, '/openai/v1/chat/completions');
84
152
  });
85
153
 
86
154
  it('converts HTML to text when HTML is longer', async () => {
87
155
  mock.setHandler(() => chatResponse(summaryResult));
88
156
 
89
- const htmlMessage = {
90
- headers: [{ key: 'from', value: 'test@example.com' }],
91
- text: 'Short',
92
- html: '<p>This is a much longer HTML content that should be converted to text and used instead of the short plain text version.</p>'
93
- };
157
+ await generateSummary(
158
+ {
159
+ headers: [{ key: 'from', value: 'test@example.com' }],
160
+ text: 'Short',
161
+ html: '<p>This is a much longer HTML content that should be converted to text and used instead of the short plain text version.</p>'
162
+ },
163
+ 'test-token',
164
+ { baseApiUrl: mock.url }
165
+ );
94
166
 
95
- await generateSummary(htmlMessage, 'test-token', { baseApiUrl: mock.url });
167
+ const input = userObject(mock.requests[0]);
168
+ assert.ok(input.text.includes('This is a much longer HTML content'));
169
+ assert.ok(!input.text.includes('<p>'));
170
+ });
96
171
 
97
- const req = mock.requests[0];
98
- const userContent = req.body.messages[1].content;
99
- assert.ok(userContent.includes('This is a much longer HTML content'));
100
- assert.ok(!userContent.includes('<p>'));
172
+ it('passes only whitelisted headers and keeps the topmost authentication result', async () => {
173
+ mock.setHandler(() => chatResponse(summaryResult));
174
+
175
+ await generateSummary(
176
+ {
177
+ headers: [
178
+ { key: 'from', value: 'test@example.com' },
179
+ { key: 'x-custom-header', value: 'should be filtered' },
180
+ { key: 'received', value: 'should be filtered' },
181
+ { key: 'arc-seal', value: 'i=1; a=rsa-sha256; b=AAAA' },
182
+ { key: 'in-reply-to', value: '<parent@example.com>' },
183
+ { key: 'authentication-results', value: 'first result' },
184
+ { key: 'authentication-results', value: 'second result' }
185
+ ],
186
+ text: 'Test email'
187
+ },
188
+ 'test-token',
189
+ { baseApiUrl: mock.url }
190
+ );
191
+
192
+ const input = userObject(mock.requests[0]);
193
+ assert.deepEqual(input.headers, {
194
+ 'in-reply-to': '<parent@example.com>',
195
+ 'authentication-results': 'first result'
196
+ });
101
197
  });
102
198
 
103
- it('filters headers using whitelist', async () => {
199
+ it('merges custom allowedHeaders with defaults', async () => {
104
200
  mock.setHandler(() => chatResponse(summaryResult));
105
201
 
106
- const messageWithExtraHeaders = {
107
- headers: [
108
- { key: 'from', value: 'test@example.com' },
109
- { key: 'subject', value: 'Test' },
110
- { key: 'x-custom-header', value: 'should be filtered' },
111
- { key: 'received', value: 'should be filtered' },
112
- { key: 'authentication-results', value: 'spf=pass' }
113
- ],
114
- text: 'Test email'
115
- };
202
+ await generateSummary(
203
+ {
204
+ headers: [
205
+ { key: 'from', value: 'test@example.com' },
206
+ { key: 'x-priority', value: '1 (Highest)' }
207
+ ],
208
+ text: 'Urgent email'
209
+ },
210
+ 'test-token',
211
+ { baseApiUrl: mock.url, allowedHeaders: ['X-Priority'] }
212
+ );
116
213
 
117
- await generateSummary(messageWithExtraHeaders, 'test-token', { baseApiUrl: mock.url });
214
+ const input = userObject(mock.requests[0]);
215
+ assert.equal(input.headers['x-priority'], '1 (Highest)');
216
+ });
118
217
 
119
- const userContent = mock.requests[0].body.messages[1].content;
120
- assert.ok(userContent.includes('authentication-results'));
121
- assert.ok(!userContent.includes('x-custom-header'));
122
- assert.ok(!userContent.includes('received'));
218
+ it('lists attachments by name and type', async () => {
219
+ mock.setHandler(() => chatResponse(summaryResult));
220
+
221
+ await generateSummary(
222
+ {
223
+ headers: [{ key: 'from', value: 'test@example.com' }],
224
+ text: 'See attached.',
225
+ attachments: [
226
+ { filename: 'document.pdf', contentType: 'application/pdf', content: Buffer.from('x') },
227
+ { filename: 'image.png', contentType: 'image/png' },
228
+ { id: 'no-name-no-type' }
229
+ ]
230
+ },
231
+ 'test-token',
232
+ { baseApiUrl: mock.url }
233
+ );
234
+
235
+ const input = userObject(mock.requests[0]);
236
+ assert.deepEqual(input.attachments, [
237
+ { filename: 'document.pdf', contentType: 'application/pdf' },
238
+ { filename: 'image.png', contentType: 'image/png' }
239
+ ]);
123
240
  });
124
241
 
125
- it('deduplicates authentication headers', async () => {
242
+ it('sends a low reasoning effort to reasoning models and nothing to others', async () => {
126
243
  mock.setHandler(() => chatResponse(summaryResult));
127
244
 
128
- const messageWithDupAuth = {
129
- headers: [
130
- { key: 'from', value: 'test@example.com' },
131
- { key: 'authentication-results', value: 'first result' },
132
- { key: 'authentication-results', value: 'second result' }
133
- ],
134
- text: 'Test'
135
- };
245
+ await generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url, gptModel: 'gpt-5-mini' });
246
+ assert.equal(mock.requests[0].body.reasoning_effort, 'low');
136
247
 
137
- await generateSummary(messageWithDupAuth, 'test-token', { baseApiUrl: mock.url });
248
+ await generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url, gptModel: 'gpt-4.1-mini' });
249
+ assert.ok(!('reasoning_effort' in mock.requests[1].body));
138
250
 
139
- const userContent = mock.requests[0].body.messages[1].content;
140
- assert.ok(userContent.includes('first result'));
141
- assert.ok(!userContent.includes('second result'));
251
+ await generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url, gptModel: 'gpt-4.1-mini', reasoningEffort: 'High' });
252
+ assert.equal(mock.requests[2].body.reasoning_effort, 'high');
142
253
  });
143
254
 
144
- it('merges custom allowedHeaders with defaults', async () => {
255
+ it('sends temperature and top_p when given, including zero', async () => {
145
256
  mock.setHandler(() => chatResponse(summaryResult));
146
257
 
147
- const messageWithCustomHeader = {
148
- headers: [
149
- { key: 'from', value: 'test@example.com' },
150
- { key: 'x-priority', value: '1 (Highest)' }
151
- ],
152
- text: 'Urgent email'
153
- };
258
+ await generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url, gptModel: 'gpt-4.1', temperature: 0, topP: '0.9' });
154
259
 
155
- await generateSummary(messageWithCustomHeader, 'test-token', {
156
- baseApiUrl: mock.url,
157
- allowedHeaders: ['x-priority']
260
+ const req = mock.requests[0];
261
+ assert.equal(req.body.temperature, 0);
262
+ assert.equal(req.body.top_p, 0.9);
263
+
264
+ await generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url, gptModel: 'gpt-4.1', temperature: '', topP: null });
265
+ assert.ok(!('temperature' in mock.requests[1].body));
266
+ assert.ok(!('top_p' in mock.requests[1].body));
267
+ });
268
+
269
+ it('drops a parameter the backend refuses and remembers it', async () => {
270
+ mock.setHandler((req, body) => {
271
+ if ('reasoning_effort' in body) {
272
+ // the structured field names the parameter, the text does not
273
+ return errorResponse(400, 'Unsupported parameter for this model.', 'unsupported_parameter', 'reasoning_effort');
274
+ }
275
+ if ('temperature' in body) {
276
+ return errorResponse(
277
+ 400,
278
+ "Unsupported value: 'temperature' does not support 0.7 with this model. Only the default (1) value is supported.",
279
+ 'unsupported_value'
280
+ );
281
+ }
282
+ return chatResponse(summaryResult);
283
+ });
284
+
285
+ const opts = { baseApiUrl: mock.url, gptModel: 'gpt-4.1', temperature: 0.7, reasoningEffort: 'low' };
286
+ const first = await generateSummary(simpleMessage, 'test-token', opts);
287
+ assert.equal(first.result.summary, 'A test email greeting.');
288
+ assert.equal(mock.requests.length, 3);
289
+ assert.ok(!('reasoning_effort' in mock.requests[2].body));
290
+ assert.ok(!('temperature' in mock.requests[2].body));
291
+ assert.deepEqual(mock.requests[2].body.response_format, { type: 'json_object' }, 'an accepted parameter stays');
292
+ assert.ok(first.usage.time >= 0);
293
+
294
+ mock.clearRequests();
295
+ await generateSummary(simpleMessage, 'test-token', opts);
296
+ assert.equal(mock.requests.length, 1, 'the refusal is remembered for the next call');
297
+ assert.ok(!('reasoning_effort' in mock.requests[0].body));
298
+ assert.ok(!('temperature' in mock.requests[0].body));
299
+
300
+ mock.clearRequests();
301
+ await generateSummary(simpleMessage, 'test-token', Object.assign({}, opts, { gptModel: 'gpt-4o' }));
302
+ assert.equal(mock.requests.length, 3, 'another model starts afresh');
303
+ });
304
+
305
+ it('drops every parameter one refusal names', async () => {
306
+ mock.setHandler((req, body) => {
307
+ if ('temperature' in body || 'top_p' in body) {
308
+ return errorResponse(400, "Unsupported parameters: 'temperature' and 'top_p' are not supported with this model.", 'unsupported_parameter');
309
+ }
310
+ return chatResponse(summaryResult);
158
311
  });
159
312
 
160
- const userContent = mock.requests[0].body.messages[1].content;
161
- assert.ok(userContent.includes('x-priority'));
162
- assert.ok(userContent.includes('1 (Highest)'));
313
+ await generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url, gptModel: 'gpt-4.1-nano', temperature: 0.2, topP: 0.5 });
314
+
315
+ assert.equal(mock.requests.length, 2);
316
+ assert.ok(!('temperature' in mock.requests[1].body));
317
+ assert.ok(!('top_p' in mock.requests[1].body));
163
318
  });
164
319
 
165
- it('uses instruct endpoint for gpt-3.5-turbo-instruct', async () => {
166
- mock.setHandler(() => instructResponse(JSON.stringify(summaryResult)));
320
+ it('does not send sampling parameters to a model that is reasoning', async () => {
321
+ mock.setHandler(() => chatResponse(summaryResult));
167
322
 
168
- const result = await generateSummary(simpleMessage, 'test-token', {
169
- baseApiUrl: mock.url,
170
- gptModel: 'gpt-3.5-turbo-instruct'
323
+ await generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url, gptModel: 'gpt-5-mini', temperature: 0.5, topP: 0.9 });
324
+ assert.equal(mock.requests[0].body.reasoning_effort, 'low');
325
+ assert.ok(!('temperature' in mock.requests[0].body));
326
+ assert.ok(!('top_p' in mock.requests[0].body));
327
+
328
+ // with the reasoning switched off the model takes them again
329
+ await generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url, gptModel: 'gpt-5.1', temperature: 0.5, reasoningEffort: 'none' });
330
+ assert.equal(mock.requests[1].body.reasoning_effort, 'none');
331
+ assert.equal(mock.requests[1].body.temperature, 0.5);
332
+ });
333
+
334
+ it('does not retry a 400 that names no optional parameter', async () => {
335
+ mock.setHandler(() => errorResponse(400, "This model's maximum context length is 128000 tokens.", 'context_length_exceeded'));
336
+
337
+ await assert.rejects(() => generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url }), {
338
+ code: 'context_length_exceeded',
339
+ statusCode: 400
171
340
  });
341
+ assert.equal(mock.requests.length, 1);
342
+ });
172
343
 
173
- assert.equal(result.model, 'gpt-3.5-turbo-instruct');
174
- const req = mock.requests[0];
175
- assert.equal(req.url, '/v1/completions');
176
- assert.ok(typeof req.body.prompt === 'string');
177
- assert.ok(req.body.max_tokens > 0);
178
- assert.ok(!req.body.messages);
344
+ it('can switch JSON mode off', async () => {
345
+ mock.setHandler(() => chatResponse(summaryResult));
346
+
347
+ await generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url, jsonMode: false });
348
+
349
+ assert.ok(!('response_format' in mock.requests[0].body));
179
350
  });
180
351
 
181
- it('removes null and empty string values from response', async () => {
352
+ it('normalizes the documented properties and keeps custom ones', async () => {
182
353
  mock.setHandler(() =>
183
354
  chatResponse({
184
- sentiment: 'neutral',
185
- summary: 'Test',
186
- shouldReply: false,
187
- riskAssessment: { risk: 1, assessment: null },
188
- events: null,
355
+ sentiment: ' Positive ',
356
+ summary: ' Trimmed ',
357
+ shouldReply: 'true',
358
+ riskAssessment: { risk: '7', assessment: null },
359
+ events: { description: 'single event', startTime: '2026-10-02' },
360
+ actions: ['not an object'],
361
+ language: 'et',
362
+ emailType: 'inquiry',
189
363
  replyText: ''
190
364
  })
191
365
  );
192
366
 
193
- const result = await generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url });
367
+ const { result } = await generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url });
194
368
 
195
- assert.equal(result.sentiment, 'neutral');
196
- assert.ok(!('assessment' in result.riskAssessment));
197
- assert.ok(!('events' in result));
198
- assert.ok(!('replyText' in result));
369
+ assert.deepEqual(result, {
370
+ sentiment: 'positive',
371
+ summary: 'Trimmed',
372
+ shouldReply: true,
373
+ riskAssessment: { risk: 5 },
374
+ events: [{ description: 'single event', startTime: '2026-10-02' }],
375
+ language: 'et',
376
+ emailType: 'inquiry'
377
+ });
199
378
  });
200
379
 
201
- it('extracts JSON from response with surrounding text', async () => {
380
+ it('drops documented properties that cannot be made to fit', async () => {
381
+ mock.setHandler(() =>
382
+ chatResponse({
383
+ sentiment: 'mixed',
384
+ summary: { text: 'not a string' },
385
+ shouldReply: 'maybe',
386
+ riskAssessment: 'unknown',
387
+ events: null,
388
+ actions: []
389
+ })
390
+ );
391
+
392
+ const { result } = await generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url });
393
+
394
+ assert.deepEqual(result, {});
395
+ });
396
+
397
+ it('accepts a bare risk number as the risk assessment', async () => {
398
+ mock.setHandler(() => chatResponse({ summary: 'x', riskAssessment: 3 }));
399
+
400
+ const { result } = await generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url });
401
+
402
+ assert.deepEqual(result.riskAssessment, { risk: 3 });
403
+ });
404
+
405
+ it('extracts the JSON object from a response with surrounding text', async () => {
202
406
  mock.setHandler(() =>
203
407
  chatResponse(
204
- 'Here is my analysis:\n' +
205
- '{"sentiment":"positive","summary":"Extracted JSON","shouldReply":true,"riskAssessment":{"risk":1}}\n' +
408
+ 'Here is my analysis:\n```json\n' +
409
+ '{"sentiment":"positive","summary":"Extracted JSON","shouldReply":true,"riskAssessment":{"risk":1}}\n```\n' +
206
410
  'End of analysis.'
207
411
  )
208
412
  );
209
413
 
210
- const result = await generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url });
414
+ const { result } = await generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url });
211
415
 
212
416
  assert.equal(result.sentiment, 'positive');
213
417
  assert.equal(result.summary, 'Extracted JSON');
214
418
  });
215
419
 
216
- it('uses custom system and user prompts', async () => {
420
+ it('uses custom system prompt and instructions', async () => {
217
421
  mock.setHandler(() => chatResponse(summaryResult));
218
422
 
219
423
  await generateSummary(simpleMessage, 'test-token', {
220
424
  baseApiUrl: mock.url,
221
425
  systemPrompt: 'Custom system prompt here',
222
- userPrompt: 'Custom user prompt here'
426
+ instructions: 'Return the JSON property "language".'
223
427
  });
224
428
 
225
- const req = mock.requests[0];
226
- assert.equal(req.body.messages[0].content, 'Custom system prompt here');
227
- assert.ok(req.body.messages[1].content.startsWith('Custom user prompt here'));
429
+ const system = mock.requests[0].body.messages[0].content;
430
+ assert.ok(system.startsWith('Custom system prompt here\n\nReturn the JSON property "language".'));
431
+ assert.ok(!system.includes(DEFAULT_INSTRUCTIONS));
432
+ assert.ok(system.includes('The user message is a JSON object'), 'the input format stays');
228
433
  });
229
434
 
230
- it('handles message with attachments', async () => {
435
+ it('handles an empty message', async () => {
231
436
  mock.setHandler(() => chatResponse(summaryResult));
232
437
 
233
- const messageWithAttachments = {
234
- headers: [{ key: 'from', value: 'test@example.com' }],
235
- text: 'See attached.',
236
- attachments: [
237
- { filename: 'document.pdf', contentType: 'application/pdf' },
238
- { filename: 'image.png', contentType: 'image/png' }
239
- ]
240
- };
241
-
242
- const result = await generateSummary(messageWithAttachments, 'test-token', { baseApiUrl: mock.url });
243
-
244
- assert.equal(result.sentiment, 'neutral');
245
- const userContent = mock.requests[0].body.messages[1].content;
246
- assert.ok(userContent.includes('document.pdf'));
247
- assert.ok(userContent.includes('image.png'));
248
- });
249
-
250
- it('handles empty message', async () => {
251
- mock.setHandler(() => chatResponse(summaryResult));
252
-
253
- const result = await generateSummary({ headers: [], text: '' }, 'test-token', { baseApiUrl: mock.url });
438
+ const { result } = await generateSummary({}, 'test-token', { baseApiUrl: mock.url });
254
439
 
255
440
  assert.equal(result.sentiment, 'neutral');
441
+ assert.deepEqual(userObject(mock.requests[0]), { subject: '', from: '', date: '', headers: {}, attachments: [], text: '' });
256
442
  });
257
443
 
258
444
  it('retries on 429 rate limit', { timeout: 10000 }, async () => {
@@ -265,7 +451,7 @@ describe('generateSummary', () => {
265
451
  return chatResponse(summaryResult);
266
452
  });
267
453
 
268
- const result = await generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url });
454
+ const { result } = await generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url });
269
455
 
270
456
  assert.equal(result.summary, 'A test email greeting.');
271
457
  assert.equal(callCount, 2);
@@ -298,40 +484,58 @@ describe('generateSummary', () => {
298
484
  );
299
485
  });
300
486
 
301
- it('throws on invalid JSON response', async () => {
302
- mock.setHandler(() => chatResponse('This response contains no JSON at all'));
487
+ it('throws on a response without a JSON object and reports why the model stopped', async () => {
488
+ mock.setHandler(() => chatResponse('', { finishReason: 'length' }));
303
489
 
304
490
  await assert.rejects(
305
491
  () => generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url }),
306
492
  err => {
307
493
  assert.ok(err.message.includes('Failed to parse'));
494
+ assert.equal(err.finishReason, 'length');
495
+ assert.equal(err.textContent, '');
308
496
  return true;
309
497
  }
310
498
  );
311
499
  });
312
500
 
313
- it('includes verbose fields when verbose is true', async () => {
314
- mock.setHandler(() => chatResponse(summaryResult));
315
-
316
- const result = await generateSummary(simpleMessage, 'test-token', {
317
- baseApiUrl: mock.url,
318
- verbose: true
319
- });
501
+ it('throws when the model returns a list of objects instead of one', async () => {
502
+ mock.setHandler(() => chatResponse('[{"summary":"x"},{"summary":"y"}]'));
320
503
 
321
- assert.ok('_text' in result);
322
- assert.ok('_time' in result);
323
- assert.ok('_cr' in result);
324
- assert.equal(typeof result._time, 'number');
325
- assert.ok(result._time >= 0);
504
+ await assert.rejects(() => generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url }), /Failed to parse/);
326
505
  });
327
506
 
328
- it('does not include verbose fields by default', async () => {
507
+ it('includes the prompt text in the usage when verbose', async () => {
329
508
  mock.setHandler(() => chatResponse(summaryResult));
330
509
 
331
- const result = await generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url });
510
+ const { usage } = await generateSummary(simpleMessage, 'test-token', { baseApiUrl: mock.url, verbose: true });
511
+
512
+ assert.equal(usage.text, 'Hello, this is a test email.');
513
+ });
514
+ });
515
+
516
+ describe('isReasoningModel', () => {
517
+ it('recognizes the reasoning families', () => {
518
+ for (const model of [
519
+ 'gpt-5',
520
+ 'gpt-5-mini',
521
+ 'gpt-5.1',
522
+ 'gpt-5.4-nano',
523
+ 'gpt-5.6-luna',
524
+ 'gpt-6-luna',
525
+ 'gpt-6.1-sol',
526
+ 'gpt-10',
527
+ 'gpt-oss-20b',
528
+ 'o1',
529
+ 'o3-mini',
530
+ 'o4-mini'
531
+ ]) {
532
+ assert.equal(isReasoningModel(model), true, model);
533
+ }
534
+ });
332
535
 
333
- assert.ok(!('_text' in result));
334
- assert.ok(!('_time' in result));
335
- assert.ok(!('_cr' in result));
536
+ it('leaves out chat variants, older families and unknown names', () => {
537
+ for (const model of ['gpt-5-chat-latest', 'chat-latest', 'gpt-4.1', 'gpt-4o-mini', 'gpt-3.5-turbo', 'llama3.2', 'mistral-nemo', '', undefined]) {
538
+ assert.equal(isReasoningModel(model), false, String(model));
539
+ }
336
540
  });
337
541
  });