@openclaw/msteams 2026.3.13 → 2026.5.2-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/api.ts +3 -0
  2. package/channel-config-api.ts +1 -0
  3. package/channel-plugin-api.ts +2 -0
  4. package/config-api.ts +4 -0
  5. package/contract-api.ts +4 -0
  6. package/index.ts +15 -12
  7. package/openclaw.plugin.json +553 -1
  8. package/package.json +46 -12
  9. package/runtime-api.ts +73 -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.test.ts +461 -0
  16. package/src/attachments/bot-framework.ts +362 -0
  17. package/src/attachments/download.ts +63 -19
  18. package/src/attachments/graph.test.ts +416 -0
  19. package/src/attachments/graph.ts +163 -72
  20. package/src/attachments/html.ts +33 -1
  21. package/src/attachments/payload.ts +1 -1
  22. package/src/attachments/remote-media.test.ts +137 -0
  23. package/src/attachments/remote-media.ts +75 -8
  24. package/src/attachments/shared.test.ts +138 -1
  25. package/src/attachments/shared.ts +193 -26
  26. package/src/attachments/types.ts +10 -0
  27. package/src/attachments.graph.test.ts +342 -0
  28. package/src/attachments.helpers.test.ts +246 -0
  29. package/src/attachments.test-helpers.ts +17 -0
  30. package/src/attachments.test.ts +163 -418
  31. package/src/attachments.ts +5 -5
  32. package/src/block-streaming-config.test.ts +61 -0
  33. package/src/channel-api.ts +1 -0
  34. package/src/channel.actions.test.ts +742 -0
  35. package/src/channel.directory.test.ts +145 -4
  36. package/src/channel.runtime.ts +56 -0
  37. package/src/channel.setup.ts +77 -0
  38. package/src/channel.test.ts +128 -0
  39. package/src/channel.ts +1077 -395
  40. package/src/config-schema.ts +6 -0
  41. package/src/config-ui-hints.ts +12 -0
  42. package/src/conversation-store-fs.test.ts +4 -5
  43. package/src/conversation-store-fs.ts +35 -51
  44. package/src/conversation-store-helpers.test.ts +202 -0
  45. package/src/conversation-store-helpers.ts +105 -0
  46. package/src/conversation-store-memory.ts +27 -23
  47. package/src/conversation-store.shared.test.ts +225 -0
  48. package/src/conversation-store.ts +30 -0
  49. package/src/directory-live.test.ts +156 -0
  50. package/src/directory-live.ts +7 -4
  51. package/src/doctor.ts +27 -0
  52. package/src/errors.test.ts +64 -1
  53. package/src/errors.ts +50 -9
  54. package/src/feedback-reflection-prompt.ts +117 -0
  55. package/src/feedback-reflection-store.ts +114 -0
  56. package/src/feedback-reflection.test.ts +237 -0
  57. package/src/feedback-reflection.ts +283 -0
  58. package/src/file-consent-helpers.test.ts +83 -0
  59. package/src/file-consent-helpers.ts +64 -11
  60. package/src/file-consent-invoke.ts +150 -0
  61. package/src/file-consent.test.ts +363 -0
  62. package/src/file-consent.ts +165 -4
  63. package/src/graph-chat.ts +5 -3
  64. package/src/graph-group-management.test.ts +318 -0
  65. package/src/graph-group-management.ts +168 -0
  66. package/src/graph-members.test.ts +89 -0
  67. package/src/graph-members.ts +48 -0
  68. package/src/graph-messages.actions.test.ts +243 -0
  69. package/src/graph-messages.read.test.ts +391 -0
  70. package/src/graph-messages.search.test.ts +213 -0
  71. package/src/graph-messages.test-helpers.ts +50 -0
  72. package/src/graph-messages.ts +534 -0
  73. package/src/graph-teams.test.ts +215 -0
  74. package/src/graph-teams.ts +114 -0
  75. package/src/graph-thread.test.ts +246 -0
  76. package/src/graph-thread.ts +146 -0
  77. package/src/graph-upload.test.ts +161 -4
  78. package/src/graph-upload.ts +147 -56
  79. package/src/graph.test.ts +516 -0
  80. package/src/graph.ts +233 -21
  81. package/src/inbound.test.ts +156 -1
  82. package/src/inbound.ts +101 -1
  83. package/src/media-helpers.ts +1 -1
  84. package/src/mentions.test.ts +27 -18
  85. package/src/mentions.ts +2 -2
  86. package/src/messenger.test.ts +504 -23
  87. package/src/messenger.ts +133 -52
  88. package/src/monitor-handler/access.ts +125 -0
  89. package/src/monitor-handler/inbound-media.test.ts +289 -0
  90. package/src/monitor-handler/inbound-media.ts +57 -5
  91. package/src/monitor-handler/message-handler-mock-support.test-support.ts +28 -0
  92. package/src/monitor-handler/message-handler.authz.test.ts +588 -74
  93. package/src/monitor-handler/message-handler.dm-media.test.ts +54 -0
  94. package/src/monitor-handler/message-handler.test-support.ts +100 -0
  95. package/src/monitor-handler/message-handler.thread-parent.test.ts +223 -0
  96. package/src/monitor-handler/message-handler.thread-session.test.ts +77 -0
  97. package/src/monitor-handler/message-handler.ts +470 -164
  98. package/src/monitor-handler/reaction-handler.test.ts +267 -0
  99. package/src/monitor-handler/reaction-handler.ts +210 -0
  100. package/src/monitor-handler/thread-session.ts +17 -0
  101. package/src/monitor-handler.adaptive-card.test.ts +162 -0
  102. package/src/monitor-handler.feedback-authz.test.ts +314 -0
  103. package/src/monitor-handler.file-consent.test.ts +281 -79
  104. package/src/monitor-handler.sso.test.ts +563 -0
  105. package/src/monitor-handler.test-helpers.ts +180 -0
  106. package/src/monitor-handler.ts +459 -115
  107. package/src/monitor-handler.types.ts +27 -0
  108. package/src/monitor-types.ts +1 -0
  109. package/src/monitor.lifecycle.test.ts +74 -10
  110. package/src/monitor.test.ts +35 -1
  111. package/src/monitor.ts +143 -46
  112. package/src/oauth.flow.ts +77 -0
  113. package/src/oauth.shared.ts +37 -0
  114. package/src/oauth.test.ts +305 -0
  115. package/src/oauth.token.ts +158 -0
  116. package/src/oauth.ts +130 -0
  117. package/src/outbound.test.ts +10 -11
  118. package/src/outbound.ts +62 -44
  119. package/src/pending-uploads-fs.test.ts +246 -0
  120. package/src/pending-uploads-fs.ts +235 -0
  121. package/src/pending-uploads.test.ts +173 -0
  122. package/src/pending-uploads.ts +34 -2
  123. package/src/policy.test.ts +11 -5
  124. package/src/policy.ts +5 -5
  125. package/src/polls.test.ts +106 -5
  126. package/src/polls.ts +15 -7
  127. package/src/presentation.ts +68 -0
  128. package/src/probe.test.ts +27 -8
  129. package/src/probe.ts +43 -9
  130. package/src/reply-dispatcher.test.ts +437 -0
  131. package/src/reply-dispatcher.ts +259 -73
  132. package/src/reply-stream-controller.test.ts +235 -0
  133. package/src/reply-stream-controller.ts +147 -0
  134. package/src/resolve-allowlist.test.ts +105 -1
  135. package/src/resolve-allowlist.ts +112 -7
  136. package/src/runtime.ts +6 -3
  137. package/src/sdk-types.ts +43 -3
  138. package/src/sdk.test.ts +666 -0
  139. package/src/sdk.ts +867 -16
  140. package/src/secret-contract.ts +49 -0
  141. package/src/secret-input.ts +1 -1
  142. package/src/send-context.ts +76 -9
  143. package/src/send.test.ts +389 -5
  144. package/src/send.ts +140 -32
  145. package/src/sent-message-cache.ts +30 -18
  146. package/src/session-route.ts +40 -0
  147. package/src/setup-core.ts +160 -0
  148. package/src/setup-surface.test.ts +202 -0
  149. package/src/setup-surface.ts +320 -0
  150. package/src/sso-token-store.test.ts +72 -0
  151. package/src/sso-token-store.ts +166 -0
  152. package/src/sso.ts +300 -0
  153. package/src/storage.ts +1 -1
  154. package/src/store-fs.ts +2 -2
  155. package/src/streaming-message.test.ts +262 -0
  156. package/src/streaming-message.ts +297 -0
  157. package/src/test-runtime.ts +1 -1
  158. package/src/thread-parent-context.test.ts +224 -0
  159. package/src/thread-parent-context.ts +159 -0
  160. package/src/token.test.ts +237 -50
  161. package/src/token.ts +162 -7
  162. package/src/user-agent.test.ts +86 -0
  163. package/src/user-agent.ts +53 -0
  164. package/src/webhook-timeouts.ts +27 -0
  165. package/src/welcome-card.test.ts +81 -0
  166. package/src/welcome-card.ts +57 -0
  167. package/test-api.ts +1 -0
  168. package/tsconfig.json +16 -0
  169. package/CHANGELOG.md +0 -107
  170. package/src/file-lock.ts +0 -1
  171. package/src/graph-users.test.ts +0 -66
  172. package/src/onboarding.ts +0 -381
  173. package/src/polls-store.test.ts +0 -38
  174. package/src/revoked-context.test.ts +0 -39
  175. package/src/token-response.test.ts +0 -23
package/src/graph.ts CHANGED
@@ -1,8 +1,11 @@
1
- import type { MSTeamsConfig } from "openclaw/plugin-sdk/msteams";
1
+ import { fetchWithSsrFGuard, type MSTeamsConfig } from "../runtime-api.js";
2
2
  import { GRAPH_ROOT } from "./attachments/shared.js";
3
- import { loadMSTeamsSdkWithAuth } from "./sdk.js";
3
+
4
+ const GRAPH_BETA = "https://graph.microsoft.com/beta";
5
+ import { createMSTeamsTokenProvider, loadMSTeamsSdkWithAuth } from "./sdk.js";
4
6
  import { readAccessToken } from "./token-response.js";
5
- import { resolveMSTeamsCredentials } from "./token.js";
7
+ import { resolveDelegatedAccessToken, resolveMSTeamsCredentials } from "./token.js";
8
+ import { buildUserAgent } from "./user-agent.js";
6
9
 
7
10
  export type GraphUser = {
8
11
  id?: string;
@@ -11,12 +14,12 @@ export type GraphUser = {
11
14
  mail?: string;
12
15
  };
13
16
 
14
- export type GraphGroup = {
17
+ type GraphGroup = {
15
18
  id?: string;
16
19
  displayName?: string;
17
20
  };
18
21
 
19
- export type GraphChannel = {
22
+ type GraphChannel = {
20
23
  id?: string;
21
24
  displayName?: string;
22
25
  };
@@ -31,35 +34,186 @@ export function escapeOData(value: string): string {
31
34
  return value.replace(/'/g, "''");
32
35
  }
33
36
 
34
- export async function fetchGraphJson<T>(params: {
37
+ async function requestGraph(params: {
35
38
  token: string;
36
39
  path: string;
40
+ method?: "GET" | "POST" | "PATCH" | "DELETE";
41
+ root?: string;
37
42
  headers?: Record<string, string>;
38
- }): Promise<T> {
39
- const res = await fetch(`${GRAPH_ROOT}${params.path}`, {
43
+ body?: unknown;
44
+ errorPrefix?: string;
45
+ }): Promise<Response> {
46
+ const hasBody = params.body !== undefined;
47
+ const res = await fetch(`${params.root ?? GRAPH_ROOT}${params.path}`, {
48
+ method: params.method,
40
49
  headers: {
50
+ "User-Agent": buildUserAgent(),
41
51
  Authorization: `Bearer ${params.token}`,
52
+ ...(hasBody ? { "Content-Type": "application/json" } : {}),
42
53
  ...params.headers,
43
54
  },
55
+ body: hasBody ? JSON.stringify(params.body) : undefined,
44
56
  });
45
57
  if (!res.ok) {
46
58
  const text = await res.text().catch(() => "");
47
- throw new Error(`Graph ${params.path} failed (${res.status}): ${text || "unknown error"}`);
59
+ throw new Error(
60
+ `${params.errorPrefix ?? "Graph"} ${params.path} failed (${res.status}): ${text || "unknown error"}`,
61
+ );
62
+ }
63
+ return res;
64
+ }
65
+
66
+ async function readOptionalGraphJson<T>(res: Response): Promise<T> {
67
+ // Use optional chaining to stay resilient to partial test mocks that do not
68
+ // provide a status or Headers instance (they only shim `ok` + `json()`).
69
+ if (res.status === 204 || res.headers?.get?.("content-length") === "0") {
70
+ return undefined as T;
48
71
  }
49
72
  return (await res.json()) as T;
50
73
  }
51
74
 
52
- export async function resolveGraphToken(cfg: unknown): Promise<string> {
53
- const creds = resolveMSTeamsCredentials(
54
- (cfg as { channels?: { msteams?: unknown } })?.channels?.msteams as MSTeamsConfig | undefined,
55
- );
75
+ export async function fetchGraphJson<T>(params: {
76
+ token: string;
77
+ path: string;
78
+ headers?: Record<string, string>;
79
+ /** HTTP method; defaults to "GET" */
80
+ method?: string;
81
+ /** Request body (serialized as JSON). Only used for non-GET methods. */
82
+ body?: unknown;
83
+ }): Promise<T> {
84
+ const res = await requestGraph({
85
+ token: params.token,
86
+ path: params.path,
87
+ method: params.method as "GET" | "POST" | "DELETE" | undefined,
88
+ body: params.body,
89
+ headers: params.headers,
90
+ });
91
+ return await readOptionalGraphJson<T>(res);
92
+ }
93
+
94
+ /**
95
+ * Fetch JSON from an absolute Graph API URL (for example @odata.nextLink
96
+ * pagination URLs) without prepending GRAPH_ROOT.
97
+ */
98
+ export async function fetchGraphAbsoluteUrl<T>(params: {
99
+ token: string;
100
+ url: string;
101
+ headers?: Record<string, string>;
102
+ }): Promise<T> {
103
+ const { response, release } = await fetchWithSsrFGuard({
104
+ url: params.url,
105
+ init: {
106
+ headers: {
107
+ "User-Agent": buildUserAgent(),
108
+ Authorization: `Bearer ${params.token}`,
109
+ ...params.headers,
110
+ },
111
+ },
112
+ auditContext: "msteams.graph.absolute",
113
+ });
114
+ try {
115
+ if (!response.ok) {
116
+ const text = await response.text().catch(() => "");
117
+ throw new Error(
118
+ `Graph ${params.url} failed (${response.status}): ${text || "unknown error"}`,
119
+ );
120
+ }
121
+ return (await response.json()) as T;
122
+ } finally {
123
+ await release();
124
+ }
125
+ }
126
+
127
+ /** Graph collection response with optional pagination link. */
128
+ type GraphPagedResponse<T> = {
129
+ value?: T[];
130
+ "@odata.nextLink"?: string;
131
+ };
132
+
133
+ /** Result of a paginated Graph API fetch. */
134
+ type PaginatedResult<T> = {
135
+ items: T[];
136
+ truncated: boolean;
137
+ found?: T;
138
+ };
139
+
140
+ /**
141
+ * Fetch all pages of a Graph API collection, following @odata.nextLink.
142
+ * Optionally stop early when `findOne` matches an item.
143
+ */
144
+ export async function fetchAllGraphPages<T>(params: {
145
+ token: string;
146
+ path: string;
147
+ headers?: Record<string, string>;
148
+ /** Max pages to fetch before stopping. Default: 50. */
149
+ maxPages?: number;
150
+ /** Stop pagination early when this predicate returns true. */
151
+ findOne?: (item: T) => boolean;
152
+ }): Promise<PaginatedResult<T>> {
153
+ const maxPages = params.maxPages ?? 50;
154
+ const items: T[] = [];
155
+ let nextPath: string | undefined = params.path;
156
+
157
+ for (let page = 0; page < maxPages && nextPath; page++) {
158
+ const res: GraphPagedResponse<T> = await fetchGraphJson<GraphPagedResponse<T>>({
159
+ token: params.token,
160
+ path: nextPath,
161
+ headers: params.headers,
162
+ });
163
+
164
+ const pageItems = res.value ?? [];
165
+
166
+ if (params.findOne) {
167
+ const match = pageItems.find(params.findOne);
168
+ if (match) {
169
+ items.push(...pageItems);
170
+ return { items, truncated: false, found: match };
171
+ }
172
+ }
173
+
174
+ items.push(...pageItems);
175
+
176
+ // @odata.nextLink is an absolute URL; strip the Graph root to get a relative path
177
+ const rawNext: string | undefined = res["@odata.nextLink"];
178
+ if (rawNext) {
179
+ nextPath = rawNext
180
+ .replace("https://graph.microsoft.com/v1.0", "")
181
+ .replace("https://graph.microsoft.com/beta", "");
182
+ } else {
183
+ nextPath = undefined;
184
+ }
185
+ }
186
+
187
+ return { items, truncated: Boolean(nextPath) };
188
+ }
189
+
190
+ export async function resolveGraphToken(
191
+ cfg: unknown,
192
+ options?: { preferDelegated?: boolean },
193
+ ): Promise<string> {
194
+ const msteamsCfg = (cfg as { channels?: { msteams?: MSTeamsConfig } })?.channels?.msteams;
195
+ const creds = resolveMSTeamsCredentials(msteamsCfg);
56
196
  if (!creds) {
57
197
  throw new Error("MS Teams credentials missing");
58
198
  }
59
- const { sdk, authConfig } = await loadMSTeamsSdkWithAuth(creds);
60
- const tokenProvider = new sdk.MsalTokenProvider(authConfig);
61
- const token = await tokenProvider.getAccessToken("https://graph.microsoft.com");
62
- const accessToken = readAccessToken(token);
199
+
200
+ // Try delegated token if requested and configured
201
+ if (options?.preferDelegated && msteamsCfg?.delegatedAuth?.enabled && creds.type === "secret") {
202
+ const delegated = await resolveDelegatedAccessToken({
203
+ tenantId: creds.tenantId,
204
+ clientId: creds.appId,
205
+ clientSecret: creds.appPassword,
206
+ });
207
+ if (delegated) {
208
+ return delegated;
209
+ }
210
+ // Fall through to app-only token
211
+ }
212
+
213
+ const { app } = await loadMSTeamsSdkWithAuth(creds);
214
+ const tokenProvider = createMSTeamsTokenProvider(app);
215
+ const graphTokenValue = await tokenProvider.getAccessToken("https://graph.microsoft.com");
216
+ const accessToken = readAccessToken(graphTokenValue);
63
217
  if (!accessToken) {
64
218
  throw new Error("MS Teams graph token unavailable");
65
219
  }
@@ -70,12 +224,70 @@ export async function listTeamsByName(token: string, query: string): Promise<Gra
70
224
  const escaped = escapeOData(query);
71
225
  const filter = `resourceProvisioningOptions/Any(x:x eq 'Team') and startsWith(displayName,'${escaped}')`;
72
226
  const path = `/groups?$filter=${encodeURIComponent(filter)}&$select=id,displayName`;
73
- const res = await fetchGraphJson<GraphResponse<GraphGroup>>({ token, path });
74
- return res.value ?? [];
227
+ const { items } = await fetchAllGraphPages<GraphGroup>({ token, path, maxPages: 5 });
228
+ return items;
229
+ }
230
+
231
+ export async function postGraphJson<T>(params: {
232
+ token: string;
233
+ path: string;
234
+ body?: unknown;
235
+ }): Promise<T> {
236
+ const res = await requestGraph({
237
+ token: params.token,
238
+ path: params.path,
239
+ method: "POST",
240
+ body: params.body,
241
+ errorPrefix: "Graph POST",
242
+ });
243
+ return readOptionalGraphJson<T>(res);
244
+ }
245
+
246
+ export async function postGraphBetaJson<T>(params: {
247
+ token: string;
248
+ path: string;
249
+ body?: unknown;
250
+ }): Promise<T> {
251
+ const res = await requestGraph({
252
+ token: params.token,
253
+ path: params.path,
254
+ method: "POST",
255
+ root: GRAPH_BETA,
256
+ body: params.body,
257
+ errorPrefix: "Graph beta POST",
258
+ });
259
+ return readOptionalGraphJson<T>(res);
260
+ }
261
+
262
+ export async function deleteGraphRequest(params: { token: string; path: string }): Promise<void> {
263
+ await requestGraph({
264
+ token: params.token,
265
+ path: params.path,
266
+ method: "DELETE",
267
+ errorPrefix: "Graph DELETE",
268
+ });
269
+ }
270
+
271
+ export async function patchGraphJson<T>(params: {
272
+ token: string;
273
+ path: string;
274
+ body?: unknown;
275
+ }): Promise<T> {
276
+ const res = await requestGraph({
277
+ token: params.token,
278
+ path: params.path,
279
+ method: "PATCH",
280
+ body: params.body,
281
+ errorPrefix: "Graph PATCH",
282
+ });
283
+ if (res.status === 204 || res.headers.get("content-length") === "0") {
284
+ return undefined as T;
285
+ }
286
+ return (await res.json()) as T;
75
287
  }
76
288
 
77
289
  export async function listChannelsForTeam(token: string, teamId: string): Promise<GraphChannel[]> {
78
290
  const path = `/teams/${encodeURIComponent(teamId)}/channels?$select=id,displayName`;
79
- const res = await fetchGraphJson<GraphResponse<GraphChannel>>({ token, path });
80
- return res.value ?? [];
291
+ const { items } = await fetchAllGraphPages<GraphChannel>({ token, path, maxPages: 10 });
292
+ return items;
81
293
  }
@@ -1,5 +1,8 @@
1
1
  import { describe, expect, it } from "vitest";
2
2
  import {
3
+ decodeHtmlEntities,
4
+ extractMSTeamsQuoteInfo,
5
+ htmlToPlainText,
3
6
  normalizeMSTeamsConversationId,
4
7
  parseMSTeamsActivityTimestamp,
5
8
  stripMSTeamsMentionTags,
@@ -35,7 +38,10 @@ describe("msteams inbound", () => {
35
38
 
36
39
  it("parses string timestamps", () => {
37
40
  const ts = parseMSTeamsActivityTimestamp("2024-01-01T00:00:00.000Z");
38
- expect(ts?.toISOString()).toBe("2024-01-01T00:00:00.000Z");
41
+ if (!ts) {
42
+ throw new Error("expected MSTeams timestamp parser to return a Date");
43
+ }
44
+ expect(ts.toISOString()).toBe("2024-01-01T00:00:00.000Z");
39
45
  });
40
46
 
41
47
  it("passes through Date instances", () => {
@@ -63,4 +69,153 @@ describe("msteams inbound", () => {
63
69
  ).toBe(false);
64
70
  });
65
71
  });
72
+
73
+ describe("decodeHtmlEntities", () => {
74
+ it("decodes common entities", () => {
75
+ expect(decodeHtmlEntities("&amp;&lt;&gt;&quot;&#39;&#x27;&nbsp;")).toBe("&<>\"'' ");
76
+ });
77
+
78
+ it("leaves plain text unchanged", () => {
79
+ expect(decodeHtmlEntities("hello world")).toBe("hello world");
80
+ });
81
+
82
+ it("prevents double-decoding: &amp;lt; should become &lt; not <", () => {
83
+ // If &amp; were decoded first, &amp;lt; → &lt; → < (wrong).
84
+ // With &amp; decoded last, &amp;lt; stays as &lt; (correct).
85
+ expect(decodeHtmlEntities("&amp;lt;b&amp;gt;")).toBe("&lt;b&gt;");
86
+ });
87
+ });
88
+
89
+ describe("htmlToPlainText", () => {
90
+ it("strips tags and decodes entities", () => {
91
+ expect(htmlToPlainText("<strong>Hello &amp; world</strong>")).toBe("Hello & world");
92
+ });
93
+
94
+ it("collapses whitespace from tag removal", () => {
95
+ expect(htmlToPlainText("<p>foo</p><p>bar</p>")).toBe("foo bar");
96
+ });
97
+
98
+ it("trims leading and trailing whitespace", () => {
99
+ expect(htmlToPlainText(" <span>hi</span> ")).toBe("hi");
100
+ });
101
+ });
102
+
103
+ describe("extractMSTeamsQuoteInfo", () => {
104
+ const replyAttachment = (overrides?: { content?: string; contentType?: string }) => ({
105
+ contentType: overrides?.contentType ?? "text/html",
106
+ content:
107
+ overrides?.content ??
108
+ '<blockquote itemtype="http://schema.skype.com/Reply" itemscope>' +
109
+ '<strong itemprop="mri">Alice</strong>' +
110
+ '<p itemprop="copy">Hello world</p>' +
111
+ "</blockquote>",
112
+ });
113
+
114
+ it("extracts sender and body from a Teams reply attachment", () => {
115
+ const result = extractMSTeamsQuoteInfo([replyAttachment()]);
116
+ expect(result).toEqual({ sender: "Alice", body: "Hello world" });
117
+ });
118
+
119
+ it("returns undefined for empty attachments array", () => {
120
+ expect(extractMSTeamsQuoteInfo([])).toBeUndefined();
121
+ });
122
+
123
+ it("returns undefined when no reply blockquote is present", () => {
124
+ expect(
125
+ extractMSTeamsQuoteInfo([{ contentType: "text/html", content: "<p>just a message</p>" }]),
126
+ ).toBeUndefined();
127
+ });
128
+
129
+ it("uses 'unknown' as sender when sender element is absent", () => {
130
+ const result = extractMSTeamsQuoteInfo([
131
+ {
132
+ contentType: "text/html",
133
+ content:
134
+ '<blockquote itemtype="http://schema.skype.com/Reply" itemscope>' +
135
+ '<p itemprop="copy">quoted text</p>' +
136
+ "</blockquote>",
137
+ },
138
+ ]);
139
+ expect(result).toEqual({ sender: "unknown", body: "quoted text" });
140
+ });
141
+
142
+ it("returns undefined when body element is absent", () => {
143
+ const result = extractMSTeamsQuoteInfo([
144
+ {
145
+ contentType: "text/html",
146
+ content:
147
+ '<blockquote itemtype="http://schema.skype.com/Reply" itemscope>' +
148
+ '<strong itemprop="mri">Alice</strong>' +
149
+ "</blockquote>",
150
+ },
151
+ ]);
152
+ expect(result).toBeUndefined();
153
+ });
154
+
155
+ it("decodes HTML entities in body text", () => {
156
+ const result = extractMSTeamsQuoteInfo([
157
+ {
158
+ contentType: "text/html",
159
+ content:
160
+ '<blockquote itemtype="http://schema.skype.com/Reply" itemscope>' +
161
+ '<strong itemprop="mri">Bob</strong>' +
162
+ '<p itemprop="copy">2 &lt; 3 &amp; 4 &gt; 1</p>' +
163
+ "</blockquote>",
164
+ },
165
+ ]);
166
+ expect(result).toEqual({ sender: "Bob", body: "2 < 3 & 4 > 1" });
167
+ });
168
+
169
+ it("handles multiline body by collapsing whitespace", () => {
170
+ const result = extractMSTeamsQuoteInfo([
171
+ {
172
+ contentType: "text/html",
173
+ content:
174
+ '<blockquote itemtype="http://schema.skype.com/Reply" itemscope>' +
175
+ '<strong itemprop="mri">Carol</strong>' +
176
+ '<p itemprop="copy">line one\nline two</p>' +
177
+ "</blockquote>",
178
+ },
179
+ ]);
180
+ expect(result?.body).toBe("line one line two");
181
+ });
182
+
183
+ it("skips non-string content values", () => {
184
+ expect(
185
+ extractMSTeamsQuoteInfo([{ contentType: "application/json", content: { foo: "bar" } }]),
186
+ ).toBeUndefined();
187
+ });
188
+
189
+ it("handles object content with .text property containing the reply HTML", () => {
190
+ const htmlContent =
191
+ '<blockquote itemtype="http://schema.skype.com/Reply" itemscope>' +
192
+ '<strong itemprop="mri">Dave</strong>' +
193
+ '<p itemprop="copy">hello from object</p>' +
194
+ "</blockquote>";
195
+ const result = extractMSTeamsQuoteInfo([
196
+ { contentType: "text/html", content: { text: htmlContent } },
197
+ ]);
198
+ expect(result).toEqual({ sender: "Dave", body: "hello from object" });
199
+ });
200
+
201
+ it("handles object content with .body property containing the reply HTML", () => {
202
+ const htmlContent =
203
+ '<blockquote itemtype="http://schema.skype.com/Reply" itemscope>' +
204
+ '<strong itemprop="mri">Eve</strong>' +
205
+ '<p itemprop="copy">hello from body field</p>' +
206
+ "</blockquote>";
207
+ const result = extractMSTeamsQuoteInfo([
208
+ { contentType: "text/html", content: { body: htmlContent } },
209
+ ]);
210
+ expect(result).toEqual({ sender: "Eve", body: "hello from body field" });
211
+ });
212
+
213
+ it("finds quote in second attachment when first has no quote", () => {
214
+ const result = extractMSTeamsQuoteInfo([
215
+ { contentType: "text/plain", content: "plain text" },
216
+ replyAttachment(),
217
+ ]);
218
+ expect(result).toEqual({ sender: "Alice", body: "Hello world" });
219
+ });
220
+ });
66
221
  });
package/src/inbound.ts CHANGED
@@ -1,4 +1,80 @@
1
- export type MentionableActivity = {
1
+ type MSTeamsQuoteInfo = {
2
+ sender: string;
3
+ body: string;
4
+ };
5
+
6
+ /**
7
+ * Decode common HTML entities to plain text.
8
+ */
9
+ export function decodeHtmlEntities(html: string): string {
10
+ return html
11
+ .replace(/&lt;/g, "<")
12
+ .replace(/&gt;/g, ">")
13
+ .replace(/&quot;/g, '"')
14
+ .replace(/&#39;/g, "'")
15
+ .replace(/&#x27;/g, "'")
16
+ .replace(/&nbsp;/g, " ")
17
+ .replace(/&amp;/g, "&"); // must be last to prevent double-decoding (e.g. &amp;lt; → &lt; not <)
18
+ }
19
+
20
+ /**
21
+ * Strip HTML tags, preserving text content.
22
+ */
23
+ export function htmlToPlainText(html: string): string {
24
+ return decodeHtmlEntities(
25
+ html
26
+ .replace(/<[^>]*>/g, " ")
27
+ .replace(/\s+/g, " ")
28
+ .trim(),
29
+ );
30
+ }
31
+
32
+ /**
33
+ * Extract quote info from MS Teams HTML reply attachments.
34
+ * Teams wraps quoted content in a blockquote with itemtype="http://schema.skype.com/Reply".
35
+ */
36
+ export function extractMSTeamsQuoteInfo(
37
+ attachments: Array<{ contentType?: string | null; content?: unknown }>,
38
+ ): MSTeamsQuoteInfo | undefined {
39
+ for (const att of attachments) {
40
+ // Content may be a plain string or an object with .text/.body (e.g. Adaptive Card payloads).
41
+ let content = "";
42
+ if (typeof att.content === "string") {
43
+ content = att.content;
44
+ } else if (typeof att.content === "object" && att.content !== null) {
45
+ const record = att.content as Record<string, unknown>;
46
+ content =
47
+ typeof record.text === "string"
48
+ ? record.text
49
+ : typeof record.body === "string"
50
+ ? record.body
51
+ : "";
52
+ }
53
+ if (!content) {
54
+ continue;
55
+ }
56
+
57
+ // Look for the Skype Reply schema blockquote.
58
+ if (!content.includes("http://schema.skype.com/Reply")) {
59
+ continue;
60
+ }
61
+
62
+ // Extract sender from <strong itemprop="mri">.
63
+ const senderMatch = /<strong[^>]*itemprop=["']mri["'][^>]*>(.*?)<\/strong>/i.exec(content);
64
+ const sender = senderMatch?.[1] ? htmlToPlainText(senderMatch[1]) : undefined;
65
+
66
+ // Extract body from <p itemprop="copy">.
67
+ const bodyMatch = /<p[^>]*itemprop=["']copy["'][^>]*>(.*?)<\/p>/is.exec(content);
68
+ const body = bodyMatch?.[1] ? htmlToPlainText(bodyMatch[1]) : undefined;
69
+
70
+ if (body) {
71
+ return { sender: sender ?? "unknown", body };
72
+ }
73
+ }
74
+ return undefined;
75
+ }
76
+
77
+ type MentionableActivity = {
2
78
  recipient?: { id?: string } | null;
3
79
  entities?: Array<{
4
80
  type?: string;
@@ -38,6 +114,30 @@ export function stripMSTeamsMentionTags(text: string): string {
38
114
  return text.replace(/<at[^>]*>.*?<\/at>/gi, "").trim();
39
115
  }
40
116
 
117
+ /**
118
+ * Bot Framework uses 'a:xxx' conversation IDs for personal chats, but Graph API
119
+ * requires the '19:{userId}_{botAppId}@unq.gbl.spaces' format.
120
+ *
121
+ * This is the documented Graph API format for 1:1 chat thread IDs between a user
122
+ * and a bot/app. See Microsoft docs "Get chat between user and app":
123
+ * https://learn.microsoft.com/en-us/graph/api/userscopeteamsappinstallation-get-chat
124
+ *
125
+ * The format is only synthesized when the Bot Framework conversation ID starts with
126
+ * 'a:' (the opaque format used by BF but not recognized by Graph). If the ID already
127
+ * has the '19:...' Graph format, it is passed through unchanged.
128
+ */
129
+ export function translateMSTeamsDmConversationIdForGraph(params: {
130
+ isDirectMessage: boolean;
131
+ conversationId: string;
132
+ aadObjectId?: string | null;
133
+ appId?: string | null;
134
+ }): string {
135
+ const { isDirectMessage, conversationId, aadObjectId, appId } = params;
136
+ return isDirectMessage && conversationId.startsWith("a:") && aadObjectId && appId
137
+ ? `19:${aadObjectId}_${appId}@unq.gbl.spaces`
138
+ : conversationId;
139
+ }
140
+
41
141
  export function wasMSTeamsBotMentioned(activity: MentionableActivity): boolean {
42
142
  const botId = activity.recipient?.id;
43
143
  if (!botId) {
@@ -8,7 +8,7 @@ import {
8
8
  extensionForMime,
9
9
  extractOriginalFilename,
10
10
  getFileExtension,
11
- } from "openclaw/plugin-sdk/msteams";
11
+ } from "../runtime-api.js";
12
12
 
13
13
  /**
14
14
  * Detect MIME type from URL extension or data URL.