@effect/chat-teams 0.0.0 → 4.1.5

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 (162) hide show
  1. package/AGENTS.md +434 -0
  2. package/CLAUDE.md +434 -0
  3. package/LICENSE +21 -0
  4. package/README.md +116 -0
  5. package/ai-docs/README.md +44 -0
  6. package/ai-docs/package.json +36 -0
  7. package/ai-docs/src/01_effect/01_basics/01_effect-gen.ts +30 -0
  8. package/ai-docs/src/01_effect/01_basics/02_effect-fn.ts +52 -0
  9. package/ai-docs/src/01_effect/01_basics/10_creating-effects.ts +74 -0
  10. package/ai-docs/src/01_effect/01_basics/index.md +7 -0
  11. package/ai-docs/src/01_effect/02_schema/10_schema-basics.ts +43 -0
  12. package/ai-docs/src/01_effect/02_schema/index.md +7 -0
  13. package/ai-docs/src/01_effect/03_services/01_service.ts +45 -0
  14. package/ai-docs/src/01_effect/03_services/10_reference.ts +10 -0
  15. package/ai-docs/src/01_effect/03_services/20_layer-composition.ts +70 -0
  16. package/ai-docs/src/01_effect/03_services/20_layer-unwrap.ts +66 -0
  17. package/ai-docs/src/01_effect/03_services/index.md +5 -0
  18. package/ai-docs/src/01_effect/04_errors/01_error-handling.ts +30 -0
  19. package/ai-docs/src/01_effect/04_errors/10_catch-tags.ts +24 -0
  20. package/ai-docs/src/01_effect/04_errors/20_reason-errors.ts +64 -0
  21. package/ai-docs/src/01_effect/04_errors/index.md +1 -0
  22. package/ai-docs/src/01_effect/05_resources/10_acquire-release.ts +105 -0
  23. package/ai-docs/src/01_effect/05_resources/20_layer-side-effects.ts +31 -0
  24. package/ai-docs/src/01_effect/05_resources/30_layer-map.ts +86 -0
  25. package/ai-docs/src/01_effect/05_resources/index.md +3 -0
  26. package/ai-docs/src/01_effect/06_running/10_run-main.ts +30 -0
  27. package/ai-docs/src/01_effect/06_running/20_layer-launch.ts +27 -0
  28. package/ai-docs/src/01_effect/06_running/index.md +1 -0
  29. package/ai-docs/src/01_effect/07_pubsub/10_pubsub.ts +56 -0
  30. package/ai-docs/src/01_effect/07_pubsub/index.md +3 -0
  31. package/ai-docs/src/03_stream/10_creating-streams.ts +103 -0
  32. package/ai-docs/src/03_stream/20_consuming-streams.ts +137 -0
  33. package/ai-docs/src/03_stream/30_encoding.ts +163 -0
  34. package/ai-docs/src/03_stream/index.md +4 -0
  35. package/ai-docs/src/04_integration/10_managed-runtime.ts +129 -0
  36. package/ai-docs/src/04_integration/index.md +5 -0
  37. package/ai-docs/src/05_batching/10_request-resolver.ts +89 -0
  38. package/ai-docs/src/05_batching/index.md +3 -0
  39. package/ai-docs/src/06_schedule/10_schedules.ts +111 -0
  40. package/ai-docs/src/06_schedule/index.md +3 -0
  41. package/ai-docs/src/07_datetime/10_creating-and-formatting.ts +30 -0
  42. package/ai-docs/src/07_datetime/20_time-zones.ts +44 -0
  43. package/ai-docs/src/07_datetime/index.md +5 -0
  44. package/ai-docs/src/08_observability/10_logging.ts +66 -0
  45. package/ai-docs/src/08_observability/20_otlp-tracing.ts +95 -0
  46. package/ai-docs/src/08_observability/index.md +7 -0
  47. package/ai-docs/src/09_testing/10_effect-tests.ts +55 -0
  48. package/ai-docs/src/09_testing/20_layer-tests.ts +138 -0
  49. package/ai-docs/src/09_testing/index.md +1 -0
  50. package/ai-docs/src/10_predicate/01_basics.ts +14 -0
  51. package/ai-docs/src/10_predicate/index.md +9 -0
  52. package/ai-docs/src/40_sql/10_basics.ts +175 -0
  53. package/ai-docs/src/40_sql/index.md +6 -0
  54. package/ai-docs/src/50_http-client/10_basics.ts +102 -0
  55. package/ai-docs/src/50_http-client/index.md +3 -0
  56. package/ai-docs/src/51_http-server/10_basics.ts +118 -0
  57. package/ai-docs/src/51_http-server/20_testing.ts +100 -0
  58. package/ai-docs/src/51_http-server/fixtures/api/Api.ts +14 -0
  59. package/ai-docs/src/51_http-server/fixtures/api/Authorization.ts +36 -0
  60. package/ai-docs/src/51_http-server/fixtures/api/System.ts +10 -0
  61. package/ai-docs/src/51_http-server/fixtures/api/Users.ts +107 -0
  62. package/ai-docs/src/51_http-server/fixtures/domain/User.ts +21 -0
  63. package/ai-docs/src/51_http-server/fixtures/domain/UserErrors.ts +22 -0
  64. package/ai-docs/src/51_http-server/fixtures/server/Authorization.ts +37 -0
  65. package/ai-docs/src/51_http-server/fixtures/server/Users/http.ts +80 -0
  66. package/ai-docs/src/51_http-server/fixtures/server/Users.ts +183 -0
  67. package/ai-docs/src/51_http-server/index.md +3 -0
  68. package/ai-docs/src/52_graphql/10_basics.ts +117 -0
  69. package/ai-docs/src/52_graphql/20_testing.ts +45 -0
  70. package/ai-docs/src/52_graphql/30_batching.ts +118 -0
  71. package/ai-docs/src/52_graphql/40_aliased-batching.ts +124 -0
  72. package/ai-docs/src/52_graphql/50_errors-and-retries.ts +74 -0
  73. package/ai-docs/src/52_graphql/index.md +6 -0
  74. package/ai-docs/src/60_child-process/10_working-with-child-processes.ts +117 -0
  75. package/ai-docs/src/60_child-process/index.md +3 -0
  76. package/ai-docs/src/70_cli/10_basics.ts +162 -0
  77. package/ai-docs/src/70_cli/index.md +5 -0
  78. package/ai-docs/src/71_ai/10_language-model.ts +156 -0
  79. package/ai-docs/src/71_ai/20_tools.ts +226 -0
  80. package/ai-docs/src/71_ai/30_chat.ts +158 -0
  81. package/ai-docs/src/71_ai/fixtures/domain/LaunchPlan.ts +9 -0
  82. package/ai-docs/src/71_ai/index.md +5 -0
  83. package/ai-docs/src/80_cluster/10_entities.ts +97 -0
  84. package/ai-docs/src/80_cluster/index.md +4 -0
  85. package/ai-docs/src/index.md +10 -0
  86. package/ai-docs/tsconfig.json +28 -0
  87. package/dist/TeamsChat.d.ts +318 -0
  88. package/dist/TeamsChat.d.ts.map +1 -0
  89. package/dist/TeamsChat.js +316 -0
  90. package/dist/TeamsChat.js.map +1 -0
  91. package/dist/index.d.ts +10 -0
  92. package/dist/index.d.ts.map +1 -0
  93. package/dist/index.js +11 -0
  94. package/dist/index.js.map +1 -0
  95. package/dist/internal/adapter.d.ts +2 -0
  96. package/dist/internal/adapter.d.ts.map +1 -0
  97. package/dist/internal/adapter.js +300 -0
  98. package/dist/internal/adapter.js.map +1 -0
  99. package/dist/internal/address.d.ts +2 -0
  100. package/dist/internal/address.d.ts.map +1 -0
  101. package/dist/internal/address.js +52 -0
  102. package/dist/internal/address.js.map +1 -0
  103. package/dist/internal/auth.d.ts +2 -0
  104. package/dist/internal/auth.d.ts.map +1 -0
  105. package/dist/internal/auth.js +142 -0
  106. package/dist/internal/auth.js.map +1 -0
  107. package/dist/internal/connector.d.ts +2 -0
  108. package/dist/internal/connector.d.ts.map +1 -0
  109. package/dist/internal/connector.js +173 -0
  110. package/dist/internal/connector.js.map +1 -0
  111. package/dist/internal/download.d.ts +5 -0
  112. package/dist/internal/download.d.ts.map +1 -0
  113. package/dist/internal/download.js +183 -0
  114. package/dist/internal/download.js.map +1 -0
  115. package/dist/internal/envelope.d.ts +2 -0
  116. package/dist/internal/envelope.d.ts.map +1 -0
  117. package/dist/internal/envelope.js +337 -0
  118. package/dist/internal/envelope.js.map +1 -0
  119. package/dist/internal/errors.d.ts +2 -0
  120. package/dist/internal/errors.d.ts.map +1 -0
  121. package/dist/internal/errors.js +113 -0
  122. package/dist/internal/errors.js.map +1 -0
  123. package/dist/internal/interactions.d.ts +2 -0
  124. package/dist/internal/interactions.d.ts.map +1 -0
  125. package/dist/internal/interactions.js +288 -0
  126. package/dist/internal/interactions.js.map +1 -0
  127. package/dist/internal/length.d.ts +2 -0
  128. package/dist/internal/length.d.ts.map +1 -0
  129. package/dist/internal/length.js +147 -0
  130. package/dist/internal/length.js.map +1 -0
  131. package/dist/internal/normalize.d.ts +2 -0
  132. package/dist/internal/normalize.d.ts.map +1 -0
  133. package/dist/internal/normalize.js +224 -0
  134. package/dist/internal/normalize.js.map +1 -0
  135. package/dist/internal/parse.d.ts +2 -0
  136. package/dist/internal/parse.d.ts.map +1 -0
  137. package/dist/internal/parse.js +33 -0
  138. package/dist/internal/parse.js.map +1 -0
  139. package/dist/internal/render.d.ts +2 -0
  140. package/dist/internal/render.d.ts.map +1 -0
  141. package/dist/internal/render.js +316 -0
  142. package/dist/internal/render.js.map +1 -0
  143. package/dist/internal/webhook.d.ts +2 -0
  144. package/dist/internal/webhook.d.ts.map +1 -0
  145. package/dist/internal/webhook.js +88 -0
  146. package/dist/internal/webhook.js.map +1 -0
  147. package/package.json +61 -1
  148. package/src/TeamsChat.ts +470 -0
  149. package/src/index.ts +12 -0
  150. package/src/internal/adapter.ts +351 -0
  151. package/src/internal/address.ts +67 -0
  152. package/src/internal/auth.ts +192 -0
  153. package/src/internal/connector.ts +253 -0
  154. package/src/internal/download.ts +277 -0
  155. package/src/internal/envelope.ts +427 -0
  156. package/src/internal/errors.ts +94 -0
  157. package/src/internal/interactions.ts +294 -0
  158. package/src/internal/length.ts +170 -0
  159. package/src/internal/normalize.ts +232 -0
  160. package/src/internal/parse.ts +41 -0
  161. package/src/internal/render.ts +318 -0
  162. package/src/internal/webhook.ts +117 -0
@@ -0,0 +1,351 @@
1
+ import {
2
+ type ChatAdapter,
3
+ checkMessageLength,
4
+ type Descriptor,
5
+ type Posted,
6
+ type ThreadInfo,
7
+ type User
8
+ } from "effect/chat/ChatAdapter"
9
+ import { type Capability, type ChatError, type ChatErrorReason, interactionExpired } from "effect/chat/ChatError"
10
+ import type { Defer } from "effect/chat/ChatInteraction"
11
+ import type { Attachment } from "effect/chat/ChatMessage"
12
+ import type { ChatThread } from "effect/chat/ChatThread"
13
+ import type { Action } from "effect/chat/ChatUi"
14
+ import * as Clock from "effect/Clock"
15
+ import * as DateTime from "effect/DateTime"
16
+ import * as Duration from "effect/Duration"
17
+ import * as Effect from "effect/Effect"
18
+ import type * as HttpClient from "effect/http/HttpClient"
19
+ import * as Option from "effect/Option"
20
+ import type * as Redacted from "effect/Redacted"
21
+ import type * as Schema from "effect/Schema"
22
+ import * as Stream from "effect/Stream"
23
+ import type { Cloud, Unverified } from "../TeamsChat.ts"
24
+ import * as Address from "./address.ts"
25
+ import { type Connector, segment } from "./connector.ts"
26
+ import * as Download from "./download.ts"
27
+ import type * as Envelope from "./envelope.ts"
28
+ import * as Errors from "./errors.ts"
29
+ import * as Length from "./length.ts"
30
+ import { botId, userId } from "./normalize.ts"
31
+ import { isObject, object, string } from "./parse.ts"
32
+ import * as Render from "./render.ts"
33
+
34
+ /** The adapter's own cap on elements in one message. @internal */
35
+ export const actionsPerMessage = Render.actionsPerRow
36
+
37
+ /**
38
+ * The adapter's own cap on an element's id plus value, counted as the
39
+ * signed token that carries them: 329 units of it are the envelope with a
40
+ * GUID app and tenant, which leaves about 500 ASCII characters.
41
+ *
42
+ * @internal
43
+ */
44
+ export const actionDataLength = 1_000
45
+
46
+ /**
47
+ * The adapter's own cap on a modal's id plus metadata, counted as the whole
48
+ * signed dialog token that carries them: the claims, the metadata and the
49
+ * modal's definition (title, labels, options, texts). With a GUID app and
50
+ * tenant and every id at its longest, the claims take at most 1,483 units,
51
+ * which leaves about 1,880 bytes for the rest of the modal's JSON.
52
+ *
53
+ * @internal
54
+ */
55
+ export const modalMetadataLength = 4_000
56
+
57
+ /** The adapter's own cap on a modal's inputs and texts. @internal */
58
+ export const modalFields = 10
59
+
60
+ /** How long a targeted message can be answered. @internal */
61
+ export const followUpAge = Duration.hours(24)
62
+
63
+ /** @internal */
64
+ export const capabilitiesOf = (unverified: Unverified, hasKeys: boolean): ReadonlySet<Capability> => {
65
+ const set = new Set<Capability>(["edit", "delete", "getThread", "getUser"])
66
+ if (unverified.startThread === true) set.add("startThread")
67
+ if (unverified.download === true) set.add("download")
68
+ if (hasKeys && unverified.buttons === true) {
69
+ set.add("buttons")
70
+ if (unverified.modals === true) {
71
+ set.add("modals")
72
+ set.add("modalErrors")
73
+ }
74
+ }
75
+ if (unverified.commands === true) {
76
+ set.add("commands")
77
+ set.add("ephemeral")
78
+ }
79
+ return set
80
+ }
81
+
82
+ /** @internal */
83
+ export const makeDescriptor = (capabilities: ReadonlySet<Capability>, tokenLength: Length.TokenLength): Descriptor => ({
84
+ platform: Address.platform,
85
+ capabilities,
86
+ measure: Length.makeMeasure(tokenLength),
87
+ limits: {
88
+ messageLength: Length.messageLength,
89
+ filesPerMessage: 0,
90
+ uploadBytes: 0,
91
+ minWriteInterval: Duration.seconds(1),
92
+ ...(capabilities.has("buttons") ? { actionsPerMessage, actionDataLength } : {}),
93
+ ...(capabilities.has("modals") ? { modalMetadataLength, modalFields } : {}),
94
+ ...(capabilities.has("commands") ? { followUpAge } : {})
95
+ }
96
+ })
97
+
98
+ /** A fallback token length for a layer without keys: the largest a token can be. */
99
+ const noKeys: Length.TokenLength = () => 0
100
+
101
+ /** @internal */
102
+ export interface Options {
103
+ readonly connector: Connector
104
+ readonly http: HttpClient.HttpClient
105
+ readonly cloud: Cloud
106
+ readonly appId: string
107
+ readonly tenantId: string
108
+ readonly envelope: Envelope.Envelope | undefined
109
+ readonly unverified: Unverified
110
+ readonly token: Effect.Effect<Redacted.Redacted<string>, ChatError>
111
+ /** The ids of the buttons that open a dialog. */
112
+ readonly modalButtons: ReadonlySet<string>
113
+ }
114
+
115
+ /** @internal */
116
+ export interface Made {
117
+ readonly adapter: ChatAdapter
118
+ /**
119
+ * Sends a command's answer through the inbound `serviceUrl` in `raw`:
120
+ * private as a targeted message to the command's user, public as a new
121
+ * post. A failure is never retried in the other form.
122
+ */
123
+ readonly answer: (
124
+ op: string,
125
+ raw: Schema.Json,
126
+ content: { readonly markdown: string; readonly actions?: ReadonlyArray<Action> | undefined },
127
+ visibility: "ephemeral" | "public"
128
+ ) => Effect.Effect<void, ChatError>
129
+ }
130
+
131
+ const fail = (op: string, reason: ChatErrorReason) => Effect.fail(Errors.chatError(op, reason))
132
+
133
+ /** @internal */
134
+ export const make = (options: Options): Made => {
135
+ const capabilities = capabilitiesOf(options.unverified, options.envelope !== undefined)
136
+ const descriptor = makeDescriptor(capabilities, options.envelope?.tokenLength ?? noKeys)
137
+ const { connector } = options
138
+ const self = botId(options.appId)
139
+ const downloadOptions = {
140
+ token: options.token,
141
+ connectorHosts: new Set(options.cloud.connectorHosts),
142
+ fileHostSuffixes: options.cloud.fileHostSuffixes,
143
+ redirectHosts: new Set(options.cloud.redirectHosts),
144
+ http: options.http
145
+ }
146
+
147
+ const unsupported = (op: string, capability: Capability) => fail(op, Errors.unsupported(capability))
148
+
149
+ const address = (op: string, thread: ChatThread): Effect.Effect<Address.Parts, ChatError> => {
150
+ const parts = Address.parts(thread)
151
+ return Option.isSome(parts) ? Effect.succeed(parts.value) : fail(op, Errors.invalidRequest("invalid_thread"))
152
+ }
153
+
154
+ const checkId = (op: string, id: string): Effect.Effect<void, ChatError> =>
155
+ id.length === 0 || id.length > Address.maxIdLength ? fail(op, Errors.invalidRequest("invalid_id")) : Effect.void
156
+
157
+ /**
158
+ * The activity body for Markdown and elements: the text form without
159
+ * elements, one card with them. Checks capabilities and limits first.
160
+ */
161
+ const body = (
162
+ op: string,
163
+ conversationId: string,
164
+ content: { readonly markdown: string; readonly actions?: ReadonlyArray<Action> | undefined }
165
+ ): Effect.Effect<Record<string, unknown>, ChatError> =>
166
+ Effect.gen(function*() {
167
+ const actions = content.actions ?? []
168
+ if (actions.some((action) => action._tag === "Select")) return yield* unsupported(op, "selects")
169
+ if (actions.length > 0 && (!capabilities.has("buttons") || options.envelope === undefined)) {
170
+ return yield* unsupported(op, "buttons")
171
+ }
172
+ yield* checkMessageLength(descriptor, op, content.markdown, actions)
173
+ if (actions.length === 0) return Render.textActivity(content.markdown)
174
+ if (actions.length > actionsPerMessage) return yield* fail(op, Errors.tooLarge(undefined, "too_many_actions"))
175
+ const tokens = new Map<Action, string>()
176
+ for (const action of actions) {
177
+ if (action._tag !== "Button") continue
178
+ if (options.envelope!.tokenLength(action) > actionDataLength) {
179
+ return yield* fail(op, Errors.tooLarge(undefined, "action_data_too_long"))
180
+ }
181
+ const token = yield* Effect.mapError(
182
+ options.envelope!.signButton(conversationId, {
183
+ id: action.id,
184
+ ...(action.value === undefined ? {} : { value: action.value })
185
+ }),
186
+ (reason) => Errors.chatError(op, reason)
187
+ )
188
+ tokens.set(action, token)
189
+ }
190
+ return Render.cardActivity(
191
+ content.markdown,
192
+ actions,
193
+ (button) => tokens.get(button)!,
194
+ (button) => options.modalButtons.has(button.id)
195
+ )
196
+ })
197
+
198
+ const now = Effect.map(Clock.currentTimeMillis, (millis) => DateTime.makeUnsafe(millis))
199
+
200
+ const activityId = (op: string, answer: Schema.Json | undefined): Effect.Effect<string, ChatError> => {
201
+ const id = string(answer, "id")
202
+ return id === undefined ? fail(op, Errors.invalidResponse(true, "missing_id")) : Effect.succeed(id)
203
+ }
204
+
205
+ const activities = (conversationId: string) => `/v3/conversations/${segment(conversationId)}/activities`
206
+
207
+ const adapter: ChatAdapter = {
208
+ descriptor,
209
+ post: Effect.fnUntraced(function*(thread, content) {
210
+ const op = "post"
211
+ const parts = yield* address(op, thread)
212
+ if (content.files !== undefined && content.files.length > 0) return yield* unsupported(op, "files")
213
+ if (content.replyTo !== undefined) return yield* unsupported(op, "replyTo")
214
+ const activity = yield* body(op, parts.conversationId, content)
215
+ const answer = yield* connector.call("POST", activities(parts.conversationId), activity, { write: true, op })
216
+ const id = yield* activityId(op, answer)
217
+ return { id, thread, timestamp: yield* now } satisfies Posted
218
+ }),
219
+ edit: Effect.fnUntraced(function*(thread, messageId, content) {
220
+ const op = "edit"
221
+ const parts = yield* address(op, thread)
222
+ yield* checkId(op, messageId)
223
+ const activity = yield* body(op, parts.conversationId, content)
224
+ yield* connector.call(
225
+ "PUT",
226
+ `${activities(parts.conversationId)}/${segment(messageId)}`,
227
+ { ...activity, id: messageId },
228
+ { write: true, op }
229
+ )
230
+ }),
231
+ delete: Effect.fnUntraced(function*(thread, messageId) {
232
+ const op = "delete"
233
+ const parts = yield* address(op, thread)
234
+ yield* checkId(op, messageId)
235
+ yield* connector.call("DELETE", `${activities(parts.conversationId)}/${segment(messageId)}`, undefined, {
236
+ write: true,
237
+ op
238
+ })
239
+ }),
240
+ fetchMessage: () => unsupported("fetchMessage", "fetchMessage"),
241
+ history: () => Stream.fail(Errors.chatError("history", Errors.unsupported("history"))),
242
+ download: (_thread: ChatThread, attachment: Attachment, { maxBytes }: { readonly maxBytes: number }) =>
243
+ capabilities.has("download")
244
+ ? Download.download(attachment.id, { ...downloadOptions, maxBytes })
245
+ : Stream.fail(Errors.chatError("download", Errors.unsupported("download"))),
246
+ startThread: Effect.fnUntraced(function*(thread, messageId) {
247
+ const op = "startThread"
248
+ if (!capabilities.has("startThread")) return yield* unsupported(op, "startThread")
249
+ const parts = yield* address(op, thread)
250
+ yield* checkId(op, messageId)
251
+ if (parts.root !== undefined) return parts.root === messageId ? thread : Address.threadOf(parts.base, messageId)
252
+ if (!Address.isChannel(parts.base)) return yield* fail(op, Errors.invalidRequest("not_a_channel"))
253
+ if (!/^\d+$/.test(messageId)) return yield* fail(op, Errors.invalidRequest("invalid_id"))
254
+ return Address.threadOf(parts.base, messageId)
255
+ }),
256
+ getThread: Effect.fnUntraced(function*(thread) {
257
+ const op = "getThread"
258
+ const parts = yield* address(op, thread)
259
+ const raw = yield* connector.call(
260
+ "GET",
261
+ `/v3/conversations/${segment(parts.base)}/pagedmembers`,
262
+ undefined,
263
+ { op, query: { pageSize: "1" } }
264
+ )
265
+ const info: ThreadInfo = {
266
+ thread,
267
+ kind: Address.kind(parts.conversationId),
268
+ ...(parts.root === undefined ? {} : { parent: Address.thread(parts.base) }),
269
+ raw: raw ?? null
270
+ }
271
+ return info
272
+ }),
273
+ opener: () => unsupported("opener", "opener"),
274
+ getUser: Effect.fnUntraced(function*(id, userOptions) {
275
+ const op = "getUser"
276
+ if (userOptions?.in === undefined) return yield* fail(op, Errors.invalidRequest("thread_required"))
277
+ const parts = yield* address(op, userOptions.in)
278
+ yield* checkId(op, id)
279
+ const raw = yield* connector.call(
280
+ "GET",
281
+ `/v3/conversations/${segment(parts.base)}/members/${segment(id)}`,
282
+ undefined,
283
+ { op }
284
+ )
285
+ const connectorId = string(raw, "id")
286
+ const canonical = userId(raw)
287
+ if (!isObject(raw) || connectorId === undefined || canonical === undefined) {
288
+ return yield* fail(op, Errors.invalidResponse(false, "invalid_member"))
289
+ }
290
+ const user: User = {
291
+ id: canonical,
292
+ name: string(raw, "name") ?? string(raw, "givenName") ?? canonical,
293
+ isBot: connectorId.startsWith("28:"),
294
+ isSelf: connectorId === self,
295
+ raw
296
+ }
297
+ return user
298
+ }),
299
+ followUp: Effect.fnUntraced(function*(deferred: Defer, content) {
300
+ const op = "followUp"
301
+ if (!capabilities.has("commands")) return yield* unsupported(op, "commands")
302
+ const raw = deferred.command.raw
303
+ const sent = string(raw, "timestamp")
304
+ const at = sent === undefined ? undefined : Option.getOrUndefined(DateTime.make(sent))
305
+ const current = yield* Clock.currentTimeMillis
306
+ if (at === undefined || current - DateTime.toEpochMillis(at) > Duration.toMillis(followUpAge)) {
307
+ return yield* fail(op, Errors.notFound(interactionExpired))
308
+ }
309
+ yield* answer(op, raw, content, deferred.visibility)
310
+ })
311
+ }
312
+
313
+ const answer: Made["answer"] = Effect.fnUntraced(function*(op, raw, content, visibility) {
314
+ if (!isObject(raw)) return yield* fail(op, Errors.invalidRequest("invalid_command"))
315
+ const serviceUrl = string(raw, "serviceUrl")
316
+ const conversationId = string(object(raw, "conversation"), "id")
317
+ const messageId = string(raw, "id")
318
+ const recipientId = string(object(raw, "from"), "id")
319
+ if (
320
+ serviceUrl === undefined || conversationId === undefined || messageId === undefined ||
321
+ recipientId === undefined
322
+ ) {
323
+ return yield* fail(op, Errors.invalidRequest("invalid_command"))
324
+ }
325
+ for (const id of [conversationId, messageId, recipientId]) yield* checkId(op, id)
326
+ const activity = yield* body(op, conversationId, content)
327
+ if (visibility === "ephemeral") {
328
+ yield* connector.call("POST", activities(conversationId), {
329
+ ...activity,
330
+ // Only the id: `Length.A` reserves it, and an unbounded name would break the size bound.
331
+ recipient: { id: recipientId },
332
+ entities: [{ type: "targetedMessageInfo", messageId }]
333
+ }, { write: true, op, serviceUrl, query: { isTargetedActivity: "true" } })
334
+ } else {
335
+ yield* connector.call("POST", activities(conversationId), activity, { write: true, op, serviceUrl })
336
+ }
337
+ })
338
+
339
+ return { adapter, answer }
340
+ }
341
+
342
+ /** What `layerWebhook` needs from the layer that registered the adapter. @internal */
343
+ export interface Internals {
344
+ readonly capabilities: ReadonlySet<Capability>
345
+ readonly envelope: Envelope.Envelope | undefined
346
+ readonly modalButtons: ReadonlySet<string>
347
+ readonly answer: Made["answer"]
348
+ }
349
+
350
+ /** Keyed by the `TeamsChat` service the layer built. @internal */
351
+ export const internals = new WeakMap<object, Internals>()
@@ -0,0 +1,67 @@
1
+ import type { ThreadKind } from "effect/chat/ChatEvent"
2
+ import * as ChatThread from "effect/chat/ChatThread"
3
+ import * as Option from "effect/Option"
4
+
5
+ /** @internal */
6
+ export const platform = "teams"
7
+
8
+ const replyChain = ";messageid="
9
+
10
+ /**
11
+ * A Teams address is the Bot Framework conversation id as it is. A channel
12
+ * thread is the channel's id with `;messageid={root}` after it.
13
+ *
14
+ * @internal
15
+ */
16
+ export const thread = (conversationId: string): ChatThread.ChatThread => ChatThread.make(platform, conversationId)
17
+
18
+ /** @internal */
19
+ export interface Parts {
20
+ /** The conversation id, as the Connector takes it. */
21
+ readonly conversationId: string
22
+ /** The conversation without a reply chain suffix. */
23
+ readonly base: string
24
+ /** The root message of a channel thread. */
25
+ readonly root?: string | undefined
26
+ }
27
+
28
+ /** @internal */
29
+ export const parts = (address: ChatThread.ChatThread): Option.Option<Parts> => {
30
+ if (address.platform !== platform || address.id.length === 0 || address.id.length > maxIdLength) {
31
+ return Option.none()
32
+ }
33
+ const at = address.id.indexOf(replyChain)
34
+ if (at === -1) return Option.some({ conversationId: address.id, base: address.id })
35
+ const base = address.id.slice(0, at)
36
+ const root = address.id.slice(at + replyChain.length)
37
+ if (base.length === 0 || !/^\d+$/.test(root)) return Option.none()
38
+ return Option.some({ conversationId: address.id, base, root })
39
+ }
40
+
41
+ /** The conversation id without its reply chain suffix. @internal */
42
+ export const baseConversation = (conversationId: string): string => {
43
+ const at = conversationId.indexOf(replyChain)
44
+ return at === -1 ? conversationId : conversationId.slice(0, at)
45
+ }
46
+
47
+ /** @internal */
48
+ export const threadOf = (base: string, root: string): ChatThread.ChatThread => thread(`${base}${replyChain}${root}`)
49
+
50
+ /** A personal chat: a one-to-one conversation with the bot. @internal */
51
+ export const isDirect = (conversationId: string): boolean => conversationId.startsWith("a:")
52
+
53
+ /** A team channel, as opposed to a group or personal chat. @internal */
54
+ export const isChannel = (conversationId: string): boolean =>
55
+ /@thread\.(tacv2|skype)$/.test(baseConversation(conversationId))
56
+
57
+ /** @internal */
58
+ export const kind = (conversationId: string): ThreadKind =>
59
+ conversationId.includes(replyChain) ? "thread" : isDirect(conversationId) ? "direct" : "channel"
60
+
61
+ /**
62
+ * The longest id the adapter puts in a request: a conversation, message,
63
+ * user or tenant id. A longer one fails `InvalidRequest` before the call.
64
+ *
65
+ * @internal
66
+ */
67
+ export const maxIdLength = 256
@@ -0,0 +1,192 @@
1
+ import * as Clock from "effect/Clock"
2
+ import type * as Signature from "effect/crypto/Signature"
3
+ import * as Effect from "effect/Effect"
4
+ import * as Exit from "effect/Exit"
5
+ import * as HttpClient from "effect/http/HttpClient"
6
+ import * as HttpClientRequest from "effect/http/HttpClientRequest"
7
+ import type * as HttpClientResponse from "effect/http/HttpClientResponse"
8
+ import * as Jwks from "effect/jose/Jwks"
9
+ import * as Jwt from "effect/jose/Jwt"
10
+ import * as Predicate from "effect/Predicate"
11
+ import * as Schema from "effect/Schema"
12
+ import * as Scope from "effect/Scope"
13
+ import * as Semaphore from "effect/Semaphore"
14
+ import * as Stream from "effect/Stream"
15
+ import type { Cloud } from "../TeamsChat.ts"
16
+ import { noRedirects, send } from "./connector.ts"
17
+ import { parseUrl } from "./parse.ts"
18
+
19
+ /** The longest `Authorization` header read. Anything longer is refused unread. */
20
+ const maxAuthorizationLength = 16 * 1024
21
+
22
+ /** How long after a failed metadata or key set fetch the next is tried. */
23
+ const retryAfter = 30_000
24
+
25
+ /** The longest OpenID metadata document read. */
26
+ const maxMetadataBytes = 64 * 1024
27
+
28
+ const Claims = Schema.Struct({
29
+ serviceurl: Schema.optionalKey(Schema.String),
30
+ serviceUrl: Schema.optionalKey(Schema.String)
31
+ })
32
+
33
+ /**
34
+ * Keeps a key only when its `endorsements` is an array of strings holding
35
+ * `msteams`. A key without them is dropped: fails closed.
36
+ *
37
+ * @internal
38
+ */
39
+ export const endorsedForTeams = (jwk: { readonly [key: string]: unknown }): boolean => {
40
+ const endorsements = jwk.endorsements
41
+ return Array.isArray(endorsements) && endorsements.every((e) => typeof e === "string") &&
42
+ endorsements.includes("msteams")
43
+ }
44
+
45
+ /** The body, or `undefined` once it passes `maxBytes` or can't be read. Never reads past the limit. */
46
+ const readBounded = (
47
+ response: HttpClientResponse.HttpClientResponse,
48
+ maxBytes: number
49
+ ): Effect.Effect<Uint8Array | undefined> => {
50
+ const declared = Number(response.headers["content-length"])
51
+ if (Number.isFinite(declared) && declared > maxBytes) return Effect.succeed(undefined)
52
+ const body = new Uint8Array(maxBytes)
53
+ return Stream.runFoldEffect(response.stream, () => 0, (length, chunk) =>
54
+ chunk.length > maxBytes - length
55
+ ? Effect.fail("too_large" as const)
56
+ : Effect.sync(() => {
57
+ body.set(chunk, length)
58
+ return length + chunk.length
59
+ })).pipe(
60
+ Effect.map((length) => body.subarray(0, length)),
61
+ Effect.orElseSucceed(() => undefined)
62
+ )
63
+ }
64
+
65
+ /** @internal */
66
+ export type Verdict = "ok" | "forbidden" | "unavailable"
67
+
68
+ /** What the token is checked against, from the activity's body. @internal */
69
+ export interface Activity {
70
+ readonly serviceUrl: unknown
71
+ readonly channelId: unknown
72
+ readonly tenantId: string | undefined
73
+ }
74
+
75
+ /** The tenant of an activity: `conversation.tenantId`, else `channelData.tenant.id`. @internal */
76
+ export const tenantOf = (activity: Record<string, unknown>): string | undefined => {
77
+ const conversation = activity.conversation
78
+ if (Predicate.isObject(conversation) && typeof conversation.tenantId === "string") return conversation.tenantId
79
+ const channelData = activity.channelData
80
+ if (
81
+ Predicate.isObject(channelData) && Predicate.isObject(channelData.tenant) &&
82
+ typeof channelData.tenant.id === "string"
83
+ ) {
84
+ return channelData.tenant.id
85
+ }
86
+ return undefined
87
+ }
88
+
89
+ /**
90
+ * Checks a Bot Framework bearer token: RS256 with a key endorsed for
91
+ * `msteams` from the cloud's key set, the cloud's issuer, the app id as
92
+ * audience, five minutes of skew and a required `exp`. Then the
93
+ * `serviceurl` claim must equal the activity's `serviceUrl`, its
94
+ * `channelId` must be `msteams` and its tenant the configured one.
95
+ *
96
+ * The key set is found lazily from the cloud's OpenID metadata, whose
97
+ * `jwks_uri` must be `https:` on the metadata's own host. Neither fetch
98
+ * follows a redirect: the key set's client has Fetch's redirects off for
99
+ * each request, refreshes included. The metadata is read to at most 64 KiB.
100
+ * Metadata that can't be fetched, read or parsed is `unavailable`. A key set that can't be read is `unavailable`, so
101
+ * the webhook answers 503 and Teams retries; every other failure is
102
+ * `forbidden`.
103
+ *
104
+ * @internal
105
+ */
106
+ export const makeVerifier = Effect.fnUntraced(function*(options: {
107
+ readonly cloud: Cloud
108
+ readonly appId: string
109
+ readonly tenantId: string
110
+ }) {
111
+ const http = yield* HttpClient.HttpClient
112
+ const scope = yield* Effect.scope
113
+ const signature = yield* Effect.context<Signature.Signature>()
114
+ const lock = Semaphore.makeUnsafe(1)
115
+ let keys: Jwks.Jwks["Service"] | undefined
116
+ let failedAt = Number.NEGATIVE_INFINITY
117
+
118
+ const jwksUri = Effect.gen(function*() {
119
+ const metadataUrl = parseUrl(options.cloud.openIdMetadataUrl)
120
+ if (metadataUrl === undefined) return yield* Effect.fail("metadata_url" as const)
121
+ const response = yield* send(http, HttpClientRequest.get(metadataUrl.href), false, "openIdMetadata")
122
+ if (response.status !== 200) return yield* Effect.fail("metadata_status" as const)
123
+ const body = yield* readBounded(response, maxMetadataBytes)
124
+ if (body === undefined || body.length === 0) return yield* Effect.fail("metadata_size" as const)
125
+ let json: unknown
126
+ try {
127
+ json = JSON.parse(new TextDecoder().decode(body))
128
+ } catch {
129
+ return yield* Effect.fail("metadata_json" as const)
130
+ }
131
+ const uri = Predicate.isObject(json) ? json.jwks_uri : undefined
132
+ const parsed = typeof uri === "string" ? parseUrl(uri) : undefined
133
+ if (parsed === undefined) return yield* Effect.fail("metadata_jwks_uri" as const)
134
+ if (parsed.protocol !== "https:" || parsed.port !== "" || parsed.hostname !== metadataUrl.hostname) {
135
+ return yield* Effect.fail("metadata_jwks_host" as const)
136
+ }
137
+ return parsed.href
138
+ }).pipe(Effect.scoped)
139
+
140
+ // The key set, found once. A failure is not retried for `retryAfter`, so
141
+ // unauthenticated requests can't drive a metadata fetch each.
142
+ const keySet: Effect.Effect<Jwks.Jwks["Service"] | undefined> = lock.withPermit(Effect.gen(function*() {
143
+ if (keys !== undefined) return keys
144
+ const now = yield* Clock.currentTimeMillis
145
+ if (now - failedAt < retryAfter) return undefined
146
+ const made = yield* jwksUri.pipe(
147
+ Effect.flatMap((url) => Jwks.makeRemote({ url, filter: endorsedForTeams })),
148
+ Effect.provideService(Scope.Scope, scope),
149
+ Effect.provideService(HttpClient.HttpClient, noRedirects(http)),
150
+ Effect.option
151
+ )
152
+ if (made._tag === "None") {
153
+ failedAt = now
154
+ return undefined
155
+ }
156
+ keys = made.value
157
+ return keys
158
+ }))
159
+
160
+ return (authorization: string | undefined, activity: Activity): Effect.Effect<Verdict> =>
161
+ Effect.gen(function*() {
162
+ if (authorization === undefined || authorization.length > maxAuthorizationLength) return "forbidden"
163
+ const match = /^Bearer ([A-Za-z0-9_.-]+)$/.exec(authorization)
164
+ if (match === null) return "forbidden"
165
+ const resolved = yield* keySet
166
+ if (resolved === undefined) return "unavailable"
167
+ const exit = yield* Jwt.verifyWithKeySet(Claims, match[1], {
168
+ algorithms: ["RS256"],
169
+ issuer: options.cloud.issuer,
170
+ audience: options.appId,
171
+ clockTolerance: "5 minutes",
172
+ requiredClaims: ["exp"]
173
+ }).pipe(
174
+ Effect.provideService(Jwks.Jwks, resolved),
175
+ Effect.provideContext(signature),
176
+ Effect.exit
177
+ )
178
+ if (Exit.isFailure(exit)) {
179
+ const unavailable = exit.cause.reasons.some((reason) =>
180
+ reason._tag === "Fail" && reason.error._tag === "JoseError" &&
181
+ reason.error.reason._tag === "KeySetUnavailable"
182
+ )
183
+ return unavailable ? "unavailable" : "forbidden"
184
+ }
185
+ const claims = exit.value.claims
186
+ const claimed = claims.serviceurl ?? claims.serviceUrl
187
+ if (typeof activity.serviceUrl !== "string" || claimed !== activity.serviceUrl) return "forbidden"
188
+ if (activity.channelId !== "msteams") return "forbidden"
189
+ if (activity.tenantId !== options.tenantId) return "forbidden"
190
+ return "ok"
191
+ })
192
+ })