@cuylabs/agent-channel-teams 0.10.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,121 @@
1
+ # @cuylabs/agent-channel-teams
2
+
3
+ Teams-native channel features for `@cuylabs/agent-core`, layered above `@cuylabs/agent-channel-m365`.
4
+
5
+ This package exists because `agent-channel-m365` is intentionally transport-first:
6
+
7
+ - it is the right layer for ordinary message turns over the Microsoft 365 Activity Protocol
8
+ - it is not the right layer for every Teams-specific surface
9
+
10
+ `agent-channel-teams` adds a Teams-focused layer without forcing your library to adopt Microsoft's `AgentApplication` architecture.
11
+
12
+ ## What It Gives You
13
+
14
+ `agent-channel-teams` keeps your stack:
15
+
16
+ ```text
17
+ Teams
18
+ -> @microsoft/agents-hosting
19
+ -> @cuylabs/agent-channel-teams
20
+ -> @cuylabs/agent-channel-m365
21
+ -> @cuylabs/agent-core
22
+ ```
23
+
24
+ The value is:
25
+
26
+ - parsed Teams activity metadata instead of raw `activity.channelData`
27
+ - Teams-specific hooks for dialog open/submit, search-style invokes, card submit, feedback, edits, deletes, and reactions
28
+ - Teams response builders for dialog and search-style invoke payloads
29
+ - invoke response helpers for Teams handlers, plus fallback access to generic M365 `onInvoke`
30
+ - ambient Teams turn context that tools and middleware can read
31
+ - a way for Teams-specific handlers to still call back into `agent-core`
32
+
33
+ ## What It Does Not Do
34
+
35
+ - it does not replace `agent-channel-m365`
36
+ - it does not require `@microsoft/agents-hosting-extensions-teams`
37
+ - it does not copy Microsoft's routing model
38
+ - it does not turn `agent-core` into a Teams-only framework
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ pnpm add @cuylabs/agent-channel-teams @cuylabs/agent-channel-m365 @microsoft/agents-hosting express
44
+ ```
45
+
46
+ ## Example
47
+
48
+ ```ts
49
+ import { createAgent } from "@cuylabs/agent-core";
50
+ import {
51
+ createTeamsChannelAdapter,
52
+ createTeamsDialogMessage,
53
+ } from "@cuylabs/agent-channel-teams";
54
+
55
+ const agent = createAgent({ model });
56
+
57
+ const teams = createTeamsChannelAdapter({
58
+ agent,
59
+ prepareTurn: ({ teams, user }) => ({
60
+ system: `You are helping ${user.userName}.`,
61
+ scopeAttributes: {
62
+ teamsSurface: teams.surface,
63
+ teamsKind: teams.kind,
64
+ },
65
+ }),
66
+ handlers: {
67
+ async dialogSubmit(ctx) {
68
+ const prompt = JSON.stringify(ctx.turnContext.activity.value);
69
+ const events = ctx.runAgent(`Handle this Teams dialog payload:\n${prompt}`);
70
+
71
+ let text = "";
72
+ for await (const event of events) {
73
+ if (event.type === "text-delta") {
74
+ text += event.text;
75
+ }
76
+ }
77
+
78
+ await ctx.sendInvoke(createTeamsDialogMessage(text));
79
+ },
80
+ },
81
+ });
82
+ ```
83
+
84
+ ## Main API
85
+
86
+ ### `createTeamsChannelAdapter(...)`
87
+
88
+ Creates a Teams-aware adapter. Ordinary message turns still flow through the
89
+ underlying M365 adapter. Teams-specific activities can be intercepted by
90
+ `handlers`.
91
+
92
+ ### `mountTeamsAgent(...)`
93
+
94
+ Express helper equivalent to `mountM365Agent(...)`, but with the Teams-aware
95
+ adapter already wired in.
96
+
97
+ ### `currentTeamsTurnContext()`
98
+
99
+ Read Teams metadata from tools or middleware during a turn.
100
+
101
+ ### `sendTeamsInvoke(...)`
102
+
103
+ Send a Teams invoke response body without manually constructing an
104
+ `invokeResponse` activity.
105
+
106
+ ### `createTeamsDialog(...)` and `createTeamsSearchResult(...)`
107
+
108
+ Build common Teams dialog/search invoke bodies without making callers hand-roll
109
+ raw payload objects.
110
+
111
+ ## Why This Package Exists
112
+
113
+ This package is the bridge between:
114
+
115
+ - your `agent-core` execution model
116
+ - the generic M365 transport layer
117
+ - the richer Teams-native surfaces you will want later
118
+
119
+ That means you can start with ordinary Teams bot chat now, and then add
120
+ dialogs, message actions, or search-oriented Teams invokes without changing
121
+ your core agent architecture.
@@ -0,0 +1,182 @@
1
+ import { AgentEvent } from '@cuylabs/agent-core';
2
+ import { M365ChannelOptions, M365TurnRequestContext, M365TurnPreparation, M365UserIdentity, M365TurnSource, M365ChannelAdapter, M365AmbientTurnContext } from '@cuylabs/agent-channel-m365';
3
+ import { TurnContext, AuthConfiguration, CloudAdapter } from '@microsoft/agents-hosting';
4
+ import { Server } from 'node:http';
5
+ import { Application } from 'express';
6
+ import { Activity, Attachment } from '@microsoft/agents-activity';
7
+
8
+ type TeamsSurface = "personal" | "channel" | "group" | "meeting" | "unknown";
9
+ type TeamsActivityKind = "message" | "message-edit" | "message-delete" | "message-restore" | "reaction" | "card-submit" | "feedback" | "dialog-open" | "dialog-submit" | "search-command" | "select-result" | "invoke" | "conversation-update" | "other";
10
+ interface TeamsActorReference {
11
+ id?: string;
12
+ displayName?: string;
13
+ tenantId?: string;
14
+ userPrincipalName?: string;
15
+ }
16
+ interface TeamsActivityInfo {
17
+ channelId: string;
18
+ conversationId: string;
19
+ activityId?: string;
20
+ messageId?: string;
21
+ replyToId?: string;
22
+ invokeName?: string;
23
+ eventType?: string;
24
+ tenantId?: string;
25
+ teamId?: string;
26
+ channelThreadId?: string;
27
+ meetingId?: string;
28
+ surface: TeamsSurface;
29
+ kind: TeamsActivityKind;
30
+ actors: TeamsActorReference[];
31
+ }
32
+ interface TeamsTurnRequestContext extends M365TurnRequestContext {
33
+ teams: TeamsActivityInfo;
34
+ }
35
+ type TeamsTurnPreparation = M365TurnPreparation;
36
+ type TeamsHandlerDecision = void | "continue";
37
+ interface TeamsHandlerContext {
38
+ turnContext: TurnContext;
39
+ user: M365UserIdentity;
40
+ teams: TeamsActivityInfo;
41
+ sessionId: string;
42
+ source: M365TurnSource;
43
+ /**
44
+ * Start an agent turn inside the current Teams request context.
45
+ *
46
+ * This is useful for dialog submit/search-command handlers that still want
47
+ * to delegate their actual reasoning to agent-core.
48
+ */
49
+ runAgent(message: string, options?: {
50
+ abort?: AbortSignal;
51
+ system?: string;
52
+ }): AsyncGenerator<AgentEvent>;
53
+ /**
54
+ * Send an invoke response payload back to Teams.
55
+ */
56
+ sendInvoke(body?: unknown, status?: number): Promise<void>;
57
+ }
58
+ interface TeamsActivityHandlers {
59
+ messageEdited?: (context: TeamsHandlerContext) => TeamsHandlerDecision | Promise<TeamsHandlerDecision>;
60
+ messageDeleted?: (context: TeamsHandlerContext) => TeamsHandlerDecision | Promise<TeamsHandlerDecision>;
61
+ messageRestored?: (context: TeamsHandlerContext) => TeamsHandlerDecision | Promise<TeamsHandlerDecision>;
62
+ reaction?: (context: TeamsHandlerContext) => TeamsHandlerDecision | Promise<TeamsHandlerDecision>;
63
+ cardSubmit?: (context: TeamsHandlerContext) => TeamsHandlerDecision | Promise<TeamsHandlerDecision>;
64
+ feedbackSubmit?: (context: TeamsHandlerContext) => TeamsHandlerDecision | Promise<TeamsHandlerDecision>;
65
+ dialogOpen?: (context: TeamsHandlerContext) => TeamsHandlerDecision | Promise<TeamsHandlerDecision>;
66
+ dialogSubmit?: (context: TeamsHandlerContext) => TeamsHandlerDecision | Promise<TeamsHandlerDecision>;
67
+ searchCommand?: (context: TeamsHandlerContext) => TeamsHandlerDecision | Promise<TeamsHandlerDecision>;
68
+ selectResult?: (context: TeamsHandlerContext) => TeamsHandlerDecision | Promise<TeamsHandlerDecision>;
69
+ invoke?: (context: TeamsHandlerContext) => TeamsHandlerDecision | Promise<TeamsHandlerDecision>;
70
+ }
71
+ interface TeamsChannelOptions extends Omit<M365ChannelOptions, "prepareTurn"> {
72
+ /**
73
+ * Teams-native turn preparation hook. The result is forwarded into the
74
+ * underlying M365 channel adapter.
75
+ */
76
+ prepareTurn?: (request: TeamsTurnRequestContext) => TeamsTurnPreparation | Promise<TeamsTurnPreparation>;
77
+ /**
78
+ * Teams-specific activity hooks that run before generic M365 handling.
79
+ *
80
+ * Note: the `"feedback"` kind falls through to `cardSubmit` when
81
+ * `feedbackSubmit` is not defined. Define `feedbackSubmit` explicitly
82
+ * if you need to distinguish feedback actions from card submits.
83
+ */
84
+ handlers?: TeamsActivityHandlers;
85
+ }
86
+ interface TeamsChannelAdapter extends M365ChannelAdapter {
87
+ /**
88
+ * The underlying generic M365 adapter used for ordinary message turns.
89
+ */
90
+ readonly m365: M365ChannelAdapter;
91
+ }
92
+
93
+ declare function createTeamsChannelAdapter(options: TeamsChannelOptions): TeamsChannelAdapter;
94
+
95
+ interface MountTeamsAgentOptions extends Omit<TeamsChannelOptions, "agent" | "source"> {
96
+ path?: string;
97
+ authConfig?: AuthConfiguration;
98
+ port?: number | null;
99
+ host?: string;
100
+ adapter?: CloudAdapter;
101
+ app?: Application;
102
+ }
103
+ interface MountTeamsAgentResult {
104
+ app: Application;
105
+ channelAdapter: ReturnType<typeof createTeamsChannelAdapter>;
106
+ cloudAdapter: CloudAdapter;
107
+ server?: Server;
108
+ }
109
+ declare function mountTeamsAgent(source: M365TurnSource, options?: MountTeamsAgentOptions): Promise<MountTeamsAgentResult>;
110
+
111
+ interface TeamsAmbientTurnContext extends M365AmbientTurnContext {
112
+ teams: TeamsActivityInfo;
113
+ }
114
+ declare function currentTeamsTurnContext(): Readonly<TeamsAmbientTurnContext> | undefined;
115
+ declare function runWithTeamsTurnContext<T>(value: TeamsAmbientTurnContext, fn: () => T | Promise<T>): Promise<T>;
116
+
117
+ interface TeamsInvokeResult<T = unknown> {
118
+ status: number;
119
+ body?: T;
120
+ }
121
+ declare function createTeamsInvokeActivity<T = unknown>(result: TeamsInvokeResult<T>): Activity;
122
+ declare function sendTeamsInvoke<T = unknown>(context: TurnContext, body?: T, status?: number): Promise<void>;
123
+
124
+ type TeamsSearchLayout = "list" | "grid";
125
+ type TeamsSearchResultType = "result" | "auth" | "config" | "message" | "botMessagePreview" | "silentAuth";
126
+ interface TeamsSearchAttachment extends Attachment {
127
+ preview?: Attachment;
128
+ }
129
+ interface TeamsSearchResult {
130
+ type?: TeamsSearchResultType;
131
+ layout?: TeamsSearchLayout;
132
+ attachments?: TeamsSearchAttachment[];
133
+ text?: string;
134
+ preview?: Activity;
135
+ }
136
+ interface TeamsSearchResultBody {
137
+ composeExtension: {
138
+ type?: TeamsSearchResultType;
139
+ attachmentLayout?: TeamsSearchLayout;
140
+ attachments?: TeamsSearchAttachment[];
141
+ text?: string;
142
+ activityPreview?: Activity;
143
+ };
144
+ cacheInfo?: unknown;
145
+ }
146
+ interface TeamsSearchMessageBody {
147
+ composeExtension: {
148
+ type: "message";
149
+ text: string;
150
+ };
151
+ }
152
+ type TeamsSearchResponse = TeamsSearchResultBody | TeamsSearchMessageBody;
153
+ declare function createTeamsSearchResult(result: TeamsSearchResult): TeamsSearchResultBody;
154
+ declare function createTeamsSearchMessage(text: string): TeamsSearchMessageBody;
155
+ type TeamsDialogSize = number | "small" | "medium" | "large";
156
+ interface TeamsDialogDefinition {
157
+ title?: string;
158
+ height?: TeamsDialogSize;
159
+ width?: TeamsDialogSize;
160
+ url?: string;
161
+ fallbackUrl?: string;
162
+ card?: Attachment;
163
+ completionAgentId?: string;
164
+ }
165
+ interface TeamsDialogResponse {
166
+ task: {
167
+ type: "continue";
168
+ value: TeamsDialogDefinition;
169
+ };
170
+ }
171
+ interface TeamsDialogMessageBody {
172
+ task: {
173
+ type: "message";
174
+ value: string;
175
+ };
176
+ }
177
+ declare function createTeamsDialog(dialog: TeamsDialogDefinition): TeamsDialogResponse;
178
+ declare function createTeamsDialogMessage(message: string): TeamsDialogMessageBody;
179
+
180
+ declare function parseTeamsActivity(context: TurnContext): TeamsActivityInfo;
181
+
182
+ export { type MountTeamsAgentOptions, type MountTeamsAgentResult, type TeamsActivityHandlers, type TeamsActivityInfo, type TeamsActivityKind, type TeamsActorReference, type TeamsAmbientTurnContext, type TeamsChannelAdapter, type TeamsChannelOptions, type TeamsDialogDefinition, type TeamsDialogMessageBody, type TeamsDialogResponse, type TeamsDialogSize, type TeamsHandlerContext, type TeamsHandlerDecision, type TeamsInvokeResult, type TeamsSearchAttachment, type TeamsSearchLayout, type TeamsSearchMessageBody, type TeamsSearchResponse, type TeamsSearchResult, type TeamsSearchResultBody, type TeamsSearchResultType, type TeamsSurface, type TeamsTurnPreparation, type TeamsTurnRequestContext, createTeamsChannelAdapter, createTeamsDialog, createTeamsDialogMessage, createTeamsInvokeActivity, createTeamsSearchMessage, createTeamsSearchResult, currentTeamsTurnContext, mountTeamsAgent, parseTeamsActivity, runWithTeamsTurnContext, sendTeamsInvoke };
package/dist/index.js ADDED
@@ -0,0 +1,460 @@
1
+ // src/adapter.ts
2
+ import {
3
+ createM365ChannelAdapter,
4
+ extractUserIdentity,
5
+ runWithM365TurnContext
6
+ } from "@cuylabs/agent-channel-m365";
7
+ import { ActivityTypes as ActivityTypes3 } from "@microsoft/agents-activity";
8
+
9
+ // src/invoke.ts
10
+ import { Activity, ActivityTypes } from "@microsoft/agents-activity";
11
+ function createTeamsInvokeActivity(result) {
12
+ const activity = new Activity(ActivityTypes.InvokeResponse);
13
+ activity.value = result.body === void 0 ? { status: result.status } : { status: result.status, body: result.body };
14
+ return activity;
15
+ }
16
+ async function sendTeamsInvoke(context, body, status = 200) {
17
+ await context.sendActivity(
18
+ createTeamsInvokeActivity({
19
+ status,
20
+ ...body === void 0 ? {} : { body }
21
+ })
22
+ );
23
+ }
24
+
25
+ // src/teams-activity.ts
26
+ import { ActivityTypes as ActivityTypes2 } from "@microsoft/agents-activity";
27
+ function asObject(value) {
28
+ return value && typeof value === "object" ? value : void 0;
29
+ }
30
+ function readString(value, key) {
31
+ const candidate = value?.[key];
32
+ return typeof candidate === "string" && candidate.trim() ? candidate : void 0;
33
+ }
34
+ function detectSurface(conversationType, meetingId, teamId) {
35
+ if (meetingId) return "meeting";
36
+ if (teamId) return "channel";
37
+ if (conversationType === "personal") return "personal";
38
+ if (conversationType === "groupChat") return "group";
39
+ return "unknown";
40
+ }
41
+ function detectKind(context, eventType) {
42
+ const { activity } = context;
43
+ const payload = asObject(activity.value);
44
+ const invokeName = activity.name;
45
+ switch (activity.type) {
46
+ case ActivityTypes2.Message:
47
+ return "message";
48
+ case ActivityTypes2.MessageReaction:
49
+ return "reaction";
50
+ case ActivityTypes2.ConversationUpdate:
51
+ return "conversation-update";
52
+ case ActivityTypes2.MessageUpdate:
53
+ if (eventType === "editMessage") return "message-edit";
54
+ if (eventType === "undeleteMessage") return "message-restore";
55
+ return "other";
56
+ case ActivityTypes2.MessageDelete:
57
+ if (eventType === "softDeleteMessage") return "message-delete";
58
+ return "other";
59
+ case ActivityTypes2.Invoke:
60
+ if (invokeName === "task/fetch" || invokeName === "composeExtension/fetchTask") {
61
+ return "dialog-open";
62
+ }
63
+ if (invokeName === "task/submit") return "dialog-submit";
64
+ if (invokeName === "composeExtension/query" || invokeName === "composeExtension/queryLink" || invokeName === "composeExtension/anonymousQueryLink") {
65
+ return "search-command";
66
+ }
67
+ if (invokeName === "composeExtension/selectItem") return "select-result";
68
+ if (invokeName === "message/submitAction" || invokeName === "composeExtension/submitAction") {
69
+ return payload?.actionName === "feedback" ? "feedback" : "card-submit";
70
+ }
71
+ return "invoke";
72
+ default:
73
+ return "other";
74
+ }
75
+ }
76
+ function parseActors(channelData) {
77
+ const raw = channelData?.onBehalfOf;
78
+ if (!Array.isArray(raw)) return [];
79
+ const actors = [];
80
+ for (const item of raw) {
81
+ const actor = asObject(item);
82
+ const itemRef = asObject(actor?.item);
83
+ actors.push({
84
+ id: readString(itemRef, "id"),
85
+ displayName: readString(itemRef, "displayName"),
86
+ tenantId: readString(actor, "tenantId"),
87
+ userPrincipalName: readString(itemRef, "userPrincipalName")
88
+ });
89
+ }
90
+ return actors.filter(
91
+ (actor) => actor.id !== void 0 || actor.displayName !== void 0 || actor.userPrincipalName !== void 0
92
+ );
93
+ }
94
+ function parseTeamsActivity(context) {
95
+ const { activity } = context;
96
+ const channelData = asObject(activity.channelData);
97
+ const team = asObject(channelData?.team);
98
+ const channel = asObject(channelData?.channel);
99
+ const tenant = asObject(channelData?.tenant);
100
+ const meeting = asObject(channelData?.meeting);
101
+ const eventType = readString(channelData, "eventType");
102
+ const conversationType = typeof activity.conversation?.conversationType === "string" ? activity.conversation.conversationType : void 0;
103
+ const teamId = readString(team, "aadGroupId") ?? readString(team, "id");
104
+ const meetingId = readString(meeting, "id");
105
+ const surface = detectSurface(
106
+ conversationType,
107
+ meetingId,
108
+ teamId
109
+ );
110
+ return {
111
+ channelId: activity.channelId ?? "unknown",
112
+ conversationId: activity.conversation?.id ?? "unknown",
113
+ activityId: activity.id ?? void 0,
114
+ messageId: activity.id ?? void 0,
115
+ replyToId: activity.replyToId ?? void 0,
116
+ invokeName: activity.name ?? void 0,
117
+ eventType,
118
+ tenantId: readString(tenant, "id") ?? activity.conversation?.tenantId,
119
+ teamId,
120
+ channelThreadId: readString(channel, "id"),
121
+ meetingId,
122
+ surface,
123
+ kind: detectKind(context, eventType),
124
+ actors: parseActors(channelData)
125
+ };
126
+ }
127
+
128
+ // src/adapter.ts
129
+ function createTeamsChannelAdapter(options) {
130
+ const {
131
+ prepareTurn,
132
+ handlers,
133
+ onInvoke: fallbackInvoke,
134
+ ...baseOptions
135
+ } = options;
136
+ const base = createM365ChannelAdapter({
137
+ ...baseOptions,
138
+ prepareTurn: async (request) => {
139
+ const teams = parseTeamsActivity(request.turnContext);
140
+ const prepared = prepareTurn ? await prepareTurn({ ...request, teams }) : void 0;
141
+ return {
142
+ ...prepared ?? {},
143
+ scopeName: prepared?.scopeName?.trim() || "teams-activity",
144
+ scopeAttributes: {
145
+ teamsKind: teams.kind,
146
+ teamsSurface: teams.surface,
147
+ teamsTenantId: teams.tenantId,
148
+ teamsTeamId: teams.teamId,
149
+ teamsChannelId: teams.channelThreadId,
150
+ teamsMeetingId: teams.meetingId,
151
+ teamsInvokeName: teams.invokeName,
152
+ teamsEventType: teams.eventType,
153
+ ...prepared?.scopeAttributes ?? {}
154
+ },
155
+ context: {
156
+ ...prepared?.context ?? {},
157
+ teams
158
+ }
159
+ };
160
+ },
161
+ onInvoke: async (context) => {
162
+ const teams = parseTeamsActivity(context);
163
+ const handled = await dispatchTeamsHandler(
164
+ handlers,
165
+ teams.kind,
166
+ await createHandlerContext(options, base, context, teams)
167
+ );
168
+ if (!handled && fallbackInvoke) {
169
+ await fallbackInvoke(context);
170
+ }
171
+ }
172
+ });
173
+ async function handler(context) {
174
+ const teams = parseTeamsActivity(context);
175
+ if (teams.channelId !== "msteams") {
176
+ await base.handler(context);
177
+ return;
178
+ }
179
+ if (context.activity.type === ActivityTypes3.MessageUpdate || context.activity.type === ActivityTypes3.MessageDelete || context.activity.type === ActivityTypes3.MessageReaction) {
180
+ const handled = await dispatchTeamsHandler(
181
+ handlers,
182
+ teams.kind,
183
+ await createHandlerContext(options, base, context, teams)
184
+ );
185
+ if (handled) {
186
+ return;
187
+ }
188
+ }
189
+ await base.handler(context);
190
+ }
191
+ return {
192
+ ...base,
193
+ handler,
194
+ m365: base
195
+ };
196
+ }
197
+ async function createHandlerContext(options, base, turnContext, teams = parseTeamsActivity(turnContext)) {
198
+ const conversationId = turnContext.activity.conversation?.id ?? "unknown";
199
+ const channelId = turnContext.activity.channelId ?? "unknown";
200
+ const sessionId = await base.getSessionId(conversationId, channelId);
201
+ const user = extractUserIdentity(turnContext);
202
+ const source = resolveSource(options);
203
+ const ambient = {
204
+ turnContext,
205
+ user,
206
+ sessionId,
207
+ message: (turnContext.activity.text ?? "").trim(),
208
+ teams,
209
+ context: { teams }
210
+ };
211
+ return {
212
+ turnContext,
213
+ user,
214
+ teams,
215
+ sessionId,
216
+ source,
217
+ runAgent(message, runOptions) {
218
+ return runAgentWithTeamsContext(
219
+ ambient,
220
+ source,
221
+ sessionId,
222
+ message,
223
+ runOptions
224
+ );
225
+ },
226
+ async sendInvoke(body, status = 200) {
227
+ await sendTeamsInvoke(turnContext, body, status);
228
+ }
229
+ };
230
+ }
231
+ async function dispatchTeamsHandler(handlers, kind, context) {
232
+ const handler = resolveHandler(handlers, kind);
233
+ if (!handler) {
234
+ return false;
235
+ }
236
+ const result = await handler(context);
237
+ return result !== "continue";
238
+ }
239
+ function resolveHandler(handlers, kind) {
240
+ switch (kind) {
241
+ case "message-edit":
242
+ return handlers?.messageEdited;
243
+ case "message-delete":
244
+ return handlers?.messageDeleted;
245
+ case "message-restore":
246
+ return handlers?.messageRestored;
247
+ case "reaction":
248
+ return handlers?.reaction;
249
+ case "feedback":
250
+ return handlers?.feedbackSubmit ?? handlers?.cardSubmit;
251
+ case "card-submit":
252
+ return handlers?.cardSubmit;
253
+ case "dialog-open":
254
+ return handlers?.dialogOpen;
255
+ case "dialog-submit":
256
+ return handlers?.dialogSubmit;
257
+ case "search-command":
258
+ return handlers?.searchCommand;
259
+ case "select-result":
260
+ return handlers?.selectResult;
261
+ case "invoke":
262
+ return handlers?.invoke;
263
+ default:
264
+ return void 0;
265
+ }
266
+ }
267
+ function resolveSource(options) {
268
+ if (options.source) return options.source;
269
+ if (options.agent) return options.agent;
270
+ throw new Error(
271
+ "Provide exactly one of TeamsChannelOptions.agent or TeamsChannelOptions.source."
272
+ );
273
+ }
274
+ function runAgentWithTeamsContext(ambient, source, sessionId, message, options) {
275
+ return streamAgentWithTeamsContext(
276
+ ambient,
277
+ source,
278
+ sessionId,
279
+ message,
280
+ options
281
+ );
282
+ }
283
+ async function* streamAgentWithTeamsContext(ambient, source, sessionId, message, options) {
284
+ const contextValue = {
285
+ ...ambient,
286
+ message,
287
+ context: {
288
+ ...ambient.context ?? {},
289
+ teams: ambient.teams
290
+ }
291
+ };
292
+ const iterator = await runWithM365TurnContext(
293
+ contextValue,
294
+ async () => source.chat(sessionId, message, options)[Symbol.asyncIterator]()
295
+ );
296
+ let completed = false;
297
+ try {
298
+ while (true) {
299
+ const result = await runWithM365TurnContext(
300
+ contextValue,
301
+ () => iterator.next()
302
+ );
303
+ if (result.done) {
304
+ completed = true;
305
+ return result.value;
306
+ }
307
+ yield result.value;
308
+ }
309
+ } finally {
310
+ if (!completed && iterator.return) {
311
+ await runWithM365TurnContext(
312
+ contextValue,
313
+ () => iterator.return(void 0)
314
+ );
315
+ }
316
+ }
317
+ }
318
+
319
+ // src/express.ts
320
+ async function mountTeamsAgent(source, options = {}) {
321
+ const expressModule = await import("express");
322
+ const hostingModule = await import("@microsoft/agents-hosting");
323
+ const {
324
+ path: routePath = "/api/messages",
325
+ authConfig: providedAuthConfig,
326
+ port: portOption,
327
+ host,
328
+ adapter: providedAdapter,
329
+ app: providedApp,
330
+ ...adapterOptions
331
+ } = options;
332
+ const authConfig = hostingModule.getAuthConfigWithDefaults(
333
+ providedAuthConfig
334
+ );
335
+ const cloudAdapter = providedAdapter ?? new hostingModule.CloudAdapter(authConfig);
336
+ const expressApp = providedApp ?? expressModule.default();
337
+ const channelAdapter = createTeamsChannelAdapter({
338
+ source,
339
+ ...adapterOptions
340
+ });
341
+ const jsonParser = expressModule.json();
342
+ const jwtAuthorizer = hostingModule.authorizeJWT(authConfig);
343
+ expressApp.post(
344
+ routePath,
345
+ jsonParser,
346
+ jwtAuthorizer,
347
+ (req, res) => cloudAdapter.process(
348
+ req,
349
+ res,
350
+ (context) => channelAdapter.handler(context)
351
+ )
352
+ );
353
+ const port = portOption === void 0 ? resolvePort(process.env.PORT) : portOption;
354
+ let server;
355
+ if (port !== null) {
356
+ const onListen = () => {
357
+ console.log(
358
+ `Teams agent listening on port ${port} \u2014 appId: ${authConfig.clientId ?? "(not set)"}`
359
+ );
360
+ };
361
+ server = host ? expressApp.listen(port, host, onListen) : expressApp.listen(port, onListen);
362
+ }
363
+ return {
364
+ app: expressApp,
365
+ channelAdapter,
366
+ cloudAdapter,
367
+ server
368
+ };
369
+ }
370
+ function resolvePort(port) {
371
+ if (!port) return 3978;
372
+ const parsed = Number(port);
373
+ if (!Number.isInteger(parsed) || parsed < 0) {
374
+ throw new Error(`Invalid PORT value: ${port}`);
375
+ }
376
+ return parsed;
377
+ }
378
+
379
+ // src/context.ts
380
+ import {
381
+ currentM365TurnContext,
382
+ runWithM365TurnContext as runWithM365TurnContext2
383
+ } from "@cuylabs/agent-channel-m365";
384
+ function readTeamsContext(context) {
385
+ const payload = context?.context;
386
+ if (!payload || typeof payload !== "object") return void 0;
387
+ const teams = payload.teams;
388
+ return teams && typeof teams === "object" ? teams : void 0;
389
+ }
390
+ function currentTeamsTurnContext() {
391
+ const current = currentM365TurnContext();
392
+ const teams = readTeamsContext(current);
393
+ if (!current || !teams) return void 0;
394
+ return {
395
+ ...current,
396
+ teams
397
+ };
398
+ }
399
+ function runWithTeamsTurnContext(value, fn) {
400
+ return runWithM365TurnContext2(
401
+ {
402
+ ...value,
403
+ context: {
404
+ ...value.context ?? {},
405
+ teams: value.teams
406
+ }
407
+ },
408
+ fn
409
+ );
410
+ }
411
+
412
+ // src/responses.ts
413
+ function createTeamsSearchResult(result) {
414
+ return {
415
+ composeExtension: {
416
+ ...result.type ? { type: result.type } : { type: "result" },
417
+ ...result.layout ? { attachmentLayout: result.layout } : {},
418
+ ...result.attachments ? { attachments: result.attachments } : {},
419
+ ...result.text ? { text: result.text } : {},
420
+ ...result.preview ? { activityPreview: result.preview } : {}
421
+ }
422
+ };
423
+ }
424
+ function createTeamsSearchMessage(text) {
425
+ return {
426
+ composeExtension: {
427
+ type: "message",
428
+ text
429
+ }
430
+ };
431
+ }
432
+ function createTeamsDialog(dialog) {
433
+ return {
434
+ task: {
435
+ type: "continue",
436
+ value: dialog
437
+ }
438
+ };
439
+ }
440
+ function createTeamsDialogMessage(message) {
441
+ return {
442
+ task: {
443
+ type: "message",
444
+ value: message
445
+ }
446
+ };
447
+ }
448
+ export {
449
+ createTeamsChannelAdapter,
450
+ createTeamsDialog,
451
+ createTeamsDialogMessage,
452
+ createTeamsInvokeActivity,
453
+ createTeamsSearchMessage,
454
+ createTeamsSearchResult,
455
+ currentTeamsTurnContext,
456
+ mountTeamsAgent,
457
+ parseTeamsActivity,
458
+ runWithTeamsTurnContext,
459
+ sendTeamsInvoke
460
+ };
package/package.json ADDED
@@ -0,0 +1,72 @@
1
+ {
2
+ "name": "@cuylabs/agent-channel-teams",
3
+ "version": "0.10.0",
4
+ "description": "Teams-native channel layer for @cuylabs/agent-core built on top of @cuylabs/agent-channel-m365",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "default": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md"
18
+ ],
19
+ "dependencies": {
20
+ "@cuylabs/agent-channel-m365": "^0.10.0",
21
+ "@cuylabs/agent-core": "^0.10.0"
22
+ },
23
+ "peerDependencies": {
24
+ "@microsoft/agents-activity": ">=0.1.0",
25
+ "@microsoft/agents-hosting": ">=0.1.0",
26
+ "express": ">=4.21.0 || >=5.0.0"
27
+ },
28
+ "peerDependenciesMeta": {
29
+ "express": {
30
+ "optional": true
31
+ }
32
+ },
33
+ "devDependencies": {
34
+ "@microsoft/agents-activity": "^1.4.2",
35
+ "@microsoft/agents-hosting": "^1.4.2",
36
+ "@types/express": "^5.0.0",
37
+ "@types/node": "^22.0.0",
38
+ "express": "^5.2.1",
39
+ "tsup": "^8.0.0",
40
+ "typescript": "^5.7.0",
41
+ "vitest": "^4.0.18"
42
+ },
43
+ "keywords": [
44
+ "agent",
45
+ "teams",
46
+ "microsoft",
47
+ "m365",
48
+ "channel",
49
+ "bot"
50
+ ],
51
+ "author": "cuylabs",
52
+ "license": "Apache-2.0",
53
+ "repository": {
54
+ "type": "git",
55
+ "url": "https://github.com/cuylabs-ai/agents-ts.git",
56
+ "directory": "packages/agent-channel-teams"
57
+ },
58
+ "engines": {
59
+ "node": ">=20"
60
+ },
61
+ "publishConfig": {
62
+ "access": "public"
63
+ },
64
+ "scripts": {
65
+ "build": "tsup src/index.ts --format esm --dts --clean",
66
+ "dev": "tsup src/index.ts --format esm --dts --watch",
67
+ "typecheck": "tsc --noEmit",
68
+ "test": "vitest run",
69
+ "test:watch": "vitest",
70
+ "clean": "rm -rf dist"
71
+ }
72
+ }