@kodelyth/msteams 2026.5.39 → 2026.5.42

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 (208) 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/dist/api.js +3 -0
  7. package/dist/channel-BvTXHuGs.js +1161 -0
  8. package/dist/channel-config-api.js +2 -0
  9. package/dist/channel-plugin-api.js +2 -0
  10. package/dist/channel.runtime-NssGKZm5.js +650 -0
  11. package/dist/config-schema-Btk-XCOd.js +43 -0
  12. package/dist/contract-api.js +2 -0
  13. package/dist/graph-users-D-gKCguI.js +1411 -0
  14. package/dist/index.js +22 -0
  15. package/dist/oauth-BUxlphX3.js +114 -0
  16. package/dist/oauth.token-ebId9946.js +116 -0
  17. package/dist/probe-Cj2KsAGF.js +2190 -0
  18. package/dist/runtime-api-BL4DOWXD.js +28 -0
  19. package/dist/runtime-api.js +2 -0
  20. package/dist/secret-contract-Bo7kdUrT.js +35 -0
  21. package/dist/secret-contract-api.js +2 -0
  22. package/dist/setup-entry.js +15 -0
  23. package/dist/setup-plugin-api.js +64 -0
  24. package/dist/setup-surface-COTQDcTQ.js +531 -0
  25. package/dist/src-tvpsGYPV.js +4226 -0
  26. package/dist/test-api.js +2 -0
  27. package/index.ts +20 -0
  28. package/klaw.plugin.json +2 -726
  29. package/package.json +4 -4
  30. package/runtime-api.ts +66 -0
  31. package/secret-contract-api.ts +5 -0
  32. package/setup-entry.ts +13 -0
  33. package/setup-plugin-api.ts +3 -0
  34. package/src/ai-entity.ts +7 -0
  35. package/src/approval-auth.ts +44 -0
  36. package/src/attachments/bot-framework.test.ts +506 -0
  37. package/src/attachments/bot-framework.ts +348 -0
  38. package/src/attachments/download.ts +328 -0
  39. package/src/attachments/graph.test.ts +441 -0
  40. package/src/attachments/graph.ts +489 -0
  41. package/src/attachments/html.ts +122 -0
  42. package/src/attachments/payload.ts +14 -0
  43. package/src/attachments/remote-media.test.ts +187 -0
  44. package/src/attachments/remote-media.ts +86 -0
  45. package/src/attachments/shared.test.ts +547 -0
  46. package/src/attachments/shared.ts +655 -0
  47. package/src/attachments/types.ts +47 -0
  48. package/src/attachments.graph.test.ts +414 -0
  49. package/src/attachments.helpers.test.ts +245 -0
  50. package/src/attachments.test-helpers.ts +17 -0
  51. package/src/attachments.test.ts +754 -0
  52. package/src/attachments.ts +18 -0
  53. package/src/block-streaming-config.test.ts +61 -0
  54. package/src/channel-api.ts +1 -0
  55. package/src/channel.actions.test.ts +797 -0
  56. package/src/channel.directory.test.ts +176 -0
  57. package/src/channel.message-adapter.test.ts +227 -0
  58. package/src/channel.runtime.ts +56 -0
  59. package/src/channel.setup.ts +77 -0
  60. package/src/channel.test.ts +136 -0
  61. package/src/channel.ts +1176 -0
  62. package/src/config-schema.ts +6 -0
  63. package/src/config-ui-hints.ts +40 -0
  64. package/src/conversation-store-fs.test.ts +81 -0
  65. package/src/conversation-store-fs.ts +149 -0
  66. package/src/conversation-store-helpers.test.ts +202 -0
  67. package/src/conversation-store-helpers.ts +105 -0
  68. package/src/conversation-store-memory.ts +51 -0
  69. package/src/conversation-store.shared.test.ts +260 -0
  70. package/src/conversation-store.ts +71 -0
  71. package/src/directory-live.test.ts +156 -0
  72. package/src/directory-live.ts +111 -0
  73. package/src/doctor.ts +27 -0
  74. package/src/errors.test.ts +154 -0
  75. package/src/errors.ts +270 -0
  76. package/src/feedback-reflection-prompt.ts +117 -0
  77. package/src/feedback-reflection-store.ts +113 -0
  78. package/src/feedback-reflection.test.ts +237 -0
  79. package/src/feedback-reflection.ts +268 -0
  80. package/src/file-consent-helpers.test.ts +328 -0
  81. package/src/file-consent-helpers.ts +115 -0
  82. package/src/file-consent-invoke.ts +150 -0
  83. package/src/file-consent.test.ts +378 -0
  84. package/src/file-consent.ts +223 -0
  85. package/src/graph-chat.ts +36 -0
  86. package/src/graph-group-management.test.ts +332 -0
  87. package/src/graph-group-management.ts +168 -0
  88. package/src/graph-members.test.ts +89 -0
  89. package/src/graph-members.ts +48 -0
  90. package/src/graph-messages.actions.test.ts +253 -0
  91. package/src/graph-messages.read.test.ts +391 -0
  92. package/src/graph-messages.search.test.ts +227 -0
  93. package/src/graph-messages.test-helpers.ts +50 -0
  94. package/src/graph-messages.ts +534 -0
  95. package/src/graph-teams.test.ts +222 -0
  96. package/src/graph-teams.ts +114 -0
  97. package/src/graph-thread.test.ts +252 -0
  98. package/src/graph-thread.ts +146 -0
  99. package/src/graph-upload.test.ts +253 -0
  100. package/src/graph-upload.ts +531 -0
  101. package/src/graph-users.ts +29 -0
  102. package/src/graph.test.ts +540 -0
  103. package/src/graph.ts +308 -0
  104. package/src/inbound.test.ts +221 -0
  105. package/src/inbound.ts +148 -0
  106. package/src/index.ts +4 -0
  107. package/src/media-helpers.test.ts +220 -0
  108. package/src/media-helpers.ts +105 -0
  109. package/src/mentions.test.ts +254 -0
  110. package/src/mentions.ts +114 -0
  111. package/src/messenger.test.ts +961 -0
  112. package/src/messenger.ts +608 -0
  113. package/src/monitor-handler/access.ts +136 -0
  114. package/src/monitor-handler/inbound-media.test.ts +314 -0
  115. package/src/monitor-handler/inbound-media.ts +180 -0
  116. package/src/monitor-handler/message-handler-mock-support.test-support.ts +28 -0
  117. package/src/monitor-handler/message-handler.authz.test.ts +739 -0
  118. package/src/monitor-handler/message-handler.dm-media.test.ts +54 -0
  119. package/src/monitor-handler/message-handler.test-support.ts +99 -0
  120. package/src/monitor-handler/message-handler.thread-parent.test.ts +225 -0
  121. package/src/monitor-handler/message-handler.thread-session.test.ts +132 -0
  122. package/src/monitor-handler/message-handler.ts +1003 -0
  123. package/src/monitor-handler/reaction-handler.test.ts +325 -0
  124. package/src/monitor-handler/reaction-handler.ts +122 -0
  125. package/src/monitor-handler/thread-session.ts +30 -0
  126. package/src/monitor-handler.adaptive-card.test.ts +158 -0
  127. package/src/monitor-handler.feedback-authz.test.ts +357 -0
  128. package/src/monitor-handler.file-consent.test.ts +443 -0
  129. package/src/monitor-handler.sso.test.ts +576 -0
  130. package/src/monitor-handler.test-helpers.ts +181 -0
  131. package/src/monitor-handler.ts +538 -0
  132. package/src/monitor-handler.types.ts +27 -0
  133. package/src/monitor-types.ts +6 -0
  134. package/src/monitor.lifecycle.test.ts +457 -0
  135. package/src/monitor.test.ts +119 -0
  136. package/src/monitor.ts +476 -0
  137. package/src/oauth.flow.ts +77 -0
  138. package/src/oauth.shared.ts +37 -0
  139. package/src/oauth.test.ts +350 -0
  140. package/src/oauth.token.ts +162 -0
  141. package/src/oauth.ts +130 -0
  142. package/src/outbound.test.ts +400 -0
  143. package/src/outbound.ts +198 -0
  144. package/src/pending-uploads-fs.test.ts +261 -0
  145. package/src/pending-uploads-fs.ts +235 -0
  146. package/src/pending-uploads.test.ts +186 -0
  147. package/src/pending-uploads.ts +121 -0
  148. package/src/policy.test.ts +156 -0
  149. package/src/policy.ts +245 -0
  150. package/src/polls-store-memory.ts +32 -0
  151. package/src/polls.test.ts +169 -0
  152. package/src/polls.ts +312 -0
  153. package/src/presentation.ts +93 -0
  154. package/src/probe.test.ts +79 -0
  155. package/src/probe.ts +132 -0
  156. package/src/reply-dispatcher.test.ts +543 -0
  157. package/src/reply-dispatcher.ts +523 -0
  158. package/src/reply-stream-controller.test.ts +424 -0
  159. package/src/reply-stream-controller.ts +334 -0
  160. package/src/resolve-allowlist.test.ts +253 -0
  161. package/src/resolve-allowlist.ts +309 -0
  162. package/src/revoked-context.ts +17 -0
  163. package/src/runtime.ts +12 -0
  164. package/src/sdk-types.ts +59 -0
  165. package/src/sdk.test.ts +727 -0
  166. package/src/sdk.ts +916 -0
  167. package/src/secret-contract.ts +49 -0
  168. package/src/secret-input.ts +7 -0
  169. package/src/send-context.test.ts +93 -0
  170. package/src/send-context.ts +269 -0
  171. package/src/send.test.ts +588 -0
  172. package/src/send.ts +697 -0
  173. package/src/sent-message-cache.test.ts +106 -0
  174. package/src/sent-message-cache.ts +174 -0
  175. package/src/session-route.ts +40 -0
  176. package/src/setup-core.ts +162 -0
  177. package/src/setup-surface.test.ts +175 -0
  178. package/src/setup-surface.ts +319 -0
  179. package/src/sso-token-store.test.ts +74 -0
  180. package/src/sso-token-store.ts +166 -0
  181. package/src/sso.ts +300 -0
  182. package/src/storage.ts +25 -0
  183. package/src/store-fs.ts +42 -0
  184. package/src/streaming-message.test.ts +323 -0
  185. package/src/streaming-message.ts +327 -0
  186. package/src/test-runtime.ts +16 -0
  187. package/src/thread-parent-context.test.ts +224 -0
  188. package/src/thread-parent-context.ts +159 -0
  189. package/src/token-response.ts +11 -0
  190. package/src/token.test.ts +268 -0
  191. package/src/token.ts +194 -0
  192. package/src/user-agent.test.ts +121 -0
  193. package/src/user-agent.ts +53 -0
  194. package/src/webhook-timeouts.ts +27 -0
  195. package/src/welcome-card.test.ts +104 -0
  196. package/src/welcome-card.ts +57 -0
  197. package/test-api.ts +1 -0
  198. package/tsconfig.json +16 -0
  199. package/api.js +0 -7
  200. package/channel-config-api.js +0 -7
  201. package/channel-plugin-api.js +0 -7
  202. package/contract-api.js +0 -7
  203. package/index.js +0 -7
  204. package/runtime-api.js +0 -7
  205. package/secret-contract-api.js +0 -7
  206. package/setup-entry.js +0 -7
  207. package/setup-plugin-api.js +0 -7
  208. package/test-api.js +0 -7
package/src/sso.ts ADDED
@@ -0,0 +1,300 @@
1
+ /**
2
+ * Bot Framework OAuth SSO invoke handlers for Microsoft Teams.
3
+ *
4
+ * Handles two invoke activities Teams sends when the bot has presented
5
+ * an `oauthCard` or when the user completes an interactive sign-in:
6
+ *
7
+ * 1. `signin/tokenExchange`
8
+ * The Teams client obtained an exchangeable token from the bot's
9
+ * AAD app and forwards it to the bot. The bot exchanges that token
10
+ * with the Bot Framework User Token service, which returns the real
11
+ * delegated user token (for example, a Microsoft Graph access token
12
+ * if the OAuth connection is set up for Graph).
13
+ *
14
+ * 2. `signin/verifyState`
15
+ * Fallback for the magic-code flow: the user finishes sign-in in a
16
+ * browser tab, receives a 6-digit code, and pastes it back into the
17
+ * chat. The bot then asks the User Token service for the token
18
+ * corresponding to that code.
19
+ *
20
+ * In both cases the bot must reply with an `invokeResponse` (HTTP 200)
21
+ * immediately or the Teams UI shows "Something went wrong". Callers of
22
+ * {@link handleSigninTokenExchangeInvoke} and
23
+ * {@link handleSigninVerifyStateInvoke} are responsible for sending
24
+ * that ack; these helpers encapsulate token exchange and persistence.
25
+ */
26
+
27
+ import type { MSTeamsAccessTokenProvider } from "./attachments/types.js";
28
+ import type { MSTeamsSsoTokenStore } from "./sso-token-store.js";
29
+ import { buildUserAgent } from "./user-agent.js";
30
+
31
+ /** Scope used to obtain a Bot Framework service token. */
32
+ const BOT_FRAMEWORK_TOKEN_SCOPE = "https://api.botframework.com/.default";
33
+
34
+ /** Bot Framework User Token service base URL. */
35
+ const BOT_FRAMEWORK_USER_TOKEN_BASE_URL = "https://token.botframework.com";
36
+
37
+ /**
38
+ * Response shape returned by the Bot Framework User Token service for
39
+ * `GetUserToken` and `ExchangeToken`.
40
+ *
41
+ * @see https://learn.microsoft.com/azure/bot-service/rest-api/bot-framework-rest-connector-user-token-service
42
+ */
43
+ type BotFrameworkUserTokenResponse = {
44
+ channelId?: string;
45
+ connectionName: string;
46
+ token: string;
47
+ expiration?: string;
48
+ };
49
+
50
+ export type MSTeamsSsoFetch = (
51
+ input: string,
52
+ init?: {
53
+ method?: string;
54
+ headers?: Record<string, string>;
55
+ body?: string;
56
+ },
57
+ ) => Promise<{
58
+ ok: boolean;
59
+ status: number;
60
+ json(): Promise<unknown>;
61
+ text(): Promise<string>;
62
+ }>;
63
+
64
+ export type MSTeamsSsoDeps = {
65
+ tokenProvider: MSTeamsAccessTokenProvider;
66
+ tokenStore: MSTeamsSsoTokenStore;
67
+ connectionName: string;
68
+ /** Override `fetch` for testing. */
69
+ fetchImpl?: MSTeamsSsoFetch;
70
+ /** Override the User Token service base URL (testing / sovereign clouds). */
71
+ userTokenBaseUrl?: string;
72
+ };
73
+
74
+ type MSTeamsSsoUser = {
75
+ /** Stable user identifier — AAD object ID when available. */
76
+ userId: string;
77
+ /** Bot Framework channel ID (default: "msteams"). */
78
+ channelId?: string;
79
+ };
80
+
81
+ type MSTeamsSsoResult =
82
+ | {
83
+ ok: true;
84
+ token: string;
85
+ expiresAt?: string;
86
+ }
87
+ | {
88
+ ok: false;
89
+ code:
90
+ | "missing_user"
91
+ | "missing_connection"
92
+ | "missing_token"
93
+ | "missing_state"
94
+ | "service_error"
95
+ | "unexpected_response";
96
+ message: string;
97
+ status?: number;
98
+ };
99
+
100
+ type SigninTokenExchangeValue = {
101
+ id?: string;
102
+ connectionName?: string;
103
+ token?: string;
104
+ };
105
+
106
+ type SigninVerifyStateValue = {
107
+ state?: string;
108
+ };
109
+
110
+ /**
111
+ * Extract and validate the `signin/tokenExchange` activity value. Teams
112
+ * delivers `{ id, connectionName, token }`; any field may be missing on
113
+ * malformed invocations, so callers should check the parsed result.
114
+ */
115
+ export function parseSigninTokenExchangeValue(value: unknown): SigninTokenExchangeValue | null {
116
+ if (!value || typeof value !== "object") {
117
+ return null;
118
+ }
119
+ const obj = value as Record<string, unknown>;
120
+ const id = typeof obj.id === "string" ? obj.id : undefined;
121
+ const connectionName = typeof obj.connectionName === "string" ? obj.connectionName : undefined;
122
+ const token = typeof obj.token === "string" ? obj.token : undefined;
123
+ return { id, connectionName, token };
124
+ }
125
+
126
+ /** Extract the `signin/verifyState` activity value `{ state }`. */
127
+ export function parseSigninVerifyStateValue(value: unknown): SigninVerifyStateValue | null {
128
+ if (!value || typeof value !== "object") {
129
+ return null;
130
+ }
131
+ const obj = value as Record<string, unknown>;
132
+ const state = typeof obj.state === "string" ? obj.state : undefined;
133
+ return { state };
134
+ }
135
+
136
+ type UserTokenServiceCallParams = {
137
+ baseUrl: string;
138
+ path: string;
139
+ query: Record<string, string>;
140
+ method: "GET" | "POST";
141
+ body?: unknown;
142
+ bearerToken: string;
143
+ fetchImpl: MSTeamsSsoFetch;
144
+ };
145
+
146
+ async function callUserTokenService(
147
+ params: UserTokenServiceCallParams,
148
+ ): Promise<BotFrameworkUserTokenResponse | { error: string; status: number }> {
149
+ const qs = new URLSearchParams(params.query).toString();
150
+ const url = `${params.baseUrl.replace(/\/+$/, "")}${params.path}?${qs}`;
151
+ const headers: Record<string, string> = {
152
+ Accept: "application/json",
153
+ Authorization: `Bearer ${params.bearerToken}`,
154
+ "User-Agent": buildUserAgent(),
155
+ };
156
+ if (params.body !== undefined) {
157
+ headers["Content-Type"] = "application/json";
158
+ }
159
+ const response = await params.fetchImpl(url, {
160
+ method: params.method,
161
+ headers,
162
+ body: params.body === undefined ? undefined : JSON.stringify(params.body),
163
+ });
164
+ if (!response.ok) {
165
+ const text = await response.text().catch(() => "");
166
+ return { error: text || `HTTP ${response.status}`, status: response.status };
167
+ }
168
+ let parsed: unknown;
169
+ try {
170
+ parsed = await response.json();
171
+ } catch {
172
+ return { error: "invalid JSON from User Token service", status: response.status };
173
+ }
174
+ if (!parsed || typeof parsed !== "object") {
175
+ return { error: "empty response from User Token service", status: response.status };
176
+ }
177
+ const obj = parsed as Record<string, unknown>;
178
+ const token = typeof obj.token === "string" ? obj.token : undefined;
179
+ const connectionName = typeof obj.connectionName === "string" ? obj.connectionName : undefined;
180
+ const channelId = typeof obj.channelId === "string" ? obj.channelId : undefined;
181
+ const expiration = typeof obj.expiration === "string" ? obj.expiration : undefined;
182
+ if (!token || !connectionName) {
183
+ return { error: "User Token service response missing token/connectionName", status: 502 };
184
+ }
185
+ return { channelId, connectionName, token, expiration };
186
+ }
187
+
188
+ /**
189
+ * Exchange a Teams SSO token for a delegated user token via Bot
190
+ * Framework's User Token service, then persist the result.
191
+ */
192
+ export async function handleSigninTokenExchangeInvoke(params: {
193
+ value: SigninTokenExchangeValue;
194
+ user: MSTeamsSsoUser;
195
+ deps: MSTeamsSsoDeps;
196
+ }): Promise<MSTeamsSsoResult> {
197
+ const { value, user, deps } = params;
198
+ if (!user.userId) {
199
+ return { ok: false, code: "missing_user", message: "no user id on invoke activity" };
200
+ }
201
+ const connectionName = value.connectionName?.trim() || deps.connectionName;
202
+ if (!connectionName) {
203
+ return { ok: false, code: "missing_connection", message: "no OAuth connection name" };
204
+ }
205
+ if (!value.token) {
206
+ return { ok: false, code: "missing_token", message: "no exchangeable token on invoke" };
207
+ }
208
+
209
+ const bearer = await deps.tokenProvider.getAccessToken(BOT_FRAMEWORK_TOKEN_SCOPE);
210
+ const fetchImpl = deps.fetchImpl ?? (globalThis.fetch as unknown as MSTeamsSsoFetch);
211
+ const result = await callUserTokenService({
212
+ baseUrl: deps.userTokenBaseUrl ?? BOT_FRAMEWORK_USER_TOKEN_BASE_URL,
213
+ path: "/api/usertoken/exchange",
214
+ query: {
215
+ userId: user.userId,
216
+ connectionName,
217
+ channelId: user.channelId ?? "msteams",
218
+ },
219
+ method: "POST",
220
+ body: { token: value.token },
221
+ bearerToken: bearer,
222
+ fetchImpl,
223
+ });
224
+
225
+ if ("error" in result) {
226
+ return {
227
+ ok: false,
228
+ code: result.status >= 500 ? "service_error" : "unexpected_response",
229
+ message: result.error,
230
+ status: result.status,
231
+ };
232
+ }
233
+
234
+ await deps.tokenStore.save({
235
+ connectionName,
236
+ userId: user.userId,
237
+ token: result.token,
238
+ expiresAt: result.expiration,
239
+ updatedAt: new Date().toISOString(),
240
+ });
241
+
242
+ return { ok: true, token: result.token, expiresAt: result.expiration };
243
+ }
244
+
245
+ /**
246
+ * Finish a magic-code sign-in: look up the user token for the state
247
+ * code via Bot Framework's User Token service, then persist it.
248
+ */
249
+ export async function handleSigninVerifyStateInvoke(params: {
250
+ value: SigninVerifyStateValue;
251
+ user: MSTeamsSsoUser;
252
+ deps: MSTeamsSsoDeps;
253
+ }): Promise<MSTeamsSsoResult> {
254
+ const { value, user, deps } = params;
255
+ if (!user.userId) {
256
+ return { ok: false, code: "missing_user", message: "no user id on invoke activity" };
257
+ }
258
+ if (!deps.connectionName) {
259
+ return { ok: false, code: "missing_connection", message: "no OAuth connection name" };
260
+ }
261
+ const state = value.state?.trim();
262
+ if (!state) {
263
+ return { ok: false, code: "missing_state", message: "no state code on invoke" };
264
+ }
265
+
266
+ const bearer = await deps.tokenProvider.getAccessToken(BOT_FRAMEWORK_TOKEN_SCOPE);
267
+ const fetchImpl = deps.fetchImpl ?? (globalThis.fetch as unknown as MSTeamsSsoFetch);
268
+ const result = await callUserTokenService({
269
+ baseUrl: deps.userTokenBaseUrl ?? BOT_FRAMEWORK_USER_TOKEN_BASE_URL,
270
+ path: "/api/usertoken/GetToken",
271
+ query: {
272
+ userId: user.userId,
273
+ connectionName: deps.connectionName,
274
+ channelId: user.channelId ?? "msteams",
275
+ code: state,
276
+ },
277
+ method: "GET",
278
+ bearerToken: bearer,
279
+ fetchImpl,
280
+ });
281
+
282
+ if ("error" in result) {
283
+ return {
284
+ ok: false,
285
+ code: result.status >= 500 ? "service_error" : "unexpected_response",
286
+ message: result.error,
287
+ status: result.status,
288
+ };
289
+ }
290
+
291
+ await deps.tokenStore.save({
292
+ connectionName: deps.connectionName,
293
+ userId: user.userId,
294
+ token: result.token,
295
+ expiresAt: result.expiration,
296
+ updatedAt: new Date().toISOString(),
297
+ });
298
+
299
+ return { ok: true, token: result.token, expiresAt: result.expiration };
300
+ }
package/src/storage.ts ADDED
@@ -0,0 +1,25 @@
1
+ import path from "node:path";
2
+ import { getMSTeamsRuntime } from "./runtime.js";
3
+
4
+ type MSTeamsStorePathOptions = {
5
+ env?: NodeJS.ProcessEnv;
6
+ homedir?: () => string;
7
+ stateDir?: string;
8
+ storePath?: string;
9
+ filename: string;
10
+ };
11
+
12
+ export function resolveMSTeamsStorePath(params: MSTeamsStorePathOptions): string {
13
+ if (params.storePath) {
14
+ return params.storePath;
15
+ }
16
+ if (params.stateDir) {
17
+ return path.join(params.stateDir, params.filename);
18
+ }
19
+
20
+ const env = params.env ?? process.env;
21
+ const stateDir = params.homedir
22
+ ? getMSTeamsRuntime().state.resolveStateDir(env, params.homedir)
23
+ : getMSTeamsRuntime().state.resolveStateDir(env);
24
+ return path.join(stateDir, params.filename);
25
+ }
@@ -0,0 +1,42 @@
1
+ import { withFileLock as withPathLock } from "klaw/plugin-sdk/file-lock";
2
+ import { readJsonFileWithFallback, writeJsonFileAtomically } from "klaw/plugin-sdk/json-store";
3
+ import { pathExists } from "klaw/plugin-sdk/security-runtime";
4
+
5
+ const STORE_LOCK_OPTIONS = {
6
+ retries: {
7
+ retries: 10,
8
+ factor: 2,
9
+ minTimeout: 100,
10
+ maxTimeout: 10_000,
11
+ randomize: true,
12
+ },
13
+ stale: 30_000,
14
+ } as const;
15
+
16
+ export async function readJsonFile<T>(
17
+ filePath: string,
18
+ fallback: T,
19
+ ): Promise<{ value: T; exists: boolean }> {
20
+ return await readJsonFileWithFallback(filePath, fallback);
21
+ }
22
+
23
+ export async function writeJsonFile(filePath: string, value: unknown): Promise<void> {
24
+ await writeJsonFileAtomically(filePath, value);
25
+ }
26
+
27
+ async function ensureJsonFile(filePath: string, fallback: unknown) {
28
+ if (!(await pathExists(filePath))) {
29
+ await writeJsonFile(filePath, fallback);
30
+ }
31
+ }
32
+
33
+ export async function withFileLock<T>(
34
+ filePath: string,
35
+ fallback: unknown,
36
+ fn: () => Promise<T>,
37
+ ): Promise<T> {
38
+ await ensureJsonFile(filePath, fallback);
39
+ return await withPathLock(filePath, STORE_LOCK_OPTIONS, async () => {
40
+ return await fn();
41
+ });
42
+ }
@@ -0,0 +1,323 @@
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
+ import { TeamsHttpStream } from "./streaming-message.js";
3
+
4
+ async function flushStreamTimer(): Promise<void> {
5
+ await vi.advanceTimersByTimeAsync(1);
6
+ }
7
+
8
+ function requireMessageActivity(sent: unknown[]): Record<string, unknown> {
9
+ const activity = sent.find((entry) => (entry as Record<string, unknown>).type === "message") as
10
+ | Record<string, unknown>
11
+ | undefined;
12
+ if (!activity) {
13
+ throw new Error("expected final Teams message activity");
14
+ }
15
+ return activity;
16
+ }
17
+
18
+ function requireEntities(activity: Record<string, unknown>): Array<Record<string, unknown>> {
19
+ const entities = activity.entities;
20
+ if (!Array.isArray(entities)) {
21
+ throw new Error("expected Teams activity entities");
22
+ }
23
+ return entities as Array<Record<string, unknown>>;
24
+ }
25
+
26
+ function requireEntity(
27
+ activity: Record<string, unknown>,
28
+ predicate: (entity: Record<string, unknown>) => boolean,
29
+ label: string,
30
+ ): Record<string, unknown> {
31
+ const entity = requireEntities(activity).find(predicate);
32
+ if (!entity) {
33
+ throw new Error(`expected ${label} entity`);
34
+ }
35
+ return entity;
36
+ }
37
+
38
+ function requireSendActivity(
39
+ sendActivity: ReturnType<typeof vi.fn>,
40
+ predicate: (activity: Record<string, unknown>) => boolean,
41
+ label: string,
42
+ ): Record<string, unknown> {
43
+ const activity = sendActivity.mock.calls
44
+ .map(([sent]) => sent as Record<string, unknown>)
45
+ .find(predicate);
46
+ if (!activity) {
47
+ throw new Error(`expected ${label} sendActivity call`);
48
+ }
49
+ return activity;
50
+ }
51
+
52
+ describe("TeamsHttpStream", () => {
53
+ afterEach(() => {
54
+ vi.useRealTimers();
55
+ });
56
+
57
+ it("sends first chunk as typing activity with streaminfo", async () => {
58
+ vi.useFakeTimers();
59
+
60
+ const sent: unknown[] = [];
61
+ const stream = new TeamsHttpStream({
62
+ sendActivity: vi.fn(async (activity) => {
63
+ sent.push(activity);
64
+ return { id: "stream-1" };
65
+ }),
66
+ throttleMs: 1,
67
+ });
68
+
69
+ // Enough text to pass MIN_INITIAL_CHARS threshold
70
+ stream.update("Hello, this is a test response that is long enough.");
71
+ await flushStreamTimer();
72
+
73
+ expect(sent.length).toBeGreaterThanOrEqual(1);
74
+ const firstActivity = sent[0] as Record<string, unknown>;
75
+ expect(firstActivity.type).toBe("typing");
76
+ expect(typeof firstActivity.text).toBe("string");
77
+ expect(firstActivity.text as string).toContain("Hello");
78
+ // Should have streaminfo entity
79
+ const streamInfo = requireEntity(
80
+ firstActivity,
81
+ (entity) => entity.type === "streaminfo",
82
+ "streaminfo",
83
+ );
84
+ expect(streamInfo.streamType).toBe("streaming");
85
+ });
86
+
87
+ it("sends final message activity on finalize", async () => {
88
+ vi.useFakeTimers();
89
+
90
+ const sent: unknown[] = [];
91
+ const stream = new TeamsHttpStream({
92
+ sendActivity: vi.fn(async (activity) => {
93
+ sent.push(activity);
94
+ return { id: "stream-1" };
95
+ }),
96
+ throttleMs: 1,
97
+ });
98
+
99
+ stream.update("Hello, this is a complete response for finalization testing.");
100
+ await flushStreamTimer();
101
+
102
+ await stream.finalize();
103
+
104
+ // Find the final message activity
105
+ const finalActivity = requireMessageActivity(sent);
106
+
107
+ expect(finalActivity.text).toBe("Hello, this is a complete response for finalization testing.");
108
+ // No cursor in final
109
+ expect(finalActivity.text as string).not.toContain("\u258D");
110
+
111
+ // Should have AI-generated entity
112
+ const aiGenerated = requireEntity(
113
+ finalActivity,
114
+ (entity) =>
115
+ Array.isArray(entity.additionalType) &&
116
+ entity.additionalType.includes("AIGeneratedContent"),
117
+ "AI-generated content",
118
+ );
119
+ expect(aiGenerated.additionalType).toEqual(["AIGeneratedContent"]);
120
+
121
+ // Should have streaminfo with final type
122
+ const streamInfo = requireEntity(
123
+ finalActivity,
124
+ (entity) => entity.type === "streaminfo",
125
+ "streaminfo",
126
+ );
127
+ expect(streamInfo.streamType).toBe("final");
128
+ });
129
+
130
+ it("does not send below MIN_INITIAL_CHARS", async () => {
131
+ vi.useFakeTimers();
132
+
133
+ const sendActivity = vi.fn(async () => ({ id: "x" }));
134
+ const stream = new TeamsHttpStream({ sendActivity, throttleMs: 1 });
135
+
136
+ stream.update("Hi");
137
+ await flushStreamTimer();
138
+
139
+ expect(sendActivity).not.toHaveBeenCalled();
140
+ });
141
+
142
+ it("finalize with no content does nothing", async () => {
143
+ const sendActivity = vi.fn(async () => ({ id: "x" }));
144
+ const stream = new TeamsHttpStream({ sendActivity });
145
+
146
+ await stream.finalize();
147
+ expect(sendActivity).not.toHaveBeenCalled();
148
+ });
149
+
150
+ it("finalize sends content even if no chunks were streamed", async () => {
151
+ const sent: unknown[] = [];
152
+ const stream = new TeamsHttpStream({
153
+ sendActivity: vi.fn(async (activity) => {
154
+ sent.push(activity);
155
+ return { id: "msg-1" };
156
+ }),
157
+ });
158
+
159
+ // Short text — below MIN_INITIAL_CHARS, so no streaming chunk sent
160
+ stream.update("Short");
161
+ await stream.finalize();
162
+
163
+ // Should send final message even though no chunks were streamed
164
+ expect(sent.length).toBe(1);
165
+ const activity = sent[0] as Record<string, unknown>;
166
+ expect(activity.type).toBe("message");
167
+ expect(activity.text).toBe("Short");
168
+ });
169
+
170
+ it("sets feedbackLoopEnabled on final message", async () => {
171
+ vi.useFakeTimers();
172
+
173
+ const sent: unknown[] = [];
174
+ const stream = new TeamsHttpStream({
175
+ sendActivity: vi.fn(async (activity) => {
176
+ sent.push(activity);
177
+ return { id: "stream-1" };
178
+ }),
179
+ feedbackLoopEnabled: true,
180
+ throttleMs: 1,
181
+ });
182
+
183
+ stream.update("A response long enough to pass the minimum character threshold for streaming.");
184
+ await flushStreamTimer();
185
+ await stream.finalize();
186
+
187
+ const finalActivity = sent.find(
188
+ (a) => (a as Record<string, unknown>).type === "message",
189
+ ) as Record<string, unknown>;
190
+
191
+ const channelData = finalActivity.channelData as Record<string, unknown>;
192
+ expect(channelData.feedbackLoopEnabled).toBe(true);
193
+ });
194
+
195
+ it("sends informative update with streamType informative", async () => {
196
+ const sent: unknown[] = [];
197
+ const stream = new TeamsHttpStream({
198
+ sendActivity: vi.fn(async (activity) => {
199
+ sent.push(activity);
200
+ return { id: "stream-1" };
201
+ }),
202
+ });
203
+
204
+ await stream.sendInformativeUpdate("Thinking...");
205
+
206
+ expect(sent.length).toBe(1);
207
+ const activity = sent[0] as Record<string, unknown>;
208
+ expect(activity.type).toBe("typing");
209
+ expect(activity.text).toBe("Thinking...");
210
+ const streamInfo = requireEntity(
211
+ activity,
212
+ (entity) => entity.type === "streaminfo",
213
+ "streaminfo",
214
+ );
215
+ expect(streamInfo.streamType).toBe("informative");
216
+ expect(streamInfo.streamSequence).toBe(1);
217
+ });
218
+
219
+ it("informative update establishes streamId for subsequent chunks", async () => {
220
+ vi.useFakeTimers();
221
+
222
+ const sent: unknown[] = [];
223
+ const stream = new TeamsHttpStream({
224
+ sendActivity: vi.fn(async (activity) => {
225
+ sent.push(activity);
226
+ return { id: "stream-1" };
227
+ }),
228
+ throttleMs: 1,
229
+ });
230
+
231
+ await stream.sendInformativeUpdate("Working...");
232
+ stream.update("Hello, this is a long enough response for streaming to begin.");
233
+ await flushStreamTimer();
234
+
235
+ // Second activity (streaming chunk) should have the streamId from the informative update
236
+ expect(sent.length).toBeGreaterThanOrEqual(2);
237
+ const chunk = sent[1] as Record<string, unknown>;
238
+ const streamInfo = requireEntity(chunk, (entity) => entity.type === "streaminfo", "streaminfo");
239
+ expect(streamInfo.streamId).toBe("stream-1");
240
+ });
241
+
242
+ it("reports failure when replacing informative progress with final text fails", async () => {
243
+ const sendActivity = vi.fn(async (activity: Record<string, unknown>) => {
244
+ if (activity.type === "message") {
245
+ throw new Error("final send rejected");
246
+ }
247
+ return { id: "stream-1" };
248
+ });
249
+ const stream = new TeamsHttpStream({ sendActivity, throttleMs: 1 });
250
+
251
+ await stream.sendInformativeUpdate("Thinking");
252
+ const carried = await stream.replaceInformativeWithFinal(
253
+ "Final response long enough to stream before the final message send fails.",
254
+ );
255
+
256
+ expect(carried).toBe(false);
257
+ expect(stream.isFailed).toBe(true);
258
+ const finalSend = requireSendActivity(
259
+ sendActivity,
260
+ (activity) => activity.type === "message",
261
+ "final message",
262
+ );
263
+ expect(finalSend.type).toBe("message");
264
+ expect(finalSend.text).toBe(
265
+ "Final response long enough to stream before the final message send fails.",
266
+ );
267
+ });
268
+
269
+ it("hasContent is true after update", () => {
270
+ const stream = new TeamsHttpStream({
271
+ sendActivity: vi.fn(async () => ({ id: "x" })),
272
+ });
273
+
274
+ expect(stream.hasContent).toBe(false);
275
+ stream.update("some text");
276
+ expect(stream.hasContent).toBe(true);
277
+ });
278
+
279
+ it("double finalize is a no-op", async () => {
280
+ const sendActivity = vi.fn(async () => ({ id: "x" }));
281
+ const stream = new TeamsHttpStream({ sendActivity });
282
+
283
+ stream.update("A response long enough to pass the minimum character threshold.");
284
+ await stream.finalize();
285
+ const callCount = sendActivity.mock.calls.length;
286
+
287
+ await stream.finalize();
288
+ expect(sendActivity.mock.calls.length).toBe(callCount);
289
+ });
290
+
291
+ it("stops streaming before stream age timeout and finalizes with last good text", async () => {
292
+ vi.useFakeTimers();
293
+
294
+ const sent: unknown[] = [];
295
+ const sendActivity = vi.fn(async (activity) => {
296
+ sent.push(activity);
297
+ return { id: "stream-1" };
298
+ });
299
+ const stream = new TeamsHttpStream({ sendActivity, throttleMs: 1 });
300
+
301
+ stream.update("Hello, this is a long enough response for streaming to begin.");
302
+ await vi.advanceTimersByTimeAsync(1);
303
+
304
+ stream.update(
305
+ "Hello, this is a long enough response for streaming to begin. More text before timeout.",
306
+ );
307
+ await vi.advanceTimersByTimeAsync(1);
308
+
309
+ vi.setSystemTime(new Date(Date.now() + 45_001));
310
+ stream.update(
311
+ "Hello, this is a long enough response for streaming to begin. More text before timeout. Even more text after timeout.",
312
+ );
313
+ await vi.advanceTimersByTimeAsync(1);
314
+
315
+ expect(stream.isFailed).toBe(true);
316
+
317
+ const finalActivity = requireMessageActivity(sent);
318
+
319
+ expect(finalActivity.text).toBe(
320
+ "Hello, this is a long enough response for streaming to begin. More text before timeout.",
321
+ );
322
+ });
323
+ });