@gakr-gakr/msteams 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/api.ts +3 -0
  2. package/autobot.plugin.json +15 -0
  3. package/channel-config-api.ts +1 -0
  4. package/channel-plugin-api.ts +2 -0
  5. package/config-api.ts +4 -0
  6. package/contract-api.ts +4 -0
  7. package/index.ts +20 -0
  8. package/package.json +72 -0
  9. package/runtime-api.ts +66 -0
  10. package/secret-contract-api.ts +5 -0
  11. package/setup-entry.ts +13 -0
  12. package/setup-plugin-api.ts +3 -0
  13. package/src/ai-entity.ts +7 -0
  14. package/src/approval-auth.ts +44 -0
  15. package/src/attachments/bot-framework.ts +348 -0
  16. package/src/attachments/download.ts +328 -0
  17. package/src/attachments/graph.ts +489 -0
  18. package/src/attachments/html.ts +122 -0
  19. package/src/attachments/payload.ts +14 -0
  20. package/src/attachments/remote-media.ts +86 -0
  21. package/src/attachments/shared.ts +655 -0
  22. package/src/attachments/types.ts +47 -0
  23. package/src/attachments.ts +18 -0
  24. package/src/channel-api.ts +1 -0
  25. package/src/channel.runtime.ts +56 -0
  26. package/src/channel.setup.ts +77 -0
  27. package/src/channel.ts +1176 -0
  28. package/src/config-schema.ts +6 -0
  29. package/src/config-ui-hints.ts +40 -0
  30. package/src/conversation-store-fs.ts +149 -0
  31. package/src/conversation-store-helpers.ts +105 -0
  32. package/src/conversation-store-memory.ts +51 -0
  33. package/src/conversation-store.ts +71 -0
  34. package/src/directory-live.ts +111 -0
  35. package/src/doctor.ts +27 -0
  36. package/src/errors.ts +270 -0
  37. package/src/feedback-reflection-prompt.ts +117 -0
  38. package/src/feedback-reflection-store.ts +113 -0
  39. package/src/feedback-reflection.ts +271 -0
  40. package/src/file-consent-helpers.ts +115 -0
  41. package/src/file-consent-invoke.ts +150 -0
  42. package/src/file-consent.ts +223 -0
  43. package/src/graph-chat.ts +36 -0
  44. package/src/graph-group-management.ts +168 -0
  45. package/src/graph-members.ts +48 -0
  46. package/src/graph-messages.ts +534 -0
  47. package/src/graph-teams.ts +114 -0
  48. package/src/graph-thread.ts +146 -0
  49. package/src/graph-upload.ts +531 -0
  50. package/src/graph-users.ts +29 -0
  51. package/src/graph.ts +308 -0
  52. package/src/inbound.ts +148 -0
  53. package/src/index.ts +4 -0
  54. package/src/media-helpers.ts +105 -0
  55. package/src/mentions.ts +114 -0
  56. package/src/messenger.ts +608 -0
  57. package/src/monitor-handler/access.ts +136 -0
  58. package/src/monitor-handler/inbound-media.ts +180 -0
  59. package/src/monitor-handler/message-handler-mock-support.test-support.ts +28 -0
  60. package/src/monitor-handler/message-handler.test-support.ts +102 -0
  61. package/src/monitor-handler/message-handler.ts +1015 -0
  62. package/src/monitor-handler/reaction-handler.ts +124 -0
  63. package/src/monitor-handler/thread-session.ts +30 -0
  64. package/src/monitor-handler.ts +538 -0
  65. package/src/monitor-handler.types.ts +27 -0
  66. package/src/monitor-types.ts +6 -0
  67. package/src/monitor.ts +476 -0
  68. package/src/oauth.flow.ts +77 -0
  69. package/src/oauth.shared.ts +37 -0
  70. package/src/oauth.token.ts +162 -0
  71. package/src/oauth.ts +130 -0
  72. package/src/outbound.ts +198 -0
  73. package/src/pending-uploads-fs.ts +235 -0
  74. package/src/pending-uploads.ts +121 -0
  75. package/src/policy.ts +245 -0
  76. package/src/polls-store-memory.ts +32 -0
  77. package/src/polls.ts +312 -0
  78. package/src/presentation.ts +93 -0
  79. package/src/probe.ts +132 -0
  80. package/src/reply-dispatcher.ts +523 -0
  81. package/src/reply-stream-controller.ts +334 -0
  82. package/src/resolve-allowlist.ts +309 -0
  83. package/src/revoked-context.ts +17 -0
  84. package/src/runtime.ts +12 -0
  85. package/src/sdk-types.ts +59 -0
  86. package/src/sdk.ts +916 -0
  87. package/src/secret-contract.ts +49 -0
  88. package/src/secret-input.ts +7 -0
  89. package/src/send-context.ts +269 -0
  90. package/src/send.ts +697 -0
  91. package/src/sent-message-cache.ts +174 -0
  92. package/src/session-route.ts +40 -0
  93. package/src/setup-core.ts +162 -0
  94. package/src/setup-surface.ts +319 -0
  95. package/src/sso-token-store.ts +166 -0
  96. package/src/sso.ts +300 -0
  97. package/src/storage.ts +25 -0
  98. package/src/store-fs.ts +42 -0
  99. package/src/streaming-message.ts +327 -0
  100. package/src/thread-parent-context.ts +159 -0
  101. package/src/token-response.ts +11 -0
  102. package/src/token.ts +194 -0
  103. package/src/user-agent.ts +53 -0
  104. package/src/webhook-timeouts.ts +27 -0
  105. package/src/welcome-card.ts +57 -0
  106. package/test-api.ts +1 -0
  107. package/tsconfig.json +16 -0
@@ -0,0 +1,327 @@
1
+ /**
2
+ * Teams streaming message using the streaminfo entity protocol.
3
+ *
4
+ * Follows the official Teams SDK pattern:
5
+ * 1. First chunk → POST a typing activity with streaminfo entity (streamType: "streaming")
6
+ * 2. Subsequent chunks → POST typing activities with streaminfo + incrementing streamSequence
7
+ * 3. Finalize → POST a message activity with streaminfo (streamType: "final")
8
+ *
9
+ * Uses the shared draft-stream-loop for throttling (avoids rate limits).
10
+ */
11
+
12
+ import { createDraftStreamLoop, type DraftStreamLoop } from "autobot/plugin-sdk/channel-lifecycle";
13
+ import { readStringValue } from "autobot/plugin-sdk/string-coerce-runtime";
14
+
15
+ /** Default throttle interval between stream updates (ms).
16
+ * Teams docs recommend buffering tokens for 1.5-2s; limit is 1 req/s. */
17
+ const DEFAULT_THROTTLE_MS = 1500;
18
+
19
+ /** Minimum chars before sending the first streaming message. */
20
+ const MIN_INITIAL_CHARS = 20;
21
+
22
+ /** Teams message text limit. */
23
+ const TEAMS_MAX_CHARS = 4000;
24
+
25
+ /**
26
+ * Stop streaming before Teams expires the content stream server-side.
27
+ * The exact service limit is opaque, so stay comfortably under it.
28
+ */
29
+ const MAX_STREAM_AGE_MS = 45_000;
30
+
31
+ type StreamSendFn = (activity: Record<string, unknown>) => Promise<unknown>;
32
+
33
+ type TeamsStreamOptions = {
34
+ /** Function to send an activity (POST to Bot Framework). */
35
+ sendActivity: StreamSendFn;
36
+ /** Whether to enable feedback loop on the final message. */
37
+ feedbackLoopEnabled?: boolean;
38
+ /** Throttle interval in ms. Default: 600. */
39
+ throttleMs?: number;
40
+ /** Called on errors during streaming. */
41
+ onError?: (err: unknown) => void;
42
+ };
43
+
44
+ import { AI_GENERATED_ENTITY } from "./ai-entity.js";
45
+ import { formatUnknownError } from "./errors.js";
46
+
47
+ function extractId(response: unknown): string | undefined {
48
+ if (response && typeof response === "object" && "id" in response) {
49
+ return readStringValue((response as { id?: unknown }).id);
50
+ }
51
+ return undefined;
52
+ }
53
+
54
+ function buildStreamInfoEntity(
55
+ streamId: string | undefined,
56
+ streamType: "informative" | "streaming" | "final",
57
+ streamSequence?: number,
58
+ ): Record<string, unknown> {
59
+ const entity: Record<string, unknown> = {
60
+ type: "streaminfo",
61
+ streamType,
62
+ };
63
+ // streamId is only present after the first chunk (returned by the service)
64
+ if (streamId) {
65
+ entity.streamId = streamId;
66
+ }
67
+ // streamSequence must be present for start/continue, but NOT for final
68
+ if (streamSequence != null) {
69
+ entity.streamSequence = streamSequence;
70
+ }
71
+ return entity;
72
+ }
73
+
74
+ export class TeamsHttpStream {
75
+ private sendActivity: StreamSendFn;
76
+ private feedbackLoopEnabled: boolean;
77
+ private onError?: (err: unknown) => void;
78
+
79
+ private accumulatedText = "";
80
+ private streamId: string | undefined = undefined;
81
+ private sequenceNumber = 0;
82
+ private stopped = false;
83
+ private finalized = false;
84
+ private streamFailed = false;
85
+ private lastStreamedText = "";
86
+ private finalMessageId: string | undefined = undefined;
87
+ private streamStartedAt: number | undefined = undefined;
88
+ private loop: DraftStreamLoop;
89
+
90
+ constructor(options: TeamsStreamOptions) {
91
+ this.sendActivity = options.sendActivity;
92
+ this.feedbackLoopEnabled = options.feedbackLoopEnabled ?? false;
93
+ this.onError = options.onError;
94
+
95
+ this.loop = createDraftStreamLoop({
96
+ throttleMs: options.throttleMs ?? DEFAULT_THROTTLE_MS,
97
+ isStopped: () => this.stopped,
98
+ sendOrEditStreamMessage: (text) => this.pushStreamChunk(text),
99
+ });
100
+ }
101
+
102
+ /**
103
+ * Send an informative status update (blue progress bar in Teams).
104
+ * Call this immediately when a message is received, before LLM starts generating.
105
+ * Establishes the stream so subsequent chunks continue from this stream ID.
106
+ */
107
+ async sendInformativeUpdate(text: string): Promise<void> {
108
+ if (this.stopped || this.finalized) {
109
+ return;
110
+ }
111
+
112
+ this.sequenceNumber++;
113
+
114
+ const activity: Record<string, unknown> = {
115
+ type: "typing",
116
+ text,
117
+ entities: [buildStreamInfoEntity(this.streamId, "informative", this.sequenceNumber)],
118
+ };
119
+
120
+ try {
121
+ const response = await this.sendActivity(activity);
122
+ if (!this.streamId) {
123
+ this.streamId = extractId(response);
124
+ }
125
+ } catch (err) {
126
+ this.onError?.(err);
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Ingest partial text from the LLM token stream.
132
+ * Called by onPartialReply — accumulates text and throttles updates.
133
+ */
134
+ update(text: string): void {
135
+ if (this.stopped || this.finalized) {
136
+ return;
137
+ }
138
+ this.accumulatedText = text;
139
+
140
+ // Wait for minimum chars before first send (avoids push notification flicker)
141
+ if (!this.streamId && this.accumulatedText.length < MIN_INITIAL_CHARS) {
142
+ return;
143
+ }
144
+
145
+ // Text exceeded Teams limit — finalize immediately with what we have
146
+ // so the user isn't left waiting while the LLM keeps generating.
147
+ if (this.accumulatedText.length > TEAMS_MAX_CHARS) {
148
+ this.streamFailed = true;
149
+ void this.finalize();
150
+ return;
151
+ }
152
+
153
+ // Stop early before Teams expires the stream server-side. finalize() will
154
+ // close the stream with the last good content, and reply-stream-controller
155
+ // will deliver any remaining suffix via normal fallback delivery.
156
+ if (this.streamStartedAt && Date.now() - this.streamStartedAt >= MAX_STREAM_AGE_MS) {
157
+ this.streamFailed = true;
158
+ void this.finalize();
159
+ return;
160
+ }
161
+
162
+ // Don't append cursor — Teams requires each chunk to be a prefix of subsequent chunks.
163
+ // The cursor character would cause "content should contain previously streamed content" errors.
164
+ this.loop.update(this.accumulatedText);
165
+ }
166
+
167
+ /**
168
+ * Replace an informative progress update with final answer text.
169
+ * Returns false when the stream could not safely carry the final text, so
170
+ * callers can deliver the answer through the normal Teams message path.
171
+ */
172
+ async replaceInformativeWithFinal(text: string): Promise<boolean> {
173
+ if (this.stopped || this.finalized) {
174
+ return false;
175
+ }
176
+ this.update(text);
177
+ await this.loop.flush();
178
+ await this.finalize();
179
+ return !this.streamFailed && this.hasContent;
180
+ }
181
+
182
+ /**
183
+ * Finalize the stream — send the final message activity.
184
+ */
185
+ async finalize(): Promise<string | undefined> {
186
+ if (this.finalized) {
187
+ return this.finalMessageId;
188
+ }
189
+ this.finalized = true;
190
+ this.stopped = true;
191
+ this.loop.stop();
192
+ await this.loop.waitForInFlight();
193
+
194
+ // If no text was streamed (e.g. agent sent a card via tool instead of
195
+ // streaming text), just return. Teams auto-clears the informative progress
196
+ // bar after its streaming timeout. Sending an empty final message fails
197
+ // with 403.
198
+ if (!this.accumulatedText.trim()) {
199
+ return this.finalMessageId;
200
+ }
201
+
202
+ // If streaming failed (>4000 chars or POST errors), close the stream
203
+ // with the last successfully streamed text so Teams removes the "Stop"
204
+ // button and replaces the partial chunks. deliver() handles the complete
205
+ // response since hasContent returns false when streamFailed is true.
206
+ if (this.streamFailed) {
207
+ if (this.streamId) {
208
+ try {
209
+ const response = await this.sendActivity({
210
+ type: "message",
211
+ text: this.lastStreamedText || "",
212
+ channelData: { feedbackLoopEnabled: this.feedbackLoopEnabled },
213
+ entities: [AI_GENERATED_ENTITY, buildStreamInfoEntity(this.streamId, "final")],
214
+ });
215
+ this.finalMessageId = extractId(response);
216
+ } catch {
217
+ // Best effort — stream will auto-close after Teams timeout
218
+ }
219
+ }
220
+ return this.finalMessageId;
221
+ }
222
+
223
+ // Send final message activity.
224
+ // Per the spec: type=message, streamType=final, NO streamSequence.
225
+ try {
226
+ const entities: Array<Record<string, unknown>> = [AI_GENERATED_ENTITY];
227
+ if (this.streamId) {
228
+ entities.push(buildStreamInfoEntity(this.streamId, "final"));
229
+ }
230
+
231
+ const finalActivity: Record<string, unknown> = {
232
+ type: "message",
233
+ text: this.accumulatedText,
234
+ channelData: {
235
+ feedbackLoopEnabled: this.feedbackLoopEnabled,
236
+ },
237
+ entities,
238
+ };
239
+
240
+ const response = await this.sendActivity(finalActivity);
241
+ this.finalMessageId = extractId(response);
242
+ } catch (err) {
243
+ this.streamFailed = true;
244
+ this.onError?.(err);
245
+ }
246
+ return this.finalMessageId;
247
+ }
248
+
249
+ /** Whether streaming successfully delivered content (at least one chunk sent, not failed). */
250
+ get hasContent(): boolean {
251
+ return this.accumulatedText.length > 0 && !this.streamFailed;
252
+ }
253
+
254
+ /** Whether streaming failed and fallback delivery is needed. */
255
+ get isFailed(): boolean {
256
+ return this.streamFailed;
257
+ }
258
+
259
+ /** Number of characters successfully streamed before failure. */
260
+ get streamedLength(): number {
261
+ return this.lastStreamedText.length;
262
+ }
263
+
264
+ /** Whether the stream has been finalized. */
265
+ get isFinalized(): boolean {
266
+ return this.finalized;
267
+ }
268
+
269
+ /** Platform id returned by the final message activity, when available. */
270
+ get messageId(): string | undefined {
271
+ return this.finalMessageId;
272
+ }
273
+
274
+ /** Stream id returned by the first streaminfo activity, when available. */
275
+ get previewStreamId(): string | undefined {
276
+ return this.streamId;
277
+ }
278
+
279
+ /** Whether streaming fell back (not used in this implementation). */
280
+ get isFallback(): boolean {
281
+ return false;
282
+ }
283
+
284
+ /**
285
+ * Send a single streaming chunk as a typing activity with streaminfo.
286
+ * Per the Teams REST API spec:
287
+ * - First chunk: no streamId, streamSequence=1 → returns 201 with { id: streamId }
288
+ * - Subsequent chunks: include streamId, increment streamSequence → returns 202
289
+ */
290
+ private async pushStreamChunk(text: string): Promise<boolean> {
291
+ if (this.stopped && !this.finalized) {
292
+ return false;
293
+ }
294
+
295
+ this.sequenceNumber++;
296
+
297
+ const activity: Record<string, unknown> = {
298
+ type: "typing",
299
+ text,
300
+ entities: [buildStreamInfoEntity(this.streamId, "streaming", this.sequenceNumber)],
301
+ };
302
+
303
+ try {
304
+ const response = await this.sendActivity(activity);
305
+ if (!this.streamStartedAt) {
306
+ this.streamStartedAt = Date.now();
307
+ }
308
+ if (!this.streamId) {
309
+ this.streamId = extractId(response);
310
+ }
311
+ this.lastStreamedText = text;
312
+ return true;
313
+ } catch (err) {
314
+ const axiosData = (err as { response?: { data?: unknown; status?: number } })?.response;
315
+ const statusCode = axiosData?.status ?? (err as { statusCode?: number })?.statusCode;
316
+ const responseBody = axiosData?.data ? JSON.stringify(axiosData.data).slice(0, 300) : "";
317
+ const msg = formatUnknownError(err);
318
+ this.onError?.(
319
+ new Error(
320
+ `stream POST failed (HTTP ${statusCode ?? "?"}): ${msg}${responseBody ? ` body=${responseBody}` : ""}`,
321
+ ),
322
+ );
323
+ this.streamFailed = true;
324
+ return false;
325
+ }
326
+ }
327
+ }
@@ -0,0 +1,159 @@
1
+ // Parent-message context injection for Teams channel thread replies.
2
+ //
3
+ // When an inbound message arrives as a reply inside a Teams channel thread,
4
+ // the triggering message often makes no sense on its own (for example, a
5
+ // one-word "yes" or "go ahead"). Per-thread session isolation (PR #62713)
6
+ // gives each thread its own session, but the first message in a brand-new
7
+ // thread session still has no parent context.
8
+ //
9
+ // This module fetches the parent message via Graph and prepends a compact
10
+ // `Replying to @sender: …` system event to the next agent turn so the agent
11
+ // knows what is being responded to. Fetches are cached to avoid repeated
12
+ // Graph calls within the same active thread, and per-session dedupe ensures
13
+ // the same parent is not re-injected on every subsequent reply in the
14
+ // thread.
15
+
16
+ import { fetchChannelMessage, stripHtmlFromTeamsMessage } from "./graph-thread.js";
17
+ import type { GraphThreadMessage } from "./graph-thread.js";
18
+
19
+ // LRU cache for parent message fetches. Keyed by `teamId:channelId:parentId`.
20
+ // 5-minute TTL and 100-entry cap keep active-thread chatter fast without
21
+ // holding stale data when a thread goes quiet. Eviction uses Map insertion
22
+ // order for LRU semantics (get() re-inserts on hit).
23
+ const PARENT_CACHE_TTL_MS = 5 * 60 * 1000;
24
+ const PARENT_CACHE_MAX = 100;
25
+
26
+ type ParentCacheEntry = {
27
+ message: GraphThreadMessage | undefined;
28
+ expiresAt: number;
29
+ };
30
+
31
+ const parentCache = new Map<string, ParentCacheEntry>();
32
+
33
+ // Per-session dedupe: remembers the most recent parent id we injected for a
34
+ // given session key. When the same thread session sees another reply against
35
+ // the same parent, we skip re-enqueueing the identical system event. We keep
36
+ // a small LRU so idle sessions eventually drop out.
37
+ const INJECTED_MAX = 200;
38
+ const injectedParents = new Map<string, string>();
39
+
40
+ type ThreadParentContextFetcher = (
41
+ token: string,
42
+ groupId: string,
43
+ channelId: string,
44
+ messageId: string,
45
+ ) => Promise<GraphThreadMessage | undefined>;
46
+
47
+ function touchLru<K, V>(map: Map<K, V>, key: K, value: V, max: number): void {
48
+ if (map.has(key)) {
49
+ map.delete(key);
50
+ } else if (map.size >= max) {
51
+ // Drop the oldest (first-inserted) entry.
52
+ const firstKey = map.keys().next().value;
53
+ if (firstKey !== undefined) {
54
+ map.delete(firstKey);
55
+ }
56
+ }
57
+ map.set(key, value);
58
+ }
59
+
60
+ function buildParentCacheKey(groupId: string, channelId: string, parentId: string): string {
61
+ return `${groupId}\u0000${channelId}\u0000${parentId}`;
62
+ }
63
+
64
+ /**
65
+ * Fetch a channel parent message with an LRU+TTL cache.
66
+ *
67
+ * Uses the injected `fetchParent` (defaults to `fetchChannelMessage`) so
68
+ * tests can swap in a stub without mocking the Graph transport.
69
+ */
70
+ export async function fetchParentMessageCached(
71
+ token: string,
72
+ groupId: string,
73
+ channelId: string,
74
+ parentId: string,
75
+ fetchParent: ThreadParentContextFetcher = fetchChannelMessage,
76
+ ): Promise<GraphThreadMessage | undefined> {
77
+ const key = buildParentCacheKey(groupId, channelId, parentId);
78
+ const now = Date.now();
79
+ const cached = parentCache.get(key);
80
+ if (cached && cached.expiresAt > now) {
81
+ // Refresh LRU ordering on hit.
82
+ parentCache.delete(key);
83
+ parentCache.set(key, cached);
84
+ return cached.message;
85
+ }
86
+ const message = await fetchParent(token, groupId, channelId, parentId);
87
+ touchLru(parentCache, key, { message, expiresAt: now + PARENT_CACHE_TTL_MS }, PARENT_CACHE_MAX);
88
+ return message;
89
+ }
90
+
91
+ type ParentContextSummary = {
92
+ /** Display name of the parent message author, or "unknown". */
93
+ sender: string;
94
+ /** Stripped, single-line parent body text (or empty if unresolved). */
95
+ text: string;
96
+ };
97
+
98
+ const PARENT_TEXT_MAX_CHARS = 400;
99
+
100
+ /**
101
+ * Extract a compact summary (sender + plain-text body) from a Graph parent
102
+ * message. Returns undefined when the parent cannot be summarized (missing
103
+ * or blank body).
104
+ */
105
+ export function summarizeParentMessage(
106
+ message: GraphThreadMessage | undefined,
107
+ ): ParentContextSummary | undefined {
108
+ if (!message) {
109
+ return undefined;
110
+ }
111
+ const sender =
112
+ message.from?.user?.displayName ?? message.from?.application?.displayName ?? "unknown";
113
+ const contentType = message.body?.contentType ?? "text";
114
+ const raw = message.body?.content ?? "";
115
+ const text =
116
+ contentType === "html" ? stripHtmlFromTeamsMessage(raw) : raw.replace(/\s+/g, " ").trim();
117
+ if (!text) {
118
+ return undefined;
119
+ }
120
+ return {
121
+ sender,
122
+ text:
123
+ text.length > PARENT_TEXT_MAX_CHARS ? `${text.slice(0, PARENT_TEXT_MAX_CHARS - 1)}…` : text,
124
+ };
125
+ }
126
+
127
+ /**
128
+ * Build the single-line `Replying to @sender: body` system event text.
129
+ * Callers should pass this text to `enqueueSystemEvent` together with a
130
+ * stable contextKey derived from the parent id.
131
+ */
132
+ export function formatParentContextEvent(summary: ParentContextSummary): string {
133
+ return `Replying to @${summary.sender}: ${summary.text}`;
134
+ }
135
+
136
+ /**
137
+ * Decide whether a parent context event should be enqueued for the current
138
+ * session. Returns `false` when we already injected the same parent for this
139
+ * session recently (prevents re-prepending identical context on every reply
140
+ * in the thread).
141
+ */
142
+ export function shouldInjectParentContext(sessionKey: string, parentId: string): boolean {
143
+ const key = sessionKey;
144
+ return injectedParents.get(key) !== parentId;
145
+ }
146
+
147
+ /**
148
+ * Record that `parentId` was just injected for `sessionKey` so subsequent
149
+ * replies with the same parent can short-circuit via `shouldInjectParentContext`.
150
+ */
151
+ export function markParentContextInjected(sessionKey: string, parentId: string): void {
152
+ touchLru(injectedParents, sessionKey, parentId, INJECTED_MAX);
153
+ }
154
+
155
+ // Exported for test isolation.
156
+ export function resetThreadParentContextCachesForTest(): void {
157
+ parentCache.clear();
158
+ injectedParents.clear();
159
+ }
@@ -0,0 +1,11 @@
1
+ export function readAccessToken(value: unknown): string | null {
2
+ if (typeof value === "string") {
3
+ return value;
4
+ }
5
+ if (value && typeof value === "object") {
6
+ const token =
7
+ (value as { accessToken?: unknown }).accessToken ?? (value as { token?: unknown }).token;
8
+ return typeof token === "string" ? token : null;
9
+ }
10
+ return null;
11
+ }
package/src/token.ts ADDED
@@ -0,0 +1,194 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { basename, dirname } from "node:path";
3
+ import { privateFileStoreSync } from "autobot/plugin-sdk/security-runtime";
4
+ import type { MSTeamsConfig } from "../runtime-api.js";
5
+ import type { MSTeamsDelegatedTokens } from "./oauth.shared.js";
6
+ import { refreshMSTeamsDelegatedTokens } from "./oauth.token.js";
7
+ import {
8
+ hasConfiguredSecretInput,
9
+ normalizeResolvedSecretInputString,
10
+ normalizeSecretInputString,
11
+ } from "./secret-input.js";
12
+ import { resolveMSTeamsStorePath } from "./storage.js";
13
+
14
+ // ── Credential types ───────────────────────────────────────────────────────
15
+
16
+ export type MSTeamsSecretCredentials = {
17
+ type: "secret";
18
+ appId: string;
19
+ appPassword: string;
20
+ tenantId: string;
21
+ };
22
+
23
+ export type MSTeamsFederatedCredentials = {
24
+ type: "federated";
25
+ appId: string;
26
+ tenantId: string;
27
+ certificatePath?: string;
28
+ certificateThumbprint?: string;
29
+ useManagedIdentity?: boolean;
30
+ managedIdentityClientId?: string;
31
+ };
32
+
33
+ export type MSTeamsCredentials = MSTeamsSecretCredentials | MSTeamsFederatedCredentials;
34
+
35
+ // ── Helpers ────────────────────────────────────────────────────────────────
36
+
37
+ function resolveAuthType(cfg?: MSTeamsConfig): "secret" | "federated" {
38
+ const fromCfg = cfg?.authType;
39
+ if (fromCfg === "secret" || fromCfg === "federated") {
40
+ return fromCfg;
41
+ }
42
+
43
+ const fromEnv = process.env.MSTEAMS_AUTH_TYPE;
44
+ if (fromEnv === "federated") {
45
+ return "federated";
46
+ }
47
+
48
+ return "secret";
49
+ }
50
+
51
+ // ── hasConfiguredMSTeamsCredentials ────────────────────────────────────────
52
+
53
+ export function hasConfiguredMSTeamsCredentials(cfg?: MSTeamsConfig): boolean {
54
+ const authType = resolveAuthType(cfg);
55
+
56
+ const hasAppId = Boolean(
57
+ normalizeSecretInputString(cfg?.appId) ||
58
+ normalizeSecretInputString(process.env.MSTEAMS_APP_ID),
59
+ );
60
+ const hasTenantId = Boolean(
61
+ normalizeSecretInputString(cfg?.tenantId) ||
62
+ normalizeSecretInputString(process.env.MSTEAMS_TENANT_ID),
63
+ );
64
+
65
+ if (authType === "federated") {
66
+ const hasCert = Boolean(cfg?.certificatePath || process.env.MSTEAMS_CERTIFICATE_PATH);
67
+ const hasManagedIdentity =
68
+ cfg?.useManagedIdentity ?? process.env.MSTEAMS_USE_MANAGED_IDENTITY === "true";
69
+
70
+ return hasAppId && hasTenantId && (hasCert || hasManagedIdentity);
71
+ }
72
+
73
+ // "secret" (default) — original logic
74
+ return Boolean(
75
+ normalizeSecretInputString(cfg?.appId) &&
76
+ hasConfiguredSecretInput(cfg?.appPassword) &&
77
+ normalizeSecretInputString(cfg?.tenantId),
78
+ );
79
+ }
80
+
81
+ // ── resolveMSTeamsCredentials ─────────────────────────────────────────────
82
+
83
+ export function resolveMSTeamsCredentials(cfg?: MSTeamsConfig): MSTeamsCredentials | undefined {
84
+ const authType = resolveAuthType(cfg);
85
+
86
+ const appId =
87
+ normalizeSecretInputString(cfg?.appId) ||
88
+ normalizeSecretInputString(process.env.MSTEAMS_APP_ID);
89
+
90
+ const tenantId =
91
+ normalizeSecretInputString(cfg?.tenantId) ||
92
+ normalizeSecretInputString(process.env.MSTEAMS_TENANT_ID);
93
+
94
+ if (!appId || !tenantId) {
95
+ return undefined;
96
+ }
97
+
98
+ if (authType === "federated") {
99
+ const certificatePath =
100
+ cfg?.certificatePath || process.env.MSTEAMS_CERTIFICATE_PATH || undefined;
101
+
102
+ const certificateThumbprint =
103
+ cfg?.certificateThumbprint || process.env.MSTEAMS_CERTIFICATE_THUMBPRINT || undefined;
104
+
105
+ const useManagedIdentity =
106
+ cfg?.useManagedIdentity ?? process.env.MSTEAMS_USE_MANAGED_IDENTITY === "true";
107
+
108
+ const managedIdentityClientId =
109
+ cfg?.managedIdentityClientId || process.env.MSTEAMS_MANAGED_IDENTITY_CLIENT_ID || undefined;
110
+
111
+ // At least one federated mechanism must be configured.
112
+ if (!certificatePath && !useManagedIdentity) {
113
+ return undefined;
114
+ }
115
+
116
+ return {
117
+ type: "federated",
118
+ appId,
119
+ tenantId,
120
+ certificatePath,
121
+ certificateThumbprint,
122
+ useManagedIdentity: useManagedIdentity || undefined,
123
+ managedIdentityClientId,
124
+ };
125
+ }
126
+
127
+ // "secret" (default) — original logic
128
+ const appPassword =
129
+ normalizeResolvedSecretInputString({
130
+ value: cfg?.appPassword,
131
+ path: "channels.msteams.appPassword",
132
+ }) || normalizeSecretInputString(process.env.MSTEAMS_APP_PASSWORD);
133
+
134
+ if (!appPassword) {
135
+ return undefined;
136
+ }
137
+
138
+ return { type: "secret", appId, appPassword, tenantId };
139
+ }
140
+
141
+ // ---------------------------------------------------------------------------
142
+ // Delegated token storage / resolution
143
+ // ---------------------------------------------------------------------------
144
+
145
+ const DELEGATED_TOKEN_FILENAME = "msteams-delegated.json";
146
+
147
+ function resolveDelegatedTokenPath(): string {
148
+ return resolveMSTeamsStorePath({ filename: DELEGATED_TOKEN_FILENAME });
149
+ }
150
+
151
+ export function loadDelegatedTokens(): MSTeamsDelegatedTokens | undefined {
152
+ try {
153
+ const content = readFileSync(resolveDelegatedTokenPath(), "utf8");
154
+ return JSON.parse(content) as MSTeamsDelegatedTokens;
155
+ } catch {
156
+ return undefined;
157
+ }
158
+ }
159
+
160
+ export function saveDelegatedTokens(tokens: MSTeamsDelegatedTokens): void {
161
+ const tokenPath = resolveDelegatedTokenPath();
162
+ privateFileStoreSync(dirname(tokenPath)).writeJson(basename(tokenPath), tokens);
163
+ }
164
+
165
+ export async function resolveDelegatedAccessToken(params: {
166
+ tenantId: string;
167
+ clientId: string;
168
+ clientSecret: string;
169
+ }): Promise<string | undefined> {
170
+ const tokens = loadDelegatedTokens();
171
+ if (!tokens) {
172
+ return undefined;
173
+ }
174
+
175
+ // Token still valid (5-min buffer already baked into expiresAt)
176
+ if (tokens.expiresAt > Date.now()) {
177
+ return tokens.accessToken;
178
+ }
179
+
180
+ // Attempt refresh
181
+ try {
182
+ const refreshed = await refreshMSTeamsDelegatedTokens({
183
+ tenantId: params.tenantId,
184
+ clientId: params.clientId,
185
+ clientSecret: params.clientSecret,
186
+ refreshToken: tokens.refreshToken,
187
+ scopes: tokens.scopes,
188
+ });
189
+ saveDelegatedTokens(refreshed);
190
+ return refreshed.accessToken;
191
+ } catch {
192
+ return undefined;
193
+ }
194
+ }