@kodelyth/msteams 2026.5.42 → 2026.6.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 (177) hide show
  1. package/klaw.plugin.json +726 -2
  2. package/package.json +16 -4
  3. package/api.ts +0 -3
  4. package/channel-config-api.ts +0 -1
  5. package/channel-plugin-api.ts +0 -2
  6. package/config-api.ts +0 -4
  7. package/contract-api.ts +0 -4
  8. package/index.ts +0 -20
  9. package/runtime-api.ts +0 -66
  10. package/secret-contract-api.ts +0 -5
  11. package/setup-entry.ts +0 -13
  12. package/setup-plugin-api.ts +0 -3
  13. package/src/ai-entity.ts +0 -7
  14. package/src/approval-auth.ts +0 -44
  15. package/src/attachments/bot-framework.test.ts +0 -506
  16. package/src/attachments/bot-framework.ts +0 -348
  17. package/src/attachments/download.ts +0 -328
  18. package/src/attachments/graph.test.ts +0 -441
  19. package/src/attachments/graph.ts +0 -489
  20. package/src/attachments/html.ts +0 -122
  21. package/src/attachments/payload.ts +0 -14
  22. package/src/attachments/remote-media.test.ts +0 -187
  23. package/src/attachments/remote-media.ts +0 -86
  24. package/src/attachments/shared.test.ts +0 -547
  25. package/src/attachments/shared.ts +0 -655
  26. package/src/attachments/types.ts +0 -47
  27. package/src/attachments.graph.test.ts +0 -414
  28. package/src/attachments.helpers.test.ts +0 -245
  29. package/src/attachments.test-helpers.ts +0 -17
  30. package/src/attachments.test.ts +0 -754
  31. package/src/attachments.ts +0 -18
  32. package/src/block-streaming-config.test.ts +0 -61
  33. package/src/channel-api.ts +0 -1
  34. package/src/channel.actions.test.ts +0 -797
  35. package/src/channel.directory.test.ts +0 -176
  36. package/src/channel.message-adapter.test.ts +0 -227
  37. package/src/channel.runtime.ts +0 -56
  38. package/src/channel.setup.ts +0 -77
  39. package/src/channel.test.ts +0 -136
  40. package/src/channel.ts +0 -1176
  41. package/src/config-schema.ts +0 -6
  42. package/src/config-ui-hints.ts +0 -40
  43. package/src/conversation-store-fs.test.ts +0 -81
  44. package/src/conversation-store-fs.ts +0 -149
  45. package/src/conversation-store-helpers.test.ts +0 -202
  46. package/src/conversation-store-helpers.ts +0 -105
  47. package/src/conversation-store-memory.ts +0 -51
  48. package/src/conversation-store.shared.test.ts +0 -260
  49. package/src/conversation-store.ts +0 -71
  50. package/src/directory-live.test.ts +0 -156
  51. package/src/directory-live.ts +0 -111
  52. package/src/doctor.ts +0 -27
  53. package/src/errors.test.ts +0 -154
  54. package/src/errors.ts +0 -270
  55. package/src/feedback-reflection-prompt.ts +0 -117
  56. package/src/feedback-reflection-store.ts +0 -113
  57. package/src/feedback-reflection.test.ts +0 -237
  58. package/src/feedback-reflection.ts +0 -268
  59. package/src/file-consent-helpers.test.ts +0 -328
  60. package/src/file-consent-helpers.ts +0 -115
  61. package/src/file-consent-invoke.ts +0 -150
  62. package/src/file-consent.test.ts +0 -378
  63. package/src/file-consent.ts +0 -223
  64. package/src/graph-chat.ts +0 -36
  65. package/src/graph-group-management.test.ts +0 -332
  66. package/src/graph-group-management.ts +0 -168
  67. package/src/graph-members.test.ts +0 -89
  68. package/src/graph-members.ts +0 -48
  69. package/src/graph-messages.actions.test.ts +0 -253
  70. package/src/graph-messages.read.test.ts +0 -391
  71. package/src/graph-messages.search.test.ts +0 -227
  72. package/src/graph-messages.test-helpers.ts +0 -50
  73. package/src/graph-messages.ts +0 -534
  74. package/src/graph-teams.test.ts +0 -222
  75. package/src/graph-teams.ts +0 -114
  76. package/src/graph-thread.test.ts +0 -252
  77. package/src/graph-thread.ts +0 -146
  78. package/src/graph-upload.test.ts +0 -253
  79. package/src/graph-upload.ts +0 -531
  80. package/src/graph-users.ts +0 -29
  81. package/src/graph.test.ts +0 -540
  82. package/src/graph.ts +0 -308
  83. package/src/inbound.test.ts +0 -221
  84. package/src/inbound.ts +0 -148
  85. package/src/index.ts +0 -4
  86. package/src/media-helpers.test.ts +0 -220
  87. package/src/media-helpers.ts +0 -105
  88. package/src/mentions.test.ts +0 -254
  89. package/src/mentions.ts +0 -114
  90. package/src/messenger.test.ts +0 -961
  91. package/src/messenger.ts +0 -608
  92. package/src/monitor-handler/access.ts +0 -136
  93. package/src/monitor-handler/inbound-media.test.ts +0 -314
  94. package/src/monitor-handler/inbound-media.ts +0 -180
  95. package/src/monitor-handler/message-handler-mock-support.test-support.ts +0 -28
  96. package/src/monitor-handler/message-handler.authz.test.ts +0 -739
  97. package/src/monitor-handler/message-handler.dm-media.test.ts +0 -54
  98. package/src/monitor-handler/message-handler.test-support.ts +0 -99
  99. package/src/monitor-handler/message-handler.thread-parent.test.ts +0 -225
  100. package/src/monitor-handler/message-handler.thread-session.test.ts +0 -132
  101. package/src/monitor-handler/message-handler.ts +0 -1003
  102. package/src/monitor-handler/reaction-handler.test.ts +0 -325
  103. package/src/monitor-handler/reaction-handler.ts +0 -122
  104. package/src/monitor-handler/thread-session.ts +0 -30
  105. package/src/monitor-handler.adaptive-card.test.ts +0 -158
  106. package/src/monitor-handler.feedback-authz.test.ts +0 -357
  107. package/src/monitor-handler.file-consent.test.ts +0 -443
  108. package/src/monitor-handler.sso.test.ts +0 -576
  109. package/src/monitor-handler.test-helpers.ts +0 -181
  110. package/src/monitor-handler.ts +0 -538
  111. package/src/monitor-handler.types.ts +0 -27
  112. package/src/monitor-types.ts +0 -6
  113. package/src/monitor.lifecycle.test.ts +0 -457
  114. package/src/monitor.test.ts +0 -119
  115. package/src/monitor.ts +0 -476
  116. package/src/oauth.flow.ts +0 -77
  117. package/src/oauth.shared.ts +0 -37
  118. package/src/oauth.test.ts +0 -350
  119. package/src/oauth.token.ts +0 -162
  120. package/src/oauth.ts +0 -130
  121. package/src/outbound.test.ts +0 -400
  122. package/src/outbound.ts +0 -198
  123. package/src/pending-uploads-fs.test.ts +0 -261
  124. package/src/pending-uploads-fs.ts +0 -235
  125. package/src/pending-uploads.test.ts +0 -186
  126. package/src/pending-uploads.ts +0 -121
  127. package/src/policy.test.ts +0 -156
  128. package/src/policy.ts +0 -245
  129. package/src/polls-store-memory.ts +0 -32
  130. package/src/polls.test.ts +0 -169
  131. package/src/polls.ts +0 -312
  132. package/src/presentation.ts +0 -93
  133. package/src/probe.test.ts +0 -79
  134. package/src/probe.ts +0 -132
  135. package/src/reply-dispatcher.test.ts +0 -543
  136. package/src/reply-dispatcher.ts +0 -523
  137. package/src/reply-stream-controller.test.ts +0 -424
  138. package/src/reply-stream-controller.ts +0 -334
  139. package/src/resolve-allowlist.test.ts +0 -253
  140. package/src/resolve-allowlist.ts +0 -309
  141. package/src/revoked-context.ts +0 -17
  142. package/src/runtime.ts +0 -12
  143. package/src/sdk-types.ts +0 -59
  144. package/src/sdk.test.ts +0 -727
  145. package/src/sdk.ts +0 -916
  146. package/src/secret-contract.ts +0 -49
  147. package/src/secret-input.ts +0 -7
  148. package/src/send-context.test.ts +0 -93
  149. package/src/send-context.ts +0 -269
  150. package/src/send.test.ts +0 -588
  151. package/src/send.ts +0 -697
  152. package/src/sent-message-cache.test.ts +0 -106
  153. package/src/sent-message-cache.ts +0 -174
  154. package/src/session-route.ts +0 -40
  155. package/src/setup-core.ts +0 -162
  156. package/src/setup-surface.test.ts +0 -175
  157. package/src/setup-surface.ts +0 -319
  158. package/src/sso-token-store.test.ts +0 -74
  159. package/src/sso-token-store.ts +0 -166
  160. package/src/sso.ts +0 -300
  161. package/src/storage.ts +0 -25
  162. package/src/store-fs.ts +0 -42
  163. package/src/streaming-message.test.ts +0 -323
  164. package/src/streaming-message.ts +0 -327
  165. package/src/test-runtime.ts +0 -16
  166. package/src/thread-parent-context.test.ts +0 -224
  167. package/src/thread-parent-context.ts +0 -159
  168. package/src/token-response.ts +0 -11
  169. package/src/token.test.ts +0 -268
  170. package/src/token.ts +0 -194
  171. package/src/user-agent.test.ts +0 -121
  172. package/src/user-agent.ts +0 -53
  173. package/src/webhook-timeouts.ts +0 -27
  174. package/src/welcome-card.test.ts +0 -104
  175. package/src/welcome-card.ts +0 -57
  176. package/test-api.ts +0 -1
  177. package/tsconfig.json +0 -16
package/src/sso.ts DELETED
@@ -1,300 +0,0 @@
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 DELETED
@@ -1,25 +0,0 @@
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
- }
package/src/store-fs.ts DELETED
@@ -1,42 +0,0 @@
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
- }
@@ -1,323 +0,0 @@
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
- });