@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,294 @@
1
+ import type { Capability, ChatError } from "effect/chat/ChatError"
2
+ import * as ChatInteraction from "effect/chat/ChatInteraction"
3
+ import type * as ChatUi from "effect/chat/ChatUi"
4
+ import * as Duration from "effect/Duration"
5
+ import * as Effect from "effect/Effect"
6
+ import * as Option from "effect/Option"
7
+ import type * as Schema from "effect/Schema"
8
+ import * as Str from "effect/String"
9
+ import type { Made } from "./adapter.ts"
10
+ import { modalFields, modalMetadataLength } from "./adapter.ts"
11
+ import * as Envelope from "./envelope.ts"
12
+ import * as Errors from "./errors.ts"
13
+ import { locate, threadOf, userId } from "./normalize.ts"
14
+ import { isObject, type JsonObject, object, string } from "./parse.ts"
15
+ import * as Render from "./render.ts"
16
+
17
+ /** The default share of Teams' invoke timeout the handler gets. @internal */
18
+ export const defaultDeadline = Duration.seconds(4)
19
+
20
+ /** An answer to an invoke: the HTTP status and the JSON body, if any. @internal */
21
+ export interface InvokeResponse {
22
+ readonly status: number
23
+ readonly body?: Schema.Json | undefined
24
+ }
25
+
26
+ const ok: InvokeResponse = { status: 200 }
27
+
28
+ /** What an invoke that fails a check gets. It names no reason. */
29
+ const safeFailure = (name: string): InvokeResponse =>
30
+ name === "adaptiveCard/action"
31
+ ? {
32
+ status: 200,
33
+ body: {
34
+ statusCode: 400,
35
+ type: "application/vnd.microsoft.error",
36
+ value: { code: "BadRequest", message: "This action could not be completed." }
37
+ }
38
+ }
39
+ : { status: 200, body: { task: { type: "message", value: "This action could not be completed." } } }
40
+
41
+ const executeAck: InvokeResponse = {
42
+ status: 200,
43
+ body: { statusCode: 200, type: "application/vnd.microsoft.activity.message", value: "" }
44
+ }
45
+
46
+ /** @internal */
47
+ export interface Options {
48
+ readonly capabilities: ReadonlySet<Capability>
49
+ readonly envelope: Envelope.Envelope | undefined
50
+ /** The ids of the buttons that open a dialog. */
51
+ readonly modalButtons: ReadonlySet<string>
52
+ readonly answer: Made["answer"]
53
+ readonly deadline: Duration.Duration
54
+ }
55
+
56
+ const refused = (event: ChatInteraction.ButtonClicked | ChatInteraction.CommandInvoked, error: ChatError) =>
57
+ Effect.flatMap(ChatInteraction.Handler, (handler) => handler.refused(event, error))
58
+
59
+ /** The adaptive card of a dialog, built only from the signed definition. */
60
+ const dialogCard = (
61
+ modal: ChatUi.Modal,
62
+ token: string,
63
+ submitted?: {
64
+ readonly values: Readonly<Record<string, string>>
65
+ readonly errors: Readonly<Record<string, string>>
66
+ }
67
+ ) => {
68
+ // A dialog sent again with errors keeps what the user entered, not the
69
+ // definition's `initial`. Lookups are own properties only, so a field id
70
+ // such as `constructor` reads nothing inherited.
71
+ const own = (record: Readonly<Record<string, string>>, key: string): string | undefined =>
72
+ Object.hasOwn(record, key) && typeof record[key] === "string" ? record[key] : undefined
73
+ const valueOf = (element: ChatUi.TextInput | ChatUi.SelectInput) =>
74
+ submitted === undefined ? element.initial : own(submitted.values, element.id)
75
+ const body: Array<unknown> = []
76
+ for (const element of modal.elements) {
77
+ if (element._tag === "Text") {
78
+ body.push(Render.textBlock(Render.escapeText(Str.toWellFormed(element.text))))
79
+ continue
80
+ }
81
+ if (element._tag === "TextInput") {
82
+ body.push({
83
+ type: "Input.Text",
84
+ id: element.id,
85
+ label: element.label,
86
+ isMultiline: element.multiline === true,
87
+ isRequired: element.optional !== true,
88
+ maxLength: element.maxLength ?? Envelope.defaultMaxLength,
89
+ ...(element.placeholder === undefined ? {} : { placeholder: element.placeholder }),
90
+ ...(valueOf(element) === undefined ? {} : { value: valueOf(element) })
91
+ })
92
+ } else {
93
+ body.push({
94
+ type: "Input.ChoiceSet",
95
+ id: element.id,
96
+ label: element.label,
97
+ style: "compact",
98
+ isRequired: element.optional !== true,
99
+ choices: element.options.map((option) => ({ title: option.label, value: option.value })),
100
+ ...(element.placeholder === undefined ? {} : { placeholder: element.placeholder }),
101
+ ...(valueOf(element) === undefined ? {} : { value: valueOf(element) })
102
+ })
103
+ }
104
+ const error = submitted === undefined ? undefined : own(submitted.errors, element.id)
105
+ if (error !== undefined) {
106
+ body.push({ ...Render.textBlock(Render.escapeText(Str.toWellFormed(error))), color: "attention" })
107
+ }
108
+ }
109
+ return {
110
+ task: {
111
+ type: "continue",
112
+ value: {
113
+ title: modal.title,
114
+ card: {
115
+ contentType: Render.cardContentType,
116
+ content: {
117
+ ...Render.card(body),
118
+ actions: [{
119
+ type: "Action.Submit",
120
+ title: modal.submitLabel ?? "Submit",
121
+ data: { [Envelope.reservedKey]: token }
122
+ }]
123
+ }
124
+ }
125
+ }
126
+ }
127
+ }
128
+ }
129
+
130
+ const modalRefusal = (modal: ChatUi.Modal) =>
131
+ modal.elements.length > modalFields
132
+ ? Errors.tooLarge(undefined, "too_many_modal_fields")
133
+ : Envelope.checkModal(modal)
134
+
135
+ /**
136
+ * One verified invoke, or a card's `Action.Submit` fallback, which comes as
137
+ * a `message` with a `value`.
138
+ *
139
+ * - `adaptiveCard/action` and the fallback are clicks. A click can't open
140
+ * a dialog there: an `OpenModal` goes to `Handler.refused` as
141
+ * `Unsupported`.
142
+ * - `task/fetch` is a click on a button named in `modalButtons`, whose
143
+ * `OpenModal` opens the dialog, signed for the clicking user.
144
+ * - `task/submit` is a dialog submit, checked against its signed
145
+ * definition.
146
+ * - A token that does not verify, or values that do not match the
147
+ * definition, get the safe failure and dispatch nothing.
148
+ *
149
+ * @internal
150
+ */
151
+ export const invoke = (
152
+ activity: JsonObject,
153
+ options: Options
154
+ ): Effect.Effect<InvokeResponse, never, ChatInteraction.Handler> =>
155
+ Effect.gen(function*() {
156
+ const name = activity.type === "message" ? "message" : string(activity, "name") ?? ""
157
+ const failure = safeFailure(name)
158
+ const envelope = options.envelope
159
+ if (envelope === undefined || !options.capabilities.has("buttons")) return failure
160
+ const conversationId = string(object(activity, "conversation"), "id")
161
+ const user = userId(object(activity, "from"))
162
+ if (conversationId === undefined || user === undefined) return failure
163
+ const value = object(activity, "value")
164
+ const data = name === "adaptiveCard/action"
165
+ ? object(object(value, "action"), "data")
166
+ : name === "message"
167
+ ? value
168
+ : object(value, "data")
169
+ const token = data?.[Envelope.reservedKey]
170
+
171
+ if (name === "task/submit") {
172
+ if (!options.capabilities.has("modals")) return failure
173
+ const dialog = yield* envelope.verifyDialog(token, { conversationId, userId: user })
174
+ if (Option.isNone(dialog)) return failure
175
+ const values = Envelope.validateSubmission(dialog.value.modal, data)
176
+ // The thread of the click that opened it, from the signed conversation
177
+ // id and message, never from the submit.
178
+ const origin = locate(dialog.value.conversationId, dialog.value.messageId)?.thread
179
+ if (Option.isNone(values) || origin === undefined) return failure
180
+ const modal = dialog.value.modal
181
+ const event = ChatInteraction.ModalSubmitted.make({
182
+ id: modal.id,
183
+ ...(modal.metadata === undefined ? {} : { metadata: modal.metadata }),
184
+ values: values.value,
185
+ thread: origin,
186
+ ...(dialog.value.messageId === undefined ? {} : { messageId: dialog.value.messageId }),
187
+ userId: user,
188
+ raw: activity
189
+ })
190
+ const reply = yield* ChatInteraction.handle(event, options.deadline)
191
+ if (reply._tag === "Late") return failure
192
+ if (reply._tag === "Errors") {
193
+ return {
194
+ status: 200,
195
+ body: dialogCard(modal, token as string, { values: values.value, errors: reply.errors }) as Schema.Json
196
+ }
197
+ }
198
+ return ok
199
+ }
200
+
201
+ if (name !== "adaptiveCard/action" && name !== "message" && name !== "task/fetch") return failure
202
+ const button = yield* envelope.verifyButton(token, { conversationId })
203
+ const messageId = string(activity, "replyToId")
204
+ // A card posted as a channel post has the channel as its address, as `normalize` gives it.
205
+ const thread = locate(conversationId, messageId)?.thread
206
+ if (Option.isNone(button) || thread === undefined || messageId === undefined) return failure
207
+ const opensDialog = name === "task/fetch"
208
+ if (opensDialog !== options.modalButtons.has(button.value.id)) return failure
209
+ const event = ChatInteraction.ButtonClicked.make({
210
+ id: button.value.id,
211
+ ...(button.value.value === undefined ? {} : { value: button.value.value }),
212
+ thread,
213
+ messageId,
214
+ userId: user,
215
+ raw: activity
216
+ })
217
+ const reply = yield* ChatInteraction.handle(event, options.deadline)
218
+ const acked = name === "adaptiveCard/action" ? executeAck : name === "message" ? ok : failure
219
+ if (reply._tag === "Late" || reply._tag === "Ack") return acked
220
+ if (!opensDialog || !options.capabilities.has("modals")) {
221
+ yield* refused(event, Errors.chatError("openModal", Errors.unsupported("modals")))
222
+ return acked
223
+ }
224
+ const refusal = modalRefusal(reply.modal)
225
+ if (refusal !== undefined) {
226
+ yield* refused(event, Errors.chatError("openModal", refusal))
227
+ return failure
228
+ }
229
+ const signed = yield* Effect.result(
230
+ envelope.signDialog({ conversationId, userId: user, messageId, modal: reply.modal })
231
+ )
232
+ // `modalMetadataLength` holds the whole signed token: the definition,
233
+ // the metadata and every claim. Signing is local, so the check is exact
234
+ // and nothing has opened yet.
235
+ const tooLong = signed._tag === "Success" && signed.success.length > modalMetadataLength
236
+ if (signed._tag === "Failure" || tooLong) {
237
+ const reason = signed._tag === "Failure" ? signed.failure : Errors.tooLarge(undefined, "modal_too_large")
238
+ yield* refused(event, Errors.chatError("openModal", reason))
239
+ return failure
240
+ }
241
+ return { status: 200, body: dialogCard(reply.modal, signed.success) as Schema.Json }
242
+ })
243
+
244
+ /** Leading `<at>…</at>` tokens, spaces and one slash, before a command's name. */
245
+ const commandPrefix = /^(?:\s|<at>[^<]*<\/at>)*\/?/
246
+
247
+ /**
248
+ * A verified targeted message. Its first word names the command, and the
249
+ * rest is the command's `text`. A message whose first word names no
250
+ * registered command is acked and nothing is sent. Nothing here ever
251
+ * reaches `ChatHandler` or posts in public unless the handler asks.
252
+ *
253
+ * @internal
254
+ */
255
+ export const command = (
256
+ activity: JsonObject,
257
+ options: Options & { readonly isRegistered: (id: string) => Effect.Effect<boolean> }
258
+ ): Effect.Effect<void, never, ChatInteraction.Handler> =>
259
+ Effect.gen(function*() {
260
+ if (!options.capabilities.has("commands")) return
261
+ const text = typeof activity.text === "string" ? activity.text : ""
262
+ const rest = text.replace(commandPrefix, "")
263
+ const match = /^(\S+)\s*([\s\S]*)$/.exec(rest)
264
+ const user = userId(object(activity, "from"))
265
+ const at = threadOf(activity)
266
+ if (match === null || user === undefined || at === undefined) return
267
+ const id = match[1]
268
+ if (!(yield* options.isRegistered(id))) return
269
+ const event = ChatInteraction.CommandInvoked.make({
270
+ id,
271
+ text: match[2],
272
+ thread: at.thread,
273
+ userId: user,
274
+ raw: activity
275
+ })
276
+ const reply = yield* ChatInteraction.handle(event, options.deadline)
277
+ switch (reply._tag) {
278
+ case "Late":
279
+ case "Ack":
280
+ case "Defer":
281
+ return
282
+ case "OpenModal":
283
+ return yield* refused(event, Errors.chatError("openModal", Errors.unsupported("modals")))
284
+ case "Respond":
285
+ return yield* options.answer("respond", activity, {
286
+ markdown: reply.markdown,
287
+ ...(reply.actions === undefined ? {} : { actions: reply.actions })
288
+ }, reply.visibility).pipe(Effect.catch((error) => refused(event, error)))
289
+ }
290
+ })
291
+
292
+ /** Whether a `message` is a card's `Action.Submit` fallback. @internal */
293
+ export const isSubmitFallback = (activity: JsonObject): boolean =>
294
+ activity.type === "message" && isObject(activity.value) && Envelope.reservedKey in activity.value
@@ -0,0 +1,170 @@
1
+ /**
2
+ * What a message costs against the Connector's limit, counted in UTF-16
3
+ * units of `JSON.stringify(activity)`, the serialised activity body.
4
+ *
5
+ * Every fixed size here comes from serialising the templates in
6
+ * `render.ts`, so the numbers follow the renderer.
7
+ */
8
+ import type { Action } from "effect/chat/ChatUi"
9
+ import { maxIdLength } from "./address.ts"
10
+ import * as Render from "./render.ts"
11
+
12
+ const size = (value: unknown): number => JSON.stringify(value).length
13
+
14
+ /** An element in an array, with the comma before or after it. */
15
+ const element = (value: unknown): number => size(value) + 1
16
+
17
+ /**
18
+ * The size of a serialised activity body the Connector takes, in UTF-16
19
+ * units.
20
+ *
21
+ * Provisional: Microsoft documents no exact number, and this is not verified
22
+ * against the Connector yet.
23
+ *
24
+ * @internal
25
+ */
26
+ export const Edge = 50_000
27
+
28
+ /** The text form with empty `text`. @internal */
29
+ export const S = size(Render.textActivity(""))
30
+
31
+ /** The card form with an empty card body. @internal */
32
+ export const T = size(Render.cardActivityOf([]))
33
+
34
+ /** One table cell and its column definition. @internal */
35
+ export const K = element(Render.tableCell("")) + element(Render.column)
36
+
37
+ /**
38
+ * The largest element group a source line can add: a `TextBlock`, a
39
+ * `CodeBlock` (with `PlainText` as its language), or a `Table` with one
40
+ * row of one cell, which is also more than a new row of one cell.
41
+ *
42
+ * @internal
43
+ */
44
+ export const E = Math.max(
45
+ element(Render.textBlock("")),
46
+ element(Render.codeBlock("", "PlainText")),
47
+ element(Render.table([[""]]))
48
+ )
49
+
50
+ const id = "x".repeat(maxIdLength)
51
+
52
+ /**
53
+ * The members the adapter may add to an activity besides what the renderer
54
+ * gives, each id at `maxIdLength`: `replyToId`, `recipient`, and
55
+ * `entities` holding a `streaminfo` entity, the AI-generated label and a
56
+ * `targetedMessageInfo` entity. Ids are sent without JSON escapes.
57
+ *
58
+ * @internal
59
+ */
60
+ export const A = size({
61
+ replyToId: id,
62
+ recipient: { id },
63
+ entities: [
64
+ { type: "streaminfo", streamId: id, streamType: "informative", streamSequence: Number.MAX_SAFE_INTEGER },
65
+ {
66
+ type: "https://schema.org/Message",
67
+ "@type": "Message",
68
+ "@context": "https://schema.org",
69
+ "@id": "",
70
+ additionalType: ["AIGeneratedContent"]
71
+ },
72
+ { type: "targetedMessageInfo", messageId: id }
73
+ ]
74
+ }) - 1
75
+
76
+ /**
77
+ * Units set aside for mention entities.
78
+ *
79
+ * Provisional: the adapter does not send mentions in v1.
80
+ *
81
+ * @internal
82
+ */
83
+ export const M_units = 4_000
84
+
85
+ /** Units set aside for file attachments: none, files are not sent in v1. @internal */
86
+ export const F_units = 0
87
+
88
+ /**
89
+ * The fixed part of a message: the larger of the two forms with the first
90
+ * element of the card. The first source line has no line break before it to
91
+ * pay for its element, so `E` is reserved once for it.
92
+ *
93
+ * @internal
94
+ */
95
+ export const skeleton = Math.max(S, T + E)
96
+
97
+ /** @internal */
98
+ export const R = skeleton + A + M_units + F_units
99
+
100
+ /** @internal */
101
+ export const messageLength = Edge - R
102
+
103
+ /**
104
+ * What one UTF-16 unit of the source can cost once rendered and serialised.
105
+ * A line break pays for the element its line may start, and a pipe for the
106
+ * table cell and column it may add.
107
+ */
108
+ const unit = (code: number): number => {
109
+ switch (code) {
110
+ case 0x0a:
111
+ case 0x0d:
112
+ return 2 + E
113
+ case 0x7c:
114
+ return 1 + K
115
+ case 0x22:
116
+ case 0x5c:
117
+ return 2
118
+ case 0x09: // A partially stripped tab in fenced code can leave three spaces.
119
+ case 0x24:
120
+ return 3
121
+ case 0x3c:
122
+ return 4
123
+ case 0x26:
124
+ return 5
125
+ default:
126
+ return code < 0x20 ? 6 : 1
127
+ }
128
+ }
129
+
130
+ /** @internal */
131
+ export const weight = (text: string): number => {
132
+ let total = 0
133
+ for (let i = 0; i < text.length; i++) total += unit(text.charCodeAt(i))
134
+ return total
135
+ }
136
+
137
+ const row = element(Render.actionSet([]))
138
+
139
+ /** @internal */
140
+ export type TokenLength = (button: { readonly id: string; readonly value?: string | undefined }) => number
141
+
142
+ const actionCost = (action: Action, tokenLength: TokenLength): number => {
143
+ switch (action._tag) {
144
+ case "Button":
145
+ return element(Render.buttonAction({ ...action, label: "" }, "")) + 2 * weight(action.label) +
146
+ 2 * tokenLength(action) + row
147
+ case "LinkButton":
148
+ return element(Render.linkAction({ ...action, label: "", url: "" })) + weight(action.label) +
149
+ weight(action.url) + row
150
+ case "Select":
151
+ // The adapter refuses a select before it renders anything.
152
+ return 0
153
+ }
154
+ }
155
+
156
+ /**
157
+ * The descriptor's `measure`: the weight of each unit of the Markdown plus
158
+ * the cost of each action, where a button's cost holds its token twice (the
159
+ * action and its fallback) at `tokenLength`, and each action pays for a
160
+ * whole `ActionSet` row. With `R` added it is never less than the size of
161
+ * either form of the activity.
162
+ *
163
+ * @internal
164
+ */
165
+ export const makeMeasure =
166
+ (tokenLength: TokenLength) => (markdown: string, actions?: ReadonlyArray<Action>): number => {
167
+ let total = weight(markdown)
168
+ for (const action of actions ?? []) total += actionCost(action, tokenLength)
169
+ return total
170
+ }
@@ -0,0 +1,232 @@
1
+ import type * as ChatEvent from "effect/chat/ChatEvent"
2
+ import type * as ChatMessage from "effect/chat/ChatMessage"
3
+ import type * as ChatThread from "effect/chat/ChatThread"
4
+ import * as DateTime from "effect/DateTime"
5
+ import * as Option from "effect/Option"
6
+ import * as Address from "./address.ts"
7
+ import * as Download from "./download.ts"
8
+ import { isObject, type JsonObject, object, string } from "./parse.ts"
9
+
10
+ /** @internal */
11
+ export interface Context {
12
+ readonly appId: string
13
+ readonly connectorHosts: ReadonlySet<string>
14
+ readonly fileHostSuffixes: ReadonlyArray<string>
15
+ }
16
+
17
+ /** The bot's own Connector id. @internal */
18
+ export const botId = (appId: string): string => `28:${appId}`
19
+
20
+ /**
21
+ * The public id of a user: the Entra object id for a person, the Connector
22
+ * id (`29:…`, `28:…`) for a bot or anyone without one.
23
+ *
24
+ * @internal
25
+ */
26
+ export const userId = (account: unknown): string | undefined => string(account, "aadObjectId") ?? string(account, "id")
27
+
28
+ /**
29
+ * Whether the activity was sent to the bot alone, as a targeted message.
30
+ * Read from `recipient.isTargeted`.
31
+ *
32
+ * @internal
33
+ */
34
+ export const isTargeted = (activity: JsonObject): boolean => object(activity, "recipient")?.isTargeted === true
35
+
36
+ /**
37
+ * Where a message lives, and what kind of address it is. A channel post's
38
+ * conversation names the post itself as its reply chain root: such a post
39
+ * is addressed to the channel, and is the opener of the thread under it.
40
+ *
41
+ * @internal
42
+ */
43
+ export const locate = (
44
+ conversationId: string | undefined,
45
+ messageId: string | undefined,
46
+ conversationType?: string | undefined
47
+ ): { readonly thread: ChatThread.ChatThread; readonly kind: ChatEvent.ThreadKind } | undefined => {
48
+ if (conversationId === undefined || conversationId.length > Address.maxIdLength) return undefined
49
+ const parts = Address.parts(Address.thread(conversationId))
50
+ if (Option.isNone(parts)) return undefined
51
+ const { base, root } = parts.value
52
+ if (root !== undefined && root === messageId) return { thread: Address.thread(base), kind: "channel" }
53
+ return {
54
+ thread: Address.thread(conversationId),
55
+ kind: root !== undefined ? "thread" : conversationType === "personal" ? "direct" : "channel"
56
+ }
57
+ }
58
+
59
+ /** Where an activity's message lives. @internal */
60
+ export const threadOf = (activity: JsonObject) => {
61
+ const conversation = object(activity, "conversation")
62
+ return locate(string(conversation, "id"), string(activity, "id"), string(conversation, "conversationType"))
63
+ }
64
+
65
+ const timestamp = (activity: JsonObject): DateTime.Utc | undefined => {
66
+ const value = string(activity, "timestamp")
67
+ if (value === undefined) return undefined
68
+ return Option.getOrUndefined(DateTime.make(value).pipe(Option.map(DateTime.toUtc)))
69
+ }
70
+
71
+ const mentionKind = (mentioned: JsonObject, conversationId: string): ChatMessage.Mention["kind"] => {
72
+ if (string(mentioned, "type") === "tag") return "role"
73
+ const id = string(mentioned, "id") ?? ""
74
+ if (id === Address.baseConversation(conversationId) || id.startsWith("19:")) return "channel"
75
+ return "user"
76
+ }
77
+
78
+ /**
79
+ * The mention entities, in order, located in `text` by their `<at>` text.
80
+ * An entity whose text is not found is left out.
81
+ */
82
+ const mentions = (activity: JsonObject, text: string, self: string): Array<ChatMessage.Mention> => {
83
+ const entities = activity.entities
84
+ if (!Array.isArray(entities)) return []
85
+ const conversationId = string(object(activity, "conversation"), "id") ?? ""
86
+ const out: Array<ChatMessage.Mention> = []
87
+ let from = 0
88
+ for (const entity of entities) {
89
+ if (!isObject(entity) || entity.type !== "mention") continue
90
+ const mentioned = object(entity, "mentioned")
91
+ const token = string(entity, "text")
92
+ const id = userId(mentioned)
93
+ if (mentioned === undefined || token === undefined || id === undefined) continue
94
+ const start = text.indexOf(token, from)
95
+ if (start === -1) continue
96
+ from = start + token.length
97
+ out.push({
98
+ kind: mentionKind(mentioned, conversationId),
99
+ id,
100
+ start,
101
+ end: start + token.length,
102
+ isSelf: string(mentioned, "id") === self
103
+ })
104
+ }
105
+ return out
106
+ }
107
+
108
+ const attachments = (activity: JsonObject, context: Context): Array<ChatMessage.Attachment> => {
109
+ const list = activity.attachments
110
+ const serviceUrl = string(activity, "serviceUrl")
111
+ if (!Array.isArray(list) || serviceUrl === undefined) return []
112
+ const conversationType = string(object(activity, "conversation"), "conversationType")
113
+ const out: Array<ChatMessage.Attachment> = []
114
+ for (const attachment of list) {
115
+ if (isObject(attachment) && attachment.contentType === "text/html") continue
116
+ const classified = Download.classify(attachment, {
117
+ serviceUrl,
118
+ ...(conversationType === undefined ? {} : { conversationType }),
119
+ connectorHosts: context.connectorHosts,
120
+ fileHostSuffixes: context.fileHostSuffixes
121
+ })
122
+ if (classified !== undefined) out.push(classified)
123
+ }
124
+ return out
125
+ }
126
+
127
+ /**
128
+ * A `message` activity as a `ChatMessage`.
129
+ *
130
+ * - `text` is Teams' `text` as delivered, with `<at>…</at>` for each
131
+ * mention, which is where `mentions` point.
132
+ * - The author id follows `userId`. `raw` keeps the Connector id.
133
+ *
134
+ * @internal
135
+ */
136
+ export const message = (activity: JsonObject, context: Context): ChatMessage.ChatMessage | undefined => {
137
+ const id = string(activity, "id")
138
+ const from = object(activity, "from")
139
+ const author = userId(from)
140
+ const at = threadOf(activity)
141
+ const time = timestamp(activity)
142
+ if (id === undefined || author === undefined || at === undefined || time === undefined) {
143
+ return undefined
144
+ }
145
+ const self = botId(context.appId)
146
+ const connectorId = string(from, "id") ?? ""
147
+ const text = typeof activity.text === "string" ? activity.text : ""
148
+ const name = string(from, "name")
149
+ return {
150
+ id,
151
+ thread: at.thread,
152
+ author: {
153
+ id: author,
154
+ ...(name === undefined ? {} : { name }),
155
+ isBot: connectorId.startsWith("28:"),
156
+ isSelf: connectorId === self
157
+ },
158
+ text,
159
+ mentions: mentions(activity, text, self),
160
+ attachments: attachments(activity, context),
161
+ timestamp: time,
162
+ raw: activity
163
+ }
164
+ }
165
+
166
+ const reactionEmoji: Readonly<Record<string, string>> = {
167
+ like: "\u{1F44D}",
168
+ heart: "\u2764\uFE0F",
169
+ laugh: "\u{1F606}",
170
+ surprised: "\u{1F62E}",
171
+ sad: "\u{1F622}",
172
+ angry: "\u{1F621}"
173
+ }
174
+
175
+ /**
176
+ * A Teams reaction type as an emoji: the six documented types as Unicode,
177
+ * any other as `custom:{type}`.
178
+ *
179
+ * @internal
180
+ */
181
+ export const emoji = (type: string): string => reactionEmoji[type] ?? `custom:${type}`
182
+
183
+ const reactions = (activity: JsonObject): Array<ChatEvent.ChatEvent> => {
184
+ const messageId = string(activity, "replyToId")
185
+ const user = userId(object(activity, "from"))
186
+ const at = threadOf(activity)
187
+ if (messageId === undefined || user === undefined || at === undefined) return []
188
+ const time = timestamp(activity)
189
+ const out: Array<ChatEvent.ChatEvent> = []
190
+ for (const [key, tag] of [["reactionsAdded", "ReactionAdded"], ["reactionsRemoved", "ReactionRemoved"]] as const) {
191
+ const list = activity[key]
192
+ if (!Array.isArray(list)) continue
193
+ for (const reaction of list) {
194
+ const type = string(reaction, "type")
195
+ if (type === undefined) continue
196
+ out.push({
197
+ _tag: tag,
198
+ thread: at.thread,
199
+ messageId,
200
+ userId: user,
201
+ emoji: emoji(type),
202
+ ...(time === undefined ? {} : { timestamp: time }),
203
+ raw: activity
204
+ })
205
+ }
206
+ }
207
+ return out
208
+ }
209
+
210
+ /**
211
+ * A verified, untargeted activity as zero or more events. A `message`
212
+ * carrying a card submit (`value`) is an interaction, not a message, and
213
+ * gives none here.
214
+ *
215
+ * @internal
216
+ */
217
+ export const normalize = (activity: unknown, context: Context): ReadonlyArray<ChatEvent.ChatEvent> => {
218
+ if (!isObject(activity) || isTargeted(activity)) return []
219
+ switch (activity.type) {
220
+ case "message": {
221
+ if (activity.value !== undefined) return []
222
+ const at = threadOf(activity)
223
+ const created = message(activity, context)
224
+ if (at === undefined || created === undefined) return []
225
+ return [{ _tag: "MessageCreated", thread: at.thread, kind: at.kind, message: created, raw: activity }]
226
+ }
227
+ case "messageReaction":
228
+ return reactions(activity)
229
+ default:
230
+ return []
231
+ }
232
+ }