@chrischall/microsoft-teams-mcp 0.4.0 → 0.5.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.
@@ -1,18 +1,23 @@
1
1
  import { z } from 'zod';
2
- import { McpToolError, toolAnnotations } from '@chrischall/mcp-utils';
2
+ import { CONFIRM_INJECTION_RULE, confirmTokenParam, mapWithConcurrency, McpToolError, toolAnnotations, } from '@chrischall/mcp-utils';
3
3
  import { isUnread, isUserMessage, matchConversations, normaliseMessage, oldestFirst, readHorizon, SELF_CHAT_ALIASES, summariseAll, } from '../model.js';
4
4
  import { confirmedSummary } from './confirm.js';
5
5
  import { enrichTitles } from './titles.js';
6
6
  import { wrapApiError } from './errors.js';
7
7
  import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
8
8
  import { DEFAULT_LIMIT, limitArg, makeLimitedStopAt, sinceArg } from './limit.js';
9
+ import { resolveTimeZone, TIME_ZONE_DESCRIPTION, tzArg } from './timezone.js';
10
+ import { afterMessageIdArg, CURSOR_NO_CACHE_DESCRIPTION, newestId } from './cursor.js';
11
+ import { FORMAT_DESCRIPTION, formatArg, formatBody, formatConversation } from './format.js';
12
+ import { fetchOutsideRoots, MAX_ROOT_FETCHES, rootBudget } from './roots.js';
13
+ import { advancesHorizon, applyMarks, confirmMarks, horizonMessageId, MARK_READ_DESCRIPTION, markReadArg, assertMarkReadFormat, } from './markread.js';
9
14
  const MAX_MESSAGES = 500;
10
15
  /**
11
16
  * Raw messages read before giving up (20 pages of 200). The real bound is the
12
17
  * `stopAt` boundary; this only caps a conversation of nothing but system events.
13
18
  */
14
19
  const MAX_RAW_MESSAGES = 4000;
15
- /** Candidates an ambiguous-name error lists. */
20
+ /** Candidates an ambiguous name lists, as an error or as data. */
16
21
  const MAX_CANDIDATES = 10;
17
22
  /** Arrival time in epoch ms: a message's id IS its arrival ms; the ISO fields are the fallback. */
18
23
  export function arrivalMs(m) {
@@ -21,27 +26,6 @@ export function arrivalMs(m) {
21
26
  return n;
22
27
  return Date.parse(m.originalarrivaltime ?? m.composetime ?? '');
23
28
  }
24
- /**
25
- * Group oldest-first channel messages under their root post, in order of first
26
- * appearance. A reply whose root is older than the window still appears, under
27
- * a `{ id, missing: true }` placeholder root.
28
- */
29
- export function groupThreads(messages) {
30
- const byRoot = new Map();
31
- for (const m of messages) {
32
- const rootId = m.replyTo ?? m.id;
33
- let thread = byRoot.get(rootId);
34
- if (thread === undefined) {
35
- thread = { root: { id: rootId, missing: true }, replies: [] };
36
- byRoot.set(rootId, thread);
37
- }
38
- if (m.replyTo === undefined)
39
- thread.root = m;
40
- else
41
- thread.replies.push(m);
42
- }
43
- return [...byRoot.values()];
44
- }
45
29
  /**
46
30
  * Settle a listing's unread hint with what the read actually found: an unread
47
31
  * message confirms it, and a read that saw everything past the horizon without
@@ -54,13 +38,56 @@ export function confirmUnread(summary, unreadCount, exact) {
54
38
  }
55
39
  function describeCandidate(s) {
56
40
  const where = s.team !== undefined ? ` in ${s.team}` : '';
57
- return `"${s.title}"${where} (${s.kind}, id ${s.id})`;
41
+ const how = s.match_reason !== undefined ? `, matched by ${s.match_reason}` : '';
42
+ return `"${s.title}"${where} (${s.kind}, id ${s.id}${how})`;
43
+ }
44
+ /**
45
+ * A name that matched several conversations. It is an `McpToolError` — the
46
+ * write tools let it through, as a write must never guess — that also carries
47
+ * every match, so `teams_read_conversation` can return the candidates as data.
48
+ */
49
+ export class AmbiguousConversationError extends McpToolError {
50
+ query;
51
+ matches;
52
+ constructor(query, matches, verb) {
53
+ const named = matches.slice(0, MAX_CANDIDATES).map(describeCandidate).join('; ');
54
+ const more = matches.length > MAX_CANDIDATES ? ` (first ${MAX_CANDIDATES} shown)` : '';
55
+ super(`"${query}" matches ${matches.length} conversations${more}: ${named}.`, {
56
+ hint: `Pass the id of the one to ${verb} as conversation.`,
57
+ });
58
+ this.query = query;
59
+ this.matches = matches;
60
+ this.name = 'AmbiguousConversationError';
61
+ }
62
+ }
63
+ /**
64
+ * An ambiguous name as a read's result: the first 10 candidates, each with
65
+ * what tells them apart and how it matched, and how many matched in all.
66
+ */
67
+ export function ambiguousResult(err) {
68
+ return {
69
+ ambiguous: true,
70
+ query: err.query,
71
+ match_count: err.matches.length,
72
+ candidates: err.matches.slice(0, MAX_CANDIDATES).map((s) => ({
73
+ id: s.id,
74
+ title: s.title,
75
+ kind: s.kind,
76
+ ...(s.team !== undefined ? { team: s.team } : {}),
77
+ ...(s.lastActivity !== undefined ? { lastActivity: s.lastActivity } : {}),
78
+ ...(s.match_reason !== undefined ? { match_reason: s.match_reason } : {}),
79
+ })),
80
+ hint: 'pass one id as conversation',
81
+ };
58
82
  }
59
83
  /**
60
84
  * The one conversation a `conversation` argument names: an exact id, else a
61
- * unique title/team substring. None, or several, is an `McpToolError` — the
62
- * latter naming up to 10 candidates so the caller can pass an id. `verb` fills
63
- * the hint ("Pass the id of the one to read").
85
+ * unique title/team/participant substring — never what was said in a chat,
86
+ * since this names the target of sends and reactions too. The match carries
87
+ * its `match_reason`. None is an `McpToolError`; several is an
88
+ * {@link AmbiguousConversationError} naming up to 10 candidates, each with how
89
+ * it matched, so the caller can pass an id. `verb` fills the hint ("Pass the
90
+ * id of the one to read").
64
91
  */
65
92
  export function resolveConversation(summaries, conversation, verb) {
66
93
  const matches = matchConversations(summaries, conversation);
@@ -69,109 +96,306 @@ export function resolveConversation(summaries, conversation, verb) {
69
96
  hint: 'List them with teams_list_chats or teams_list_teams_and_channels and pass an id.',
70
97
  });
71
98
  }
72
- if (matches.length > 1) {
73
- const named = matches.slice(0, MAX_CANDIDATES).map(describeCandidate).join('; ');
74
- const more = matches.length > MAX_CANDIDATES ? ` (first ${MAX_CANDIDATES} shown)` : '';
75
- throw new McpToolError(`"${conversation}" matches ${matches.length} conversations${more}: ${named}.`, {
76
- hint: `Pass the id of the one to ${verb} as conversation.`,
77
- });
78
- }
99
+ if (matches.length > 1)
100
+ throw new AmbiguousConversationError(conversation, matches, verb);
79
101
  return matches[0];
80
102
  }
81
103
  /**
82
- * {@link resolveConversation} against the whole listing, with untitled group
83
- * chats titled by their participants and 1:1s by the other person
84
- * (`titles.ts`) so a name can pick one of several chats that share a last
85
- * sender, or a 1:1 the user wrote in last. An exact id titles just that one,
86
- * and a self-chat alias (`notes`, `self`) titles nothing.
104
+ * A resolver of `conversation` arguments against one listing: an exact id is
105
+ * {@link resolveConversation}d with just that one titled, a self-chat alias
106
+ * (`notes`, `self`) with nothing titled, and a name against the whole listing
107
+ * with untitled group chats titled by their participants and 1:1s by the
108
+ * other person (`titles.ts`) — so a name can pick one of several chats that
109
+ * share a last sender, or a 1:1 the user wrote in last. The whole-listing
110
+ * titling runs once, however many names the resolver is asked for.
87
111
  */
88
- export async function resolveListed(chatsvc, raw, me, conversation, verb) {
112
+ function listedResolver(chatsvc, raw, me, verb) {
89
113
  const summaries = summariseAll(raw, me);
90
- if (SELF_CHAT_ALIASES.has(conversation.trim().toLowerCase()))
91
- return resolveConversation(summaries, conversation, verb);
92
- const exact = summaries.find((s) => s.id === conversation);
93
- return resolveConversation(await enrichTitles(chatsvc, raw, me, exact ? [exact] : summaries), conversation, verb);
114
+ let titled;
115
+ return async (conversation) => {
116
+ if (SELF_CHAT_ALIASES.has(conversation.trim().toLowerCase()))
117
+ return resolveConversation(summaries, conversation, verb);
118
+ const exact = summaries.find((s) => s.id === conversation);
119
+ if (exact)
120
+ return resolveConversation(await enrichTitles(chatsvc, raw, me, [exact]), conversation, verb);
121
+ titled ??= enrichTitles(chatsvc, raw, me, summaries);
122
+ return resolveConversation(await titled, conversation, verb);
123
+ };
124
+ }
125
+ /** {@link resolveConversation} against the whole listing, titled as {@link listedResolver} says. */
126
+ export async function resolveListed(chatsvc, raw, me, conversation, verb) {
127
+ return listedResolver(chatsvc, raw, me, verb)(conversation);
128
+ }
129
+ /** Conversations one call may read. */
130
+ export const MAX_CONVERSATIONS = 20;
131
+ /** Conversations read at once in a multi-conversation read. */
132
+ export const READ_CONCURRENCY = 4;
133
+ /** Read one resolved conversation. */
134
+ async function readOne(chatsvc, raw, me, summary, { unreadOnly, since, afterMessageId, limit, timeZone, format, roots }) {
135
+ // The self-chat resolves even when the listing does not carry it.
136
+ const conv = raw.find((c) => c.id === summary.id) ?? { id: summary.id };
137
+ const horizon = readHorizon(conv);
138
+ const cutoff = since !== undefined ? Date.parse(since) : undefined;
139
+ const cursor = afterMessageId !== undefined ? Number(afterMessageId) : undefined;
140
+ const wanted = (m) => isUserMessage(m) && (!unreadOnly || isUnread(m, horizon, me));
141
+ const limited = makeLimitedStopAt(unreadOnly ? horizon : undefined, wanted, limit);
142
+ // A cursor or `since` cutoff above the read horizon leaves unread messages unseen.
143
+ let windowCut = false;
144
+ // Only `since` leaves out messages the caller has not seen: a cursor's were returned by an earlier read.
145
+ let sinceCut = false;
146
+ let capped = false;
147
+ // The oldest message paging looked at — where a limit or the raw cap cut the read.
148
+ let lastSeen;
149
+ const stopAt = (m) => {
150
+ lastSeen = Number(m.id);
151
+ // The read horizon (checked inside `limited`) wins over the cursor and `since`, as the nearer boundary.
152
+ const atHorizon = unreadOnly && Number(m.id) <= horizon;
153
+ const at = arrivalMs(m);
154
+ const atCursor = cursor !== undefined && Number(m.id) <= cursor;
155
+ const atSince = cutoff !== undefined && Number.isFinite(at) && at < cutoff;
156
+ if (!atHorizon && (atCursor || atSince)) {
157
+ if (Number(m.id) > horizon) {
158
+ windowCut = true;
159
+ if (atSince && !atCursor)
160
+ sinceCut = true;
161
+ }
162
+ return true;
163
+ }
164
+ return limited.stopAt(m);
165
+ };
166
+ const fetched = await chatsvc.getMessages(summary.id, {
167
+ stopAt,
168
+ max: MAX_RAW_MESSAGES,
169
+ onCapped: () => (capped = true),
170
+ });
171
+ const returned = fetched.filter(wanted);
172
+ const newest = newestId(returned);
173
+ const next_cursor = newest ?? afterMessageId;
174
+ const messages = oldestFirst(returned).map((m) => normaliseMessage(m, me, { timeZone }));
175
+ const unread_count = fetched.filter((m) => wanted(m) && isUnread(m, horizon, me)).length;
176
+ const outsideRoots = summary.kind === 'channel'
177
+ ? await fetchOutsideRoots(chatsvc, summary.id, messages, me, { budget: roots, timeZone })
178
+ : undefined;
179
+ const truncated = limited.truncated || capped;
180
+ // Whether every message past the read horizon was seen, so unread_count is the whole count.
181
+ const exact = !truncated && !windowCut;
182
+ // A limit or cap that cut past the read horizon may have left out older unread messages.
183
+ const limitCut = truncated && (lastSeen === undefined || !(lastSeen <= horizon));
184
+ const skip = limitCut
185
+ ? {
186
+ skipped: 'truncated',
187
+ hint: 'The read marker was left where it was: the limit cut this read, so unread messages older than those ' +
188
+ `returned were not returned. Read again with a larger limit (max ${MAX_MESSAGES}) to mark it read, or ` +
189
+ 'use teams_mark_read to mark it all read deliberately.',
190
+ }
191
+ : sinceCut
192
+ ? {
193
+ skipped: 'since',
194
+ hint: 'The read marker was left where it was: the since cutoff left out unread messages older than those ' +
195
+ 'returned. Read again with an earlier since (or without it) to mark it read, or use teams_mark_read ' +
196
+ 'to mark it all read deliberately.',
197
+ }
198
+ : undefined;
199
+ const result = {
200
+ conversation: formatConversation(confirmUnread(summary, unread_count, exact), format),
201
+ unread_count,
202
+ ...(exact ? {} : { unread_count_scope: 'window' }),
203
+ ...formatBody(summary.kind, messages, format, outsideRoots),
204
+ ...(truncated
205
+ ? {
206
+ truncated: {
207
+ returned: messages.length,
208
+ hint: `Only the newest ${messages.length} messages were returned; pass a larger limit ` +
209
+ `(max ${MAX_MESSAGES}) or a since time to read further back.`,
210
+ },
211
+ }
212
+ : {}),
213
+ ...(next_cursor !== undefined ? { next_cursor } : {}),
214
+ };
215
+ return { summary, conv, newest, ...(skip !== undefined ? { skip } : {}), result };
216
+ }
217
+ function readError(conversation, err, id) {
218
+ const e = wrapApiError(err, 'read this conversation');
219
+ return {
220
+ conversation,
221
+ ...(id !== undefined ? { id } : {}),
222
+ error: e.message,
223
+ ...(e.hint !== undefined ? { hint: e.hint } : {}),
224
+ };
225
+ }
226
+ /**
227
+ * Read several conversations: each argument resolved against one listing, the
228
+ * distinct conversations read {@link READ_CONCURRENCY} at a time, in the order
229
+ * asked. An ambiguous name takes its place among them as the same
230
+ * {@link ambiguousResult} a single read returns; one that cannot be resolved
231
+ * or read goes into `errors`; the rest still come back.
232
+ */
233
+ async function readMany(chatsvc, raw, me, conversations, opts) {
234
+ const resolve = listedResolver(chatsvc, raw, me, 'read');
235
+ const errors = [];
236
+ /** One slot per distinct conversation asked: a resolved one to read, or an ambiguous name's candidates. */
237
+ const slots = [];
238
+ const seen = new Set();
239
+ for (const asked of new Set(conversations)) {
240
+ try {
241
+ const summary = await resolve(asked);
242
+ // A conversation named twice (by id and by name, say) is read once.
243
+ if (seen.has(summary.id))
244
+ continue;
245
+ seen.add(summary.id);
246
+ slots.push({ asked, summary });
247
+ }
248
+ catch (err) {
249
+ if (err instanceof AmbiguousConversationError)
250
+ slots.push({ ambiguous: ambiguousResult(err) });
251
+ else
252
+ errors.push(readError(asked, err));
253
+ }
254
+ }
255
+ const reads = await mapWithConcurrency(slots, READ_CONCURRENCY, async (slot) => {
256
+ if ('ambiguous' in slot)
257
+ return { ok: true, result: slot };
258
+ try {
259
+ return { ok: true, result: await readOne(chatsvc, raw, me, slot.summary, opts) };
260
+ }
261
+ catch (err) {
262
+ return { ok: false, error: readError(slot.asked, err, slot.summary.id) };
263
+ }
264
+ });
265
+ const results = [];
266
+ for (const r of reads) {
267
+ if (r.ok)
268
+ results.push(r.result);
269
+ else
270
+ errors.push(r.error);
271
+ }
272
+ // Resolution failures were found first; list every error in the order asked.
273
+ const order = new Map(conversations.map((c, i) => [c, i]));
274
+ errors.sort((a, b) => (order.get(a.conversation) ?? 0) - (order.get(b.conversation) ?? 0));
275
+ return { reads: results, errors };
94
276
  }
95
277
  export function registerConversationTools(server, { chatsvc }) {
96
278
  server.registerTool('teams_read_conversation', {
97
279
  title: 'Read a Teams chat or channel',
98
280
  description: 'Read the messages of any chat or channel the signed-in user is in, by id (from ' +
99
281
  'teams_list_chats / teams_list_teams_and_channels) or by name, without opening it in ' +
100
- 'Teams. "48:notes" (or the name "notes" / "self") is the user\'s own notes self-chat. Messages come oldest first, each with id, time (ISO 8601), sender, fromMe, ' +
101
- 'text, subject, edited/deleted flags and attachments; a channel is returned as threads, ' +
102
- 'each root post with its replies (a root older than the window is marked missing). ' +
282
+ 'Teams. "48:notes" (or the name "notes" / "self") is the user\'s own notes self-chat. Messages come oldest first, each with id, time (UTC, ISO 8601), sender, fromMe, ' +
283
+ 'text (never truncated; table cells separated by " | "), subject, edited/deleted flags and attachments; a channel is returned as threads, ' +
284
+ 'each root post with its replies. A root older than the window is fetched and marked outside_window: ' +
285
+ 'true (it is context, not counted or cursored); up to ' +
286
+ `${MAX_ROOT_FETCHES} roots are fetched per call, and any beyond that or that cannot be fetched is ` +
287
+ '{ id, missing: true }. ' +
103
288
  'unread_only returns just the messages the user has not read; since stops at a time; ' +
104
289
  'limit keeps the newest (truncated says when more exist; unread_count_scope "window" says ' +
105
- 'unread_count only covers what limit/since let through). This does NOT mark anything ' +
106
- 'read — the user\'s Teams unread badges are unaffected. Attachments are listed per message (images by ref, files by ' +
107
- 'name) and fetched with teams_get_attachment.' +
290
+ 'unread_count only covers what limit/since/after_message_id let through). after_message_id returns only ' +
291
+ 'messages newer than that id; next_cursor is the newest returned message id (or after_message_id ' +
292
+ 'when nothing is new) — pass it back as after_message_id to read only what arrived since. ' +
293
+ 'after_message_id takes message-id cursors only: to read what teams_get_changes counted, pass that ' +
294
+ "row's after_message_id, never teams_get_changes' next_cursor (a time token for teams_get_changes). " +
295
+ CURSOR_NO_CACHE_DESCRIPTION +
296
+ FORMAT_DESCRIPTION +
297
+ `conversation may also be an array of up to ${MAX_CONVERSATIONS} ids/names: the result is then ` +
298
+ '{ conversations: [...], errors, fetched_at }, one single-read result per conversation (the other ' +
299
+ 'arguments apply to each); an ambiguous name takes its place among them as the same { ambiguous: true, ' +
300
+ '... } object a single read returns, and one that cannot be resolved or read is listed in errors ' +
301
+ 'while the rest still come back. ' +
302
+ MARK_READ_DESCRIPTION +
303
+ 'With mark_read the read marker of each conversation read moves up to the newest message returned ' +
304
+ '(never backwards; outside_window roots do not count) and its result says marked_read; one whose limit ' +
305
+ 'or since cut off unread messages older than those returned is not marked (marked_read: { skipped, ' +
306
+ 'hint }), while a limit that cut only already-read messages does not stop it; the user ' +
307
+ 'confirms first — a prompt where the client supports one, otherwise the first call returns only a ' +
308
+ 'preview and a confirmToken, and the repeat call with it reads and marks. ' +
309
+ CONFIRM_INJECTION_RULE +
310
+ ' Attachments are listed per message (images by ref, files by ' +
311
+ 'name) and fetched with teams_get_attachment. A name that matches several conversations is ' +
312
+ 'not an error: the result is {ambiguous: true, query, match_count, candidates (up to 10, each ' +
313
+ 'with id, title, kind, team, lastActivity and match_reason), hint} and no messages — read again ' +
314
+ 'with one candidate\'s id. ' +
315
+ TIME_ZONE_DESCRIPTION +
108
316
  UNTRUSTED_DESCRIPTION_SUFFIX,
109
- annotations: toolAnnotations({ readOnly: true, openWorld: true }),
317
+ // A write only with mark_read, but a write: it moves the user's read marker (never backwards, so a repeat is a no-op).
318
+ annotations: toolAnnotations({ readOnly: false, destructive: false, idempotent: true, openWorld: true }),
110
319
  inputSchema: {
111
320
  conversation: z
112
- .string()
113
- .min(1)
321
+ .union([z.string().min(1), z.array(z.string().min(1)).min(1).max(MAX_CONVERSATIONS)])
114
322
  .describe('The conversation id ("48:notes", "notes" or "self" for the self-chat), or a case-insensitive ' +
115
- "substring of the chat title, channel name, team name or an untitled chat's participant names."),
323
+ "substring of the chat title, channel name, team name or an untitled chat's participant names; " +
324
+ `or an array of up to ${MAX_CONVERSATIONS} of them to read several at once.`),
116
325
  unread_only: z
117
326
  .boolean()
118
327
  .optional()
119
- .describe('Only return messages the user has not read yet (default false). Never marks them read.'),
328
+ .describe('Only return messages the user has not read yet (default false). Does not mark them read unless mark_read is set.'),
120
329
  since: sinceArg,
330
+ after_message_id: afterMessageIdArg,
121
331
  limit: limitArg(MAX_MESSAGES, 'messages'),
332
+ tz: tzArg,
333
+ format: formatArg,
334
+ mark_read: markReadArg,
335
+ confirmToken: confirmTokenParam,
122
336
  },
123
- }, async ({ conversation, unread_only, since, limit }) => {
337
+ }, async ({ conversation, unread_only, since, after_message_id, limit, tz, format, mark_read, confirmToken }, ctx) => {
124
338
  try {
339
+ assertMarkReadFormat(mark_read, format);
340
+ const opts = {
341
+ unreadOnly: unread_only ?? false,
342
+ since,
343
+ afterMessageId: after_message_id,
344
+ limit: limit ?? DEFAULT_LIMIT,
345
+ timeZone: resolveTimeZone(tz),
346
+ format: format ?? 'full',
347
+ roots: rootBudget(),
348
+ };
349
+ const fetched_at = new Date().toISOString();
125
350
  const [raw, me] = await Promise.all([chatsvc.listConversations(), chatsvc.meMri()]);
126
- const summary = await resolveListed(chatsvc, raw, me, conversation, 'read');
127
- // The self-chat resolves even when the listing does not carry it.
128
- const conv = raw.find((c) => c.id === summary.id) ?? { id: summary.id };
129
- const horizon = readHorizon(conv);
130
- const cutoff = since !== undefined ? Date.parse(since) : undefined;
131
- const wanted = (m) => isUserMessage(m) && (!unread_only || isUnread(m, horizon, me));
132
- const limited = makeLimitedStopAt(unread_only ? horizon : undefined, wanted, limit ?? DEFAULT_LIMIT);
133
- // A `since` cutoff above the read horizon leaves unread messages unseen.
134
- let sinceCut = false;
135
- let capped = false;
136
- const stopAt = (m) => {
137
- // The read horizon (checked inside `limited`) wins over `since`, as it is the nearer boundary.
138
- const atHorizon = unread_only && Number(m.id) <= horizon;
139
- const at = arrivalMs(m);
140
- if (!atHorizon && cutoff !== undefined && Number.isFinite(at) && at < cutoff) {
141
- if (Number(m.id) > horizon)
142
- sinceCut = true;
143
- return true;
351
+ const many = Array.isArray(conversation)
352
+ ? await readMany(chatsvc, raw, me, conversation, opts)
353
+ : {
354
+ reads: [await readOne(chatsvc, raw, me, await resolveListed(chatsvc, raw, me, conversation, 'read'), opts)],
355
+ errors: [],
356
+ };
357
+ let marks;
358
+ if (mark_read) {
359
+ // One confirmation covers every conversation the call read; each marker moves only forwards.
360
+ const plans = [];
361
+ for (const read of many.reads) {
362
+ if ('ambiguous' in read)
363
+ continue;
364
+ const { summary, conv, newest, skip } = read;
365
+ if (skip === undefined && advancesHorizon(conv, newest))
366
+ plans.push({ summary, previous: horizonMessageId(conv), target: newest });
144
367
  }
145
- return limited.stopAt(m);
146
- };
147
- const fetched = await chatsvc.getMessages(summary.id, {
148
- stopAt,
149
- max: MAX_RAW_MESSAGES,
150
- onCapped: () => (capped = true),
151
- });
152
- const messages = oldestFirst(fetched.filter(wanted)).map((m) => normaliseMessage(m, me));
153
- const unread_count = fetched.filter((m) => wanted(m) && isUnread(m, horizon, me)).length;
154
- const body = summary.kind === 'channel' ? { threads: groupThreads(messages) } : { messages };
155
- const truncated = limited.truncated || capped;
156
- // Whether every message past the read horizon was seen, so unread_count is the whole count.
157
- const exact = !truncated && !sinceCut;
158
- return untrustedResult({
159
- conversation: confirmUnread(summary, unread_count, exact),
160
- unread_count,
161
- ...(exact ? {} : { unread_count_scope: 'window' }),
162
- ...body,
163
- ...(truncated
164
- ? {
165
- truncated: {
166
- returned: messages.length,
167
- hint: `Only the newest ${messages.length} messages were returned; pass a larger limit ` +
168
- `(max ${MAX_MESSAGES}) or a since time to read further back.`,
169
- },
170
- }
171
- : {}),
172
- });
368
+ if (plans.length > 0) {
369
+ const gate = await confirmMarks(ctx, { tool: 'teams_read_conversation', me, plans, confirmToken });
370
+ if (gate)
371
+ return gate;
372
+ }
373
+ marks = await applyMarks(chatsvc, plans);
374
+ }
375
+ const results = many.reads.map((read) => 'ambiguous' in read
376
+ ? read.ambiguous
377
+ : {
378
+ ...read.result,
379
+ ...(marks !== undefined
380
+ ? (marks.get(read.summary.id) ??
381
+ (read.skip !== undefined && advancesHorizon(read.conv, read.newest)
382
+ ? { marked_read: read.skip }
383
+ : { marked_read: false }))
384
+ : {}),
385
+ });
386
+ if (Array.isArray(conversation)) {
387
+ return untrustedResult({
388
+ conversations: results,
389
+ ...(many.errors.length > 0 ? { errors: many.errors } : {}),
390
+ fetched_at,
391
+ });
392
+ }
393
+ return untrustedResult({ ...results[0], fetched_at });
173
394
  }
174
395
  catch (err) {
396
+ // A read can safely hand back the candidates; the write tools keep refusing.
397
+ if (err instanceof AmbiguousConversationError)
398
+ return untrustedResult(ambiguousResult(err));
175
399
  throw wrapApiError(err, 'read the conversation');
176
400
  }
177
401
  });
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Message-id cursors: "only what is new since I last looked".
3
+ *
4
+ * A chat-service message id IS its arrival time in epoch ms (`arrivalMs`), so
5
+ * ids order messages, and "newer than the last one I saw" is a plain numeric
6
+ * comparison — a stop boundary for the newest-first read, exactly like the read
7
+ * horizon. The cursor handed back (`next_cursor`) is just the newest returned
8
+ * message's id; the caller passes it back as `after_message_id` (or, for
9
+ * `teams_get_unread`, inside `cursors`). The server keeps no state and no
10
+ * cache: every call reads live, and says when in `fetched_at`.
11
+ *
12
+ * `teams_get_changes` has a different, time cursor (an opaque token); it is
13
+ * not accepted here. Its rows carry the message-id cursor to hand on instead,
14
+ * `after_message_id` — its cursor time written as an id.
15
+ */
16
+ import { z } from 'zod';
17
+ /** A message id: decimal digits (its arrival epoch ms). */
18
+ const messageId = z.string().regex(/^\d+$/, {
19
+ message: 'a message id is decimal digits, e.g. "1760000000000" — a teams_get_changes next_cursor is not one; ' +
20
+ 'pass its per-conversation after_message_id instead',
21
+ });
22
+ export const afterMessageIdArg = messageId
23
+ .optional()
24
+ .describe('Only return messages newer than this message id (a previous teams_read_conversation next_cursor, a ' +
25
+ "teams_get_changes row's after_message_id, or any message id); the read stops at the first message at " +
26
+ "or before it. Not teams_get_changes' next_cursor, which is a time token.");
27
+ export const cursorsArg = z
28
+ .record(z.string(), messageId)
29
+ .optional()
30
+ .describe('Per-conversation cursors, { conversationId: messageId } (a previous result\'s next_cursors): each ' +
31
+ "conversation's read stops at the later of its read marker and its cursor, so only unread messages " +
32
+ 'newer than the cursor come back, and a conversation with none past it is left out.');
33
+ /** Shared description text: what next_cursor is and that nothing is cached. */
34
+ export const CURSOR_NO_CACHE_DESCRIPTION = 'fetched_at is when this call read Teams: the server holds no cache, so every call reads live ' +
35
+ '(there is nothing to refresh). ';
36
+ /** The id of the newest of `messages` (ids are arrival ms), or undefined when there are none. */
37
+ export function newestId(messages) {
38
+ let newest;
39
+ for (const m of messages)
40
+ if (newest === undefined || Number(m.id) > Number(newest))
41
+ newest = m.id;
42
+ return newest;
43
+ }