@littlebearapps/outlook-assistant 3.12.0 → 3.12.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/rules/index.js CHANGED
@@ -180,7 +180,7 @@ const rulesTools = [
180
180
  {
181
181
  name: 'manage-rules',
182
182
  description:
183
- 'Server-side inbox rule CRUD (destructive: covers `delete`; supports `dryRun` on create/update for preview). Rules run on the Exchange server regardless of which client is open. action=`list` (default) returns rules with id/name/sequence — pass `includeDetails: true` to expand conditions/actions/exceptions. action=`create` builds a new rule from condition params (12 supported: fromAddresses, containsSubject, bodyContains, hasAttachments, importance, sentTo, sensitivity, etc.), action params (9 supported: moveToFolder, forwardTo, redirectTo, assignCategories, markAsRead, delete, etc.), and optional `except*` exceptions. action=`update` patches the named fields by `ruleId`. action=`reorder` changes execution priority via `sequence` (lower = earlier). action=`delete` removes a rule. Recipient allowlist applies to forwardTo/redirectTo. `permanentDelete` action is intentionally omitted (too dangerous for AI use — use the Outlook UI). Subject to session rate limits (`OUTLOOK_MAX_MANAGE_RULES_PER_SESSION`).',
183
+ 'Server-side inbox rule CRUD (destructive: covers `delete`; supports `dryRun` on create/update for preview). Rules run on the Exchange server regardless of which client is open. action=`list` (default) returns rules with id/name/sequence — pass `includeDetails: true` to expand conditions/actions/exceptions. action=`create` builds a new rule from condition params (12 supported: fromAddresses, containsSubject, bodyContains, hasAttachments, importance, sentTo, sensitivity, etc.), action params (9 supported: moveToFolder/copyToFolder — folder name, nested path like `Triage/Delete`, or ID — forwardTo, redirectTo, assignCategories, markAsRead, delete, etc.), and optional `except*` exceptions. action=`update` patches the named fields by `ruleId`. action=`reorder` changes execution priority via `sequence` (lower = earlier). action=`delete` removes a rule. Recipient allowlist applies to forwardTo/redirectTo. `permanentDelete` action is intentionally omitted (too dangerous for AI use — use the Outlook UI). Subject to session rate limits (`OUTLOOK_MAX_MANAGE_RULES_PER_SESSION`).',
184
184
  annotations: {
185
185
  title: 'Inbox Rules',
186
186
  readOnlyHint: false,
@@ -304,12 +304,12 @@ const rulesTools = [
304
304
  moveToFolder: {
305
305
  type: 'string',
306
306
  description:
307
- 'Folder name to move matching emails to (action=create/update)',
307
+ 'Folder to move matching emails to: a name, a nested path like `Triage/Delete`, a well-known name (e.g. `archive`), or a folder ID (action=create/update)',
308
308
  },
309
309
  copyToFolder: {
310
310
  type: 'string',
311
311
  description:
312
- 'Folder name to copy matching emails to (action=create/update)',
312
+ 'Folder to copy matching emails to: a name, a nested path like `Projects/Backup`, a well-known name, or a folder ID (action=create/update)',
313
313
  },
314
314
  markAsRead: {
315
315
  type: 'boolean',
@@ -2,7 +2,7 @@
2
2
  * Shared rule builder utilities for creating and updating mail rules.
3
3
  * Converts flat MCP tool parameters into Microsoft Graph API rule objects.
4
4
  */
5
- const { getFolderIdByName } = require('../email/folder-utils');
5
+ const { resolveFolder, looksLikeFolderId } = require('../folder/resolve');
6
6
  const { checkRecipientAllowlist } = require('../utils/safety');
7
7
 
8
8
  const VALID_IMPORTANCE = ['low', 'normal', 'high'];
@@ -104,6 +104,49 @@ function buildConditions(args) {
104
104
  return { conditions, warnings };
105
105
  }
106
106
 
107
+ /**
108
+ * Resolve a rule's target folder (ID, well-known alias, nested path such as
109
+ * "Triage/Delete", or bare name) to a folder ID with the shared resolver. (#248)
110
+ * Not-found and ambiguous folders become a warning containing "not found", which
111
+ * create/update treat as fatal when no other action is left; any other failure
112
+ * (auth, network, Graph outage) is rethrown rather than misreported.
113
+ * @param {string} accessToken - Graph API access token
114
+ * @param {string} folder - Folder ID, alias, path, or name
115
+ * @param {string} label - Warning prefix, e.g. "Target folder"
116
+ * @returns {Promise<{ folderId?: string, warning?: string }>}
117
+ */
118
+ async function resolveRuleFolder(accessToken, folder, label) {
119
+ const spec = looksLikeFolderId(folder)
120
+ ? { id: folder.trim() }
121
+ : { name: folder };
122
+ try {
123
+ const resolved = await resolveFolder(accessToken, spec);
124
+ return { folderId: resolved.id };
125
+ } catch (error) {
126
+ const message = error.message || '';
127
+ if (message.includes('ambiguous')) {
128
+ return {
129
+ warning: `${label} "${folder}" not found as a single folder. ${message}`,
130
+ };
131
+ }
132
+ if (
133
+ message.includes('not found') ||
134
+ message.startsWith('Invalid folder path') ||
135
+ /status (400|404):/.test(message)
136
+ ) {
137
+ // The resolver's reason follows (an empty path segment, Graph's 400 text);
138
+ // its own not-found message already carries the action=list guidance.
139
+ const hint = message.includes('action=list')
140
+ ? ''
141
+ : ' Use `folders` action=list to see folders (with IDs and full paths), or pass a path like "Parent/Child" or a folderId.';
142
+ return {
143
+ warning: `${label} "${folder}" not found. ${message}${hint}`,
144
+ };
145
+ }
146
+ throw error;
147
+ }
148
+ }
149
+
107
150
  /**
108
151
  * Build a Graph API actions object from flat tool parameters.
109
152
  * Async because folder resolution requires API calls.
@@ -115,21 +158,23 @@ async function buildActions(args, accessToken) {
115
158
  const actions = {};
116
159
  const warnings = [];
117
160
 
118
- // Folder-based actions (name → ID resolution)
119
- if (args.moveToFolder) {
120
- const folderId = await getFolderIdByName(accessToken, args.moveToFolder);
121
- if (!folderId) {
122
- warnings.push(`Target folder "${args.moveToFolder}" not found.`);
123
- } else {
124
- actions.moveToFolder = folderId;
125
- }
126
- }
127
- if (args.copyToFolder) {
128
- const folderId = await getFolderIdByName(accessToken, args.copyToFolder);
129
- if (!folderId) {
130
- warnings.push(`Copy-to folder "${args.copyToFolder}" not found.`);
131
- } else {
132
- actions.copyToFolder = folderId;
161
+ // Folder-based actions (ID, alias, nested path or name → ID)
162
+ const folderActions = [
163
+ ['moveToFolder', 'Target folder'],
164
+ ['copyToFolder', 'Copy-to folder'],
165
+ ];
166
+ for (const [param, label] of folderActions) {
167
+ if (args[param]) {
168
+ const { folderId, warning } = await resolveRuleFolder(
169
+ accessToken,
170
+ args[param],
171
+ label
172
+ );
173
+ if (folderId) {
174
+ actions[param] = folderId;
175
+ } else {
176
+ warnings.push(warning);
177
+ }
133
178
  }
134
179
  }
135
180
 
@@ -0,0 +1,170 @@
1
+ /**
2
+ * Shared ISO 8601 date-time parsing and timezone conversion.
3
+ *
4
+ * Nothing here reads the server's local timezone: zoned values are converted
5
+ * with their own `Z`/offset, and wall-clock values are read in an explicit IANA
6
+ * zone through Intl, so results are the same on every machine.
7
+ */
8
+ const config = require('../config');
9
+
10
+ // An ISO 8601 instant with an explicit zone: `Z` or a ±hh:mm offset. A
11
+ // zone-less value would be read in the server's local timezone by Date.parse,
12
+ // so results would differ between machines; date-only values are rejected for
13
+ // the same reason.
14
+ const ISO_INSTANT =
15
+ /^(\d{4})-(\d{2})-(\d{2})T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:Z|[+-]\d{2}:\d{2})$/;
16
+
17
+ // A wall-clock date-time with no zone, e.g. 2026-03-01T09:00 or
18
+ // 2026-03-01T09:00:00.5. Callers decide which zone it is read in.
19
+ const WALL_TIME =
20
+ /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,9})?)?$/;
21
+
22
+ const MIN_YEAR = 1900;
23
+
24
+ /**
25
+ * Error raised for a date-time argument that can't be read, so handlers can
26
+ * report it as a tool error before touching the network.
27
+ */
28
+ class InvalidDateTimeError extends Error {}
29
+
30
+ /** True when year/month/day name a real calendar day (no 30 Feb roll-over). */
31
+ function isRealDate(year, month, day) {
32
+ return (
33
+ year >= MIN_YEAR &&
34
+ month >= 1 &&
35
+ month <= 12 &&
36
+ new Date(Date.UTC(year, month - 1, day)).getUTCDate() === day
37
+ );
38
+ }
39
+
40
+ /**
41
+ * Parse an ISO 8601 instant that carries `Z` or a ±hh:mm offset.
42
+ * @returns {number} epoch milliseconds, or NaN when the value isn't one
43
+ */
44
+ function parseIsoInstant(value) {
45
+ const s = typeof value === 'string' ? value.trim().replace(/z$/, 'Z') : '';
46
+ const m = ISO_INSTANT.exec(s);
47
+ if (!m || !isRealDate(Number(m[1]), Number(m[2]), Number(m[3]))) {
48
+ return NaN;
49
+ }
50
+ return Date.parse(s);
51
+ }
52
+
53
+ /**
54
+ * Parse a zone-less wall-clock date-time.
55
+ * @returns {number[]|null} [year, month, day, hour, minute, second], or null
56
+ */
57
+ function parseWallTime(value) {
58
+ const m = typeof value === 'string' ? WALL_TIME.exec(value.trim()) : null;
59
+ if (!m) return null;
60
+ const [year, month, day, hour, minute] = m.slice(1, 6).map(Number);
61
+ const second = m[6] === undefined ? 0 : Number(m[6]);
62
+ if (
63
+ !isRealDate(year, month, day) ||
64
+ hour > 23 ||
65
+ minute > 59 ||
66
+ second > 59
67
+ ) {
68
+ return null;
69
+ }
70
+ return [year, month, day, hour, minute, second];
71
+ }
72
+
73
+ const formatters = new Map();
74
+
75
+ /**
76
+ * Wall-clock date and time of an instant in an IANA zone.
77
+ * @returns {{date: string, time: string, wallMs: number}|null} `date` is
78
+ * YYYY-MM-DD, `time` HH:mm:ss, `wallMs` the wall-clock fields read as UTC;
79
+ * null when the zone is unknown to Intl
80
+ */
81
+ function zonedParts(ms, timeZone) {
82
+ let fmt = formatters.get(timeZone);
83
+ if (!fmt) {
84
+ try {
85
+ fmt = new Intl.DateTimeFormat('en-US', {
86
+ timeZone,
87
+ hourCycle: 'h23',
88
+ year: 'numeric',
89
+ month: '2-digit',
90
+ day: '2-digit',
91
+ hour: '2-digit',
92
+ minute: '2-digit',
93
+ second: '2-digit',
94
+ });
95
+ } catch (_e) {
96
+ return null;
97
+ }
98
+ formatters.set(timeZone, fmt);
99
+ }
100
+ const p = {};
101
+ for (const { type, value } of fmt.formatToParts(new Date(ms))) {
102
+ p[type] = value;
103
+ }
104
+ const date = `${p.year}-${p.month}-${p.day}`;
105
+ const time = `${p.hour}:${p.minute}:${p.second}`;
106
+ return {
107
+ date,
108
+ time,
109
+ wallMs: Date.parse(`${date}T${time}Z`),
110
+ };
111
+ }
112
+
113
+ /**
114
+ * Convert a wall-clock date-time in an IANA zone to an instant.
115
+ * @returns {number} epoch milliseconds, or NaN for a bad value or zone
116
+ */
117
+ function zonedWallTimeToUtcMs(wall, timeZone) {
118
+ const f = parseWallTime(wall);
119
+ if (!f) return NaN;
120
+ const guess = Date.UTC(f[0], f[1] - 1, f[2], f[3], f[4], f[5]);
121
+ const offsetAt = (t) => {
122
+ const parts = zonedParts(t, timeZone);
123
+ return parts ? parts.wallMs - t : NaN;
124
+ };
125
+ const first = offsetAt(guess);
126
+ if (Number.isNaN(first)) return NaN;
127
+ // Re-check the offset at the candidate instant, in case a DST change falls
128
+ // between the naive guess and the real instant.
129
+ const second = offsetAt(guess - first);
130
+ return guess - (second === first ? first : second);
131
+ }
132
+
133
+ /**
134
+ * Turn an ISO 8601 date-time into a Graph dateTimeTimeZone envelope.
135
+ *
136
+ * - With `Z` or a ±hh:mm offset: the same instant, sent in UTC (Graph wants
137
+ * the dateTime without a trailing Z).
138
+ * - Without a zone: sent unchanged, read in `timeZone` (default
139
+ * DEFAULT_TIMEZONE).
140
+ *
141
+ * @throws {InvalidDateTimeError} for anything else (date-only, impossible
142
+ * dates, free text)
143
+ */
144
+ function toGraphDateTimeTimeZone(
145
+ value,
146
+ paramName,
147
+ timeZone = config.DEFAULT_TIMEZONE
148
+ ) {
149
+ const instant = parseIsoInstant(value);
150
+ if (!Number.isNaN(instant)) {
151
+ return {
152
+ dateTime: new Date(instant).toISOString().replace(/(?:\.000)?Z$/, ''),
153
+ timeZone: 'UTC',
154
+ };
155
+ }
156
+ if (parseWallTime(value)) {
157
+ return { dateTime: value.trim(), timeZone };
158
+ }
159
+ throw new InvalidDateTimeError(
160
+ `Invalid ${paramName}: expected an ISO 8601 date-time with a time, e.g. "2026-03-01T09:00:00Z" (UTC), "2026-03-01T09:00:00+10:00" (offset) or "2026-03-01T09:00:00" (read in ${timeZone}) (got ${JSON.stringify(String(value).slice(0, 40))}).`
161
+ );
162
+ }
163
+
164
+ module.exports = {
165
+ InvalidDateTimeError,
166
+ parseIsoInstant,
167
+ zonedParts,
168
+ zonedWallTimeToUtcMs,
169
+ toGraphDateTimeTimeZone,
170
+ };