@gakr-gakr/msteams 0.1.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.
Files changed (107) hide show
  1. package/api.ts +3 -0
  2. package/autobot.plugin.json +15 -0
  3. package/channel-config-api.ts +1 -0
  4. package/channel-plugin-api.ts +2 -0
  5. package/config-api.ts +4 -0
  6. package/contract-api.ts +4 -0
  7. package/index.ts +20 -0
  8. package/package.json +72 -0
  9. package/runtime-api.ts +66 -0
  10. package/secret-contract-api.ts +5 -0
  11. package/setup-entry.ts +13 -0
  12. package/setup-plugin-api.ts +3 -0
  13. package/src/ai-entity.ts +7 -0
  14. package/src/approval-auth.ts +44 -0
  15. package/src/attachments/bot-framework.ts +348 -0
  16. package/src/attachments/download.ts +328 -0
  17. package/src/attachments/graph.ts +489 -0
  18. package/src/attachments/html.ts +122 -0
  19. package/src/attachments/payload.ts +14 -0
  20. package/src/attachments/remote-media.ts +86 -0
  21. package/src/attachments/shared.ts +655 -0
  22. package/src/attachments/types.ts +47 -0
  23. package/src/attachments.ts +18 -0
  24. package/src/channel-api.ts +1 -0
  25. package/src/channel.runtime.ts +56 -0
  26. package/src/channel.setup.ts +77 -0
  27. package/src/channel.ts +1176 -0
  28. package/src/config-schema.ts +6 -0
  29. package/src/config-ui-hints.ts +40 -0
  30. package/src/conversation-store-fs.ts +149 -0
  31. package/src/conversation-store-helpers.ts +105 -0
  32. package/src/conversation-store-memory.ts +51 -0
  33. package/src/conversation-store.ts +71 -0
  34. package/src/directory-live.ts +111 -0
  35. package/src/doctor.ts +27 -0
  36. package/src/errors.ts +270 -0
  37. package/src/feedback-reflection-prompt.ts +117 -0
  38. package/src/feedback-reflection-store.ts +113 -0
  39. package/src/feedback-reflection.ts +271 -0
  40. package/src/file-consent-helpers.ts +115 -0
  41. package/src/file-consent-invoke.ts +150 -0
  42. package/src/file-consent.ts +223 -0
  43. package/src/graph-chat.ts +36 -0
  44. package/src/graph-group-management.ts +168 -0
  45. package/src/graph-members.ts +48 -0
  46. package/src/graph-messages.ts +534 -0
  47. package/src/graph-teams.ts +114 -0
  48. package/src/graph-thread.ts +146 -0
  49. package/src/graph-upload.ts +531 -0
  50. package/src/graph-users.ts +29 -0
  51. package/src/graph.ts +308 -0
  52. package/src/inbound.ts +148 -0
  53. package/src/index.ts +4 -0
  54. package/src/media-helpers.ts +105 -0
  55. package/src/mentions.ts +114 -0
  56. package/src/messenger.ts +608 -0
  57. package/src/monitor-handler/access.ts +136 -0
  58. package/src/monitor-handler/inbound-media.ts +180 -0
  59. package/src/monitor-handler/message-handler-mock-support.test-support.ts +28 -0
  60. package/src/monitor-handler/message-handler.test-support.ts +102 -0
  61. package/src/monitor-handler/message-handler.ts +1015 -0
  62. package/src/monitor-handler/reaction-handler.ts +124 -0
  63. package/src/monitor-handler/thread-session.ts +30 -0
  64. package/src/monitor-handler.ts +538 -0
  65. package/src/monitor-handler.types.ts +27 -0
  66. package/src/monitor-types.ts +6 -0
  67. package/src/monitor.ts +476 -0
  68. package/src/oauth.flow.ts +77 -0
  69. package/src/oauth.shared.ts +37 -0
  70. package/src/oauth.token.ts +162 -0
  71. package/src/oauth.ts +130 -0
  72. package/src/outbound.ts +198 -0
  73. package/src/pending-uploads-fs.ts +235 -0
  74. package/src/pending-uploads.ts +121 -0
  75. package/src/policy.ts +245 -0
  76. package/src/polls-store-memory.ts +32 -0
  77. package/src/polls.ts +312 -0
  78. package/src/presentation.ts +93 -0
  79. package/src/probe.ts +132 -0
  80. package/src/reply-dispatcher.ts +523 -0
  81. package/src/reply-stream-controller.ts +334 -0
  82. package/src/resolve-allowlist.ts +309 -0
  83. package/src/revoked-context.ts +17 -0
  84. package/src/runtime.ts +12 -0
  85. package/src/sdk-types.ts +59 -0
  86. package/src/sdk.ts +916 -0
  87. package/src/secret-contract.ts +49 -0
  88. package/src/secret-input.ts +7 -0
  89. package/src/send-context.ts +269 -0
  90. package/src/send.ts +697 -0
  91. package/src/sent-message-cache.ts +174 -0
  92. package/src/session-route.ts +40 -0
  93. package/src/setup-core.ts +162 -0
  94. package/src/setup-surface.ts +319 -0
  95. package/src/sso-token-store.ts +166 -0
  96. package/src/sso.ts +300 -0
  97. package/src/storage.ts +25 -0
  98. package/src/store-fs.ts +42 -0
  99. package/src/streaming-message.ts +327 -0
  100. package/src/thread-parent-context.ts +159 -0
  101. package/src/token-response.ts +11 -0
  102. package/src/token.ts +194 -0
  103. package/src/user-agent.ts +53 -0
  104. package/src/webhook-timeouts.ts +27 -0
  105. package/src/welcome-card.ts +57 -0
  106. package/test-api.ts +1 -0
  107. package/tsconfig.json +16 -0
@@ -0,0 +1,334 @@
1
+ import {
2
+ createLiveMessageState,
3
+ createPreviewMessageReceipt,
4
+ defineFinalizableLivePreviewAdapter,
5
+ deliverWithFinalizableLivePreviewAdapter,
6
+ markLiveMessageFinalized,
7
+ type LiveMessageState,
8
+ } from "autobot/plugin-sdk/channel-message";
9
+ import {
10
+ createChannelProgressDraftGate,
11
+ type ChannelProgressDraftLine,
12
+ formatChannelProgressDraftText,
13
+ isChannelProgressDraftWorkToolName,
14
+ mergeChannelProgressDraftLine,
15
+ normalizeChannelProgressDraftLineIdentity,
16
+ resolveChannelPreviewStreamMode,
17
+ resolveChannelProgressDraftMaxLines,
18
+ resolveChannelProgressDraftLabel,
19
+ resolveChannelStreamingPreviewToolProgress,
20
+ } from "autobot/plugin-sdk/channel-streaming";
21
+ import { normalizeOptionalLowercaseString } from "autobot/plugin-sdk/string-coerce-runtime";
22
+ import type { MSTeamsConfig, ReplyPayload } from "../runtime-api.js";
23
+ import { formatUnknownError } from "./errors.js";
24
+ import type { MSTeamsMonitorLogger } from "./monitor-types.js";
25
+ import type { MSTeamsTurnContext } from "./sdk-types.js";
26
+ import { TeamsHttpStream } from "./streaming-message.js";
27
+
28
+ // Local generic wrapper to defer union resolution. Works around a
29
+ // single-file-mode limitation in the type-aware lint where imported
30
+ // types resolved via extension runtime-api barrels are treated as
31
+ // `error` (acting as `any`) and trip `no-redundant-type-constituents`
32
+ // when combined with `undefined` in a union.
33
+ type Maybe<T> = T | undefined;
34
+
35
+ export function pickInformativeStatusText(
36
+ params: { config?: MSTeamsConfig; seed?: string; random?: () => number } | (() => number) = {},
37
+ ): string | undefined {
38
+ const options = typeof params === "function" ? { random: params } : params;
39
+ return resolveChannelProgressDraftLabel({
40
+ entry: options.config,
41
+ seed: options.seed,
42
+ random: options.random,
43
+ });
44
+ }
45
+
46
+ export function createTeamsReplyStreamController(params: {
47
+ conversationType?: string;
48
+ context: MSTeamsTurnContext;
49
+ feedbackLoopEnabled: boolean;
50
+ log: MSTeamsMonitorLogger;
51
+ msteamsConfig?: MSTeamsConfig;
52
+ progressSeed?: string;
53
+ random?: () => number;
54
+ }) {
55
+ const isPersonal = normalizeOptionalLowercaseString(params.conversationType) === "personal";
56
+ const streamMode = resolveChannelPreviewStreamMode(params.msteamsConfig, "partial");
57
+ const shouldUseNativeStream =
58
+ isPersonal && (streamMode === "partial" || streamMode === "progress");
59
+ const shouldSuppressDefaultToolProgressMessages =
60
+ shouldUseNativeStream && streamMode === "progress";
61
+ const shouldStreamPreviewToolProgress =
62
+ shouldSuppressDefaultToolProgressMessages &&
63
+ resolveChannelStreamingPreviewToolProgress(params.msteamsConfig);
64
+ const stream = shouldUseNativeStream
65
+ ? new TeamsHttpStream({
66
+ sendActivity: (activity) => params.context.sendActivity(activity),
67
+ feedbackLoopEnabled: params.feedbackLoopEnabled,
68
+ onError: (err) => {
69
+ params.log.debug?.(`stream error: ${formatUnknownError(err)}`);
70
+ },
71
+ })
72
+ : undefined;
73
+
74
+ let streamReceivedTokens = false;
75
+ let informativeUpdateSent = false;
76
+ let progressLines: Array<string | ChannelProgressDraftLine> = [];
77
+ let lastInformativeText = "";
78
+ let pendingFinalize: Promise<void> | undefined;
79
+ let liveState: LiveMessageState<ReplyPayload> = createLiveMessageState({
80
+ canFinalizeInPlace: Boolean(stream),
81
+ });
82
+
83
+ const markStreamFinalized = () => {
84
+ if (!stream || stream.isFailed) {
85
+ return;
86
+ }
87
+ const messageId = stream.messageId ?? stream.previewStreamId;
88
+ if (!messageId) {
89
+ return;
90
+ }
91
+ liveState = markLiveMessageFinalized(liveState, createPreviewMessageReceipt({ id: messageId }));
92
+ };
93
+
94
+ const renderInformativeUpdate = async () => {
95
+ if (!stream) {
96
+ return;
97
+ }
98
+ const informativeText = formatChannelProgressDraftText({
99
+ entry: params.msteamsConfig,
100
+ lines: shouldStreamPreviewToolProgress ? progressLines : [],
101
+ seed: params.progressSeed,
102
+ bullet: "-",
103
+ });
104
+ if (!informativeText || informativeText === lastInformativeText) {
105
+ return;
106
+ }
107
+ lastInformativeText = informativeText;
108
+ informativeUpdateSent = true;
109
+ await stream.sendInformativeUpdate(informativeText);
110
+ };
111
+
112
+ const progressDraftGate = createChannelProgressDraftGate({
113
+ onStart: renderInformativeUpdate,
114
+ });
115
+
116
+ const noteProgressWork = async (options?: { toolName?: string }): Promise<void> => {
117
+ if (!stream || streamMode !== "progress") {
118
+ return;
119
+ }
120
+ if (options?.toolName !== undefined && !isChannelProgressDraftWorkToolName(options.toolName)) {
121
+ return;
122
+ }
123
+ const hadStarted = progressDraftGate.hasStarted;
124
+ await progressDraftGate.noteWork();
125
+ if (hadStarted && progressDraftGate.hasStarted) {
126
+ await renderInformativeUpdate();
127
+ }
128
+ };
129
+
130
+ const pushProgressLine = async (
131
+ line?: string | ChannelProgressDraftLine,
132
+ options?: { toolName?: string },
133
+ ): Promise<void> => {
134
+ if (!stream || streamMode !== "progress") {
135
+ return;
136
+ }
137
+ if (options?.toolName !== undefined && !isChannelProgressDraftWorkToolName(options.toolName)) {
138
+ return;
139
+ }
140
+ if (shouldStreamPreviewToolProgress) {
141
+ const normalized = normalizeChannelProgressDraftLineIdentity(line);
142
+ if (normalized) {
143
+ const progressLine: string | ChannelProgressDraftLine =
144
+ typeof line === "object" && line !== undefined ? line : normalized;
145
+ progressLines = mergeChannelProgressDraftLine(progressLines, progressLine, {
146
+ maxLines: resolveChannelProgressDraftMaxLines(params.msteamsConfig),
147
+ });
148
+ }
149
+ }
150
+ await noteProgressWork();
151
+ };
152
+
153
+ const fallbackAfterStreamFailure = (
154
+ payload: ReplyPayload,
155
+ hasMedia: boolean,
156
+ ): Maybe<ReplyPayload> => {
157
+ if (!payload.text) {
158
+ return payload;
159
+ }
160
+ const streamedLength = stream?.streamedLength ?? 0;
161
+ if (streamedLength <= 0) {
162
+ return payload;
163
+ }
164
+ const remainingText = payload.text.slice(streamedLength);
165
+ if (!remainingText) {
166
+ return hasMedia ? { ...payload, text: undefined } : undefined;
167
+ }
168
+ return { ...payload, text: remainingText };
169
+ };
170
+
171
+ const finalizeProgressPayload = async (
172
+ payload: ReplyPayload,
173
+ hasMedia: boolean,
174
+ ): Promise<Maybe<ReplyPayload>> => {
175
+ if (!stream || !payload.text) {
176
+ return payload;
177
+ }
178
+ const result = await deliverWithFinalizableLivePreviewAdapter({
179
+ kind: "final",
180
+ payload,
181
+ liveState,
182
+ adapter: defineFinalizableLivePreviewAdapter<ReplyPayload, string, { text: string }>({
183
+ draft: {
184
+ flush: async () => {},
185
+ clear: async () => {},
186
+ id: () => stream.previewStreamId,
187
+ },
188
+ buildFinalEdit: (candidate) => (candidate.text ? { text: candidate.text } : undefined),
189
+ editFinal: async (_previewId, edit) => {
190
+ const finalized = await stream.replaceInformativeWithFinal(edit.text);
191
+ informativeUpdateSent = false;
192
+ if (!finalized || stream.isFailed) {
193
+ throw new Error("Teams progress stream finalization failed");
194
+ }
195
+ },
196
+ resolveFinalizedId: (previewId) => stream.messageId ?? stream.previewStreamId ?? previewId,
197
+ createPreviewReceipt: (id) => createPreviewMessageReceipt({ id }),
198
+ onPreviewFinalized: (_id, _receipt, state) => {
199
+ liveState = state;
200
+ },
201
+ logPreviewEditFailure: (err) => {
202
+ params.log.debug?.(`stream finalization failed: ${formatUnknownError(err)}`);
203
+ },
204
+ }),
205
+ deliverNormally: async () => false,
206
+ });
207
+
208
+ return result.kind === "preview-finalized"
209
+ ? hasMedia
210
+ ? { ...payload, text: undefined }
211
+ : undefined
212
+ : payload;
213
+ };
214
+
215
+ return {
216
+ async onReplyStart(): Promise<void> {
217
+ return;
218
+ },
219
+
220
+ async noteProgressWork(options?: { toolName?: string }): Promise<void> {
221
+ await noteProgressWork(options);
222
+ },
223
+
224
+ onPartialReply(payload: { text?: string }): void {
225
+ if (!stream || !payload.text) {
226
+ return;
227
+ }
228
+ if (streamMode === "progress") {
229
+ return;
230
+ }
231
+ streamReceivedTokens = true;
232
+ stream.update(payload.text);
233
+ },
234
+
235
+ async pushProgressLine(
236
+ line?: string | ChannelProgressDraftLine,
237
+ options?: { toolName?: string },
238
+ ): Promise<void> {
239
+ await pushProgressLine(line, options);
240
+ },
241
+
242
+ shouldSuppressDefaultToolProgressMessages(): boolean {
243
+ return shouldSuppressDefaultToolProgressMessages;
244
+ },
245
+
246
+ shouldStreamPreviewToolProgress(): boolean {
247
+ return shouldStreamPreviewToolProgress;
248
+ },
249
+
250
+ async preparePayload(payload: ReplyPayload): Promise<Maybe<ReplyPayload>> {
251
+ const hasMedia = Boolean(payload.mediaUrl || payload.mediaUrls?.length);
252
+
253
+ if (stream && streamMode === "progress" && informativeUpdateSent && !stream.isFinalized) {
254
+ if (!payload.text) {
255
+ return payload;
256
+ }
257
+ return await finalizeProgressPayload(payload, hasMedia);
258
+ }
259
+
260
+ if (!stream || !streamReceivedTokens) {
261
+ return payload;
262
+ }
263
+
264
+ // Stream failed after partial delivery (e.g. > 4000 chars). Send only
265
+ // the unstreamed suffix via block delivery to avoid duplicate text.
266
+ if (stream.isFailed) {
267
+ streamReceivedTokens = false;
268
+
269
+ return fallbackAfterStreamFailure(payload, hasMedia);
270
+ }
271
+
272
+ if (!stream.hasContent || stream.isFinalized) {
273
+ return payload;
274
+ }
275
+
276
+ // Stream handled this text segment. Finalize it and reset so any
277
+ // subsequent text segments (after tool calls) use fallback delivery.
278
+ // finalize() is idempotent; the later call in markDispatchIdle is a no-op.
279
+ streamReceivedTokens = false;
280
+ pendingFinalize = stream.finalize().then(() => {
281
+ markStreamFinalized();
282
+ });
283
+
284
+ if (!hasMedia) {
285
+ return undefined;
286
+ }
287
+ return { ...payload, text: undefined };
288
+ },
289
+
290
+ async finalize(): Promise<void> {
291
+ progressDraftGate.cancel();
292
+ await pendingFinalize;
293
+ if (!pendingFinalize) {
294
+ await stream?.finalize();
295
+ markStreamFinalized();
296
+ }
297
+ },
298
+
299
+ hasStream(): boolean {
300
+ return Boolean(stream);
301
+ },
302
+
303
+ liveState(): LiveMessageState<ReplyPayload> {
304
+ return liveState;
305
+ },
306
+
307
+ /**
308
+ * Whether the Teams streaming card is currently receiving LLM tokens.
309
+ * Used to gate side-channel keepalive activity so we don't overlay plain
310
+ * "typing" indicators on top of a live streaming card.
311
+ *
312
+ * Returns true only while the stream is actively chunking text into the
313
+ * streaming card. The informative update (blue progress bar) is short
314
+ * lived so we intentionally do not count it as "active"; this way the
315
+ * typing keepalive can still fire during the informative window and
316
+ * during tool chains between text segments.
317
+ *
318
+ * Returns false when:
319
+ * - No stream exists (non-personal conversation).
320
+ * - Stream has not yet received any text tokens.
321
+ * - Stream has been finalized (e.g. after the first text segment, while
322
+ * tools run before the next segment).
323
+ */
324
+ isStreamActive(): boolean {
325
+ if (!stream) {
326
+ return false;
327
+ }
328
+ if (stream.isFinalized || stream.isFailed) {
329
+ return false;
330
+ }
331
+ return streamReceivedTokens;
332
+ },
333
+ };
334
+ }
@@ -0,0 +1,309 @@
1
+ import { mapAllowlistResolutionInputs } from "autobot/plugin-sdk/allow-from";
2
+ import {
3
+ normalizeLowercaseStringOrEmpty,
4
+ normalizeOptionalLowercaseString,
5
+ } from "autobot/plugin-sdk/string-coerce-runtime";
6
+ import { searchGraphUsers } from "./graph-users.js";
7
+ import {
8
+ listChannelsForTeam,
9
+ listTeamsByName,
10
+ normalizeQuery,
11
+ resolveGraphToken,
12
+ } from "./graph.js";
13
+
14
+ type MSTeamsChannelResolution = {
15
+ input: string;
16
+ resolved: boolean;
17
+ teamId?: string;
18
+ teamName?: string;
19
+ channelId?: string;
20
+ channelName?: string;
21
+ note?: string;
22
+ };
23
+
24
+ type MSTeamsUserResolution = {
25
+ input: string;
26
+ resolved: boolean;
27
+ id?: string;
28
+ name?: string;
29
+ note?: string;
30
+ };
31
+
32
+ function stripProviderPrefix(raw: string): string {
33
+ return raw.replace(/^(msteams|teams):/i, "");
34
+ }
35
+
36
+ export function normalizeMSTeamsMessagingTarget(raw: string): string | undefined {
37
+ let trimmed = raw.trim();
38
+ if (!trimmed) {
39
+ return undefined;
40
+ }
41
+ trimmed = stripProviderPrefix(trimmed).trim();
42
+ if (/^conversation:/i.test(trimmed)) {
43
+ const id = trimmed.slice("conversation:".length).trim();
44
+ return id ? `conversation:${id}` : undefined;
45
+ }
46
+ if (/^user:/i.test(trimmed)) {
47
+ const id = trimmed.slice("user:".length).trim();
48
+ return id ? `user:${id}` : undefined;
49
+ }
50
+ return trimmed || undefined;
51
+ }
52
+
53
+ export function normalizeMSTeamsUserInput(raw: string): string {
54
+ return stripProviderPrefix(raw)
55
+ .replace(/^(user|conversation):/i, "")
56
+ .trim();
57
+ }
58
+
59
+ export function parseMSTeamsConversationId(raw: string): string | null {
60
+ const trimmed = stripProviderPrefix(raw).trim();
61
+ if (!/^conversation:/i.test(trimmed)) {
62
+ return null;
63
+ }
64
+ const id = trimmed.slice("conversation:".length).trim();
65
+ return id;
66
+ }
67
+
68
+ /**
69
+ * Detect whether a raw target string looks like a Microsoft Teams conversation
70
+ * or user id that cron announce delivery and other explicit-target paths can
71
+ * forward verbatim to the channel adapter.
72
+ *
73
+ * Accepts both prefixed and bare formats:
74
+ * - `conversation:<id>` — explicit conversation prefix
75
+ * - `user:<aad-guid>` — user id (16+ hex chars, UUID-like)
76
+ * - `19:abc@thread.tacv2` / `19:abc@thread.skype` — channel / legacy group
77
+ * - `19:{userId}_{appId}@unq.gbl.spaces` — Graph 1:1 chat thread format
78
+ * - `a:1xxx` — Bot Framework personal (1:1) chat id
79
+ * - `8:orgid:xxx` — Bot Framework org-scoped personal chat id
80
+ * - `29:xxx` — Bot Framework user id
81
+ *
82
+ * Display-name user targets such as `user:John Smith` intentionally return
83
+ * false so that the Graph API directory lookup still runs for them.
84
+ */
85
+ export function looksLikeMSTeamsTargetId(raw: string): boolean {
86
+ const trimmed = raw.trim();
87
+ if (!trimmed) {
88
+ return false;
89
+ }
90
+ if (/^conversation:/i.test(trimmed)) {
91
+ return true;
92
+ }
93
+ if (/^user:/i.test(trimmed)) {
94
+ // Only treat as an id when the value after `user:` looks like a UUID;
95
+ // display names must fall through to directory lookup.
96
+ const id = trimmed.slice("user:".length).trim();
97
+ return /^[0-9a-fA-F-]{16,}$/.test(id);
98
+ }
99
+ // Bare Bot Framework / Graph conversation id formats.
100
+ // Channel / group ids always start with `19:` and include an `@thread.*`
101
+ // suffix (`@thread.tacv2` or the legacy `@thread.skype`). Personal chat
102
+ // ids come in three shapes: `a:1...` (Bot Framework), `8:orgid:...`
103
+ // (org-scoped Bot Framework), and `19:{userId}_{appId}@unq.gbl.spaces`
104
+ // (Graph API 1:1 chat thread). Bot Framework user ids use `29:...`.
105
+ if (/^19:.+@thread\.(tacv2|skype)$/i.test(trimmed)) {
106
+ return true;
107
+ }
108
+ if (/^19:.+@unq\.gbl\.spaces$/i.test(trimmed)) {
109
+ return true;
110
+ }
111
+ if (/^a:1[A-Za-z0-9_-]+$/i.test(trimmed)) {
112
+ return true;
113
+ }
114
+ if (/^8:orgid:[A-Za-z0-9-]+$/i.test(trimmed)) {
115
+ return true;
116
+ }
117
+ if (/^29:[A-Za-z0-9_-]+$/i.test(trimmed)) {
118
+ return true;
119
+ }
120
+ // Fallback: anything containing @thread is still treated as a conversation
121
+ // id so the current matches for tenant-specific suffixes remain accepted.
122
+ return /@thread\b/i.test(trimmed);
123
+ }
124
+
125
+ function normalizeMSTeamsTeamKey(raw: string): string | undefined {
126
+ const trimmed = stripProviderPrefix(raw)
127
+ .replace(/^team:/i, "")
128
+ .trim();
129
+ return trimmed || undefined;
130
+ }
131
+
132
+ function normalizeMSTeamsChannelKey(raw?: string | null): string | undefined {
133
+ const trimmed = raw?.trim().replace(/^#/, "").trim() ?? "";
134
+ return trimmed || undefined;
135
+ }
136
+
137
+ function normalizeMSTeamsConversationTargetId(raw: string): string {
138
+ const trimmed = stripProviderPrefix(raw).trim();
139
+ return parseMSTeamsConversationId(trimmed) ?? trimmed;
140
+ }
141
+
142
+ function looksLikeMSTeamsThreadConversationId(raw: string): boolean {
143
+ const normalized = normalizeMSTeamsConversationTargetId(raw);
144
+ return /^19:.+@thread\./i.test(normalized);
145
+ }
146
+
147
+ export function parseMSTeamsTeamChannelInput(raw: string): { team?: string; channel?: string } {
148
+ const trimmed = stripProviderPrefix(raw).trim();
149
+ if (!trimmed) {
150
+ return {};
151
+ }
152
+ const parts = trimmed.split("/");
153
+ const team = normalizeMSTeamsTeamKey(parts[0] ?? "");
154
+ const channel =
155
+ parts.length > 1 ? normalizeMSTeamsChannelKey(parts.slice(1).join("/")) : undefined;
156
+ return {
157
+ ...(team ? { team } : {}),
158
+ ...(channel ? { channel } : {}),
159
+ };
160
+ }
161
+
162
+ export function parseMSTeamsTeamEntry(
163
+ raw: string,
164
+ ): { teamKey: string; channelKey?: string } | null {
165
+ const { team, channel } = parseMSTeamsTeamChannelInput(raw);
166
+ if (!team) {
167
+ return null;
168
+ }
169
+ return {
170
+ teamKey: team,
171
+ ...(channel ? { channelKey: channel } : {}),
172
+ };
173
+ }
174
+
175
+ export async function resolveMSTeamsChannelAllowlist(params: {
176
+ cfg: unknown;
177
+ entries: string[];
178
+ }): Promise<MSTeamsChannelResolution[]> {
179
+ let tokenPromise: Promise<string> | undefined;
180
+ const getToken = () => {
181
+ tokenPromise ??= resolveGraphToken(params.cfg);
182
+ return tokenPromise;
183
+ };
184
+ return await mapAllowlistResolutionInputs({
185
+ inputs: params.entries,
186
+ mapInput: async (input): Promise<MSTeamsChannelResolution> => {
187
+ const { team, channel } = parseMSTeamsTeamChannelInput(input);
188
+ if (!team) {
189
+ return { input, resolved: false };
190
+ }
191
+ if (looksLikeMSTeamsThreadConversationId(team)) {
192
+ const teamId = normalizeMSTeamsConversationTargetId(team);
193
+ if (!channel) {
194
+ return { input, resolved: true, teamId, teamName: teamId };
195
+ }
196
+ if (!looksLikeMSTeamsThreadConversationId(channel)) {
197
+ return {
198
+ input,
199
+ resolved: false,
200
+ teamId,
201
+ teamName: teamId,
202
+ note: "channel id required for conversation-id team",
203
+ };
204
+ }
205
+ const channelId = normalizeMSTeamsConversationTargetId(channel);
206
+ return {
207
+ input,
208
+ resolved: true,
209
+ teamId,
210
+ teamName: teamId,
211
+ channelId,
212
+ channelName: channelId,
213
+ };
214
+ }
215
+ const token = await getToken();
216
+ const teams = /^[0-9a-fA-F-]{16,}$/.test(team)
217
+ ? [{ id: team, displayName: team }]
218
+ : await listTeamsByName(token, team);
219
+ if (teams.length === 0) {
220
+ return { input, resolved: false, note: "team not found" };
221
+ }
222
+ const teamMatch = teams[0];
223
+ const graphTeamId = teamMatch.id?.trim();
224
+ const teamName = teamMatch.displayName?.trim() || team;
225
+ if (!graphTeamId) {
226
+ return { input, resolved: false, note: "team id missing" };
227
+ }
228
+ // Bot Framework sends the General channel's conversation ID as
229
+ // channelData.team.id at runtime, NOT the Graph API group GUID.
230
+ // Fetch channels upfront so we can resolve the correct key format for
231
+ // runtime matching and reuse the list for channel lookups.
232
+ let teamChannels: Awaited<ReturnType<typeof listChannelsForTeam>> = [];
233
+ try {
234
+ teamChannels = await listChannelsForTeam(token, graphTeamId);
235
+ } catch {
236
+ // API failure (rate limit, network error) — fall back to Graph GUID as team key
237
+ }
238
+ const generalChannel = teamChannels.find(
239
+ (ch) => normalizeOptionalLowercaseString(ch.displayName) === "general",
240
+ );
241
+ // Use the General channel's conversation ID as the team key — this
242
+ // matches what Bot Framework sends at runtime. Fall back to the Graph
243
+ // GUID if the General channel isn't found (renamed or deleted).
244
+ const teamId = generalChannel?.id?.trim() || graphTeamId;
245
+ if (!channel) {
246
+ return {
247
+ input,
248
+ resolved: true,
249
+ teamId,
250
+ teamName,
251
+ note: teams.length > 1 ? "multiple teams; chose first" : undefined,
252
+ };
253
+ }
254
+ // Reuse teamChannels — already fetched above
255
+ const normalizedChannel = normalizeOptionalLowercaseString(channel);
256
+ const channelMatch =
257
+ teamChannels.find((item) => item.id === channel) ??
258
+ teamChannels.find(
259
+ (item) => normalizeOptionalLowercaseString(item.displayName) === normalizedChannel,
260
+ ) ??
261
+ teamChannels.find((item) =>
262
+ normalizeLowercaseStringOrEmpty(item.displayName ?? "").includes(normalizedChannel ?? ""),
263
+ );
264
+ if (!channelMatch?.id) {
265
+ return { input, resolved: false, note: "channel not found" };
266
+ }
267
+ return {
268
+ input,
269
+ resolved: true,
270
+ teamId,
271
+ teamName,
272
+ channelId: channelMatch.id,
273
+ channelName: channelMatch.displayName ?? channel,
274
+ note: teamChannels.length > 1 ? "multiple channels; chose first" : undefined,
275
+ };
276
+ },
277
+ });
278
+ }
279
+
280
+ export async function resolveMSTeamsUserAllowlist(params: {
281
+ cfg: unknown;
282
+ entries: string[];
283
+ }): Promise<MSTeamsUserResolution[]> {
284
+ const token = await resolveGraphToken(params.cfg);
285
+ return await mapAllowlistResolutionInputs({
286
+ inputs: params.entries,
287
+ mapInput: async (input): Promise<MSTeamsUserResolution> => {
288
+ const query = normalizeQuery(normalizeMSTeamsUserInput(input));
289
+ if (!query) {
290
+ return { input, resolved: false };
291
+ }
292
+ if (/^[0-9a-fA-F-]{16,}$/.test(query)) {
293
+ return { input, resolved: true, id: query };
294
+ }
295
+ const users = await searchGraphUsers({ token, query, top: 10 });
296
+ const match = users[0];
297
+ if (!match?.id) {
298
+ return { input, resolved: false };
299
+ }
300
+ return {
301
+ input,
302
+ resolved: true,
303
+ id: match.id,
304
+ name: match.displayName ?? undefined,
305
+ note: users.length > 1 ? "multiple matches; chose first" : undefined,
306
+ };
307
+ },
308
+ });
309
+ }
@@ -0,0 +1,17 @@
1
+ import { isRevokedProxyError } from "./errors.js";
2
+
3
+ export async function withRevokedProxyFallback<T>(params: {
4
+ run: () => Promise<T>;
5
+ onRevoked: () => Promise<T>;
6
+ onRevokedLog?: () => void;
7
+ }): Promise<T> {
8
+ try {
9
+ return await params.run();
10
+ } catch (err) {
11
+ if (!isRevokedProxyError(err)) {
12
+ throw err;
13
+ }
14
+ params.onRevokedLog?.();
15
+ return await params.onRevoked();
16
+ }
17
+ }
package/src/runtime.ts ADDED
@@ -0,0 +1,12 @@
1
+ import { createPluginRuntimeStore } from "autobot/plugin-sdk/runtime-store";
2
+ import type { PluginRuntime } from "autobot/plugin-sdk/runtime-store";
3
+
4
+ const {
5
+ setRuntime: setMSTeamsRuntime,
6
+ getRuntime: getMSTeamsRuntime,
7
+ tryGetRuntime: getOptionalMSTeamsRuntime,
8
+ } = createPluginRuntimeStore<PluginRuntime>({
9
+ pluginId: "msteams",
10
+ errorMessage: "MSTeams runtime not initialized",
11
+ });
12
+ export { getMSTeamsRuntime, getOptionalMSTeamsRuntime, setMSTeamsRuntime };