@dxv-systems/mail-graph 0.6.2 → 0.7.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
@@ -118,7 +118,7 @@ await support.sendMail({ to, subject, body: { contentType: "html", content }, at
118
118
 
119
119
  `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.
120
120
 
121
- Message summaries (delta, folder pages, `getMessage`) carry `bodyPreview`: Graph's first 255 characters of the body as plain text.
121
+ Message summaries (delta, folder pages, `getMessage`) carry `bodyPreview`: Graph's first 255 characters of the body as plain text. `getMessage` and `listFolderMessages` also carry `lastVerb` (0.7): `{ verb: "reply" | "replyAll" | "forward", at }` when the message was replied to or forwarded, in Outlook or through `createReply`/`createForward` and `sendDraft` (Exchange records it on the original), else null. It is read with `$expand=singleValueExtendedProperties` (PidTagLastVerbExecuted and its time), which needs no permission beyond reading mail. Graph answers 400 to that expand on `messages/delta`, so delta items never carry it: a reply or forward does make the original show up in delta as changed, and `getLastVerbs(ids)` reads the verb of such messages (one GET each; an id that no longer exists is left out).
122
122
 
123
123
  "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`.
124
124
 
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, CreateForwardOptions, DraftOverrides, ConversationMessage, ListConversationOptions, WellKnownFolder, WellKnownFolderIds, } from "./types";
9
+ export type { AccessCheckResult, AccessStatus, AttachmentInfo, AttachmentKind, BodyType, CreateReplyOptions, DeltaItem, DeltaOptions, DeltaPage, FolderMessagesOptions, FolderMessagesPage, ForwardInput, GetMessageOptions, InternetMessageHeader, LastVerb, MailAddress, MailFolder, Message, MessageBody, MessageSummary, OutgoingAttachment, Recipient, SendMailInput, CreateDraftInput, CreateForwardOptions, DraftOverrides, ConversationMessage, ListConversationOptions, WellKnownFolder, WellKnownFolderIds, } from "./types";
package/dist/mailbox.d.ts CHANGED
@@ -1,6 +1,11 @@
1
1
  import type { Http } from "./http";
2
- import type { AccessCheckResult, AttachmentInfo, CreateForwardOptions, CreateReplyOptions, DeltaOptions, DeltaPage, FolderMessagesOptions, FolderMessagesPage, ForwardInput, GetMessageOptions, MailFolder, Message, MessageBody, OutgoingAttachment, SendMailInput, CreateDraftInput, ConversationMessage, ListConversationOptions, WellKnownFolderIds } from "./types";
2
+ import type { AccessCheckResult, AttachmentInfo, CreateForwardOptions, CreateReplyOptions, DeltaOptions, DeltaPage, FolderMessagesOptions, FolderMessagesPage, ForwardInput, GetMessageOptions, LastVerb, MailFolder, Message, MessageBody, OutgoingAttachment, SendMailInput, CreateDraftInput, ConversationMessage, ListConversationOptions, WellKnownFolderIds } from "./types";
3
3
  export declare const LARGE_ATTACHMENT_THRESHOLD: number;
4
+ interface RawExtendedProperty {
5
+ id?: string;
6
+ value?: string;
7
+ }
8
+ export declare function parseLastVerb(props: RawExtendedProperty[] | undefined): LastVerb | null;
4
9
  export interface MailboxClient {
5
10
  readonly address: string;
6
11
  checkAccess(): Promise<{
@@ -8,6 +13,7 @@ export interface MailboxClient {
8
13
  }>;
9
14
  delta(options: DeltaOptions): Promise<DeltaPage>;
10
15
  getMessage(id: string, options?: GetMessageOptions): Promise<Message | null>;
16
+ getLastVerbs(ids: string[]): Promise<Map<string, LastVerb | null>>;
11
17
  listAttachments(messageId: string): Promise<AttachmentInfo[]>;
12
18
  downloadAttachment(messageId: string, attachmentId: string): Promise<Uint8Array>;
13
19
  createReply(messageId: string, options?: CreateReplyOptions): Promise<Message>;
@@ -45,3 +51,4 @@ export interface InboxRuleInfo {
45
51
  forwards: boolean;
46
52
  }
47
53
  export declare function createMailboxClient(http: Http, address: string): MailboxClient;
54
+ export {};
package/dist/mailbox.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.LARGE_ATTACHMENT_THRESHOLD = void 0;
4
+ exports.parseLastVerb = parseLastVerb;
4
5
  exports.createMailboxClient = createMailboxClient;
5
6
  const errors_1 = require("./errors");
6
7
  exports.LARGE_ATTACHMENT_THRESHOLD = 3 * 1024 * 1024;
@@ -10,6 +11,14 @@ const MAX_PAGES = 100;
10
11
  const SUMMARY_SELECT = "id,subject,from,receivedDateTime,internetMessageId,conversationId,hasAttachments,isRead,isDraft,parentFolderId,categories,bodyPreview";
11
12
  const WELL_KNOWN_FOLDERS = ["inbox", "archive", "deleteditems", "sentitems", "drafts", "junkemail"];
12
13
  const FOLDER_SELECT = "id,displayName,parentFolderId,childFolderCount";
14
+ const LAST_VERB_ID = "Integer 0x1081";
15
+ const LAST_VERB_TIME_ID = "SystemTime 0x1082";
16
+ const LAST_VERB_EXPAND = `singleValueExtendedProperties($filter=id eq '${LAST_VERB_ID}' or id eq '${LAST_VERB_TIME_ID}')`;
17
+ const LAST_VERBS = new Map([
18
+ ["102", "reply"],
19
+ ["103", "replyAll"],
20
+ ["104", "forward"],
21
+ ]);
13
22
  function toAddress(raw) {
14
23
  const address = raw?.emailAddress?.address;
15
24
  if (!address)
@@ -19,6 +28,14 @@ function toAddress(raw) {
19
28
  function toAddresses(raw) {
20
29
  return (raw ?? []).map(toAddress).filter((a) => a !== undefined);
21
30
  }
31
+ function parseLastVerb(props) {
32
+ const value = (id) => props?.find((p) => p.id?.toLowerCase() === id.toLowerCase())?.value;
33
+ const verb = LAST_VERBS.get(String(value(LAST_VERB_ID) ?? "").trim());
34
+ if (!verb)
35
+ return null;
36
+ const time = Date.parse(value(LAST_VERB_TIME_ID) ?? "");
37
+ return { verb, at: Number.isNaN(time) ? null : new Date(time).toISOString() };
38
+ }
22
39
  function toSummary(raw) {
23
40
  const summary = { id: raw.id };
24
41
  if (raw.subject !== undefined)
@@ -46,6 +63,9 @@ function toSummary(raw) {
46
63
  summary.bodyPreview = raw.bodyPreview;
47
64
  return summary;
48
65
  }
66
+ function withLastVerb(summary, raw) {
67
+ return { ...summary, lastVerb: parseLastVerb(raw.singleValueExtendedProperties) };
68
+ }
49
69
  function toMessage(raw, includeHeaders) {
50
70
  const contentType = raw.body?.contentType?.toLowerCase() === "text" ? "text" : "html";
51
71
  const message = {
@@ -288,10 +308,10 @@ function createMailboxClient(http, address) {
288
308
  const bodyType = options.bodyType ?? "html";
289
309
  const select = `${SUMMARY_SELECT},body,sentDateTime,toRecipients,ccRecipients,replyTo${options.includeHeaders ? ",internetMessageHeaders" : ""}`;
290
310
  try {
291
- const raw = await getJson(`${user}/messages/${requireId(id, "message id")}${query({ $select: select })}`, [
311
+ const raw = await getJson(`${user}/messages/${requireId(id, "message id")}${query({ $select: select, $expand: LAST_VERB_EXPAND })}`, [
292
312
  `outlook.body-content-type="${bodyType}"`,
293
313
  ]);
294
- return toMessage(raw, options.includeHeaders === true);
314
+ return withLastVerb(toMessage(raw, options.includeHeaders === true), raw);
295
315
  }
296
316
  catch (error) {
297
317
  if (error instanceof errors_1.GraphError && error.status === 404)
@@ -299,6 +319,21 @@ function createMailboxClient(http, address) {
299
319
  throw error;
300
320
  }
301
321
  },
322
+ async getLastVerbs(ids) {
323
+ const verbs = new Map();
324
+ for (const id of new Set(ids)) {
325
+ try {
326
+ const raw = await getJson(`${user}/messages/${requireId(id, "message id")}${query({ $select: "id", $expand: LAST_VERB_EXPAND })}`);
327
+ verbs.set(id, parseLastVerb(raw.singleValueExtendedProperties));
328
+ }
329
+ catch (error) {
330
+ if (error instanceof errors_1.GraphError && error.status === 404)
331
+ continue;
332
+ throw error;
333
+ }
334
+ }
335
+ return verbs;
336
+ },
302
337
  async listAttachments(messageId) {
303
338
  const raw = await collect(`${user}/messages/${requireId(messageId, "message id")}/attachments${query({
304
339
  $select: "id,name,contentType,size,isInline,microsoft.graph.fileAttachment/contentId",
@@ -431,11 +466,12 @@ function createMailboxClient(http, address) {
431
466
  path: `${user}/mailFolders/${requireId(folderId, "folder id")}/messages${query({
432
467
  $select: SUMMARY_SELECT,
433
468
  $orderby: "receivedDateTime desc",
469
+ $expand: LAST_VERB_EXPAND,
434
470
  $top: Math.min(100, Math.max(1, Math.floor(options.pageSize ?? 50))),
435
471
  })}`,
436
472
  });
437
473
  const page = (result.data ?? {});
438
- return { items: (page.value ?? []).map(toSummary), nextLink: page["@odata.nextLink"] ?? null };
474
+ return { items: (page.value ?? []).map((m) => withLastVerb(toSummary(m), m)), nextLink: page["@odata.nextLink"] ?? null };
439
475
  },
440
476
  async getInboxFolderId() {
441
477
  const folder = await getJson(`${user}/mailFolders/inbox${query({ $select: "id" })}`);
package/dist/types.d.ts CHANGED
@@ -8,6 +8,10 @@ export interface MessageBody {
8
8
  contentType: BodyType;
9
9
  content: string;
10
10
  }
11
+ export interface LastVerb {
12
+ verb: "reply" | "replyAll" | "forward";
13
+ at: string | null;
14
+ }
11
15
  export interface MessageSummary {
12
16
  id: string;
13
17
  subject?: string;
@@ -21,6 +25,7 @@ export interface MessageSummary {
21
25
  parentFolderId?: string;
22
26
  categories?: string[];
23
27
  bodyPreview?: string;
28
+ lastVerb?: LastVerb | null;
24
29
  }
25
30
  export interface DeltaItem extends MessageSummary {
26
31
  removed: boolean;
@@ -1,6 +1,6 @@
1
1
  # Microsoft 365 helpdesk: app integration recipe
2
2
 
3
- For a coding agent adding the Microsoft 365 helpdesk to an app built on `company-app-template`. Apply it exactly. All logic lives in `@dxv-systems/mail-graph` (Graph client, guided setup) and `@dxv-systems/helpdesk` (tickets, drafting, sending, staff inbox); the app adds a thin, fixed layer: tables, adapters, two catch-all routes, three pages, two crons. Read the package READMEs ("Guided Microsoft 365 setup", "Pilot controls", "Inbox UI") once; this recipe does not repeat them.
3
+ For a coding agent adding the Microsoft 365 helpdesk to an app built on `company-app-template`. Apply it exactly. All logic lives in `@dxv-systems/mail-graph` (Graph client, guided setup) and `@dxv-systems/helpdesk` (tickets, drafting, sending, staff inbox); the app adds a thin, fixed layer: tables, adapters, two catch-all routes, three pages, the crons. Read the package READMEs ("Guided Microsoft 365 setup", "Pilot controls", "Inbox UI") once; this recipe does not repeat them.
4
4
 
5
5
  This recipe ships inside the package: after step 1 it is at `node_modules/@dxv-systems/mail-graph/docs/app-integration.md` (from 0.1.2 on), so an agent working in the app's repository can read it without access to dxv-packages.
6
6
 
@@ -11,20 +11,20 @@ The code below was compiled, linted, knip-checked, built and tested against a fr
11
11
  - **Production only.** Microsoft 365 is off unless `VERCEL_ENV=production` and `M365_CLIENT_ID` and `APP_URL` are set (`readM365Env()`). While off, every page renders a "not enabled" card and the routes answer `503 not_configured`; nothing crashes and no Graph call is made. Previews and staging never reach a client tenant.
12
12
  - **Admin only for setup:** permission `m365:manage` (admins). **Staff only for the inbox:** permission `helpdesk:use` (managers and admins). Code checks permissions, never roles.
13
13
  - **The helpdesk runs only while the connection is `connected`** (`getHelpdeskDeps()` returns null otherwise). The scope is exactly the connected mailboxes.
14
- - **One way of working:** a person approves each reply in the helpdesk, and the helpdesk then sends it from the mailbox (`writeMode: "approve_and_send"`). Nothing reaches Outlook before that approval. The only switch is `paused` (kill switch, default off) in `helpdesk_settings`, edited on the admin page; it applies on the next call, no redeploy.
14
+ - **One way of working:** a person approves each reply in the helpdesk, and the helpdesk then sends it from the mailbox (`writeMode: "approve_and_send"`). Nothing reaches Outlook before that approval. The switches are `paused` (kill switch, default off) and `draft_mode` (when the AI writes a reply proposal: `on_request`, the default, or `auto`) in `helpdesk_settings`, edited on the admin page; they apply on the next call, no redeploy.
15
15
  - Never call Graph or the helpdesk functions anywhere else than the files below. UI never imports `@/lib/db` (ESLint).
16
16
 
17
17
  ## 1. Install
18
18
 
19
19
  ```bash
20
- npm install --save-exact @dxv-systems/mail-graph@0.6.2 @dxv-systems/helpdesk@0.15.0 @vercel/oidc@4.0.1
20
+ npm install --save-exact @dxv-systems/mail-graph@0.7.1 @dxv-systems/helpdesk@0.17.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.
24
24
 
25
25
  `@vercel/oidc` is already in the lockfile through `@dxv-systems/ai`; pin the same version so it is not duplicated.
26
26
 
27
- The FAQ distiller in `deps.ts` starts runs by gateway feature, which needs `@dxv-systems/ai` 0.3 or later. The company app template still ships `^0.2`, so raise it: `npm install @dxv-systems/ai@^0.3.2`. Its 0.3.0 dropped the agent UUID from `createRuns().fireRun`; an app that calls it elsewhere passes the feature to `createRuns` instead.
27
+ The FAQ distiller and the drafter in `deps.ts` start runs by gateway feature, which needs `@dxv-systems/ai` 0.3 or later. The company app template still ships `^0.2`, so raise it: `npm install @dxv-systems/ai@^0.3.2`. Its 0.3.0 dropped the agent UUID from `createRuns().fireRun`; an app that calls it elsewhere passes the feature to `createRuns` instead.
28
28
 
29
29
  ## 2. Environment
30
30
 
@@ -79,8 +79,10 @@ Extend the `drizzle-orm/pg-core` import with `boolean, doublePrecision, primaryK
79
79
  import type { M365Connection } from "@dxv-systems/mail-graph/setup";
80
80
  import type {
81
81
  DistillState,
82
+ DraftMode,
82
83
  DraftRunStatus,
83
84
  HistoryState,
85
+ LastVerb,
84
86
  MailAddress,
85
87
  MessageDirection,
86
88
  MessageLocation,
@@ -114,6 +116,8 @@ export const helpdeskSettings = pgTable(
114
116
  id: integer("id").primaryKey().default(1),
115
117
  /** Kill switch: no sync, drafting, sending or Graph call at all. */
116
118
  paused: boolean("paused").notNull().default(false),
119
+ /** When the AI writes a reply proposal: only when staff ask (`on_request`) or for every new mail (`auto`). */
120
+ draftMode: varchar("draft_mode", { length: 20 }).$type<DraftMode>().notNull().default("on_request"),
117
121
  /** Lease of the sync cron: a run starts only when this is null or past. */
118
122
  syncLeaseUntil: timestamp("sync_lease_until", { withTimezone: true }),
119
123
  /** Lease of the history cron, apart from the sync's, so neither waits for the other. */
@@ -217,6 +221,8 @@ export const helpdeskMessages = pgTable(
217
221
  /** To and Cc (helpdesk 0.15); null when unknown. */
218
222
  toRecipients: jsonb("to_recipients").$type<MailAddress[]>(),
219
223
  ccRecipients: jsonb("cc_recipients").$type<MailAddress[]>(),
224
+ /** Last reply or forward, in the app or in Outlook (helpdesk 0.16); null when never or unknown. */
225
+ lastVerb: jsonb("last_verb").$type<LastVerb>(),
220
226
  },
221
227
  (table) => [
222
228
  primaryKey({ columns: [table.mailbox, table.id] }),
@@ -302,7 +308,7 @@ export const helpdeskReplyAttachments = pgTable(
302
308
  );
303
309
  ```
304
310
 
305
- 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). An app on helpdesk 0.14 upgrades with one generated migration: `to_recipients` and `cc_recipients` (jsonb, nullable) on `helpdesk_messages`, and two lines in `toMessage` (see the helpdesk README, Upgrading from 0.14.0).
311
+ 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). An app on helpdesk 0.14 upgrades with one generated migration: `to_recipients` and `cc_recipients` (jsonb, nullable) on `helpdesk_messages`, and two lines in `toMessage` (see the helpdesk README, Upgrading from 0.14.0). An app on helpdesk 0.15 upgrades with one generated migration: `last_verb` (jsonb, nullable) on `helpdesk_messages`, and one line in `toMessage` (see the helpdesk README, Upgrading from 0.15.0). An app on helpdesk 0.16 upgrades with one generated migration: `draft_mode` (varchar, not null, default `on_request`) on `helpdesk_settings`, nothing dropped; then add the draft mode to `settings.ts`, the actions, the settings form and page, the drafter in `deps.ts`, and `collectDrafts` in the sync cron below (see the helpdesk README, Upgrading from 0.16.0). The store, the crons and `vercel.json` do not change.
306
312
 
307
313
  ## 5. `src/lib/m365/` (Graph sign-in and the guided setup)
308
314
 
@@ -546,6 +552,7 @@ export function toMessage(row: MessageRow): StoredMessage {
546
552
  location: row.location,
547
553
  toRecipients: row.toRecipients,
548
554
  ccRecipients: row.ccRecipients,
555
+ lastVerb: row.lastVerb,
549
556
  };
550
557
  }
551
558
 
@@ -1106,20 +1113,22 @@ export const helpdeskInbox: HelpdeskInboxQueries = {
1106
1113
  ```ts
1107
1114
  import "server-only";
1108
1115
  import { and, eq, isNull, lt, or } from "drizzle-orm";
1109
- import type { HelpdeskControls } from "@dxv-systems/helpdesk";
1116
+ import type { DraftMode, HelpdeskControls } from "@dxv-systems/helpdesk";
1110
1117
  import { db } from "@/lib/db";
1111
1118
  import { helpdeskSettings } from "@/lib/db/schema";
1112
1119
 
1113
1120
  export interface HelpdeskSettingsView {
1114
1121
  paused: boolean;
1122
+ draftMode: DraftMode;
1115
1123
  }
1116
1124
 
1117
- const DEFAULTS: HelpdeskSettingsView = { paused: false };
1125
+ // A new app starts on request: the AI writes a proposal only when staff press "Voorstel schrijven".
1126
+ const DEFAULTS: HelpdeskSettingsView = { paused: false, draftMode: "on_request" };
1118
1127
 
1119
1128
  /** The switches as stored (no row: the defaults). Not user-scoped. */
1120
1129
  export async function readHelpdeskSettings(): Promise<HelpdeskSettingsView> {
1121
1130
  const [row] = await db
1122
- .select({ paused: helpdeskSettings.paused })
1131
+ .select({ paused: helpdeskSettings.paused, draftMode: helpdeskSettings.draftMode })
1123
1132
  .from(helpdeskSettings)
1124
1133
  .where(eq(helpdeskSettings.id, 1))
1125
1134
  .limit(1);
@@ -1128,11 +1137,11 @@ export async function readHelpdeskSettings(): Promise<HelpdeskSettingsView> {
1128
1137
 
1129
1138
  /**
1130
1139
  * `HelpdeskDeps.controls`: called at the start of every helpdesk call. One way of working: a
1131
- * person approves each reply in the helpdesk, which then sends it. Pause is the only switch.
1140
+ * person approves each reply in the helpdesk, which then sends it. Switches: pause, draft mode.
1132
1141
  */
1133
1142
  export async function loadHelpdeskControls(): Promise<HelpdeskControls> {
1134
- const { paused } = await readHelpdeskSettings();
1135
- return { paused, writeMode: "approve_and_send" };
1143
+ const { paused, draftMode } = await readHelpdeskSettings();
1144
+ return { paused, writeMode: "approve_and_send", draftMode };
1136
1145
  }
1137
1146
 
1138
1147
  export async function saveHelpdeskSettings(settings: HelpdeskSettingsView, userId: number): Promise<void> {
@@ -1207,16 +1216,18 @@ export async function releaseDistillLease(): Promise<void> {
1207
1216
  }
1208
1217
  ```
1209
1218
 
1210
- **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.
1219
+ **The drafter.** The AI reply proposal is a run of the platform agent `helpdesk-drafter`, started through the gateway feature `helpdesk.draft` (`createRuns` from the template's `@/lib/ai`). The platform never calls the app, so the sync cron below polls the runs with `collectDrafts` for each mailbox right after its sync (every 5 minutes); a finished run puts its text in "Jouw antwoord" and the ticket in review. DXV creates `helpdesk-drafter` in the client's tenant and links it to `helpdesk.draft` in the Portal, as it does `klantenservice-faq` for `helpdesk.faq-distill`. The agent reads the client's FAQ in `klantenservice/faq/` itself through its docstore tools; the run input is only the conversation (helpdesk README, Drafting). Until the feature is linked, a run start fails and the ticket shows "Het voorstel kon niet worden gemaakt" with an empty box; staff write the reply themselves, as without a drafter.
1220
+
1221
+ **On request by default.** A new app stores `draft_mode = on_request`: every new customer mail opens its ticket in review (`reviewReason: "no_draft"`, label "Zelf antwoorden") with an empty "Jouw antwoord" box and the button "Voorstel schrijven" (the package's inbox shows it). Pressing it starts one run; the text arrives with the first sync after the run finishes, within about 5 minutes ("Er wordt een voorstel geschreven…" until then). Staff can also write the reply themselves: 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`). The admin switches to `auto` (a proposal for every new mail) on the settings page; it applies from the next sync on.
1211
1222
 
1212
1223
  `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.
1213
1224
 
1214
- 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.
1225
+ The drafter starts and reads runs of `helpdesk.draft` (see The drafter above). 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.
1215
1226
 
1216
1227
  ```ts
1217
1228
  import "server-only";
1218
1229
  import { inArray } from "drizzle-orm";
1219
- import type { Distiller, HelpdeskDeps, Notifier } from "@dxv-systems/helpdesk";
1230
+ import type { Distiller, Drafter, HelpdeskDeps, Notifier } from "@dxv-systems/helpdesk";
1220
1231
  import { activeScope } from "@dxv-systems/mail-graph/setup";
1221
1232
  import { createRuns } from "@/lib/ai";
1222
1233
  import { rolesWithPermission } from "@/lib/auth/permissions";
@@ -1293,6 +1304,18 @@ const distiller: Distiller = {
1293
1304
  },
1294
1305
  };
1295
1306
 
1307
+ /** Reply proposals (agent `helpdesk-drafter`). The package builds the input and the event key; the sync cron reads. */
1308
+ const drafter: Drafter = {
1309
+ async start(request) {
1310
+ const { id } = await createRuns({ feature: "helpdesk.draft" }).fireRun({ ...request.input }, { eventKey: request.eventKey });
1311
+ return { runId: String(id) };
1312
+ },
1313
+ async read(runId) {
1314
+ const run = await createRuns({ feature: "helpdesk.draft" }).getRun(runId);
1315
+ return { status: run.status, result: run.result, ...(run.error ? { error: run.error } : {}) };
1316
+ },
1317
+ };
1318
+
1296
1319
  /** The app's own sender (EMAIL_FROM): its mail is never a ticket. */
1297
1320
  function ownAddresses(): string[] {
1298
1321
  const from = process.env.EMAIL_FROM?.trim();
@@ -1317,6 +1340,7 @@ export async function getHelpdeskDeps(): Promise<HelpdeskDeps | null> {
1317
1340
  notifier,
1318
1341
  attachments: helpdeskReplyFiles,
1319
1342
  distiller,
1343
+ drafter,
1320
1344
  };
1321
1345
  }
1322
1346
  ```
@@ -1397,11 +1421,12 @@ export const helpdeskReplyFiles: ReplyAttachmentsDeps = {
1397
1421
 
1398
1422
  A `FileServiceError` from `createUploadTarget` or `completeUpload` (too large for `FILE_MAX_SIZE_MB`, a file that was not uploaded) reaches the inbox route as an unexpected error (500, "Er ging iets mis"); the package's own limits (20 MB together, 10 files) are checked first and give a clear message. `deleteFile` removes the `files` row only; the object stays in the bucket under the template's retention model.
1399
1423
 
1400
- `src/lib/helpdesk/service.ts`: setup hooks and the sync cron (one run at a time; per mailbox: `connectMailbox` (idempotent), `syncMailbox`, `sweepStuckDrafts`).
1424
+ `src/lib/helpdesk/service.ts`: setup hooks and the crons (each one run at a time; the sync per mailbox: `connectMailbox` (idempotent), `syncMailbox`, `collectDrafts`, `sweepStuckDrafts`).
1401
1425
 
1402
1426
  ```ts
1403
1427
  import "server-only";
1404
1428
  import {
1429
+ collectDrafts,
1405
1430
  connectMailbox,
1406
1431
  isPaused,
1407
1432
  isSyncFailing,
@@ -1451,7 +1476,7 @@ export async function onHelpdeskReset(adminId: number | null): Promise<void> {
1451
1476
 
1452
1477
  export type HelpdeskSyncOutcome = "not_connected" | "busy" | "paused" | "done";
1453
1478
 
1454
- /** Cron: one run at a time (lease). Per mailbox: sync, then fail draft runs that never reported. */
1479
+ /** Cron: one run at a time (lease). Per mailbox: sync, bring in finished reply proposals, fail draft runs that never reported. */
1455
1480
  export async function runHelpdeskSync(): Promise<HelpdeskSyncOutcome> {
1456
1481
  const deps = await getHelpdeskDeps();
1457
1482
  if (!deps) return "not_connected";
@@ -1462,6 +1487,13 @@ export async function runHelpdeskSync(): Promise<HelpdeskSyncOutcome> {
1462
1487
  // connectMailbox is idempotent; it covers a mailbox added after onConnected.
1463
1488
  await connectMailbox(deps, mailbox);
1464
1489
  const result = await syncMailbox(deps, mailbox);
1490
+ // The platform never calls the app: poll the reply-proposal runs. A failure here never stops the other mailboxes.
1491
+ try {
1492
+ const drafts = await collectDrafts(deps, mailbox);
1493
+ if (!isPaused(drafts) && drafts.lastError) console.warn("helpdesk drafts: run not readable", { mailbox, error: drafts.lastError });
1494
+ } catch (err) {
1495
+ console.error("helpdesk drafts: collecting failed", { mailbox, error: err instanceof Error ? err.message : String(err) });
1496
+ }
1465
1497
  if (isPaused(result)) {
1466
1498
  paused = true;
1467
1499
  continue;
@@ -1563,14 +1595,15 @@ import { saveHelpdeskSettings } from "./settings";
1563
1595
 
1564
1596
  const settingsSchema = z.object({
1565
1597
  paused: z.enum(["on", "off"], { message: "Kies aan of uit." }),
1598
+ draftMode: z.enum(["on_request", "auto"], { message: "Kies wanneer de AI een voorstel schrijft." }),
1566
1599
  });
1567
1600
 
1568
- /** The pause switch; it applies on the next helpdesk call, no redeploy. */
1601
+ /** The pause switch and the draft mode; they apply on the next helpdesk call, no redeploy. */
1569
1602
  export async function updateHelpdeskSettings(_prev: FormState, formData: FormData): Promise<FormState> {
1570
1603
  const user = await requirePermission("m365:manage");
1571
- const parsed = settingsSchema.safeParse({ paused: formData.get("paused") });
1604
+ const parsed = settingsSchema.safeParse({ paused: formData.get("paused"), draftMode: formData.get("draftMode") });
1572
1605
  if (!parsed.success) return { errors: parsed.error.flatten().fieldErrors };
1573
- await saveHelpdeskSettings({ paused: parsed.data.paused === "on" }, user.id);
1606
+ await saveHelpdeskSettings({ paused: parsed.data.paused === "on", draftMode: parsed.data.draftMode }, user.id);
1574
1607
  revalidatePath("/dashboard/helpdesk/instellingen");
1575
1608
  return { success: true, message: "Helpdesk-instellingen opgeslagen." };
1576
1609
  }
@@ -1750,12 +1783,13 @@ export function M365NotEnabled({ title, description }: { title: string; descript
1750
1783
 
1751
1784
  import { useActionState, useEffect } from "react";
1752
1785
  import { toast } from "sonner";
1786
+ import type { DraftMode } from "@dxv-systems/helpdesk";
1753
1787
  import { updateHelpdeskSettings } from "@/lib/helpdesk/actions";
1754
1788
  import type { FormState } from "@/lib/forms";
1755
1789
  import { SubmitButton } from "@/components/submit-button";
1756
1790
  import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
1757
1791
 
1758
- export function HelpdeskSettingsForm({ paused }: { paused: boolean }) {
1792
+ export function HelpdeskSettingsForm({ paused, draftMode }: { paused: boolean; draftMode: DraftMode }) {
1759
1793
  const [state, formAction] = useActionState<FormState, FormData>(updateHelpdeskSettings, {});
1760
1794
 
1761
1795
  useEffect(() => {
@@ -1783,6 +1817,15 @@ export function HelpdeskSettingsForm({ paused }: { paused: boolean }) {
1783
1817
  </label>
1784
1818
  ))}
1785
1819
  </fieldset>
1820
+ <fieldset className="space-y-2">
1821
+ <legend className="text-sm font-semibold">Voorstel van de AI</legend>
1822
+ {(["on_request", "auto"] as const).map((value) => (
1823
+ <label key={value} className="flex min-h-11 items-center gap-3">
1824
+ <input type="radio" name="draftMode" value={value} defaultChecked={draftMode === value} className="size-4 accent-primary" />
1825
+ {value === "on_request" ? "Op verzoek, met de knop “Voorstel schrijven”" : "Automatisch bij elke nieuwe mail"}
1826
+ </label>
1827
+ ))}
1828
+ </fieldset>
1786
1829
  </CardContent>
1787
1830
  <CardFooter className="justify-end">
1788
1831
  <SubmitButton pendingText="Opslaan…">Opslaan</SubmitButton>
@@ -2199,7 +2242,7 @@ export default async function HelpdeskSettingsPage() {
2199
2242
  return (
2200
2243
  <div className="space-y-6">
2201
2244
  <PageHeader title="Helpdesk-instellingen" />
2202
- <HelpdeskSettingsForm paused={settings.paused} />
2245
+ <HelpdeskSettingsForm paused={settings.paused} draftMode={settings.draftMode} />
2203
2246
  <MailHistorySettings mailboxes={historyMailboxes} />
2204
2247
  <MailDistillSettings mailboxes={historyMailboxes} />
2205
2248
  </div>
@@ -2571,4 +2614,5 @@ describe("helpdesk store on Postgres", () => {
2571
2614
  3. Production, manual flow (test tenant): Beheer → Microsoft 365 → enter mailbox(es) and a check mailbox → "Koppelen met Microsoft" (a Global Administrator signs in and consents for the organisation) → back on the page the setup is already at the access check, with no script; wait for "Gekoppeld" (up to ~2 h; the 10-minute cron keeps checking with the page closed). Also try "Liever met een PowerShell-script" once: consent, Object ID filled, run the downloaded script, "Script is uitgevoerd". Also open the IT link in a private window: it works without an account and the response has `Referrer-Policy: no-referrer`.
2572
2615
  4. Send a mail to the connected mailbox. Within 5 minutes it appears under Helpdesk as "Te beoordelen" ("Zelf antwoorden") with an empty "Jouw antwoord" box and a notification. Type a reply, "Goedkeuren en versturen" → the reply is in the mailbox's Sent Items, threaded under the customer's mail with the quote kept.
2573
2616
  5. Pause on the admin page → the inbox shows the pause banner and the next cron returns `paused`. Unpause.
2574
- 6. Files on a reply (production): open a ticket, "Bijlage toevoegen" with a PDF of a few MB and one over 4.5 MB, then "Goedkeuren en versturen". The reply in Outlook's Sent Items carries both files; the ticket shows them on the sent reply in the conversation. A file above 20 MB is refused with the limit message before any upload.
2617
+ 6. Reply proposal (once DXV has linked `helpdesk-drafter` to `helpdesk.draft`): on a ticket in review press "Voorstel schrijven" → "Er wordt een voorstel geschreven…", and after the next sync cron (within about 5 minutes of the run finishing) the AI's text is in "Jouw antwoord". Nothing is sent until "Goedkeuren en versturen".
2618
+ 7. Files on a reply (production): open a ticket, "Bijlage toevoegen" with a PDF of a few MB and one over 4.5 MB, then "Goedkeuren en versturen". The reply in Outlook's Sent Items carries both files; the ticket shows them on the sent reply in the conversation. A file above 20 MB is refused with the limit message before any upload.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxv-systems/mail-graph",
3
- "version": "0.6.2",
3
+ "version": "0.7.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",