@chrischall/microsoft-teams-mcp 0.6.2 → 0.8.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.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +184 -80
- package/dist/auth-fetchproxy.js +19 -23
- package/dist/bridge-scope.js +133 -0
- package/dist/bundle.js +5293 -2596
- package/dist/chatsvc.js +40 -3
- package/dist/index.js +4 -0
- package/dist/model.js +1 -1
- package/dist/sharepoint-auth.js +20 -22
- package/dist/substrate-auth.js +13 -18
- package/dist/tools/activity.js +36 -4
- package/dist/tools/attachment.js +26 -11
- package/dist/tools/changes.js +54 -10
- package/dist/tools/channels.js +4 -2
- package/dist/tools/chat-search.js +1 -1
- package/dist/tools/chat.js +5 -3
- package/dist/tools/conversation.js +19 -12
- package/dist/tools/cursor.js +6 -6
- package/dist/tools/export-attachments.js +114 -0
- package/dist/tools/export-format.js +101 -0
- package/dist/tools/export.js +552 -0
- package/dist/tools/format.js +3 -3
- package/dist/tools/from.js +1 -1
- package/dist/tools/hints.js +4 -0
- package/dist/tools/limit.js +1 -1
- package/dist/tools/listing.js +9 -8
- package/dist/tools/markread.js +14 -6
- package/dist/tools/react.js +10 -8
- package/dist/tools/search.js +7 -4
- package/dist/tools/send.js +9 -7
- package/dist/tools/titles.js +103 -20
- package/dist/tools/transcript.js +144 -0
- package/dist/tools/unread.js +9 -6
- package/dist/transcript.js +124 -0
- package/dist/version.js +1 -1
- package/mint.yaml +18 -0
- package/package.json +6 -2
- package/server.json +9 -2
- package/skills/teams-fpx/SKILL.md +15 -0
|
@@ -0,0 +1,552 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `teams_export_messages` — bulk-export chats and channels to files, so thousands of
|
|
3
|
+
* messages can be kept, searched or handed on without any of them entering
|
|
4
|
+
* the model's context.
|
|
5
|
+
*
|
|
6
|
+
* The tool pages the chat service server-side and writes one file per
|
|
7
|
+
* conversation (`<title>-<short id>.jsonl|md`, `export-format.ts`) through
|
|
8
|
+
* mcp-utils' export sink: on a local (stdio) install into a fresh directory
|
|
9
|
+
* under `dest` → `TEAMS_OUTPUT_DIR` → `~/Downloads/microsoft-teams-mcp`, with
|
|
10
|
+
* ABSOLUTE paths in the result; on mcp-host (which sets `MCP_BLOB_BASE_URL`
|
|
11
|
+
* and `MCP_BLOB_SIGNING_KEY`) as one zip in the hosted blob store behind a
|
|
12
|
+
* signed link. The result is only a manifest — where the files are, counts,
|
|
13
|
+
* the date span, a resume cursor — never a message.
|
|
14
|
+
*
|
|
15
|
+
* A call does bounded work: it stops at `max_items` messages or
|
|
16
|
+
* `budget_seconds`, whichever comes first, and returns `has_more` with a
|
|
17
|
+
* `cursor`; passing the cursor back continues the SAME export (the same
|
|
18
|
+
* directory on disk, the next `part-NNNN.zip` in the blob store). The cursor
|
|
19
|
+
* carries the original arguments, the conversations still to do (or, when
|
|
20
|
+
* that list is too long for a cursor, the id to go on from — conversations
|
|
21
|
+
* are exported in id order; a conversation new since the first part with an
|
|
22
|
+
* id before that point is then not exported), and where in the current
|
|
23
|
+
* conversation it stopped, as a `from.ts` position. The budget is checked
|
|
24
|
+
* between conversations and between pages of a read; a read cut by it is
|
|
25
|
+
* redone whole by the next part, except the first conversation of a call,
|
|
26
|
+
* which always finishes so every part makes progress. A rejected credential, persistent rate
|
|
27
|
+
* limiting or a Teams-side failure stops the run the same way, keeping what
|
|
28
|
+
* was written; any other failure to read one conversation is recorded in
|
|
29
|
+
* `errors` and the export moves on.
|
|
30
|
+
*
|
|
31
|
+
* Reading a conversation is `readFrom`'s rule: the chat service pages newest
|
|
32
|
+
* CHANGE first, so the read stops at the first message whose last change is
|
|
33
|
+
* before `since` (or the resume position), and messages are then taken by
|
|
34
|
+
* arrival, oldest first (`takePage`).
|
|
35
|
+
*
|
|
36
|
+
* With `attachments: true` each conversation's inline images and shared files
|
|
37
|
+
* are written beside it before its file is rendered, so every record carries
|
|
38
|
+
* their export paths (or why one was skipped) — see `export-attachments.ts`.
|
|
39
|
+
*/
|
|
40
|
+
import { createHash } from 'node:crypto';
|
|
41
|
+
import { z } from 'zod';
|
|
42
|
+
import { currentCallSignal, McpToolError, reportProgress, throwIfCancelled, toolAnnotations, } from '@chrischall/mcp-utils';
|
|
43
|
+
import { decodeExportCursor, encodeExportCursor, exportPartName, openExportSink, sanitizeExportFileName, } from '@chrischall/mcp-utils/export';
|
|
44
|
+
import { changedMs, conversationSummary, isUserMessage, lastChangeMs, normaliseMessage, summariseAll, } from '../model.js';
|
|
45
|
+
import { AmbiguousConversationError, ambiguousResult, arrivalMs, listedResolver } from './conversation.js';
|
|
46
|
+
import { wrapApiError } from './errors.js';
|
|
47
|
+
import { EXPORT_EXT, EXPORT_FORMATS, EXPORT_UNTRUSTED_NOTE, renderConversation, } from './export-format.js';
|
|
48
|
+
import { exportAttachments } from './export-attachments.js';
|
|
49
|
+
import { takePage } from './from.js';
|
|
50
|
+
import { conversationName, enrichTitles } from './titles.js';
|
|
51
|
+
import { resolveTimeZone, tzArg } from './timezone.js';
|
|
52
|
+
import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
|
|
53
|
+
import { workMeta } from './hints.js';
|
|
54
|
+
export const EXPORT_SERVER_NAME = 'microsoft-teams-mcp';
|
|
55
|
+
export const EXPORT_OUTPUT_ENV = 'TEAMS_OUTPUT_DIR';
|
|
56
|
+
export const DEFAULT_MAX_ITEMS = 5000;
|
|
57
|
+
export const MAX_ITEMS = 50_000;
|
|
58
|
+
export const DEFAULT_BUDGET_SECONDS = 90;
|
|
59
|
+
export const MAX_BUDGET_SECONDS = 600;
|
|
60
|
+
/** Conversations one call may name. */
|
|
61
|
+
export const MAX_NAMED_CONVERSATIONS = 200;
|
|
62
|
+
/** Raw messages read per conversation (250 pages of 200) before the oldest are reported as not exported. */
|
|
63
|
+
export const EXPORT_MAX_RAW = 50_000;
|
|
64
|
+
export const EXPORT_MAX_PAGES = 250;
|
|
65
|
+
/**
|
|
66
|
+
* Waits before each retry of a rate-limited read; after the last, the export stops with a cursor.
|
|
67
|
+
* Fixed rather than Retry-After driven: chatsvc's 429 McpToolError carries the status but not the
|
|
68
|
+
* header, so there is no server-given wait to honour.
|
|
69
|
+
*/
|
|
70
|
+
export const RATE_LIMIT_RETRY_MS = [2_000, 4_000, 8_000];
|
|
71
|
+
/** Files listed in the result; the manifest file lists them all. */
|
|
72
|
+
const RESULT_FILES_CAP = 50;
|
|
73
|
+
/** Errors listed in the result; the manifest file lists them all. */
|
|
74
|
+
const RESULT_ERRORS_CAP = 20;
|
|
75
|
+
export const EXPORT_KINDS = ['chat', 'channel', 'meeting'];
|
|
76
|
+
const KINDS = {
|
|
77
|
+
chat: ['oneOnOne', 'group', 'self'],
|
|
78
|
+
channel: ['channel'],
|
|
79
|
+
meeting: ['meeting'],
|
|
80
|
+
};
|
|
81
|
+
/** An ISO 8601 date or date-time; one with a time but no zone is read as UTC. */
|
|
82
|
+
function parseIsoTime(s) {
|
|
83
|
+
const zoned = /T\d{2}:\d{2}(:\d{2}(\.\d+)?)?$/.test(s) ? `${s}Z` : s;
|
|
84
|
+
return /^\d{4}-\d{2}-\d{2}/.test(s) ? Date.parse(zoned) : Number.NaN;
|
|
85
|
+
}
|
|
86
|
+
const isoTimeArg = (what) => z
|
|
87
|
+
.string()
|
|
88
|
+
.refine((s) => !Number.isNaN(parseIsoTime(s)), { message: `${what} must be an ISO 8601 date or date-time` })
|
|
89
|
+
.optional();
|
|
90
|
+
const conversationsArg = z.union([
|
|
91
|
+
z.string().min(1),
|
|
92
|
+
z.array(z.string().min(1)).min(1).max(MAX_NAMED_CONVERSATIONS),
|
|
93
|
+
]);
|
|
94
|
+
const kindsArg = z.array(z.enum(EXPORT_KINDS)).min(1);
|
|
95
|
+
/** The arguments an export keeps across its parts (in the cursor). */
|
|
96
|
+
const storedArgs = z
|
|
97
|
+
.object({
|
|
98
|
+
conversations: conversationsArg.optional(),
|
|
99
|
+
kinds: kindsArg.optional(),
|
|
100
|
+
since: isoTimeArg('since'),
|
|
101
|
+
until: isoTimeArg('until'),
|
|
102
|
+
format: z.enum(EXPORT_FORMATS),
|
|
103
|
+
attachments: z.boolean().optional(),
|
|
104
|
+
tz: tzArg,
|
|
105
|
+
})
|
|
106
|
+
.strict();
|
|
107
|
+
const resumeSchema = z.object({
|
|
108
|
+
exportId: z.string(),
|
|
109
|
+
part: z.number().int().min(2),
|
|
110
|
+
dir: z.string().optional(),
|
|
111
|
+
args: storedArgs,
|
|
112
|
+
ids: z.array(z.string().min(1)).min(1).optional(),
|
|
113
|
+
from_id: z.string().min(1).optional(),
|
|
114
|
+
pos: z
|
|
115
|
+
.object({ id: z.string().min(1), t: z.number().finite().min(0), s: z.array(z.string()).optional() })
|
|
116
|
+
.optional(),
|
|
117
|
+
});
|
|
118
|
+
function badCursor() {
|
|
119
|
+
return new McpToolError('The export cursor is not valid.', {
|
|
120
|
+
hint: 'Pass the cursor exactly as the previous call returned it, or start a new export without one.',
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
function decodeResume(cursor) {
|
|
124
|
+
const { v: _v, ...state } = decodeExportCursor(cursor);
|
|
125
|
+
const parsed = resumeSchema.safeParse(state);
|
|
126
|
+
if (!parsed.success || (parsed.data.ids === undefined) === (parsed.data.from_id === undefined))
|
|
127
|
+
throw badCursor();
|
|
128
|
+
return parsed.data;
|
|
129
|
+
}
|
|
130
|
+
/** A short, stable, filename-safe tag for a conversation id. */
|
|
131
|
+
export function shortId(id) {
|
|
132
|
+
return createHash('sha256').update(id).digest('hex').slice(0, 8);
|
|
133
|
+
}
|
|
134
|
+
/** Whether a failure to read one conversation should stop the export (with a cursor) rather than skip it. */
|
|
135
|
+
function stopsExport(err) {
|
|
136
|
+
if (!(err instanceof McpToolError))
|
|
137
|
+
return true; // a token capture failure, or something unexpected
|
|
138
|
+
if (err.status === 401 || err.status === 429 || (err.status !== undefined && err.status >= 500))
|
|
139
|
+
return true;
|
|
140
|
+
return ['no_credential', 'credential_rejected', 'session_expired', 'transport', 'timeout'].includes(err.kind ?? '');
|
|
141
|
+
}
|
|
142
|
+
/** Thrown from between pages of a read when the call's time budget is spent; the read is redone next part. */
|
|
143
|
+
class BudgetSpent extends Error {
|
|
144
|
+
}
|
|
145
|
+
const isRateLimited = (err) => err instanceof McpToolError && err.status === 429;
|
|
146
|
+
async function withRateLimitRetry(fn, sleep) {
|
|
147
|
+
for (let attempt = 0;; attempt++) {
|
|
148
|
+
try {
|
|
149
|
+
return await fn();
|
|
150
|
+
}
|
|
151
|
+
catch (err) {
|
|
152
|
+
if (!isRateLimited(err) || attempt >= RATE_LIMIT_RETRY_MS.length)
|
|
153
|
+
throw err;
|
|
154
|
+
await sleep(RATE_LIMIT_RETRY_MS[attempt]);
|
|
155
|
+
throwIfCancelled();
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
const realSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
160
|
+
/** The conversations an export covers, in id order: the named ones, or every one listed, narrowed by kind and `since`. */
|
|
161
|
+
async function selectConversations(chatsvc, raw, me, args, since) {
|
|
162
|
+
const kinds = new Set((args.kinds ?? EXPORT_KINDS).flatMap((k) => KINDS[k]));
|
|
163
|
+
let summaries;
|
|
164
|
+
if (args.conversations !== undefined) {
|
|
165
|
+
const resolve = listedResolver(chatsvc, raw, me, 'export');
|
|
166
|
+
const named = Array.isArray(args.conversations) ? args.conversations : [args.conversations];
|
|
167
|
+
summaries = [];
|
|
168
|
+
for (const n of new Set(named))
|
|
169
|
+
summaries.push(await resolve(n));
|
|
170
|
+
}
|
|
171
|
+
else {
|
|
172
|
+
summaries = raw.map((c) => conversationSummary(c, me, raw));
|
|
173
|
+
}
|
|
174
|
+
const byId = new Map(raw.map((c) => [c.id, c]));
|
|
175
|
+
const ids = new Set();
|
|
176
|
+
for (const s of summaries) {
|
|
177
|
+
if (!kinds.has(s.kind))
|
|
178
|
+
continue;
|
|
179
|
+
const conv = byId.get(s.id);
|
|
180
|
+
// Nothing changed in it since `since`, so nothing arrived since: no need to read it.
|
|
181
|
+
const changed = conv !== undefined ? lastChangeMs(conv) : undefined;
|
|
182
|
+
if (since !== undefined && changed !== undefined && changed < since)
|
|
183
|
+
continue;
|
|
184
|
+
ids.add(s.id);
|
|
185
|
+
}
|
|
186
|
+
return [...ids].sort();
|
|
187
|
+
}
|
|
188
|
+
/** The people other than the user known to be in a chat: its titled participants, then who wrote what is exported. */
|
|
189
|
+
function chatParticipants(titled, messages) {
|
|
190
|
+
const out = [];
|
|
191
|
+
const seen = new Set();
|
|
192
|
+
const add = (name) => {
|
|
193
|
+
const key = name.trim().toLowerCase();
|
|
194
|
+
if (key === '' || seen.has(key))
|
|
195
|
+
return;
|
|
196
|
+
seen.add(key);
|
|
197
|
+
out.push(name);
|
|
198
|
+
};
|
|
199
|
+
for (const p of titled.participants ?? [])
|
|
200
|
+
add(p);
|
|
201
|
+
for (const m of [...messages].reverse())
|
|
202
|
+
if (!m.fromMe)
|
|
203
|
+
add(m.sender);
|
|
204
|
+
return out;
|
|
205
|
+
}
|
|
206
|
+
/** Arguments that start an export, which a cursor already carries. */
|
|
207
|
+
const STARTING_ARGS = ['conversations', 'kinds', 'since', 'until', 'format', 'attachments', 'dest', 'tz'];
|
|
208
|
+
async function runExport({ chatsvc, sharepoint }, input, opts) {
|
|
209
|
+
const clock = opts.now ?? Date.now;
|
|
210
|
+
const sleep = opts.sleep ?? realSleep;
|
|
211
|
+
const started = clock();
|
|
212
|
+
let resume;
|
|
213
|
+
if (input.cursor !== undefined) {
|
|
214
|
+
const clash = STARTING_ARGS.find((k) => input[k] !== undefined);
|
|
215
|
+
if (clash !== undefined) {
|
|
216
|
+
throw new McpToolError(`cursor cannot be combined with ${clash}.`, {
|
|
217
|
+
hint: 'A cursor carries the export\'s original arguments: pass only cursor (and optionally max_items / budget_seconds).',
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
resume = decodeResume(input.cursor);
|
|
221
|
+
}
|
|
222
|
+
const args = resume?.args ?? {
|
|
223
|
+
...(input.conversations !== undefined ? { conversations: input.conversations } : {}),
|
|
224
|
+
...(input.kinds !== undefined ? { kinds: input.kinds } : {}),
|
|
225
|
+
...(input.since !== undefined ? { since: input.since } : {}),
|
|
226
|
+
...(input.until !== undefined ? { until: input.until } : {}),
|
|
227
|
+
format: input.format ?? 'jsonl',
|
|
228
|
+
...(input.attachments === true ? { attachments: true } : {}),
|
|
229
|
+
...(input.tz !== undefined ? { tz: input.tz } : {}),
|
|
230
|
+
};
|
|
231
|
+
const since = args.since !== undefined ? parseIsoTime(args.since) : undefined;
|
|
232
|
+
const until = args.until !== undefined ? parseIsoTime(args.until) : undefined;
|
|
233
|
+
if (since !== undefined && until !== undefined && since > until) {
|
|
234
|
+
throw new McpToolError('since is after until.', { hint: 'Pass a since at or before until.' });
|
|
235
|
+
}
|
|
236
|
+
const timeZone = resolveTimeZone(args.tz);
|
|
237
|
+
const maxItems = input.max_items ?? DEFAULT_MAX_ITEMS;
|
|
238
|
+
const budgetMs = (input.budget_seconds ?? DEFAULT_BUDGET_SECONDS) * 1000;
|
|
239
|
+
let raw;
|
|
240
|
+
let me;
|
|
241
|
+
try {
|
|
242
|
+
[raw, me] = await Promise.all([chatsvc.listConversations(), chatsvc.meMri()]);
|
|
243
|
+
}
|
|
244
|
+
catch (err) {
|
|
245
|
+
throw wrapApiError(err, 'list conversations to export');
|
|
246
|
+
}
|
|
247
|
+
let account;
|
|
248
|
+
try {
|
|
249
|
+
account = (await chatsvc.meDisplayName()) || undefined;
|
|
250
|
+
}
|
|
251
|
+
catch {
|
|
252
|
+
account = undefined;
|
|
253
|
+
}
|
|
254
|
+
let queue;
|
|
255
|
+
if (resume?.ids !== undefined) {
|
|
256
|
+
queue = resume.ids;
|
|
257
|
+
}
|
|
258
|
+
else {
|
|
259
|
+
let selected;
|
|
260
|
+
try {
|
|
261
|
+
selected = await selectConversations(chatsvc, raw, me, args, since);
|
|
262
|
+
}
|
|
263
|
+
catch (err) {
|
|
264
|
+
// A fresh export hands back the candidates, having written nothing.
|
|
265
|
+
if (err instanceof AmbiguousConversationError && resume === undefined)
|
|
266
|
+
return untrustedResult(ambiguousResult(err));
|
|
267
|
+
throw wrapApiError(err, 'resolve the conversations to export');
|
|
268
|
+
}
|
|
269
|
+
queue = resume?.from_id !== undefined ? selected.filter((id) => id >= resume.from_id) : selected;
|
|
270
|
+
}
|
|
271
|
+
const sink = await openExportSink({
|
|
272
|
+
name: EXPORT_SERVER_NAME,
|
|
273
|
+
envVar: EXPORT_OUTPUT_ENV,
|
|
274
|
+
baseName: 'teams-export',
|
|
275
|
+
...(input.dest !== undefined ? { dest: input.dest } : {}),
|
|
276
|
+
...(resume !== undefined ? { exportId: resume.exportId, part: resume.part } : {}),
|
|
277
|
+
...(resume?.dir !== undefined ? { existingDir: resume.dir } : {}),
|
|
278
|
+
...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),
|
|
279
|
+
...(currentCallSignal() !== undefined ? { signal: currentCallSignal() } : {}),
|
|
280
|
+
});
|
|
281
|
+
const header = {
|
|
282
|
+
source: 'microsoft-teams',
|
|
283
|
+
...(account !== undefined ? { account } : {}),
|
|
284
|
+
generated_at: new Date(clock()).toISOString(),
|
|
285
|
+
export_id: sink.exportId,
|
|
286
|
+
part: sink.part,
|
|
287
|
+
args,
|
|
288
|
+
};
|
|
289
|
+
const summaries = new Map(summariseAll(raw, me).map((s) => [s.id, s]));
|
|
290
|
+
const files = [];
|
|
291
|
+
const errors = [];
|
|
292
|
+
const attachmentsWritten = [];
|
|
293
|
+
let attachmentsSkipped = 0;
|
|
294
|
+
let written = 0;
|
|
295
|
+
let oldest;
|
|
296
|
+
let newest;
|
|
297
|
+
let hasMore = false;
|
|
298
|
+
let pos = resume?.pos;
|
|
299
|
+
let stopPos;
|
|
300
|
+
const total = queue.length;
|
|
301
|
+
let done = 0;
|
|
302
|
+
const overBudget = () => clock() - started >= budgetMs;
|
|
303
|
+
while (queue.length > 0) {
|
|
304
|
+
if (written >= maxItems || overBudget()) {
|
|
305
|
+
hasMore = true;
|
|
306
|
+
break;
|
|
307
|
+
}
|
|
308
|
+
throwIfCancelled();
|
|
309
|
+
const id = queue[0];
|
|
310
|
+
const resumed = pos !== undefined && pos.id === id ? pos : undefined;
|
|
311
|
+
pos = undefined;
|
|
312
|
+
const summary = summaries.get(id) ?? conversationSummary({ id }, me);
|
|
313
|
+
const [titled] = await enrichTitles(chatsvc, raw, me, [summary]);
|
|
314
|
+
const start = resumed !== undefined ? { t: resumed.t, seen: resumed.s ?? [] } : { t: since ?? 0, seen: [] };
|
|
315
|
+
// The first conversation of a call always reads to the end, so every part makes progress;
|
|
316
|
+
// a later one is cut between pages once the budget is spent and re-read by the next part.
|
|
317
|
+
const cuttable = done > 0;
|
|
318
|
+
let fetched;
|
|
319
|
+
let capped = false;
|
|
320
|
+
try {
|
|
321
|
+
fetched = await withRateLimitRetry(() => chatsvc.getMessages(id, {
|
|
322
|
+
stopAt: (m) => {
|
|
323
|
+
throwIfCancelled();
|
|
324
|
+
return start.t > 0 && changedMs(m) < start.t;
|
|
325
|
+
},
|
|
326
|
+
max: EXPORT_MAX_RAW,
|
|
327
|
+
maxPages: EXPORT_MAX_PAGES,
|
|
328
|
+
onCapped: () => (capped = true),
|
|
329
|
+
onPage: async (pages, messages) => {
|
|
330
|
+
throwIfCancelled();
|
|
331
|
+
if (cuttable && overBudget())
|
|
332
|
+
throw new BudgetSpent();
|
|
333
|
+
await reportProgress(done, total, `${done}/${total} conversations; reading page ${pages + 1} (${messages} messages so far)`);
|
|
334
|
+
},
|
|
335
|
+
}), sleep);
|
|
336
|
+
}
|
|
337
|
+
catch (err) {
|
|
338
|
+
if (currentCallSignal()?.aborted)
|
|
339
|
+
throw err;
|
|
340
|
+
if (err instanceof BudgetSpent) {
|
|
341
|
+
hasMore = true;
|
|
342
|
+
stopPos = resumed;
|
|
343
|
+
break;
|
|
344
|
+
}
|
|
345
|
+
const e = wrapApiError(err, 'read this conversation');
|
|
346
|
+
errors.push({
|
|
347
|
+
conversation: { id, title: titled.title },
|
|
348
|
+
error: e.message,
|
|
349
|
+
...(e.hint !== undefined ? { hint: e.hint } : {}),
|
|
350
|
+
});
|
|
351
|
+
if (stopsExport(err)) {
|
|
352
|
+
hasMore = true;
|
|
353
|
+
stopPos = resumed;
|
|
354
|
+
break;
|
|
355
|
+
}
|
|
356
|
+
queue.shift();
|
|
357
|
+
done++;
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
const wanted = fetched.filter((m) => isUserMessage(m) && (until === undefined || arrivalMs(m) <= until));
|
|
361
|
+
const { page, has_more, next } = takePage(wanted.map((m) => ({ ms: arrivalMs(m), key: m.id, item: m })), start, maxItems - written);
|
|
362
|
+
if (capped) {
|
|
363
|
+
errors.push({
|
|
364
|
+
conversation: { id, title: titled.title },
|
|
365
|
+
error: `Only the newest ${EXPORT_MAX_RAW} messages of this conversation could be read; older ones were not ` +
|
|
366
|
+
'exported.',
|
|
367
|
+
hint: 'Export it again with a later since to cover the rest in a separate export.',
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
if (page.length > 0) {
|
|
371
|
+
const normalised = page.map((m) => normaliseMessage(m, me, { timeZone }));
|
|
372
|
+
let messages = normalised;
|
|
373
|
+
if (args.attachments === true) {
|
|
374
|
+
const got = await exportAttachments({ chatsvc, sharepoint }, sink, shortId(id), id, normalised);
|
|
375
|
+
messages = got.messages;
|
|
376
|
+
attachmentsWritten.push(...got.written);
|
|
377
|
+
attachmentsSkipped += got.skipped;
|
|
378
|
+
}
|
|
379
|
+
const { participants: _named, ...named } = conversationName(titled);
|
|
380
|
+
const conversation = {
|
|
381
|
+
...named,
|
|
382
|
+
...(titled.kind !== 'channel' ? { participants: chatParticipants(titled, normalised) } : {}),
|
|
383
|
+
};
|
|
384
|
+
const ext = EXPORT_EXT[args.format];
|
|
385
|
+
const stem = `${sanitizeExportFileName(titled.title, 80)}-${shortId(id)}`;
|
|
386
|
+
// A conversation continued from an earlier part goes in a part-numbered file beside its first.
|
|
387
|
+
const name = resumed !== undefined ? `${stem}.${exportPartName(sink.part, ext)}` : `${stem}.${ext}`;
|
|
388
|
+
const rec = await sink.addFile(name, renderConversation(args.format, header, conversation, messages));
|
|
389
|
+
files.push({
|
|
390
|
+
name,
|
|
391
|
+
...(rec.path !== undefined ? { path: rec.path } : {}),
|
|
392
|
+
bytes: rec.bytes,
|
|
393
|
+
records: messages.length,
|
|
394
|
+
conversation: { id, kind: titled.kind, title: titled.title },
|
|
395
|
+
});
|
|
396
|
+
written += messages.length;
|
|
397
|
+
const first = messages[0].time;
|
|
398
|
+
const last = messages.at(-1).time;
|
|
399
|
+
if (oldest === undefined || first < oldest)
|
|
400
|
+
oldest = first;
|
|
401
|
+
if (newest === undefined || last > newest)
|
|
402
|
+
newest = last;
|
|
403
|
+
}
|
|
404
|
+
if (has_more) {
|
|
405
|
+
hasMore = true;
|
|
406
|
+
stopPos = { id, t: next.t, ...(next.seen.length > 0 ? { s: [...next.seen] } : {}) };
|
|
407
|
+
break;
|
|
408
|
+
}
|
|
409
|
+
queue.shift();
|
|
410
|
+
done++;
|
|
411
|
+
await reportProgress(done, total, `${done}/${total} conversations`);
|
|
412
|
+
}
|
|
413
|
+
const counts = {
|
|
414
|
+
conversations: files.length,
|
|
415
|
+
messages: written,
|
|
416
|
+
attachments: attachmentsWritten.length,
|
|
417
|
+
attachments_skipped: attachmentsSkipped,
|
|
418
|
+
};
|
|
419
|
+
const span = oldest !== undefined && newest !== undefined ? { oldest, newest } : undefined;
|
|
420
|
+
let cursor;
|
|
421
|
+
if (hasMore && queue.length > 0) {
|
|
422
|
+
const base = {
|
|
423
|
+
exportId: sink.exportId,
|
|
424
|
+
part: sink.part + 1,
|
|
425
|
+
...(sink.dir !== undefined ? { dir: sink.dir } : {}),
|
|
426
|
+
args,
|
|
427
|
+
...(stopPos !== undefined ? { pos: stopPos } : {}),
|
|
428
|
+
};
|
|
429
|
+
try {
|
|
430
|
+
cursor = encodeExportCursor({ ...base, ids: queue });
|
|
431
|
+
}
|
|
432
|
+
catch (err) {
|
|
433
|
+
if (!(err instanceof TypeError))
|
|
434
|
+
throw err;
|
|
435
|
+
cursor = encodeExportCursor({ ...base, from_id: queue[0] });
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
else {
|
|
439
|
+
hasMore = false;
|
|
440
|
+
}
|
|
441
|
+
const manifestName = sink.part === 1 ? 'manifest.json' : `manifest.${exportPartName(sink.part, 'json')}`;
|
|
442
|
+
const manifest = await sink.addFile(manifestName, `${JSON.stringify({
|
|
443
|
+
...header,
|
|
444
|
+
note: EXPORT_UNTRUSTED_NOTE,
|
|
445
|
+
files: files.map(({ path: _p, ...f }) => f),
|
|
446
|
+
...(attachmentsWritten.length > 0 ? { attachments: attachmentsWritten } : {}),
|
|
447
|
+
counts,
|
|
448
|
+
...(span !== undefined ? { span } : {}),
|
|
449
|
+
has_more: hasMore,
|
|
450
|
+
...(errors.length > 0 ? { errors } : {}),
|
|
451
|
+
}, null, 2)}\n`);
|
|
452
|
+
const loc = await sink.finish();
|
|
453
|
+
return untrustedResult({
|
|
454
|
+
mode: loc.mode,
|
|
455
|
+
location: loc.location,
|
|
456
|
+
...(loc.urlExpiresAt !== undefined ? { url_expires_at: loc.urlExpiresAt } : {}),
|
|
457
|
+
export_id: loc.exportId,
|
|
458
|
+
part: loc.part,
|
|
459
|
+
manifest: manifest.path ?? manifest.name,
|
|
460
|
+
files: files
|
|
461
|
+
.slice(0, RESULT_FILES_CAP)
|
|
462
|
+
.map((f) => ({ ...(f.path !== undefined ? { path: f.path } : { name: f.name }), bytes: f.bytes, records: f.records })),
|
|
463
|
+
...(files.length > RESULT_FILES_CAP ? { files_truncated: files.length - RESULT_FILES_CAP } : {}),
|
|
464
|
+
counts,
|
|
465
|
+
...(span !== undefined ? { span } : {}),
|
|
466
|
+
has_more: hasMore,
|
|
467
|
+
...(cursor !== undefined ? { cursor } : {}),
|
|
468
|
+
...(errors.length > 0 ? { errors: errors.slice(0, RESULT_ERRORS_CAP) } : {}),
|
|
469
|
+
...(errors.length > RESULT_ERRORS_CAP ? { errors_truncated: errors.length - RESULT_ERRORS_CAP } : {}),
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
export function registerExportTools(server, deps, opts = {}) {
|
|
473
|
+
server.registerTool('teams_export_messages', {
|
|
474
|
+
title: 'Export Teams chats and channels to files',
|
|
475
|
+
description: 'Bulk-export the messages of chats and channels to files — for archiving, or to search or analyse ' +
|
|
476
|
+
'thousands of messages with shell tools — without any message text entering this conversation. The ' +
|
|
477
|
+
'result holds no message content: only where the files are (on a local install, absolute paths in a ' +
|
|
478
|
+
`fresh folder under dest, else ${EXPORT_OUTPUT_ENV}, else ~/Downloads/${EXPORT_SERVER_NAME}; on a hosted ` +
|
|
479
|
+
'install, a signed download link to a zip that expires, url_expires_at), each file\'s size and record ' +
|
|
480
|
+
'count, counts, the time span, errors, and has_more / cursor. One file per conversation, named after it ' +
|
|
481
|
+
'(an untitled group chat after its participants), plus a manifest; JSONL by default (a header record ' +
|
|
482
|
+
'with the export\'s details and an untrusted-content note, then one record per message, oldest first, ' +
|
|
483
|
+
'each with its conversation\'s id, kind, title, team and — for chats — participants), or format ' +
|
|
484
|
+
'"markdown" for readable transcripts (a channel threaded under its root posts). Use jq, grep or rg on ' +
|
|
485
|
+
'the files rather than reading them whole. conversations names chats/channels by id or name (omit for ' +
|
|
486
|
+
'every one), kinds narrows to chat / channel / meeting, since and until bound messages by arrival ' +
|
|
487
|
+
'(default: all history). Each call stops at max_items messages ' +
|
|
488
|
+
`(default ${DEFAULT_MAX_ITEMS}, max ${MAX_ITEMS}) or budget_seconds (default ${DEFAULT_BUDGET_SECONDS}, ` +
|
|
489
|
+
`max ${MAX_BUDGET_SECONDS}); when has_more is true pass cursor back (alone, or with max_items / ` +
|
|
490
|
+
'budget_seconds) to continue the same export into the same folder (a hosted install returns a new link ' +
|
|
491
|
+
'per part). A cursor too long to list every remaining conversation resumes from an id instead, so a ' +
|
|
492
|
+
'conversation that first appears between parts may be left out. A rejected credential or persistent rate limiting stops early with a cursor and keeps what ' +
|
|
493
|
+
'was written; a conversation that cannot be read is listed in errors and skipped. Never marks anything ' +
|
|
494
|
+
'read. A name matching several conversations returns {ambiguous: true, candidates} and writes nothing. ' +
|
|
495
|
+
'With attachments true, inline images and shared files (up to 25 MB) are saved under ' +
|
|
496
|
+
'attachments/<conversation>/<message id>-<name> and each message\'s record lists them by that path ' +
|
|
497
|
+
'relative to the export folder; one that cannot be fetched (a SharePoint file the account cannot ' +
|
|
498
|
+
'open, no token yet, too large) is listed as skipped with the reason, never failing the export.' +
|
|
499
|
+
UNTRUSTED_DESCRIPTION_SUFFIX,
|
|
500
|
+
annotations: toolAnnotations({ readOnly: true, openWorld: true }),
|
|
501
|
+
_meta: workMeta('other', { aliases: ['export', 'save the chat', 'chat history'] }),
|
|
502
|
+
inputSchema: {
|
|
503
|
+
conversations: conversationsArg
|
|
504
|
+
.optional()
|
|
505
|
+
.describe('Chats/channels to export: an id ("48:notes" for the self-chat) or a case-insensitive substring of a ' +
|
|
506
|
+
`title, channel, team or participant name, or an array of up to ${MAX_NAMED_CONVERSATIONS}. Omit to ` +
|
|
507
|
+
'export every conversation.'),
|
|
508
|
+
kinds: kindsArg
|
|
509
|
+
.optional()
|
|
510
|
+
.describe('Only these kinds: chat (1:1, group chats, the self-chat), channel, meeting. Default all.'),
|
|
511
|
+
since: isoTimeArg('since').describe('Only messages that arrived at or after this ISO 8601 date/time (UTC when it names no zone). Default: all history.'),
|
|
512
|
+
until: isoTimeArg('until').describe('Only messages that arrived at or before this ISO 8601 date/time. Default: now.'),
|
|
513
|
+
format: z
|
|
514
|
+
.enum(EXPORT_FORMATS)
|
|
515
|
+
.optional()
|
|
516
|
+
.describe('jsonl (default: one JSON record per message) or markdown (readable transcripts).'),
|
|
517
|
+
attachments: z
|
|
518
|
+
.boolean()
|
|
519
|
+
.optional()
|
|
520
|
+
.describe('Also download each message\'s inline images and shared files (up to 25 MB each) into ' +
|
|
521
|
+
'attachments/<conversation>/<message id>-<name>; each record lists them with that relative path, ' +
|
|
522
|
+
'or skipped and why. Default false.'),
|
|
523
|
+
dest: z
|
|
524
|
+
.string()
|
|
525
|
+
.min(1)
|
|
526
|
+
.optional()
|
|
527
|
+
.describe(`Local install only: the folder to create the export folder in (under ${EXPORT_OUTPUT_ENV} when set, ` +
|
|
528
|
+
'else under ~/Downloads, ~/Documents or ~/Desktop). Default: ' +
|
|
529
|
+
`${EXPORT_OUTPUT_ENV}, else ~/Downloads/${EXPORT_SERVER_NAME}.`),
|
|
530
|
+
cursor: z
|
|
531
|
+
.string()
|
|
532
|
+
.min(1)
|
|
533
|
+
.optional()
|
|
534
|
+
.describe('A previous result\'s cursor, unchanged, to continue that export. Pass no other argument but max_items / budget_seconds.'),
|
|
535
|
+
max_items: z
|
|
536
|
+
.number()
|
|
537
|
+
.int()
|
|
538
|
+
.min(1)
|
|
539
|
+
.max(MAX_ITEMS)
|
|
540
|
+
.optional()
|
|
541
|
+
.describe(`Most messages this call writes (default ${DEFAULT_MAX_ITEMS}, max ${MAX_ITEMS}).`),
|
|
542
|
+
budget_seconds: z
|
|
543
|
+
.number()
|
|
544
|
+
.int()
|
|
545
|
+
.min(1)
|
|
546
|
+
.max(MAX_BUDGET_SECONDS)
|
|
547
|
+
.optional()
|
|
548
|
+
.describe(`Seconds this call may spend before stopping with a cursor (default ${DEFAULT_BUDGET_SECONDS}, max ${MAX_BUDGET_SECONDS}).`),
|
|
549
|
+
tz: tzArg,
|
|
550
|
+
},
|
|
551
|
+
}, async (input) => runExport(deps, input, opts));
|
|
552
|
+
}
|
package/dist/tools/format.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Output-size modes for the read tools (`
|
|
3
|
-
* `
|
|
2
|
+
* Output-size modes for the read tools (`teams_list_messages`,
|
|
3
|
+
* `teams_list_unread_messages`): how much of each conversation a result carries.
|
|
4
4
|
*
|
|
5
5
|
* - `full` (default) — every message field and the whole conversation summary,
|
|
6
6
|
* exactly as before.
|
|
@@ -70,7 +70,7 @@ function compactMessage(m) {
|
|
|
70
70
|
};
|
|
71
71
|
}
|
|
72
72
|
/**
|
|
73
|
-
* One message of a flat, cross-conversation list (`
|
|
73
|
+
* One message of a flat, cross-conversation list (`teams_list_unread_messages` with
|
|
74
74
|
* `from`): whole in full; compact, but keeping `replyTo`, since no thread
|
|
75
75
|
* grouping says what a channel reply answers. Summary has no messages.
|
|
76
76
|
*/
|
package/dist/tools/from.js
CHANGED
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
* reading everything that changed since `from` and taking its oldest: a call
|
|
18
18
|
* costs what has happened since its `from`, not its `limit`. Reads therefore
|
|
19
19
|
* stop on a message's last change, not its arrival (`changedMs`, as
|
|
20
|
-
* `
|
|
20
|
+
* `teams_list_changed_conversations` learned), and run deeper than other reads
|
|
21
21
|
* ({@link FROM_MAX_RAW}); a conversation busier than that since `from` cannot
|
|
22
22
|
* be paged oldest first and says so.
|
|
23
23
|
*/
|
package/dist/tools/limit.js
CHANGED
|
@@ -55,7 +55,7 @@ export function filterSince(rows, since) {
|
|
|
55
55
|
});
|
|
56
56
|
}
|
|
57
57
|
/**
|
|
58
|
-
* The `stopAt` behind `
|
|
58
|
+
* The `stopAt` behind `teams_list_messages` and `teams_list_unread_messages`. It
|
|
59
59
|
* sees each message once, newest first, so it can count: the first wanted
|
|
60
60
|
* message past `limit` is the boundary, and its existence is what says the
|
|
61
61
|
* result was truncated. `horizon` (when given) ends the read at the first
|
package/dist/tools/listing.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The conversation listing shared by `
|
|
3
|
-
* `
|
|
2
|
+
* The conversation listing shared by `teams_list_conversations` and
|
|
3
|
+
* `teams_list_channels`: one `listConversations` call, normalised
|
|
4
4
|
* against the signed-in user, then filtered by kind, unread state and query.
|
|
5
5
|
* With `unread_only`, the listing's unread flag only nominates candidates; each
|
|
6
6
|
* is confirmed by reading past its horizon (`confirm.ts`).
|
|
@@ -9,7 +9,7 @@ import { z } from 'zod';
|
|
|
9
9
|
import { confirmedSummary, confirmUnreadCandidates, olderUnreadArg, olderUnreadConversations, olderUnreadReport, sinceCutoff, sinceDaysArg, } from './confirm.js';
|
|
10
10
|
import { wrapApiError } from './errors.js';
|
|
11
11
|
import { searchRecentMessages } from './chat-search.js';
|
|
12
|
-
import { enrichTitles } from './titles.js';
|
|
12
|
+
import { enrichTitles, participantsOf } from './titles.js';
|
|
13
13
|
import { conversationSummary, matchConversations, SELF_CHAT, SELF_CHAT_ALIASES, } from '../model.js';
|
|
14
14
|
/**
|
|
15
15
|
* Whether a conversation's last activity falls in `[since, until]` (either
|
|
@@ -38,7 +38,7 @@ export const unreadOnlyArg = z
|
|
|
38
38
|
export const UNREAD_HINT_DESCRIPTION = 'Without unread_only, unread is only a hint from the listing (unread_confirmed: false): it can ' +
|
|
39
39
|
'flag a conversation whose only news is a call recording or other system event. For an exact ' +
|
|
40
40
|
'answer use unread_only (confirmed rows carry unread_confirmed: true and unread_count) or ' +
|
|
41
|
-
'
|
|
41
|
+
'teams_list_unread_messages.';
|
|
42
42
|
/** Real unread messages counted per candidate before unread_count is reported as a lower bound. */
|
|
43
43
|
const CONFIRM_LIMIT = 50;
|
|
44
44
|
/** Raw messages read per candidate — one page; the horizon is usually much nearer. */
|
|
@@ -68,9 +68,10 @@ export const MATCH_REASON_DESCRIPTION = 'With a query, each row carries match_re
|
|
|
68
68
|
'"participant" (an untitled chat\'s participant) or "message" (what was said, not what the ' +
|
|
69
69
|
'conversation is called) that applies.';
|
|
70
70
|
/** Description text on how an untitled group chat or 1:1 is titled. */
|
|
71
|
-
export const GROUP_TITLE_DESCRIPTION = 'A group chat with no topic is titled "Group chat: " and
|
|
72
|
-
'than the user,
|
|
73
|
-
'
|
|
71
|
+
export const GROUP_TITLE_DESCRIPTION = 'A group chat with no topic is titled "Group chat: " and the first three of its recent senders other ' +
|
|
72
|
+
'than the user, sorted by name ("; " between names, "+N" for more) — so it does not change when a ' +
|
|
73
|
+
'different person posts last — and carries every such recent sender, in that order, as participants; ' +
|
|
74
|
+
'it is "(untitled group chat)" when no one else wrote recently. ' +
|
|
74
75
|
'A 1:1 is titled by the other person, who is its one participant; it is "(1:1 chat)" when they ' +
|
|
75
76
|
'wrote nothing recently.';
|
|
76
77
|
/**
|
|
@@ -123,7 +124,7 @@ export async function listSummaries(chatsvc, filter) {
|
|
|
123
124
|
});
|
|
124
125
|
const errors = (titled) => outcome.failed.length > 0
|
|
125
126
|
? outcome.failed.map((f, i) => ({
|
|
126
|
-
conversation: { id: f.summary.id, title: titled[i].title },
|
|
127
|
+
conversation: { id: f.summary.id, title: titled[i].title, ...participantsOf(titled[i]) },
|
|
127
128
|
error: wrapApiError(f.error, 'confirm this conversation is unread').message,
|
|
128
129
|
}))
|
|
129
130
|
: undefined;
|