@dxv-systems/mail-graph 0.4.0 → 0.5.1

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/README.md CHANGED
@@ -114,6 +114,8 @@ await support.forward(id, { to: ["a@b.example"], comment: "" });
114
114
  await support.sendMail({ to, subject, body: { contentType: "html", content }, attachments }); // saveToSentItems: true
115
115
  ```
116
116
 
117
+ `listConversation(conversationId)` returns every message of a conversation in any folder (Inbox, Sent Items, Archive, the mailbox's own folders), oldest first. Each has `uniqueBody`: only the text that message adds, without the quoted history, as plain text by default (`{ bodyType: "html" }` for HTML). Graph refuses `$orderby` with this filter, so the package sorts. Drafts and Deleted Items are included; filter on `isDraft` and `parentFolderId` as needed.
118
+
117
119
  Message summaries (delta, folder pages, `getMessage`) carry `bodyPreview`: Graph's first 255 characters of the body as plain text.
118
120
 
119
121
  "Delete" for customer mail is `moveMessage(id, "deleteditems")`, the same as Delete in Outlook. `listFolderMessages` is for folders a caller reads live (Archive, Deleted Items, custom folders); the Inbox and Sent Items go through `delta`.
package/dist/index.d.ts CHANGED
@@ -6,4 +6,4 @@ export { LARGE_ATTACHMENT_THRESHOLD } from "./mailbox";
6
6
  export type { MailboxClient } from "./mailbox";
7
7
  export { GraphAuthError, GraphDeltaExpiredError, GraphError, GraphUsageError } from "./errors";
8
8
  export type { GraphErrorInit, UsageErrorCode } from "./errors";
9
- export type { AccessCheckResult, AccessStatus, AttachmentInfo, AttachmentKind, BodyType, CreateReplyOptions, DeltaItem, DeltaOptions, DeltaPage, FolderMessagesOptions, FolderMessagesPage, ForwardInput, GetMessageOptions, InternetMessageHeader, MailAddress, MailFolder, Message, MessageBody, MessageSummary, OutgoingAttachment, Recipient, SendMailInput, CreateDraftInput, WellKnownFolder, WellKnownFolderIds, } from "./types";
9
+ export type { AccessCheckResult, AccessStatus, AttachmentInfo, AttachmentKind, BodyType, CreateReplyOptions, DeltaItem, DeltaOptions, DeltaPage, FolderMessagesOptions, FolderMessagesPage, ForwardInput, GetMessageOptions, InternetMessageHeader, MailAddress, MailFolder, Message, MessageBody, MessageSummary, OutgoingAttachment, Recipient, SendMailInput, CreateDraftInput, ConversationMessage, ListConversationOptions, WellKnownFolder, WellKnownFolderIds, } from "./types";
package/dist/mailbox.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Http } from "./http";
2
- import type { AccessCheckResult, AttachmentInfo, CreateReplyOptions, DeltaOptions, DeltaPage, FolderMessagesOptions, FolderMessagesPage, ForwardInput, GetMessageOptions, MailFolder, Message, MessageBody, OutgoingAttachment, SendMailInput, CreateDraftInput, WellKnownFolderIds } from "./types";
2
+ import type { AccessCheckResult, AttachmentInfo, CreateReplyOptions, DeltaOptions, DeltaPage, FolderMessagesOptions, FolderMessagesPage, ForwardInput, GetMessageOptions, MailFolder, Message, MessageBody, OutgoingAttachment, SendMailInput, CreateDraftInput, ConversationMessage, ListConversationOptions, WellKnownFolderIds } from "./types";
3
3
  export declare const LARGE_ATTACHMENT_THRESHOLD: number;
4
4
  export interface MailboxClient {
5
5
  readonly address: string;
@@ -18,6 +18,7 @@ export interface MailboxClient {
18
18
  sendDraft(draftId: string): Promise<void>;
19
19
  markRead(messageId: string, isRead?: boolean): Promise<void>;
20
20
  setCategories(messageId: string, categories: string[]): Promise<void>;
21
+ listConversation(conversationId: string, options?: ListConversationOptions): Promise<ConversationMessage[]>;
21
22
  listFolders(parent: "inbox" | "root"): Promise<MailFolder[]>;
22
23
  listChildFolders(folderId: string): Promise<MailFolder[]>;
23
24
  getWellKnownFolderIds(): Promise<WellKnownFolderIds>;
package/dist/mailbox.js CHANGED
@@ -120,9 +120,9 @@ function createMailboxClient(http, address) {
120
120
  const result = await http.request({ mailbox: address, method: "GET", path, prefer });
121
121
  return (result.data ?? {});
122
122
  }
123
- async function collect(firstPath) {
123
+ async function collect(firstPath, prefer) {
124
124
  const items = [];
125
- let page = await getJson(firstPath);
125
+ let page = await getJson(firstPath, prefer);
126
126
  for (let i = 0;; i++) {
127
127
  items.push(...(page.value ?? []));
128
128
  const next = page["@odata.nextLink"];
@@ -130,7 +130,7 @@ function createMailboxClient(http, address) {
130
130
  return items;
131
131
  if (i >= MAX_PAGES)
132
132
  throw new errors_1.GraphError({ message: "Graph returned too many pages.", status: 0, code: "TooManyPages" });
133
- const result = await http.request({ mailbox: address, method: "GET", link: next });
133
+ const result = await http.request({ mailbox: address, method: "GET", link: next, prefer });
134
134
  page = (result.data ?? {});
135
135
  }
136
136
  }
@@ -375,6 +375,31 @@ function createMailboxClient(http, address) {
375
375
  }
376
376
  return ids;
377
377
  },
378
+ async listConversation(conversationId, options = {}) {
379
+ if (!conversationId)
380
+ throw new errors_1.GraphUsageError("InvalidArgument", "conversation id is required.");
381
+ const id = conversationId;
382
+ const bodyType = options.bodyType ?? "text";
383
+ const raw = await collect(`${user}/messages${query({
384
+ $filter: `conversationId eq '${id.replace(/'/g, "''")}'`,
385
+ $select: `${SUMMARY_SELECT},uniqueBody,sentDateTime,toRecipients`,
386
+ $top: 50,
387
+ })}`, [`outlook.body-content-type="${bodyType}"`]);
388
+ const time = (m) => Date.parse(m.receivedDateTime ?? m.sentDateTime ?? "") || 0;
389
+ return raw
390
+ .sort((a, b) => time(a) - time(b))
391
+ .map((m) => {
392
+ const type = m.uniqueBody?.contentType?.toLowerCase() === "html" ? "html" : "text";
393
+ const message = {
394
+ ...toSummary(m),
395
+ uniqueBody: { contentType: type, content: m.uniqueBody?.content ?? "" },
396
+ toRecipients: toAddresses(m.toRecipients),
397
+ };
398
+ if (m.sentDateTime !== undefined)
399
+ message.sentDateTime = m.sentDateTime;
400
+ return message;
401
+ });
402
+ },
378
403
  async listFolderMessages(folderId, options = {}) {
379
404
  const result = options.link
380
405
  ? await http.request({ mailbox: address, method: "GET", link: options.link })
package/dist/types.d.ts CHANGED
@@ -51,6 +51,14 @@ export interface Message extends MessageSummary {
51
51
  inReplyTo?: string;
52
52
  references?: string[];
53
53
  }
54
+ export interface ConversationMessage extends MessageSummary {
55
+ uniqueBody: MessageBody;
56
+ sentDateTime?: string;
57
+ toRecipients: MailAddress[];
58
+ }
59
+ export interface ListConversationOptions {
60
+ bodyType?: BodyType;
61
+ }
54
62
  export interface GetMessageOptions {
55
63
  bodyType?: BodyType;
56
64
  includeHeaders?: boolean;
@@ -17,7 +17,7 @@ The code below was compiled, linted, knip-checked, built and tested against a fr
17
17
  ## 1. Install
18
18
 
19
19
  ```bash
20
- npm install --save-exact @dxv-systems/mail-graph@0.4.0 @dxv-systems/helpdesk@0.13.0 @vercel/oidc@4.0.1
20
+ npm install --save-exact @dxv-systems/mail-graph@0.5.1 @dxv-systems/helpdesk@0.14.0 @vercel/oidc@4.0.1
21
21
  ```
22
22
 
23
23
  Use the published versions (exact, never a range; upgrading is a deliberate change). **Vendored variant** (before publication, e.g. the rehearsal): `npm pack` each package into `vendor/` and install `file:vendor/dxv-systems-mail-graph-<version>.tgz file:vendor/dxv-systems-helpdesk-<version>.tgz` instead; commit the tarballs with `package.json` and the lockfile.
@@ -76,6 +76,7 @@ Extend the `drizzle-orm/pg-core` import with `boolean, doublePrecision, primaryK
76
76
  ```ts
77
77
  import type { M365Connection } from "@dxv-systems/mail-graph/setup";
78
78
  import type {
79
+ DistillState,
79
80
  DraftRunStatus,
80
81
  HistoryState,
81
82
  MessageDirection,
@@ -114,6 +115,8 @@ export const helpdeskSettings = pgTable(
114
115
  syncLeaseUntil: timestamp("sync_lease_until", { withTimezone: true }),
115
116
  /** Lease of the history cron, apart from the sync's, so neither waits for the other. */
116
117
  historyLeaseUntil: timestamp("history_lease_until", { withTimezone: true }),
118
+ /** Lease of the FAQ distill cron, apart from the others. */
119
+ distillLeaseUntil: timestamp("distill_lease_until", { withTimezone: true }),
117
120
  updatedBy: integer("updated_by").references(() => users.id, { onDelete: "set null" }),
118
121
  updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(),
119
122
  },
@@ -142,6 +145,13 @@ export const helpdeskHistoryStates = pgTable("helpdesk_history_states", {
142
145
  updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(),
143
146
  });
144
147
 
148
+ /** FAQ distillation per mailbox (`DistillState`): Sent Items cursors, pending pairs and the open run, in one value. */
149
+ export const helpdeskDistillStates = pgTable("helpdesk_distill_states", {
150
+ mailbox: varchar("mailbox", { length: 320 }).primaryKey(),
151
+ state: jsonb("state").$type<DistillState>().notNull(),
152
+ updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(),
153
+ });
154
+
145
155
  /** Tickets (`Thread`), plus the inbox's assignment (app data). */
146
156
  export const helpdeskThreads = pgTable(
147
157
  "helpdesk_threads",
@@ -286,7 +296,7 @@ export const helpdeskReplyAttachments = pgTable(
286
296
  );
287
297
  ```
288
298
 
289
- Every column maps one field of the package types (`M365Connection`, `SyncState`, `Thread` incl. `dismissedBy`, `StoredMessage`, `DraftRun`, `SendIntent`, `ReplyAttachment`); `assignee_id`, `assignment_note` and `assigned_by` are the inbox's assignment, `seq` orders draft runs, `sync_lease_until` guards cron overlap. Then run `npm run db:generate`, review the SQL (nine `CREATE TABLE`s, foreign keys, nine indexes, no `DROP`) and commit it with its snapshot and journal entry. An app on helpdesk 0.2 upgrades with one generated migration: `direction` on `helpdesk_messages` (default `inbound`) and `sent_link`, `sent_last_received_at` on `helpdesk_sync_states` (see the helpdesk README, Upgrading from 0.2). An app on helpdesk 0.4 upgrades with one generated migration too: `assignment_note` and `assigned_by` on `helpdesk_threads`, both nullable (see the helpdesk README, Upgrading from 0.4). An app on helpdesk 0.5 upgrades with one generated migration: `from_name`, `preview`, `has_attachments`, `is_read` and `location` on `helpdesk_messages`, all nullable, and its store's `markMessageRemoved` becomes `updateMessageState`. Add `update helpdesk_sync_states set link = null, sent_link = null;` to the end of that generated migration, so the next sync fills the new fields of mail already stored (see the helpdesk README, Upgrading from 0.5). An app on helpdesk 0.11 upgrades with one generated migration: the table `helpdesk_history_states` and `history_lease_until` on `helpdesk_settings`, nothing dropped (see the helpdesk README, Upgrading from 0.11).
299
+ Every column maps one field of the package types (`M365Connection`, `SyncState`, `Thread` incl. `dismissedBy`, `StoredMessage`, `DraftRun`, `SendIntent`, `ReplyAttachment`); `assignee_id`, `assignment_note` and `assigned_by` are the inbox's assignment, `seq` orders draft runs, `sync_lease_until` guards cron overlap. Then run `npm run db:generate`, review the SQL (ten `CREATE TABLE`s, foreign keys, nine indexes, no `DROP`) and commit it with its snapshot and journal entry. An app on helpdesk 0.2 upgrades with one generated migration: `direction` on `helpdesk_messages` (default `inbound`) and `sent_link`, `sent_last_received_at` on `helpdesk_sync_states` (see the helpdesk README, Upgrading from 0.2). An app on helpdesk 0.4 upgrades with one generated migration too: `assignment_note` and `assigned_by` on `helpdesk_threads`, both nullable (see the helpdesk README, Upgrading from 0.4). An app on helpdesk 0.5 upgrades with one generated migration: `from_name`, `preview`, `has_attachments`, `is_read` and `location` on `helpdesk_messages`, all nullable, and its store's `markMessageRemoved` becomes `updateMessageState`. Add `update helpdesk_sync_states set link = null, sent_link = null;` to the end of that generated migration, so the next sync fills the new fields of mail already stored (see the helpdesk README, Upgrading from 0.5). An app on helpdesk 0.11 upgrades with one generated migration: the table `helpdesk_history_states` and `history_lease_until` on `helpdesk_settings`, nothing dropped (see the helpdesk README, Upgrading from 0.11). An app on helpdesk 0.13 upgrades with one generated migration: the table `helpdesk_distill_states` and `distill_lease_until` on `helpdesk_settings`, nothing dropped; then add the store methods, `claimDistillLease`, the distiller in `deps.ts`, the distill cron and the settings card below (see the helpdesk README, Upgrading from 0.13.0).
290
300
 
291
301
  ## 5. `src/lib/m365/` (Graph sign-in and the guided setup)
292
302
 
@@ -449,6 +459,7 @@ export function isCronRequest(request: Request): boolean {
449
459
  import "server-only";
450
460
  import { and, asc, desc, eq, gte, inArray, lt } from "drizzle-orm";
451
461
  import type {
462
+ DistillState,
452
463
  DraftRun,
453
464
  HelpdeskStore,
454
465
  HistoryState,
@@ -460,6 +471,7 @@ import type {
460
471
  } from "@dxv-systems/helpdesk";
461
472
  import { db, type DbClient } from "@/lib/db";
462
473
  import {
474
+ helpdeskDistillStates,
463
475
  helpdeskDraftRuns,
464
476
  helpdeskHistoryStates,
465
477
  helpdeskMessages,
@@ -637,6 +649,22 @@ export const helpdeskStore: HelpdeskStore = {
637
649
  .onConflictDoUpdate({ target: helpdeskHistoryStates.mailbox, set: { state, updatedAt: new Date() } });
638
650
  },
639
651
 
652
+ async getDistillState(mailbox): Promise<DistillState | null> {
653
+ const [row] = await db
654
+ .select({ state: helpdeskDistillStates.state })
655
+ .from(helpdeskDistillStates)
656
+ .where(eq(helpdeskDistillStates.mailbox, mailbox))
657
+ .limit(1);
658
+ return row?.state ?? null;
659
+ },
660
+
661
+ async saveDistillState(mailbox, state) {
662
+ await db
663
+ .insert(helpdeskDistillStates)
664
+ .values({ mailbox, state })
665
+ .onConflictDoUpdate({ target: helpdeskDistillStates.mailbox, set: { state, updatedAt: new Date() } });
666
+ },
667
+
640
668
  async getMessage(mailbox, id) {
641
669
  const [row] = await db
642
670
  .select()
@@ -1148,17 +1176,41 @@ export async function claimHistoryLease(ms: number): Promise<boolean> {
1148
1176
  export async function releaseHistoryLease(): Promise<void> {
1149
1177
  await db.update(helpdeskSettings).set({ historyLeaseUntil: null }).where(eq(helpdeskSettings.id, 1));
1150
1178
  }
1179
+
1180
+ /** Claims the FAQ distill cron's lease, the same way. */
1181
+ export async function claimDistillLease(ms: number): Promise<boolean> {
1182
+ await db.insert(helpdeskSettings).values({ id: 1 }).onConflictDoNothing();
1183
+ const now = new Date();
1184
+ const claimed = await db
1185
+ .update(helpdeskSettings)
1186
+ .set({ distillLeaseUntil: new Date(now.getTime() + ms) })
1187
+ .where(
1188
+ and(
1189
+ eq(helpdeskSettings.id, 1),
1190
+ or(isNull(helpdeskSettings.distillLeaseUntil), lt(helpdeskSettings.distillLeaseUntil, now)),
1191
+ ),
1192
+ )
1193
+ .returning({ id: helpdeskSettings.id });
1194
+ return claimed.length > 0;
1195
+ }
1196
+
1197
+ export async function releaseDistillLease(): Promise<void> {
1198
+ await db.update(helpdeskSettings).set({ distillLeaseUntil: null }).where(eq(helpdeskSettings.id, 1));
1199
+ }
1151
1200
  ```
1152
1201
 
1153
1202
  **No drafter yet.** `HelpdeskDeps.drafter` is optional and left out: every new customer mail opens its ticket in review (`reviewReason: "no_draft"`, label "Zelf antwoorden") with an empty "Jouw antwoord" box. Staff write the reply; saving it creates a staff run (an ordinary draft run with `text: null`, `reason: "staff"`), and "Goedkeuren en versturen" saves and sends it. A blank reply is refused (422 `empty_reply`). When the DXV AI gateway drafter is published, add it as `drafter` in `deps.ts` (its `start` calls the published agent with the idempotency key) and call `completeDraft` when it reports; nothing else changes.
1154
1203
 
1155
1204
  `src/lib/helpdesk/deps.ts`: one `HelpdeskDeps` per call, built from the stored connection. The notifier sends in-app notifications (template `notifyUsers`) to everyone with `helpdesk:use`, linking to the ticket. That matches this recipe's `getStaff`, where every helpdesk user has access to every connected mailbox; an app with access per person sends each event only to the people with access to `event.mailbox` (helpdesk README, Access per mailbox). `assigned` goes to the assignee only, with the internal note.
1156
1205
 
1206
+ The distiller starts and reads runs of the gateway feature `helpdesk.faq-distill` (`createRuns` from the template's `@/lib/ai`). DXV registers that feature for the app in the Portal, pointing to the platform agent `klantenservice-faq`. Until then a run start fails, the card shows the error and the pairs wait; nothing else is affected.
1207
+
1157
1208
  ```ts
1158
1209
  import "server-only";
1159
1210
  import { inArray } from "drizzle-orm";
1160
- import type { HelpdeskDeps, Notifier } from "@dxv-systems/helpdesk";
1211
+ import type { Distiller, HelpdeskDeps, Notifier } from "@dxv-systems/helpdesk";
1161
1212
  import { activeScope } from "@dxv-systems/mail-graph/setup";
1213
+ import { createRuns } from "@/lib/ai";
1162
1214
  import { rolesWithPermission } from "@/lib/auth/permissions";
1163
1215
  import { db } from "@/lib/db";
1164
1216
  import { users } from "@/lib/db/schema";
@@ -1221,6 +1273,18 @@ const notifier: Notifier = {
1221
1273
  },
1222
1274
  };
1223
1275
 
1276
+ /** FAQ distillation runs (agent `klantenservice-faq`). Created per call, so a missing AI setup fails only the run start. */
1277
+ const distiller: Distiller = {
1278
+ async fire(input, { eventKey }) {
1279
+ const { id } = await createRuns({ feature: "helpdesk.faq-distill" }).fireRun(input, { eventKey });
1280
+ return { runId: String(id) };
1281
+ },
1282
+ async read(runId) {
1283
+ const run = await createRuns({ feature: "helpdesk.faq-distill" }).getRun(runId);
1284
+ return { status: run.status, ...(run.error ? { error: run.error } : {}) };
1285
+ },
1286
+ };
1287
+
1224
1288
  /** The app's own sender (EMAIL_FROM): its mail is never a ticket. */
1225
1289
  function ownAddresses(): string[] {
1226
1290
  const from = process.env.EMAIL_FROM?.trim();
@@ -1244,6 +1308,7 @@ export async function getHelpdeskDeps(): Promise<HelpdeskDeps | null> {
1244
1308
  controls: loadHelpdeskControls,
1245
1309
  notifier,
1246
1310
  attachments: helpdeskReplyFiles,
1311
+ distiller,
1247
1312
  };
1248
1313
  }
1249
1314
  ```
@@ -1333,6 +1398,7 @@ import {
1333
1398
  isPaused,
1334
1399
  isSyncFailing,
1335
1400
  reconcileUnknownSends,
1401
+ runDistill,
1336
1402
  runHistory,
1337
1403
  sweepStuckDrafts,
1338
1404
  syncMailbox,
@@ -1342,7 +1408,14 @@ import { db } from "@/lib/db";
1342
1408
  import { helpdeskHistoryStates, helpdeskSyncStates } from "@/lib/db/schema";
1343
1409
  import { notifyUsers } from "@/lib/notifications/service";
1344
1410
  import { getHelpdeskDeps } from "./deps";
1345
- import { claimHistoryLease, claimSyncLease, releaseHistoryLease, releaseSyncLease } from "./settings";
1411
+ import {
1412
+ claimDistillLease,
1413
+ claimHistoryLease,
1414
+ claimSyncLease,
1415
+ releaseDistillLease,
1416
+ releaseHistoryLease,
1417
+ releaseSyncLease,
1418
+ } from "./settings";
1346
1419
 
1347
1420
  /** Longer than the cron route's maxDuration, so a dead run's lease expires on its own. */
1348
1421
  const SYNC_LEASE_MS = 6 * 60_000;
@@ -1354,7 +1427,7 @@ export async function onHelpdeskConnected(connection: M365Connection): Promise<v
1354
1427
  for (const mailbox of connection.mailboxes) await connectMailbox(deps, mailbox);
1355
1428
  }
1356
1429
 
1357
- /** Setup `onReset`: forget delta and history positions; tickets stay. Tells the admin who reset. */
1430
+ /** Setup `onReset`: forget delta and history positions; tickets and distill states stay. Tells the admin who reset. */
1358
1431
  export async function onHelpdeskReset(adminId: number | null): Promise<void> {
1359
1432
  await db.delete(helpdeskSyncStates);
1360
1433
  await db.delete(helpdeskHistoryStates);
@@ -1419,6 +1492,28 @@ export async function runHelpdeskHistory(): Promise<HelpdeskSyncOutcome> {
1419
1492
  await releaseHistoryLease();
1420
1493
  }
1421
1494
  }
1495
+
1496
+ /** Cron: FAQ distillation into the kennisbank (off until started per mailbox), one run at a time, apart from the others. */
1497
+ export async function runHelpdeskDistill(): Promise<HelpdeskSyncOutcome> {
1498
+ const deps = await getHelpdeskDeps();
1499
+ if (!deps) return "not_connected";
1500
+ if (!(await claimDistillLease(SYNC_LEASE_MS))) return "busy";
1501
+ try {
1502
+ for (const mailbox of deps.config.connectedMailboxes) {
1503
+ const result = await runDistill(deps, mailbox);
1504
+ if (isPaused(result)) return "paused";
1505
+ if (result.status === "throttled") {
1506
+ console.warn("helpdesk distill: Microsoft asked to wait", { mailbox, retryAfter: result.retryAfter, error: result.error });
1507
+ }
1508
+ if (result.status === "ran" && result.round.error) {
1509
+ console.warn("helpdesk distill: run problem", { mailbox, error: result.round.error });
1510
+ }
1511
+ }
1512
+ return "done";
1513
+ } finally {
1514
+ await releaseDistillLease();
1515
+ }
1516
+ }
1422
1517
  ```
1423
1518
 
1424
1519
  `src/lib/helpdesk/queries.ts` (guarded reads for the pages)
@@ -1434,7 +1529,7 @@ export async function getHelpdeskSettingsForAdmin(): Promise<HelpdeskSettingsVie
1434
1529
  return readHelpdeskSettings();
1435
1530
  }
1436
1531
 
1437
- /** The mailboxes whose history import the settings page shows: the connected ones the routes serve. */
1532
+ /** The mailboxes whose history import and FAQ distillation the settings page shows: the connected ones the routes serve. */
1438
1533
  export async function getHistoryMailboxesForAdmin(): Promise<string[]> {
1439
1534
  await requirePermission("m365:manage");
1440
1535
  return (await getHelpdeskDeps())?.config.connectedMailboxes ?? [];
@@ -1589,6 +1684,21 @@ export async function GET(request: Request): Promise<Response> {
1589
1684
  }
1590
1685
  ```
1591
1686
 
1687
+ `src/app/api/cron/helpdesk-distill/route.ts`
1688
+
1689
+ ```ts
1690
+ import { runHelpdeskDistill } from "@/lib/helpdesk/service";
1691
+ import { isCronRequest } from "@/lib/m365/cron";
1692
+
1693
+ export const maxDuration = 300;
1694
+
1695
+ /** FAQ distillation of the mailboxes where it was started; idle otherwise. */
1696
+ export async function GET(request: Request): Promise<Response> {
1697
+ if (!isCronRequest(request)) return new Response("Unauthorized", { status: 401 });
1698
+ return Response.json({ outcome: await runHelpdeskDistill() });
1699
+ }
1700
+ ```
1701
+
1592
1702
  `vercel.json`:
1593
1703
 
1594
1704
  ```json
@@ -1597,6 +1707,7 @@ export async function GET(request: Request): Promise<Response> {
1597
1707
  "crons": [
1598
1708
  { "path": "/api/cron/helpdesk-sync", "schedule": "*/5 * * * *" },
1599
1709
  { "path": "/api/cron/helpdesk-history", "schedule": "2-59/5 * * * *" },
1710
+ { "path": "/api/cron/helpdesk-distill", "schedule": "41 * * * *" },
1600
1711
  { "path": "/api/cron/m365-access", "schedule": "*/10 * * * *" }
1601
1712
  ]
1602
1713
  }
@@ -1885,7 +1996,182 @@ export function MailHistorySettings({ mailboxes }: { mailboxes: string[] }) {
1885
1996
  }
1886
1997
  ```
1887
1998
 
1888
- Helpdesk settings `src/app/(app)/dashboard/helpdesk/instellingen/page.tsx` (pause and write mode, and the history import; admins only, linked from the inbox and the setup page):
1999
+ `src/components/helpdesk/mail-distill-settings.tsx` (the FAQ distillation per mailbox: it reads Sent Items and has the platform agent turn question and answer pairs into general answers in the kennisbank; the package works out the stage and the counts, the cron does the work, and nothing starts until an admin presses Starten):
2000
+
2001
+ ```tsx
2002
+ "use client";
2003
+
2004
+ import { useEffect, useState } from "react";
2005
+ import { toast } from "sonner";
2006
+ import { createHelpdeskClient, HelpdeskClientError } from "@dxv-systems/helpdesk/client";
2007
+ import type { InboxDistill } from "@dxv-systems/helpdesk/server";
2008
+ import { Button } from "@/components/ui/button";
2009
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
2010
+ import { Input } from "@/components/ui/input";
2011
+ import { Label } from "@/components/ui/label";
2012
+
2013
+ const helpdesk = createHelpdeskClient();
2014
+
2015
+ const STAGE_LABELS: Record<InboxDistill["stage"], string> = {
2016
+ not_started: "Niet gestart",
2017
+ running: "Bezig met lezen",
2018
+ waiting: "Wacht op Microsoft",
2019
+ paused: "Gepauzeerd",
2020
+ done_backfill: "Historie gelezen. Nieuwe antwoorden komen er vanzelf bij.",
2021
+ };
2022
+
2023
+ const date = (iso: string) => new Date(iso).toLocaleDateString("nl-NL", { day: "numeric", month: "long", year: "numeric" });
2024
+ const time = (iso: string) => new Date(iso).toLocaleTimeString("nl-NL", { hour: "2-digit", minute: "2-digit" });
2025
+ const count = (n: number) => n.toLocaleString("nl-NL");
2026
+
2027
+ /** yyyy-mm-dd, 3 years back: the package's default start. */
2028
+ function defaultSince(): string {
2029
+ const d = new Date();
2030
+ d.setFullYear(d.getFullYear() - 3);
2031
+ return d.toISOString().slice(0, 10);
2032
+ }
2033
+
2034
+ function errorText(error: unknown): string {
2035
+ if (error instanceof HelpdeskClientError && error.status === 403) {
2036
+ return "Je hebt zelf geen toegang tot deze mailbox. Geef jezelf toegang om dit te zien en te starten.";
2037
+ }
2038
+ if (error instanceof HelpdeskClientError && error.status === 400) return "Kies een startdatum in het verleden.";
2039
+ return error instanceof HelpdeskClientError ? error.message : "De stand kon niet worden geladen. Probeer het opnieuw.";
2040
+ }
2041
+
2042
+ function MailboxDistill({ mailbox }: { mailbox: string }) {
2043
+ const [distill, setDistill] = useState<InboxDistill | null>(null);
2044
+ const [since, setSince] = useState("");
2045
+ const [error, setError] = useState<string | null>(null);
2046
+ const [busy, setBusy] = useState(false);
2047
+
2048
+ useEffect(() => {
2049
+ let live = true;
2050
+ const load = () =>
2051
+ helpdesk.distill(mailbox).then(
2052
+ (d) => {
2053
+ if (!live) return;
2054
+ setDistill(d);
2055
+ setSince((current) => current || defaultSince());
2056
+ setError(null);
2057
+ },
2058
+ (e: unknown) => {
2059
+ if (live) setError(errorText(e));
2060
+ },
2061
+ );
2062
+ void load();
2063
+ // The cron works once an hour: refresh the counts while the page is open.
2064
+ const timer = window.setInterval(() => void load(), 60_000);
2065
+ return () => {
2066
+ live = false;
2067
+ window.clearInterval(timer);
2068
+ };
2069
+ }, [mailbox]);
2070
+
2071
+ async function run(action: "start" | "pause") {
2072
+ setBusy(true);
2073
+ try {
2074
+ const first = distill?.stage === "not_started";
2075
+ setDistill(
2076
+ action === "start"
2077
+ ? await helpdesk.startDistill(mailbox, first ? { since } : {})
2078
+ : await helpdesk.pauseDistill(mailbox),
2079
+ );
2080
+ toast.success(action === "start" ? "Het lezen loopt. De eerste antwoorden gaan binnen een uur naar de kennisbank." : "Gepauzeerd.");
2081
+ } catch (e) {
2082
+ toast.error(errorText(e));
2083
+ } finally {
2084
+ setBusy(false);
2085
+ }
2086
+ }
2087
+
2088
+ const inputId = `distill-since-${mailbox}`;
2089
+ return (
2090
+ <Card>
2091
+ <CardHeader>
2092
+ <CardTitle className="break-all">{mailbox}</CardTitle>
2093
+ <CardDescription>
2094
+ Leest de antwoorden die vanuit deze mailbox zijn verstuurd, met de vraag van de klant ervoor, ook uit Archief en
2095
+ eigen mappen. Een agent maakt daar algemene antwoorden van in de kennisbank (klantenservice/faq), zonder namen of
2096
+ persoonsgegevens. Alleen lezen: in Outlook verandert niets.
2097
+ </CardDescription>
2098
+ </CardHeader>
2099
+ <CardContent className="space-y-4 text-sm">
2100
+ {error && <p className="text-muted-foreground">{error}</p>}
2101
+ {!error && !distill && <p className="text-muted-foreground">Laden…</p>}
2102
+ {!error && distill && !distill.supported && (
2103
+ <p className="text-muted-foreground">De kennisbank vullen uit mailhistorie is voor deze mailbox niet beschikbaar.</p>
2104
+ )}
2105
+ {!error && distill?.supported && (
2106
+ <>
2107
+ <div className="space-y-1">
2108
+ <p className="font-medium">{STAGE_LABELS[distill.stage]}</p>
2109
+ {distill.retryAfter && (
2110
+ <p className="text-muted-foreground">
2111
+ Microsoft vraagt even te wachten. Het lezen gaat vanzelf verder na {time(distill.retryAfter)}.
2112
+ </p>
2113
+ )}
2114
+ {distill.since && <p className="text-muted-foreground">Vanaf {date(distill.since)}</p>}
2115
+ {distill.reachedBack && <p className="text-muted-foreground">Gelezen tot en met {date(distill.reachedBack)}</p>}
2116
+ {distill.runOpen && <p className="text-muted-foreground">De agent verwerkt nu een ronde.</p>}
2117
+ {distill.lastError && <p className="text-destructive">Laatste fout: {distill.lastError}</p>}
2118
+ </div>
2119
+ {distill.stage !== "not_started" && (
2120
+ <table className="w-full max-w-sm">
2121
+ <tbody>
2122
+ <tr className="border-t">
2123
+ <td className="py-1 pr-3">Vragen met antwoord in de kennisbank</td>
2124
+ <td className="py-1 text-right tabular-nums">{count(distill.pairsSent)}</td>
2125
+ </tr>
2126
+ <tr className="border-t">
2127
+ <td className="py-1 pr-3">Verwerkte rondes</td>
2128
+ <td className="py-1 text-right tabular-nums">{count(distill.runsSent)}</td>
2129
+ </tr>
2130
+ <tr className="border-t">
2131
+ <td className="py-1 pr-3">Klaar voor de volgende ronde</td>
2132
+ <td className="py-1 text-right tabular-nums">{count(distill.pendingPairs)}</td>
2133
+ </tr>
2134
+ </tbody>
2135
+ </table>
2136
+ )}
2137
+ {distill.stage === "not_started" && (
2138
+ <div className="max-w-xs space-y-2">
2139
+ <Label htmlFor={inputId}>Startdatum</Label>
2140
+ <Input id={inputId} type="date" value={since} onChange={(e) => setSince(e.target.value)} />
2141
+ </div>
2142
+ )}
2143
+ {(distill.stage === "not_started" || distill.stage === "paused") && (
2144
+ <Button size="sm" disabled={busy || (distill.stage === "not_started" && !since)} onClick={() => void run("start")}>
2145
+ {distill.stage === "paused" ? "Hervatten" : "Starten"}
2146
+ </Button>
2147
+ )}
2148
+ {(distill.stage === "running" || distill.stage === "waiting" || distill.stage === "done_backfill") && (
2149
+ <Button size="sm" variant="outline" disabled={busy} onClick={() => void run("pause")}>
2150
+ Pauzeren
2151
+ </Button>
2152
+ )}
2153
+ </>
2154
+ )}
2155
+ </CardContent>
2156
+ </Card>
2157
+ );
2158
+ }
2159
+
2160
+ /** One card per connected mailbox; nothing when there is none. */
2161
+ export function MailDistillSettings({ mailboxes }: { mailboxes: string[] }) {
2162
+ if (mailboxes.length === 0) return null;
2163
+ return (
2164
+ <section className="space-y-4">
2165
+ <h2 className="text-lg font-semibold">Kennisbank vullen uit mailhistorie</h2>
2166
+ {mailboxes.map((mailbox) => (
2167
+ <MailboxDistill key={mailbox} mailbox={mailbox} />
2168
+ ))}
2169
+ </section>
2170
+ );
2171
+ }
2172
+ ```
2173
+
2174
+ Helpdesk settings `src/app/(app)/dashboard/helpdesk/instellingen/page.tsx` (pause and write mode, the history import and the FAQ distillation; admins only, linked from the inbox and the setup page):
1889
2175
 
1890
2176
  ```tsx
1891
2177
  import type { Metadata } from "next";
@@ -1894,6 +2180,7 @@ import { requirePermission } from "@/lib/auth/dal";
1894
2180
  import { getHelpdeskSettingsForAdmin, getHistoryMailboxesForAdmin } from "@/lib/helpdesk/queries";
1895
2181
  import { PageHeader } from "@/components/app/page-header";
1896
2182
  import { HelpdeskSettingsForm } from "@/components/helpdesk/helpdesk-settings-form";
2183
+ import { MailDistillSettings } from "@/components/helpdesk/mail-distill-settings";
1897
2184
  import { MailHistorySettings } from "@/components/helpdesk/mail-history-settings";
1898
2185
 
1899
2186
  export const metadata: Metadata = { title: "Helpdesk-instellingen" };
@@ -1906,6 +2193,7 @@ export default async function HelpdeskSettingsPage() {
1906
2193
  <PageHeader title="Helpdesk-instellingen" />
1907
2194
  <HelpdeskSettingsForm paused={settings.paused} />
1908
2195
  <MailHistorySettings mailboxes={historyMailboxes} />
2196
+ <MailDistillSettings mailboxes={historyMailboxes} />
1909
2197
  </div>
1910
2198
  );
1911
2199
  }
@@ -2226,6 +2514,30 @@ describe("helpdesk store on Postgres", () => {
2226
2514
  expect(await helpdeskStore.getSyncState(MAILBOX)).toEqual(sync);
2227
2515
  });
2228
2516
 
2517
+ it("keeps the distill state as one value per mailbox", async () => {
2518
+ const at = "2026-11-01T00:00:00.000Z";
2519
+ const distill = {
2520
+ since: "2023-11-01T00:00:00.000Z",
2521
+ startedAt: at,
2522
+ pausedAt: null,
2523
+ retryAfter: null,
2524
+ lastError: null,
2525
+ lastRunAt: null,
2526
+ backfill: { link: null, oldest: null, doneAt: null },
2527
+ forward: { after: { at, ids: [] }, link: null, reached: null, top: null },
2528
+ pending: [{ kind: "reply" as const, channel: "email" as const, question: "Vraag", answer: "Antwoord", answeredAt: "2026-10-01" }],
2529
+ unfiredBatch: null,
2530
+ openRun: null,
2531
+ lastFiredAt: null,
2532
+ firedToday: { day: "2026-11-01", runs: 0 },
2533
+ totals: { runs: 0, pairs: 0 },
2534
+ };
2535
+ expect(await helpdeskStore.getDistillState!(MAILBOX)).toBeNull();
2536
+ await helpdeskStore.saveDistillState!(MAILBOX, distill);
2537
+ await helpdeskStore.saveDistillState!(MAILBOX, { ...distill, pausedAt: at });
2538
+ expect(await helpdeskStore.getDistillState!(MAILBOX)).toEqual({ ...distill, pausedAt: at });
2539
+ });
2540
+
2229
2541
  it("lists conversations by folder with unread, preview and search, and counts unread", async () => {
2230
2542
  mailbox.deliver({ id: "m9", from: "trap@example.test", fromName: "Trap & Co", subject: "Leuning 50%", conversationId: "c9", receivedDateTime: soon(9_000), bodyText: "Graag een offerte" });
2231
2543
  await syncMailbox(deps, MAILBOX);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxv-systems/mail-graph",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "description": "Microsoft Graph mail for DXV apps — app-only auth via a caller-supplied client assertion (federated or certificate), per-mailbox delta sync, messages, attachments, threaded replies, folders, forward and send. Never deletes. Guided Microsoft 365 setup (route handlers and a React page) under ./setup. Zero runtime dependencies.",
5
5
  "keywords": [
6
6
  "dxv",