@qwen-code/channel-msteams 0.0.0-stage → 0.28.1-preview.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.
package/LICENSE ADDED
@@ -0,0 +1,203 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2025 Google LLC
191
+ Copyright 2025 Qwen
192
+
193
+ Licensed under the Apache License, Version 2.0 (the "License");
194
+ you may not use this file except in compliance with the License.
195
+ You may obtain a copy of the License at
196
+
197
+ http://www.apache.org/licenses/LICENSE-2.0
198
+
199
+ Unless required by applicable law or agreed to in writing, software
200
+ distributed under the License is distributed on an "AS IS" BASIS,
201
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202
+ See the License for the specific language governing permissions and
203
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,169 @@
1
- # Temporary Holding Version
1
+ # Microsoft Teams channel
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ This package connects Microsoft Teams to a Qwen Code `ChannelAgentBridge`.
4
+ It requires Node.js 22.12.0 or newer.
5
+ It supports commercial-cloud, single-tenant bots, personal messages, explicit
6
+ bot mentions in group chats, and channel posts with thread replies. It sends
7
+ final plain text, split into ordered UTF-8 chunks. Attachments, Graph history,
8
+ cards, national clouds, and scheduled or proactive tasks are outside this release.
9
+
10
+ ## Supported channel-base versions
11
+
12
+ Use one host-provided copy of `@qwen-code/channel-base`. The peer dependency
13
+ accepts exactly two versions: the legacy `0.23.0` peer and the exact
14
+ channel-base release this package declares in `peerDependencies`, which follows
15
+ each repository release. 0.24.x and 0.25.x are not claimed as compatible.
16
+
17
+ | Version | Supported mode | Access-control contract |
18
+ | -------------------------------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
19
+ | Exact release declared in `peerDependencies` | Standalone or hosted | Standalone uses `privatePolicy` and explicit `operators`; hosted callers also authorize controls before dispatch. |
20
+ | `0.23.0` | Hosted only | Configure the legacy `senderPolicy` and `dmPolicy`; the host authorizes every control before dispatch. This version does not enforce `operators`. |
21
+
22
+ Construction without a host fails on the older base because it lacks the lifecycle
23
+ guard needed to stop queued standalone turns. Do not install a second newer base
24
+ inside this plugin to work around the host's version. Hosted mode uses its awaited
25
+ prompt hooks and send guards to revalidate ownership before external effects.
26
+
27
+ ## Standalone extension
28
+
29
+ Build the workspace package and install this directory as a local Qwen Code
30
+ extension. `qwen-extension.json` declares the `msteams` channel provider; no
31
+ built-in CLI registry change is required. Use the existing channel configuration
32
+ workflow with these provider fields:
33
+
34
+ | Field | Meaning |
35
+ | -------------- | ------------------------------------------------------------------------------- |
36
+ | `appId` | The Microsoft Entra application ID registered with Azure Bot Service |
37
+ | `appPassword` | The application client secret, supplied through the host's secret configuration |
38
+ | `tenantId` | The one Microsoft tenant admitted by this bot |
39
+ | `approvalMode` | Explicit Qwen approval mode, such as `default` |
40
+ | `webhookPort` | Loopback HTTP port, default `3978` |
41
+ | `webhookPath` | Callback path, default `/api/messages` |
42
+
43
+ Configure the Azure Bot messaging endpoint as the public HTTPS URL forwarded to
44
+ this listener. Enable the Microsoft Teams channel on the Azure Bot and install a
45
+ Teams app whose bot scopes include `personal`, `groupChat`, and `team`. The bot ID
46
+ in the app manifest must equal `appId`. Keep HTTPS termination and request-size
47
+ limits at the ingress. Never expose the local listener without authentication;
48
+ the plugin always invokes the Microsoft SDK JWT middleware.
49
+
50
+ Use the standard `privatePolicy`, `groupPolicy`, `groups`, `allowedUsers`, and
51
+ `operators` fields to control access. `chat_thread` shares the conversation within
52
+ a group or channel post. Actor IDs have the form `msteams:<tenant-id>:<aad-user-id>`;
53
+ chat IDs also contain the tenant and an encoded conversation ID. Shared-session
54
+ operators are explicitly configured; permitting ordinary group messages does not
55
+ grant permission to cancel, clear, or approve. This adapter uses `followup`
56
+ queuing so normal messages do not implicitly cancel another user's turn.
57
+
58
+ The default reference store uses atomic files beneath the channel state directory
59
+ with private filesystem permissions. It is intended for **one process**. Input
60
+ deduplication is in memory (up to 1,000 events for ten minutes); process restart can
61
+ therefore repeat a callback. Standalone mode acknowledges a message after storing
62
+ its reply reference and scheduling it in memory. It does **not** guarantee durable
63
+ execution, prompt recovery, or delivery after a crash. Use a host for those needs.
64
+
65
+ ## Hosted mode
66
+
67
+ For an HTTP gateway that only accepts messages, use
68
+ `createTeamsIngress(name, credentials, acceptInbound)` from this package. Pass
69
+ `appId`, `appPassword` and `tenantId` as credentials; the async callback receives
70
+ the authenticated, immutable `TeamsInboundEvent`. The returned object's
71
+ `handleWebhook(input)` accepts parsed `headers` and `body` and returns status,
72
+ headers and an optional body for the application's POST route to write unchanged.
73
+ It needs no channel configuration, approval mode, bridge, router, reference store
74
+ or connect/disconnect calls. The host owns the object's lifetime and recreates it
75
+ when the channel name or credentials change. The plugin constructs a fresh SDK
76
+ request and authenticates it itself, ignoring caller-supplied identities.
77
+
78
+ Acceptance is awaited before the response. A rejected callback returns 503;
79
+ authentication failure returns 401 and normalization rejections return 400.
80
+ SDK processing failures return 503. Ignored activities do not invoke the callback;
81
+ SDK invoke responses retain
82
+ their status, headers and body. The ingress does not queue, deduplicate, execute
83
+ or send messages. Persist or consume an event before resolving the callback and
84
+ schedule execution separately. Retries and concurrent duplicate callbacks remain
85
+ the host's responsibility.
86
+
87
+ For hosted execution, construct `TeamsChannel` with `TeamsChannelOptions.host`
88
+ and a `TeamsReferenceStore`. `connect()` opens no port. Its `handleWebhook()`
89
+ uses the same SDK authentication and normalization path as the independent
90
+ ingress; gateways need not construct a channel merely to accept messages.
91
+
92
+ The host contract deliberately has five operations:
93
+
94
+ 1. `acceptInbound(event)` durably stores or consumes a verified event before
95
+ resolving. A rejected promise produces a non-success HTTP response. Do not wait
96
+ for an agent prompt here. This hook runs before Qwen pairing, so a host can
97
+ consume first-time binding commands without prior execution authorization.
98
+ 2. `beforePrompt(event, sessionId)` rechecks execution authorization and persists
99
+ submission intent. It is awaited immediately before the underlying bridge
100
+ prompt. A host must handle an uncertain submission without automatically
101
+ resubmitting it.
102
+ 3. `onPromptSettled(event, sessionId, outcome)` persists bridge success or failure.
103
+ This is execution settlement, not delivery success. A host's bridge can also
104
+ persist its native prompt ID when the underlying execution service accepts it.
105
+ 4. `beforeSend(context)` rechecks authorization immediately before each actual
106
+ platform send. It receives the original event and immutable reply target, text,
107
+ whole reply, chunk index/count, and `response` or `system` kind. Throw to stop
108
+ sending. Sends without an originating event must be explicitly authorized by
109
+ the host, or rejected.
110
+ 5. `onSendReceipt(receipt)` persists the platform message ID for a confirmed send.
111
+ Failure before a send attempt is `known_failed`; a timeout, missing receipt, or
112
+ receipt persistence failure after the send attempt is `unknown`. The plugin
113
+ does not retry uncertain sends.
114
+
115
+ After acceptance, the host loads its own stored record, revalidates its ownership
116
+ and current binding, and calls `dispatchPersisted(event)`. This is a **trusted
117
+ in-process API**, not an HTTP endpoint or a JWT bypass switch. Never populate its
118
+ argument from an unauthenticated request. Dispatch each accepted event once; the
119
+ host owns durable deduplication, leases, fencing, recovery, and binding generations.
120
+ Before every `dispatchPersisted()` or `cancelEvent()` call, the host must authorize
121
+ the current actor for that specific action. This includes built-in commands such
122
+ as `/cancel`, `/clear`, `/reset`, `/new`, permission responses and commands that
123
+ expose shared-session details. `beforePrompt` protects bridge submissions only;
124
+ commands can execute without calling it. On base `0.23.0`, an empty `allowedUsers`
125
+ list grants shared commands to everyone and `operators` is ignored. Hosts should
126
+ consume their supported controls directly and reject other slash commands unless
127
+ explicitly authorized. Merely implementing `beforePrompt` is insufficient. Do not
128
+ change global allowlists or operators temporarily for individual messages.
129
+
130
+ Keep the event immutable, including its original reply reference. Reference
131
+ storage is keyed by normalized conversation and thread; a later post cannot
132
+ redirect an earlier response.
133
+
134
+ `sendEventText(event, text, kind)` sends binding guidance or recovered final text
135
+ through the same per-send guard. Use `kind: 'response'` only for an actual final
136
+ agent result. `cancelEvent(sessionId, expectedEventId)` cancels only the matching
137
+ active event, using ChannelBase's cancellation state machine. Authorize the actor
138
+ in the host first. Dispatch control events promptly rather than placing them
139
+ behind an awaited long-running `dispatchPersisted()` call; ChannelBase already
140
+ queues ordinary prompts. Do not change the shared `operators` list for individual
141
+ messages.
142
+
143
+ When the host has durable receipts for a consecutive sent prefix, it can call
144
+ `sendEventText(event, fullText, kind, { startChunkIndex, sourceLabel })` to resume
145
+ from the first unsent chunk. Pass the unchanged full text, the original event and
146
+ the captured source label when the reply was attributed. Guards and receipts
147
+ retain the original chunk indexes, total chunk count and full text. The index must
148
+ be a nonnegative integer identifying an existing chunk; empty text permits only
149
+ zero. Out-of-range values fail before sending. The host decides whether recovery
150
+ is safe and never advances past an uncertain send. This option does not add an
151
+ automatic retry or deduplicate messages by itself.
152
+
153
+ Replies are capped at 64 KiB and split into at most 12 KiB plain-text chunks.
154
+ An attributed reply repeats its source label on every chunk, and the label is
155
+ included in each chunk's 12 KiB budget. Blank or oversized completed prompt
156
+ results become a short completion notice
157
+ through the normal response path, so cancellation and send guards still apply.
158
+ `onPromptSettled` receives the original result text. Direct `sendEventText` calls
159
+ with oversized replies fail before sending. Ingress JSON is capped at 1 MiB and normalized
160
+ message text at 64 KiB. Configure database retention, encryption, capacity, and
161
+ rate limits in the host. Do not log input text, secrets, or conversation references.
162
+
163
+ ## Validation boundary
164
+
165
+ Unit tests cover normalization, immutable target correlation, durable ACK timing,
166
+ per-send guards, receipts, prompt hooks, cancellation matching, and file reference
167
+ persistence. They do not establish Microsoft tenant installation, real JWT key
168
+ retrieval, real Bot Connector delivery, or agent tool execution. Validate those
169
+ with a real tenant and the exact installed Qwen version before production use.
@@ -0,0 +1,46 @@
1
+ import { ChannelBase } from '@qwen-code/channel-base';
2
+ import type { ChannelAgentBridge, ChannelOutputSegmentContext, ChannelTaskLifecycleEvent, Envelope } from '@qwen-code/channel-base';
3
+ import type { TeamsChannelOptions, TeamsConfig, TeamsInboundEvent, TeamsWebhookRequest, TeamsWebhookResponse } from './types.js';
4
+ export declare class TeamsDeliveryError extends Error {
5
+ readonly state: 'known_failed' | 'unknown';
6
+ constructor(state: 'known_failed' | 'unknown', options?: ErrorOptions);
7
+ }
8
+ export declare function splitTeamsText(text: string, sourceLabel?: string): string[];
9
+ export declare class TeamsChannel extends ChannelBase {
10
+ private readonly adapter;
11
+ private readonly teamsConfig;
12
+ private readonly teamsOptions;
13
+ private readonly references;
14
+ private readonly inbound;
15
+ private readonly activeEvents;
16
+ private readonly cancelledEvents;
17
+ private readonly accepting;
18
+ private readonly recent;
19
+ private server?;
20
+ private connected;
21
+ constructor(name: string, config: TeamsConfig & Record<string, unknown>, bridge: ChannelAgentBridge, options?: TeamsChannelOptions);
22
+ private eventForSession;
23
+ protected onTaskLifecycle(event: ChannelTaskLifecycleEvent): void;
24
+ setBridge(bridge: ChannelAgentBridge): void;
25
+ /** Host authorization must precede this exact-event cancellation. */
26
+ cancelEvent(sessionId: string, expectedEventId: string): Promise<boolean>;
27
+ connect(): Promise<void>;
28
+ disconnect(): Promise<void>;
29
+ protected canStartInboundTurn(): boolean;
30
+ /** Public HTTP entrypoint. An incoming `user` object is never trusted. */
31
+ handleWebhook(input: TeamsWebhookRequest): Promise<TeamsWebhookResponse>;
32
+ private accept;
33
+ /** Trusted in-process replay only. Hosts must load and authorize their own accepted records. */
34
+ dispatchPersisted(event: TeamsInboundEvent): Promise<void>;
35
+ /** Normalized envelopes alone lack authenticated Teams routing; use handleWebhook or trusted replay. */
36
+ handleInbound(_envelope: Envelope): Promise<void>;
37
+ sendMessage(chatId: string, text: string): Promise<void>;
38
+ protected sendThreadMessage(chatId: string, threadId: string | undefined, text: string, sourceLabel?: string): Promise<void>;
39
+ protected onResponseComplete(chatId: string, text: string, sessionId: string, segment?: ChannelOutputSegmentContext): Promise<void>;
40
+ /** System guidance and recovered final text use the original accepted event's target. */
41
+ sendEventText(event: TeamsInboundEvent, text: string, kind?: 'response' | 'system', options?: {
42
+ startChunkIndex?: number;
43
+ sourceLabel?: string;
44
+ }): Promise<void>;
45
+ private deliver;
46
+ }