@effect/chat-teams 0.0.0-stage → 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 +115 -2
  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 +58 -3
  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,88 @@
1
+ import * as ByteSize from "effect/ByteSize";
2
+ import * as Effect from "effect/Effect";
3
+ import * as HttpIncomingMessage from "effect/http/HttpIncomingMessage";
4
+ import * as HttpServerResponse from "effect/http/HttpServerResponse";
5
+ import * as Option from "effect/Option";
6
+ import * as Result from "effect/Result";
7
+ import { tenantOf } from "./auth.js";
8
+ import { isSubmitFallback } from "./interactions.js";
9
+ import { isTargeted, normalize } from "./normalize.js";
10
+ import { isObject, parseJson } from "./parse.js";
11
+ const status = code => HttpServerResponse.empty({
12
+ status: code
13
+ });
14
+ /**
15
+ * What is logged with each 503 of the route.
16
+ *
17
+ * @internal
18
+ */
19
+ export const unavailable = {
20
+ keys: "teams webhook: the signing keys could not be read, answered 503",
21
+ normalize: "teams webhook: the activity could not be normalised, answered 503",
22
+ notAccepted: "teams webhook: the handler refused the event, answered 503",
23
+ deadline: "teams webhook: the request passed its deadline, answered 503"
24
+ };
25
+ const decoder = /*#__PURE__*/new TextDecoder();
26
+ const respond = response => response.body === undefined ? status(response.status) : HttpServerResponse.jsonUnsafe(response.body, {
27
+ status: response.status
28
+ });
29
+ /**
30
+ * One Bot Framework activity.
31
+ *
32
+ * - 413 past the body limit, 400 for a body that is not a JSON object.
33
+ * - 403 when the token, its `serviceurl`, the channel or the tenant does
34
+ * not check out, and 503 when the signing keys can't be read.
35
+ * - A targeted activity is classified first, whatever its type: a message
36
+ * takes the command path, an invoke goes to the interaction handler, and
37
+ * anything else is answered 200 and dropped. None reaches `ChatHandler`
38
+ * or `onUnhandled`.
39
+ * - An invoke, or a card's submit fallback, goes to the interaction
40
+ * handler, whose answer is the response.
41
+ * - Every other activity is normalised and handed to the `ChatHandler`
42
+ * one event at a time: 200 when all succeed, 503 when one fails
43
+ * `NotAccepted`, or when a `message` can't be normalised. Any other
44
+ * activity that gives no event goes to `onUnhandled` and is answered 200.
45
+ * - 503 past `deadline`, the handler interrupted. Each 503 is logged with
46
+ * its own message.
47
+ *
48
+ * @internal
49
+ */
50
+ export const handleRequest = (request, options) => Effect.gen(function* () {
51
+ const read = yield* request.arrayBuffer.pipe(Effect.provideService(HttpIncomingMessage.MaxBodySize, options.maxBodySize), Effect.result);
52
+ if (Result.isFailure(read)) {
53
+ const {
54
+ reason
55
+ } = read.failure;
56
+ return status(reason._tag === "RequestParseError" && reason.reason === "BodyTooLarge" ? 413 : 400);
57
+ }
58
+ // Measured again: the request caches its body, so one read earlier under a larger limit comes back whole.
59
+ if (read.success.byteLength > ByteSize.toNumberUnsafe(options.maxBodySize)) return status(413);
60
+ const activity = parseJson(decoder.decode(read.success));
61
+ if (!isObject(activity)) return status(400);
62
+ const verdict = yield* options.verify(request.headers.authorization, {
63
+ serviceUrl: activity.serviceUrl,
64
+ channelId: activity.channelId,
65
+ tenantId: tenantOf(activity)
66
+ });
67
+ if (verdict === "forbidden") return status(403);
68
+ if (verdict === "unavailable") return yield* Effect.as(Effect.logWarning(unavailable.keys), status(503));
69
+ if (isTargeted(activity)) {
70
+ if (activity.type === "message") return yield* Effect.as(options.command(activity), status(200));
71
+ if (activity.type === "invoke") return respond(yield* options.invoke(activity));
72
+ return status(200);
73
+ }
74
+ if (activity.type === "invoke") return respond(yield* options.invoke(activity));
75
+ if (isSubmitFallback(activity)) return respond(yield* options.invoke(activity));
76
+ const events = normalize(activity, options.context);
77
+ if (events.length === 0 && activity.type === "message") {
78
+ return yield* Effect.as(Effect.logWarning(unavailable.normalize), status(503));
79
+ }
80
+ if (events.length === 0) return yield* Effect.as(options.onUnhandled(activity), status(200));
81
+ return yield* Effect.forEach(events, options.handle, {
82
+ discard: true
83
+ }).pipe(Effect.as(status(200)), Effect.catchTag("NotAccepted", () => Effect.as(Effect.logWarning(unavailable.notAccepted), status(503))));
84
+ }).pipe(Effect.timeoutOption(options.deadline), Effect.flatMap(Option.match({
85
+ onNone: () => Effect.as(Effect.logWarning(unavailable.deadline), status(503)),
86
+ onSome: Effect.succeed
87
+ })));
88
+ //# sourceMappingURL=webhook.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhook.js","names":[],"sources":["../../src/internal/webhook.ts"],"sourcesContent":[null],"mappings":"AAAA,OAAO,KAAK,QAAQ,MAAM,iBAAiB;AAI3C,OAAO,KAAK,MAAM,MAAM,eAAe;AACvC,OAAO,KAAK,mBAAmB,MAAM,iCAAiC;AAEtE,OAAO,KAAK,kBAAkB,MAAM,gCAAgC;AACpE,OAAO,KAAK,MAAM,MAAM,eAAe;AACvC,OAAO,KAAK,MAAM,MAAM,eAAe;AACvC,SAAwB,QAAQ,QAAsB,WAAW;AAEjE,SAAS,gBAAgB,QAAQ,mBAAmB;AACpD,SAAuB,UAAU,EAAE,SAAS,QAAQ,gBAAgB;AACpE,SAAS,QAAQ,EAAmB,SAAS,QAAQ,YAAY;AAEjE,MAAM,MAAM,GAAI,IAAY,IAAK,kBAAkB,CAAC,KAAK,CAAC;EAAE,MAAM,EAAE;AAAI,CAAE,CAAC;AAE3E;;;;;AAKA,OAA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C,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,WAAW,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC;EAChF;EACA,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,OAAO,OAAO,MAAM,CAAC,EAAE,CAAC,OAAO,CAAC,WAAW,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC;EAC5F,OAAO,OAAO,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE;IAAE,OAAO,EAAE;EAAI,CAAE,CAAC,CAAC,IAAI,CAC1E,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,EACtB,MAAM,CAAC,QAAQ,CAAC,aAAa,EAAE,MAAM,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,WAAW,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CACzG;AACH,CAAC,CAAC,CAAC,IAAI,CACL,MAAM,CAAC,aAAa,CAAC,OAAO,CAAC,QAAQ,CAAC,EACtC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC;EAC1B,MAAM,EAAE,MAAM,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,WAAW,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC;EAC7E,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC,CAAC,CACJ","ignoreList":[]}
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@effect/chat-teams",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "4.1.5",
4
+ "type": "module",
5
+ "license": "MIT",
6
+ "description": "The Microsoft Teams adapter for effect/chat",
7
+ "homepage": "https://effect.website",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/Effect-TS/effect.git",
11
+ "directory": "packages/chat/teams"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/Effect-TS/effect/issues"
15
+ },
16
+ "tags": [
17
+ "typescript",
18
+ "chat",
19
+ "teams"
20
+ ],
21
+ "keywords": [
22
+ "typescript",
23
+ "chat",
24
+ "teams"
25
+ ],
26
+ "sideEffects": [],
27
+ "exports": {
28
+ "./package.json": "./package.json",
29
+ ".": "./dist/index.js",
30
+ "./*": "./dist/*.js",
31
+ "./internal/*": null,
32
+ "./index": null,
33
+ "./*/index": null
34
+ },
35
+ "files": [
36
+ "src/**/*.ts",
37
+ "dist/**/*.js",
38
+ "dist/**/*.js.map",
39
+ "dist/**/*.d.ts",
40
+ "dist/**/*.d.ts.map",
41
+ "AGENTS.md",
42
+ "CLAUDE.md",
43
+ "ai-docs/**/*"
44
+ ],
45
+ "publishConfig": {
46
+ "access": "public",
47
+ "provenance": true
48
+ },
49
+ "devDependencies": {
50
+ "effect": "^4.1.5"
51
+ },
52
+ "peerDependencies": {
53
+ "effect": "^4.1.5"
54
+ },
55
+ "scripts": {
56
+ "codegen": "effect-utils codegen",
57
+ "build": "tsc -b tsconfig.json && pnpm babel",
58
+ "babel": "babel dist --plugins annotate-pure-calls --out-dir dist --source-maps",
59
+ "check": "tsc -b tsconfig.json"
60
+ }
6
61
  }
@@ -0,0 +1,470 @@
1
+ /**
2
+ * The Microsoft Teams adapter for `effect/chat`, over the Bot Framework
3
+ * Connector: the `Registry` layer, the messaging endpoint, the pure
4
+ * normaliser and address helpers.
5
+ *
6
+ * **Details**
7
+ *
8
+ * - One layer serves one Entra tenant, with a single-tenant Azure Bot
9
+ * registration. The cloud's endpoints and host allowlists come as a unit
10
+ * from `publicCloud` or a `Cloud` of the consumer's own. They are
11
+ * privileged configuration and never read from an activity.
12
+ * - Nothing here has run against a real tenant yet, the default
13
+ * capabilities included. Live testing is follow-up work, and the README
14
+ * lists its checks. Until a check passes, what it covers is unverified.
15
+ * - Implemented but unverified, and off by default: `buttons`, `modals`,
16
+ * `modalErrors`, `commands`, `ephemeral`, `startThread` and
17
+ * `download`, each behind an `unverified` option. Turning one on
18
+ * advertises a capability no tenant has confirmed.
19
+ * - Not implemented in this version, whatever the options: reading
20
+ * messages (`fetchMessage`, `history`, `opener`, which need Microsoft
21
+ * Graph), `replyTo`, files, native streams and selects. They are
22
+ * `Unsupported`.
23
+ *
24
+ * @stability unstable
25
+ * @since 4.1.5
26
+ */
27
+ import * as ByteSize from "effect/ByteSize"
28
+ import { Registry } from "effect/chat/ChatAdapter"
29
+ import type { ChatError } from "effect/chat/ChatError"
30
+ import type { ChatEvent } from "effect/chat/ChatEvent"
31
+ import { ChatHandler } from "effect/chat/ChatHandler"
32
+ import * as ChatInteraction from "effect/chat/ChatInteraction"
33
+ import type { ParseMention } from "effect/chat/ChatTest"
34
+ import type { ChatThread } from "effect/chat/ChatThread"
35
+ import * as Context from "effect/Context"
36
+ import type * as Digest from "effect/crypto/Digest"
37
+ import type * as Mac from "effect/crypto/Mac"
38
+ import type * as Signature from "effect/crypto/Signature"
39
+ import type * as DateTime from "effect/DateTime"
40
+ import * as Duration from "effect/Duration"
41
+ import * as Effect from "effect/Effect"
42
+ import * as HttpClient from "effect/http/HttpClient"
43
+ import * as HttpRouter from "effect/http/HttpRouter"
44
+ import type { SecretJwk } from "effect/jose/Jwk"
45
+ import * as Layer from "effect/Layer"
46
+ import * as Option from "effect/Option"
47
+ import type * as Redacted from "effect/Redacted"
48
+ import type * as Schema from "effect/Schema"
49
+ import * as Adapter from "./internal/adapter.ts"
50
+ import * as Address from "./internal/address.ts"
51
+ import * as Auth from "./internal/auth.ts"
52
+ import * as Connector from "./internal/connector.ts"
53
+ import * as Envelope from "./internal/envelope.ts"
54
+ import * as Interactions from "./internal/interactions.ts"
55
+ import * as Normalize from "./internal/normalize.ts"
56
+ import * as Webhook from "./internal/webhook.ts"
57
+
58
+ /**
59
+ * The endpoints and host allowlists of one Microsoft cloud.
60
+ *
61
+ * **Details**
62
+ *
63
+ * - `connectorUrl` is where thread ops go. Ops tied to an inbound activity
64
+ * (an invoke's answer, a command's answer, `followUp`) go to that
65
+ * activity's `serviceUrl`, which must be `https:` on the default port
66
+ * with a host exactly in `connectorHosts`, checked before a token is
67
+ * attached. There is no fallback from one to the other.
68
+ * - `openIdMetadataUrl` and `issuer` check inbound tokens. The metadata's
69
+ * `jwks_uri` must be on the metadata's own host.
70
+ * - `fileHostSuffixes` and `redirectHosts` bound downloads.
71
+ *
72
+ * @stability unstable
73
+ * @category models
74
+ * @since 4.1.5
75
+ */
76
+ export interface Cloud {
77
+ /** The Connector base for thread ops, such as `https://smba.trafficmanager.net/teams`. */
78
+ readonly connectorUrl: string
79
+ /** The exact hosts an activity's `serviceUrl` may name. */
80
+ readonly connectorHosts: ReadonlyArray<string>
81
+ /** Bot Framework's OpenID metadata. Its `jwks_uri` must be on the same host. */
82
+ readonly openIdMetadataUrl: string
83
+ /** The `iss` of an inbound token. */
84
+ readonly issuer: string
85
+ /** The Entra authority, without the tenant: `https://login.microsoftonline.com`. */
86
+ readonly loginUrl: string
87
+ /** The scope of a Connector token. */
88
+ readonly connectorScope: string
89
+ /** The host suffixes of a personal chat's pre-authorised file URL, matched at a label boundary. */
90
+ readonly fileHostSuffixes: ReadonlyArray<string>
91
+ /** Extra exact hosts a download may be redirected to. */
92
+ readonly redirectHosts: ReadonlyArray<string>
93
+ }
94
+
95
+ /**
96
+ * The public Azure cloud: Connector `smba.trafficmanager.net`, Bot
97
+ * Framework's OpenID metadata, Entra at `login.microsoftonline.com`, and
98
+ * `sharepoint.com` for files. No extra redirect hosts.
99
+ *
100
+ * @stability unstable
101
+ * @category constants
102
+ * @since 4.1.5
103
+ */
104
+ export const publicCloud: Cloud = Connector.publicCloud
105
+
106
+ /**
107
+ * How the adapter gets its Connector token: the bot's client secret, for
108
+ * client credentials against the tenant, or a provider that gets a token
109
+ * for a scope, for certificates or managed identities.
110
+ *
111
+ * **Details**
112
+ *
113
+ * A token is cached until five minutes before `expiresAt`. A token
114
+ * without `expiresAt` is not cached, and the provider is called for every
115
+ * request.
116
+ *
117
+ * @stability unstable
118
+ * @category models
119
+ * @since 4.1.5
120
+ */
121
+ export type Credentials =
122
+ | Redacted.Redacted<string>
123
+ | ((scope: string) => Effect.Effect<{
124
+ readonly token: Redacted.Redacted<string>
125
+ readonly expiresAt?: DateTime.DateTime | undefined
126
+ }, ChatError>)
127
+
128
+ /**
129
+ * Capabilities whose live checks have not passed. Each is off by default
130
+ * and, when off, is absent from the descriptor and its op fails
131
+ * `Unsupported`.
132
+ *
133
+ * **Details**
134
+ *
135
+ * - `buttons`: buttons and link buttons on a card. Needs
136
+ * `interactionKeys`. Selects are never supported.
137
+ * - `modals`: dialogs opened by the buttons named in `modalButtons`, with
138
+ * field errors. Needs `buttons`.
139
+ * - `commands`: agent slash commands, answered in private or in public,
140
+ * and `followUp` for 24 hours. Also turns on `ephemeral`.
141
+ * - `startThread`: the reply chain under a channel post.
142
+ * - `download`: files on inbound messages.
143
+ *
144
+ * @stability unstable
145
+ * @category models
146
+ * @since 4.1.5
147
+ */
148
+ export interface Unverified {
149
+ readonly buttons?: boolean | undefined
150
+ readonly modals?: boolean | undefined
151
+ readonly commands?: boolean | undefined
152
+ readonly startThread?: boolean | undefined
153
+ readonly download?: boolean | undefined
154
+ }
155
+
156
+ /**
157
+ * The Teams side of the adapter.
158
+ *
159
+ * **Details**
160
+ *
161
+ * - `call` sends one Connector request, with the bot's token, for what the
162
+ * adapter has no op for. `path` starts with `/v3/` and has its segments
163
+ * encoded. A `serviceUrl` routes it to an inbound activity's Connector,
164
+ * after the allowlist check. A write is never retried once sent, and a
165
+ * failure that may have landed is `uncertain`.
166
+ *
167
+ * @stability unstable
168
+ * @category services
169
+ * @since 4.1.5
170
+ */
171
+ export class TeamsChat extends Context.Service<TeamsChat, {
172
+ readonly appId: string
173
+ readonly tenantId: string
174
+ readonly cloud: Cloud
175
+ readonly call: (
176
+ method: "GET" | "POST" | "PUT" | "DELETE",
177
+ path: string,
178
+ body?: unknown,
179
+ options?: {
180
+ readonly write?: boolean | undefined
181
+ readonly serviceUrl?: string | undefined
182
+ readonly query?: Readonly<Record<string, string>> | undefined
183
+ }
184
+ ) => Effect.Effect<Schema.Json | undefined, ChatError>
185
+ }>()("@effect/chat-teams/TeamsChat") {}
186
+
187
+ /**
188
+ * Registers the Teams adapter in the `Registry`, for one tenant.
189
+ *
190
+ * **Details**
191
+ *
192
+ * - `post` and `edit` without elements send the Markdown as `text` with
193
+ * `textFormat: "extendedmarkdown"`, with every `<` and `&` as an entity,
194
+ * so no HTML and no `<at>` mention forms, and every `$` outside code as
195
+ * `\$`, so Teams reads no math. Mentions notify nobody.
196
+ * - With elements, the message is one Adaptive Card and no `text`:
197
+ * `TextBlock`, `CodeBlock` and `Table` elements from the Markdown, then
198
+ * `ActionSet` rows. An `edit` may switch between the two forms.
199
+ * - `limits.messageLength` is a budget, not Microsoft's number. It is the
200
+ * provisional size `Edge` (50,000 UTF-16 units of activity JSON, half of
201
+ * the 100 KB Microsoft documents, until a live check sets it) less a fixed
202
+ * reservation `R` for the card's structure, the auxiliary members and
203
+ * 4,000 units of mention entities: 44,288 today. `measure` prices each
204
+ * unit by what escaping and card structure can make of it.
205
+ * - A button carries a signed token (HS256 JWT) under the card data key
206
+ * `effect`, bound to the app, the tenant and the conversation. It is
207
+ * signed, not encrypted: anyone who sees the card can read the id and
208
+ * value. A token has no replay protection: a click can be sent again
209
+ * while the conversation exists. A dialog token also binds the user and
210
+ * expires after an hour.
211
+ * - The adapter's own caps, as Teams publishes none: 6 elements per
212
+ * message, 10 fields per modal, and two caps counted as the signed token
213
+ * that carries the data, envelope included. `actionDataLength` is 1,000
214
+ * units of button token, about 500 ASCII characters of id plus value with
215
+ * a GUID app and tenant. `modalMetadataLength` is 4,000 units of dialog
216
+ * token, and the whole token counts: the modal's id, metadata, title,
217
+ * labels, options and texts together get about 1,880 bytes of JSON. A
218
+ * modal over it is refused `TooLarge` before anything opens.
219
+ * A message with every element at its cap still fits `messageLength`.
220
+ * - The `HttpClient` must add no credentials of its own and follow no
221
+ * redirects. The adapter decides per request which host gets the bot's
222
+ * token, asks Fetch for `redirect: "manual"` and fails a response from
223
+ * any other URL than the one it sent to. A client other than
224
+ * `FetchHttpClient`, or middleware that rewrites requests, must keep
225
+ * that.
226
+ * - `getUser` needs `in`, the thread whose roster to read: without it
227
+ * it fails `InvalidRequest` with `thread_required`. A user's id is the
228
+ * Entra object id when Teams sends one, and the Connector id (`29:…`,
229
+ * `28:…`) otherwise; `raw` keeps the Connector record.
230
+ * - The layer provides `TeamsChat` beside registering the adapter. It
231
+ * needs `Mac` and `Digest` for the interaction tokens; the adapter
232
+ * never calls `crypto.subtle` itself.
233
+ *
234
+ * @stability unstable
235
+ * @category layers
236
+ * @since 4.1.5
237
+ */
238
+ export const layer = (options: {
239
+ readonly appId: string
240
+ readonly tenantId: string
241
+ readonly credentials: Credentials
242
+ readonly cloud?: Cloud | undefined
243
+ /**
244
+ * The keys that sign button and dialog tokens. The first signs, and any
245
+ * verifies by its `kid`, so a rotation adds a key in front and drops the
246
+ * old one later. Each needs a distinct `kid` of 1 to 16 characters from
247
+ * `[A-Za-z0-9_-]` and at least 32 bytes. Without keys, there are no
248
+ * buttons or modals.
249
+ */
250
+ readonly interactionKeys?: readonly [Redacted.Redacted<SecretJwk>, ...Array<Redacted.Redacted<SecretJwk>>] | undefined
251
+ /** The ids of the buttons that open a dialog. Only these may answer `OpenModal`. */
252
+ readonly modalButtons?: ReadonlyArray<string> | undefined
253
+ readonly unverified?: Unverified | undefined
254
+ }): Layer.Layer<TeamsChat, never, HttpClient.HttpClient | Registry | Mac.Mac | Digest.Digest> =>
255
+ Layer.effect(
256
+ TeamsChat,
257
+ Effect.gen(function*() {
258
+ const http = yield* HttpClient.HttpClient
259
+ const registry = yield* Registry
260
+ const cloud = options.cloud ?? publicCloud
261
+ const tokens = Connector.makeTokens({
262
+ http,
263
+ cloud,
264
+ appId: options.appId,
265
+ tenantId: options.tenantId,
266
+ credentials: options.credentials
267
+ })
268
+ const connector = Connector.make({ http, cloud, token: tokens })
269
+ const envelope = options.interactionKeys === undefined
270
+ ? undefined
271
+ : yield* Envelope.make({ appId: options.appId, tenantId: options.tenantId, keys: options.interactionKeys })
272
+ const modalButtons = new Set(options.modalButtons ?? [])
273
+ const { adapter, answer } = Adapter.make({
274
+ connector,
275
+ http,
276
+ cloud,
277
+ appId: options.appId,
278
+ tenantId: options.tenantId,
279
+ envelope,
280
+ unverified: options.unverified ?? {},
281
+ token: tokens(cloud.connectorScope),
282
+ modalButtons
283
+ })
284
+ yield* registry.register(adapter)
285
+ const service = TeamsChat.of({
286
+ appId: options.appId,
287
+ tenantId: options.tenantId,
288
+ cloud,
289
+ call: connector.call
290
+ })
291
+ Adapter.internals.set(service, { capabilities: adapter.descriptor.capabilities, envelope, modalButtons, answer })
292
+ return service
293
+ })
294
+ )
295
+
296
+ /**
297
+ * `POST {path}`: the bot's messaging endpoint.
298
+ *
299
+ * **Details**
300
+ *
301
+ * - Checks the bearer token: RS256 with a key from Bot Framework's key set
302
+ * that is endorsed for `msteams`, the cloud's issuer, the app id as
303
+ * audience, five minutes of skew and an `exp`. Then the token's
304
+ * `serviceurl` must equal the activity's `serviceUrl`, `channelId`
305
+ * must be `msteams` and the tenant the layer's. Any failure is 403. A
306
+ * key set that can't be read is 503.
307
+ * - A targeted activity, one only the bot can see, is classified before
308
+ * anything else, whatever its type. A targeted message takes the command
309
+ * path: its first word names the command and the rest is its `text`. One
310
+ * that names no registered command is acked and nothing is sent. A
311
+ * targeted invoke goes to the interaction handler. Any other targeted
312
+ * activity is answered 200 and dropped. None reaches the `ChatHandler`,
313
+ * `onUnhandled`, or anything public.
314
+ * - Invokes go to `ChatInteraction.Handler` within `interactionDeadline`
315
+ * (4 seconds by default). Without a `Handler` in context, every invoke
316
+ * and every targeted message gets an empty 200.
317
+ * - Other activities go through `normalize` to the `ChatHandler`: 200
318
+ * when it succeeds, 503 when it fails `NotAccepted` or a message can't
319
+ * be normalised. An activity with no event goes to `onUnhandled` and is
320
+ * answered 200. Past `deadline` (10 seconds by default) the handler is
321
+ * interrupted and the answer is 503. Each 503 is logged with its reason.
322
+ * - Answers 413 past `maxBodyBytes` (1 MiB by default), and 400 for a body
323
+ * that can't be read or is not a JSON object, both before the token is
324
+ * checked. `maxBodyBytes` must be a non-negative safe integer; another
325
+ * value is a defect when the layer is built.
326
+ *
327
+ * The metadata and the key set are fetched with redirects off, and the
328
+ * metadata is read up to 64 KiB. A metadata document or `jwks_uri` that
329
+ * can't be read is 503. The `HttpClient` has the same requirements as for
330
+ * `layer`.
331
+ *
332
+ * Token checks need the `Signature` service. Importing the key set's
333
+ * public keys goes through `Jwk.importPublic`, which needs a `WebCrypto`
334
+ * reference whatever crypto backend provides `Signature`.
335
+ *
336
+ * @stability unstable
337
+ * @category layers
338
+ * @since 4.1.5
339
+ */
340
+ export const layerWebhook = (options: {
341
+ readonly path: `/${string}`
342
+ readonly deadline?: Duration.Input | undefined
343
+ readonly interactionDeadline?: Duration.Input | undefined
344
+ readonly maxBodyBytes?: number | undefined
345
+ readonly onUnhandled?: ((activity: Schema.Json) => Effect.Effect<void>) | undefined
346
+ }): Layer.Layer<
347
+ never,
348
+ never,
349
+ HttpRouter.HttpRouter | TeamsChat | ChatHandler | HttpClient.HttpClient | Signature.Signature
350
+ > =>
351
+ HttpRouter.use(Effect.fnUntraced(function*(router) {
352
+ const teams = yield* TeamsChat
353
+ const internals = Adapter.internals.get(teams)
354
+ if (internals === undefined) return yield* Effect.die(new Error("TeamsChat.layerWebhook needs TeamsChat.layer"))
355
+ const handler = yield* ChatHandler
356
+ const interactionHandler = yield* Effect.serviceOption(ChatInteraction.Handler)
357
+ const interactionRegistry = yield* Effect.serviceOption(ChatInteraction.Registry)
358
+ const verify = yield* Auth.makeVerifier({ cloud: teams.cloud, appId: teams.appId, tenantId: teams.tenantId })
359
+ const interactionOptions: Interactions.Options = {
360
+ capabilities: internals.capabilities,
361
+ envelope: internals.envelope,
362
+ modalButtons: internals.modalButtons,
363
+ answer: internals.answer,
364
+ deadline: options.interactionDeadline === undefined
365
+ ? Interactions.defaultDeadline
366
+ : Duration.fromInputUnsafe(options.interactionDeadline)
367
+ }
368
+ const webhookOptions: Webhook.Options = {
369
+ verify,
370
+ context: {
371
+ appId: teams.appId,
372
+ connectorHosts: new Set(teams.cloud.connectorHosts),
373
+ fileHostSuffixes: teams.cloud.fileHostSuffixes
374
+ },
375
+ handle: handler.handle,
376
+ onUnhandled: options.onUnhandled ?? (() => Effect.void),
377
+ invoke: (activity) =>
378
+ Option.isNone(interactionHandler)
379
+ ? Effect.succeed({ status: 200 })
380
+ : Effect.provideService(
381
+ Interactions.invoke(activity, interactionOptions),
382
+ ChatInteraction.Handler,
383
+ interactionHandler.value
384
+ ),
385
+ command: (activity) =>
386
+ Option.isNone(interactionHandler) || Option.isNone(interactionRegistry)
387
+ ? Effect.void
388
+ : Effect.provideService(
389
+ Interactions.command(activity, {
390
+ ...interactionOptions,
391
+ isRegistered: (id) =>
392
+ Effect.map(interactionRegistry.value.get(id), (entry) => entry?.definition.kind === "command")
393
+ }),
394
+ ChatInteraction.Handler,
395
+ interactionHandler.value
396
+ ),
397
+ deadline: options.deadline ?? Duration.seconds(10),
398
+ maxBodySize: ByteSize.bytes(options.maxBodyBytes ?? 1024 * 1024)
399
+ }
400
+ yield* router.add("POST", options.path, (request) => Webhook.handleRequest(request, webhookOptions))
401
+ }))
402
+
403
+ /**
404
+ * The address of a Teams conversation: the Bot Framework conversation id as
405
+ * it is. A channel thread is the channel's id followed by
406
+ * `;messageid={root}`.
407
+ *
408
+ * @stability unstable
409
+ * @category constructors
410
+ * @since 4.1.5
411
+ */
412
+ export const thread: (conversationId: string) => ChatThread = Address.thread
413
+
414
+ /**
415
+ * The parts of a Teams address, or `None` for another platform's or a
416
+ * malformed one.
417
+ *
418
+ * @stability unstable
419
+ * @category destructors
420
+ * @since 4.1.5
421
+ */
422
+ export const parts: (thread: ChatThread) => Option.Option<{
423
+ readonly conversationId: string
424
+ readonly base: string
425
+ readonly root?: string | undefined
426
+ }> = Address.parts
427
+
428
+ /**
429
+ * The normaliser, for a consumer's own transport. It checks no token: that
430
+ * is the transport's job.
431
+ *
432
+ * **Details**
433
+ *
434
+ * - Pure: takes an activity, gives zero or more events.
435
+ * - A `message` gives a `MessageCreated`. Its `text` is Teams' `text` as
436
+ * delivered, with `<at>…</at>` for each mention, where `mentions` point.
437
+ * A channel post is addressed to the channel, a reply to the post's
438
+ * thread.
439
+ * - `messageReaction` gives a `ReactionAdded` or `ReactionRemoved` per
440
+ * reaction. The six types Teams documents are Unicode emoji; any other is
441
+ * `custom:{type}`.
442
+ * - A targeted activity, a card submit and anything else give none.
443
+ * - `raw` is the activity.
444
+ *
445
+ * @stability unstable
446
+ * @category normalization
447
+ * @since 4.1.5
448
+ */
449
+ export const normalize = (
450
+ activity: unknown,
451
+ context: { readonly appId: string; readonly cloud?: Cloud | undefined }
452
+ ): ReadonlyArray<ChatEvent> => {
453
+ const cloud = context.cloud ?? publicCloud
454
+ return Normalize.normalize(activity, {
455
+ appId: context.appId,
456
+ connectorHosts: new Set(cloud.connectorHosts),
457
+ fileHostSuffixes: cloud.fileHostSuffixes
458
+ })
459
+ }
460
+
461
+ /**
462
+ * Reads one Teams mention, `<at>…</at>`, for `ChatTest`. The tag holds a
463
+ * display name and no id, so this is always `None`; a message's
464
+ * `mentions` come from its entities.
465
+ *
466
+ * @stability unstable
467
+ * @category testing
468
+ * @since 4.1.5
469
+ */
470
+ export const parseMention: ParseMention = () => Option.none()
package/src/index.ts ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @stability unstable
3
+ * @since 4.1.5
4
+ */
5
+
6
+ // @barrel: Auto-generated exports. Do not edit manually.
7
+
8
+ /**
9
+ * @stability unstable
10
+ * @since 4.1.5
11
+ */
12
+ export * as TeamsChat from "./TeamsChat.ts"