@effect/chat-slack 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 (182) hide show
  1. package/AGENTS.md +434 -0
  2. package/CLAUDE.md +434 -0
  3. package/LICENSE +21 -0
  4. package/README.md +46 -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/SlackChat.d.ts +500 -0
  88. package/dist/SlackChat.d.ts.map +1 -0
  89. package/dist/SlackChat.js +512 -0
  90. package/dist/SlackChat.js.map +1 -0
  91. package/dist/SlackWebApi.d.ts +74 -0
  92. package/dist/SlackWebApi.d.ts.map +1 -0
  93. package/dist/SlackWebApi.js +96 -0
  94. package/dist/SlackWebApi.js.map +1 -0
  95. package/dist/index.d.ts +15 -0
  96. package/dist/index.d.ts.map +1 -0
  97. package/dist/index.js +16 -0
  98. package/dist/index.js.map +1 -0
  99. package/dist/internal/actions.d.ts +2 -0
  100. package/dist/internal/actions.d.ts.map +1 -0
  101. package/dist/internal/actions.js +169 -0
  102. package/dist/internal/actions.js.map +1 -0
  103. package/dist/internal/adapter.d.ts +2 -0
  104. package/dist/internal/adapter.d.ts.map +1 -0
  105. package/dist/internal/adapter.js +836 -0
  106. package/dist/internal/adapter.js.map +1 -0
  107. package/dist/internal/address.d.ts +2 -0
  108. package/dist/internal/address.d.ts.map +1 -0
  109. package/dist/internal/address.js +36 -0
  110. package/dist/internal/address.js.map +1 -0
  111. package/dist/internal/emoji.d.ts +2 -0
  112. package/dist/internal/emoji.d.ts.map +1 -0
  113. package/dist/internal/emoji.js +207 -0
  114. package/dist/internal/emoji.js.map +1 -0
  115. package/dist/internal/emojiData.d.ts +54 -0
  116. package/dist/internal/emojiData.d.ts.map +1 -0
  117. package/dist/internal/emojiData.js +1965 -0
  118. package/dist/internal/emojiData.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 +190 -0
  122. package/dist/internal/errors.js.map +1 -0
  123. package/dist/internal/escape.d.ts +14 -0
  124. package/dist/internal/escape.d.ts.map +1 -0
  125. package/dist/internal/escape.js +413 -0
  126. package/dist/internal/escape.js.map +1 -0
  127. package/dist/internal/interactions.d.ts +2 -0
  128. package/dist/internal/interactions.d.ts.map +1 -0
  129. package/dist/internal/interactions.js +389 -0
  130. package/dist/internal/interactions.js.map +1 -0
  131. package/dist/internal/json.d.ts +2 -0
  132. package/dist/internal/json.d.ts.map +1 -0
  133. package/dist/internal/json.js +30 -0
  134. package/dist/internal/json.js.map +1 -0
  135. package/dist/internal/length.d.ts +2 -0
  136. package/dist/internal/length.d.ts.map +1 -0
  137. package/dist/internal/length.js +33 -0
  138. package/dist/internal/length.js.map +1 -0
  139. package/dist/internal/mentions.d.ts +2 -0
  140. package/dist/internal/mentions.d.ts.map +1 -0
  141. package/dist/internal/mentions.js +229 -0
  142. package/dist/internal/mentions.js.map +1 -0
  143. package/dist/internal/normalize.d.ts +2 -0
  144. package/dist/internal/normalize.d.ts.map +1 -0
  145. package/dist/internal/normalize.js +211 -0
  146. package/dist/internal/normalize.js.map +1 -0
  147. package/dist/internal/options.d.ts +2 -0
  148. package/dist/internal/options.d.ts.map +1 -0
  149. package/dist/internal/options.js +6 -0
  150. package/dist/internal/options.js.map +1 -0
  151. package/dist/internal/richText.d.ts +2 -0
  152. package/dist/internal/richText.d.ts.map +1 -0
  153. package/dist/internal/richText.js +346 -0
  154. package/dist/internal/richText.js.map +1 -0
  155. package/dist/internal/text.d.ts +2 -0
  156. package/dist/internal/text.d.ts.map +1 -0
  157. package/dist/internal/text.js +239 -0
  158. package/dist/internal/text.js.map +1 -0
  159. package/dist/internal/webhook.d.ts +2 -0
  160. package/dist/internal/webhook.d.ts.map +1 -0
  161. package/dist/internal/webhook.js +142 -0
  162. package/dist/internal/webhook.js.map +1 -0
  163. package/package.json +59 -3
  164. package/src/SlackChat.ts +640 -0
  165. package/src/SlackWebApi.ts +135 -0
  166. package/src/index.ts +18 -0
  167. package/src/internal/actions.ts +203 -0
  168. package/src/internal/adapter.ts +961 -0
  169. package/src/internal/address.ts +50 -0
  170. package/src/internal/emoji.ts +223 -0
  171. package/src/internal/emojiData.ts +1965 -0
  172. package/src/internal/errors.ts +192 -0
  173. package/src/internal/escape.ts +428 -0
  174. package/src/internal/interactions.ts +391 -0
  175. package/src/internal/json.ts +35 -0
  176. package/src/internal/length.ts +41 -0
  177. package/src/internal/mentions.ts +224 -0
  178. package/src/internal/normalize.ts +221 -0
  179. package/src/internal/options.ts +22 -0
  180. package/src/internal/richText.ts +367 -0
  181. package/src/internal/text.ts +252 -0
  182. package/src/internal/webhook.ts +199 -0
@@ -0,0 +1,640 @@
1
+ /**
2
+ * The Slack adapter for `effect/chat`: the `Registry` layer, the Events API
3
+ * webhook, the Interactivity route for buttons and modals, the pure
4
+ * normalisers, address helpers and the scoped post options.
5
+ *
6
+ * **Details**
7
+ *
8
+ * - Bot token scopes: `chat:write`, `channels:history`, `groups:history`,
9
+ * `im:history`, `mpim:history`, `channels:read`, `groups:read`,
10
+ * `im:read`, `mpim:read`, `users:read`, `reactions:read`, `files:read`
11
+ * and `files:write`.
12
+ * - Event subscriptions, sent to `layerWebhook`'s path: `message.channels`,
13
+ * `message.groups`, `message.im`, `message.mpim`, `app_mention`,
14
+ * `reaction_added`, `reaction_removed` and `agent_session_stopped`.
15
+ * - Buttons, selects and modals need Interactivity, which is its own
16
+ * switch in the app settings, off by default, with its own Request URL,
17
+ * separate from Event Subscriptions. Point it at `layerInteractivity`'s
18
+ * path. With Socket Mode on, Slack sends interactions over the socket and
19
+ * never to the URL: pass each payload to `SlackChat.interaction` and send
20
+ * its result as the envelope ack's `payload`.
21
+ * - Slash commands need the `commands` scope. Declare each in the app
22
+ * manifest under `features.slash_commands`, or in the app settings under
23
+ * Slash Commands, with its Request URL set to `layerInteractivity`'s path.
24
+ * The name, less its slash, is the id of the `ChatInteraction.command`,
25
+ * and the manifest's description and usage hint are what Slack shows.
26
+ * With Socket Mode on, commands come as `slash_commands` envelopes: pass
27
+ * the envelope's `payload` to `SlackChat.interaction` in the same way.
28
+ * That path is from Slack's docs and was not run, nor were commands in
29
+ * Slack Connect channels or directs.
30
+ * - A command can't be run inside a thread: Slack doesn't offer it there.
31
+ * A command that acts on a thread has to be told which one. Command names are shared by every app
32
+ * in a workspace. "Escape channels, users, and links" is off by default;
33
+ * with it on, `text` carries `<@U…|name>` and `<#C…|name>` tokens.
34
+ * - Slack's stop button also needs the app declared as an agent with
35
+ * `features.agent_view` in the manifest. Slack documents that declaration
36
+ * as irreversible. Without it the adapter's session status calls answer
37
+ * `not_authorized`; it then stops making them, and replies still work.
38
+ * - A click on the stop button stops nothing by itself: the consumer gets a
39
+ * `StopRequested` and ends the reply. Until it does, the user sees a
40
+ * disabled button. Every click is a separate `StopRequested`, and only
41
+ * the first in a thread lists the open stream in `messageIds`.
42
+ *
43
+ * @stability unstable
44
+ * @since 4.1.5
45
+ */
46
+ import * as ByteSize from "effect/ByteSize"
47
+ import { Registry } from "effect/chat/ChatAdapter"
48
+ import { type ChatError, ChatErrorReason } from "effect/chat/ChatError"
49
+ import type { ChatEvent } from "effect/chat/ChatEvent"
50
+ import { ChatHandler } from "effect/chat/ChatHandler"
51
+ import * as ChatInteraction from "effect/chat/ChatInteraction"
52
+ import type { ParseMention } from "effect/chat/ChatTest"
53
+ import { ChatThread } from "effect/chat/ChatThread"
54
+ import * as Context from "effect/Context"
55
+ import type * as Mac from "effect/crypto/Mac"
56
+ import * as Duration from "effect/Duration"
57
+ import * as Effect from "effect/Effect"
58
+ import { dual } from "effect/Function"
59
+ import * as HttpClient from "effect/http/HttpClient"
60
+ import * as HttpRouter from "effect/http/HttpRouter"
61
+ import * as Layer from "effect/Layer"
62
+ import * as Option from "effect/Option"
63
+ import type * as Redacted from "effect/Redacted"
64
+ import * as Schema from "effect/Schema"
65
+ import * as Adapter from "./internal/adapter.ts"
66
+ import * as Address from "./internal/address.ts"
67
+ import * as Emoji from "./internal/emoji.ts"
68
+ import * as Errors from "./internal/errors.ts"
69
+ import * as Interactions from "./internal/interactions.ts"
70
+ import * as Json from "./internal/json.ts"
71
+ import * as Mentions from "./internal/mentions.ts"
72
+ import * as Normalize from "./internal/normalize.ts"
73
+ import { CurrentPostOptions } from "./internal/options.ts"
74
+ import * as Webhook from "./internal/webhook.ts"
75
+ import { SlackWebApi } from "./SlackWebApi.ts"
76
+ import * as WebApi from "./SlackWebApi.ts"
77
+
78
+ /**
79
+ * A Slack user from `users.info`, with guest and Slack Connect status.
80
+ *
81
+ * @stability unstable
82
+ * @category models
83
+ * @since 4.1.5
84
+ */
85
+ export interface SlackUser {
86
+ readonly id: string
87
+ readonly teamId: string
88
+ readonly name: string
89
+ readonly isBot: boolean
90
+ readonly isRestricted: boolean
91
+ readonly isUltraRestricted: boolean
92
+ /** A Slack Connect user from another organisation. */
93
+ readonly isStranger: boolean
94
+ readonly deleted: boolean
95
+ readonly raw: Schema.Json
96
+ }
97
+
98
+ /**
99
+ * The Slack side of the adapter, for what the core has no op for.
100
+ *
101
+ * **Details**
102
+ *
103
+ * - `botUserId` comes from `auth.test`, read once. A failed read is tried
104
+ * again next time.
105
+ * - `user` calls `users.info` each time. Nothing is cached.
106
+ * - `interaction` is the entry for a decoded Interactivity `payload`
107
+ * (`block_actions` or `view_submission`), as `DiscordChat.interaction`
108
+ * is for Discord, and for a slash command: the form fields of its
109
+ * request, or the `payload` of a `slash_commands` envelope, as one
110
+ * object. It normalises with `normalizeInteraction`, calls the
111
+ * handler through `ChatInteraction.handle` inside `deadline` (2.5
112
+ * seconds by default, the handler's share of Slack's 3), opens a modal
113
+ * with `views.open` and calls `Handler.refused` when it can't.
114
+ * - A modal's title is held to 24 code points, each input label to 2,000 and
115
+ * the modal's id to 255. These are not on the descriptor. A modal past one
116
+ * of them is not opened: `Handler.refused` gets `TooLarge`, and the click
117
+ * is still acked. A portable modal keeps its title to 24.
118
+ * - Slack needs a submit button on a modal with inputs, so a modal with no
119
+ * `submitLabel` gets the English "Submit". Pass `submitLabel` to localise
120
+ * it.
121
+ * - It succeeds with the body to answer Slack with: the JSON of the 200 on
122
+ * the Request URL, or the `payload` of the envelope ack on Socket Mode.
123
+ * For a command answered with `respond` that body is the message, with
124
+ * `response_type` `ephemeral` or `in_channel`, after the checks of a
125
+ * `post`; one that fails them goes to `Handler.refused`. A command's
126
+ * answer, `respond` or `followUp`, mentions nobody: `withPostOptions`
127
+ * does not reach it, so `<@U…>` goes out escaped and shows as text, as a
128
+ * `post` without `withPostOptions` does. There is no way to allow a
129
+ * mention in it.
130
+ * `undefined` is an empty answer: an ack, a close, a late click, a
131
+ * deferred command, a command that opened a modal, a command nobody
132
+ * handles, or a payload that is not from an element this adapter built.
133
+ * - `Late` is a submit or a command whose handler ran past the deadline
134
+ * and was interrupted. It is not an answer, since an empty one would close
135
+ * the modal, or tell the user the command worked: `layerInteractivity`
136
+ * answers 503 for it, and a caller on Socket Mode sends no ack. For a
137
+ * command, Slack's desktop client then shows its own private failure
138
+ * notice and keeps the text; its iOS client shows nothing. `Late` is
139
+ * itself a JSON value, so test for it with `Schema.is(ChatInteraction.Late)`
140
+ * before treating the result as a body.
141
+ * - `Chat.followUp` on a deferred command posts once to the command's
142
+ * `response_url`, which must be on a Slack host, through the layer's
143
+ * `HttpClient`. It is a write and is not retried. Slack takes five posts
144
+ * to one `response_url` within 30 minutes, each a new message. A spent
145
+ * or expired one answers 404 `used_url` or `expired_url`, which is
146
+ * `NotFound` with detail `interaction_expired`. A 410 or a JSON `error`
147
+ * with either string is mapped the same, from the docs: neither was seen.
148
+ * - A click on a private answer has no `message`. Its `messageId` is the
149
+ * answer's `container.message_ts`, which tells which answer was clicked
150
+ * and which no Web API method reaches: `chat.update` on it answers
151
+ * `message_not_found`, so `edit` fails `NotFound`. `raw` has
152
+ * `container.is_ephemeral`. A public answer reads back as a
153
+ * `bot_message` whose `bot_id` is not the app's own, so it is not
154
+ * `isSelf`.
155
+ * - `interaction` checks no signature and no app id: that is the
156
+ * transport's job. It needs `ChatInteraction.Handler` where it is
157
+ * called, so the layer does not need it.
158
+ *
159
+ * @stability unstable
160
+ * @category services
161
+ * @since 4.1.5
162
+ */
163
+ export class SlackChat extends Context.Service<SlackChat, {
164
+ readonly teamId: string
165
+ readonly botUserId: Effect.Effect<string, ChatError>
166
+ readonly user: (id: string) => Effect.Effect<SlackUser, ChatError>
167
+ readonly interaction: (payload: unknown, options?: {
168
+ /** The handler's share of Slack's 3 seconds. Default 2.5 seconds. */
169
+ readonly deadline?: Duration.Duration | undefined
170
+ }) => Effect.Effect<Schema.Json | undefined | ChatInteraction.Late, never, ChatInteraction.Handler>
171
+ }>()("@effect/chat-slack/SlackChat") {}
172
+
173
+ /**
174
+ * Registers the Slack adapter in the `Registry`, for one workspace.
175
+ *
176
+ * **Details**
177
+ *
178
+ * - `post` and `edit` send the Markdown as one `markdown` block, in which
179
+ * a `<` outside inline and fenced code goes as `&lt;`, plus a `text` the
180
+ * adapter builds, in which every `<`, `>` and `&` goes as an entity.
181
+ * Slack decides who a message mentions from `text`, so no token notifies
182
+ * unless `withPostOptions({ notify })` allows it. Allowed tokens stay
183
+ * intact in both.
184
+ * - That `text` is cut to 16,000 code points on a post and 3,800 UTF-8
185
+ * bytes on an edit, on a grapheme cluster boundary, ending in `…` with
186
+ * the allowed tokens the cut left out appended. The cut never fails.
187
+ * - Stream appends go as `markdown_text`, which has no `text` beside it.
188
+ * A stream decodes the character references for `<`, `@` and `!`, so
189
+ * the adapter finds token shapes (`<@`, and `<!` followed by a letter)
190
+ * with those references decoded, in prose and in code alike, and puts a
191
+ * zero-width space (U+200B) straight after whatever spells the `<`.
192
+ * Allowed tokens are sent as they are. An append holds back an unclosed
193
+ * `<`, a trailing character reference that is not finished and a
194
+ * trailing high surrogate, and reports them as `held`. The start and a
195
+ * `flush` hold nothing, so a shape that the next write completes gets
196
+ * its zero-width space at the start of that write.
197
+ * - Once a stream is stopped, by `stop` or by a user, a message whose appends differ from what
198
+ * `post` would send gets one `chat.update` as blocks plus `text`,
199
+ * which takes the zero-width spaces out. It is skipped, leaving them, when
200
+ * the block would pass 12,000 code points, when the edit fails, and when
201
+ * an append to the message was left unconfirmed, since `ChatMarkdown`
202
+ * then rewrites the message itself. A skip fails nothing and sets the
203
+ * span attribute `slack.stream.cleanup`. A cleanup that is interrupted
204
+ * runs again on the next `stop` for that message.
205
+ * - `post`, `edit` and stream writes fail with `TooLarge` before calling
206
+ * Slack when the text as sent passes 12,000 code points. Slack's second
207
+ * limit, 13,200 with every emoji counted as its shortcode, is left to
208
+ * Slack, whose refusal is also `TooLarge` and posts nothing.
209
+ * `descriptor.measure` keeps a part under both.
210
+ * - A post with files uploads them with no channel, posts the message, then
211
+ * attaches them with `chat.update` and `file_ids`. Both calls send the
212
+ * same blocks and `text`, so the `text` of a post with files is cut to the
213
+ * update budget of 3,800 bytes. A post with files and no Markdown carries
214
+ * the file names, joined by ", ", as its text, and keeps them.
215
+ * - A post with files is all-or-nothing. A file Slack refuses at upload,
216
+ * one past `limits`, or an attach Slack refuses fails the post `denied`
217
+ * with detail `file_refused`: a refused attach first deletes the message
218
+ * and then the files, best effort. A timed out attach is retried, for up
219
+ * to a minute in all, waits after a 429 included; past that it is rolled
220
+ * back the same way. When the message can't be deleted, the post fails
221
+ * `Unknown` with detail `attach_failed_message_left` and a
222
+ * `SlackAttachFailed` as its cause. From the post on, the route can't be
223
+ * interrupted, and each call has a timeout.
224
+ * - `edit` keeps a message's files, and `delete` removes the message and
225
+ * not its files: a user may have shared them on. Read the file ids with
226
+ * `fetchMessage` before deleting to remove them too.
227
+ * - A mention in a post with files can notify for a message that a refused
228
+ * attach then deletes.
229
+ * - A post with files in a Slack Connect channel is untested.
230
+ * - `replyTo` is not supported.
231
+ * - A message from another app or an incoming webhook (`bot_message`) has
232
+ * the `bot_id` as its author id. `getUser` on that id fails `NotFound`.
233
+ * - `getUser`'s `raw` is the user from `users.info`, with its `team_id`.
234
+ * `SlackChat.user` is the same call with the team, guest and Slack
235
+ * Connect status as typed fields.
236
+ * - The layer provides the `SlackChat` and `SlackWebApi` services as well
237
+ * as registering the adapter. A consumer that needs more of Slack than
238
+ * `Chat` has reads either from context beside `Chat`.
239
+ * - A thread root whose subtype is not a message, such as an agent-view
240
+ * chat's `assistant_app_thread` root, is treated as deleted: `opener`
241
+ * gives `None` and history starts at the first reply.
242
+ * - Edits to one message are at least 3 seconds apart.
243
+ * - After a 429 on a stream append or an edit, the next write to that
244
+ * message waits for the retry-after, and later writes to it wait twice
245
+ * the interval, for the rest of the reply. A stream started with
246
+ * `continues` keeps the pace of the part it continues.
247
+ * - The native stream needs a thread and a recipient, and rotates before
248
+ * Slack's ten minute cap. A reply that ends after a click on the stop
249
+ * button moves the agent session off `processing`.
250
+ * - A message's buttons, link buttons and selects go in one `actions` block
251
+ * after the `markdown` block, on `post` and on `edit`. A button's id is
252
+ * its `action_id` and its value its `value`. A message with elements and
253
+ * no Markdown has no `markdown` block, and its `text` is the button
254
+ * labels joined by a space. A streamed reply gets its buttons by `edit`
255
+ * after the stream stops.
256
+ * - Elements are refused before the call past 25 in a message, for an id
257
+ * longer than 255 or holding U+241F, and for an id plus a value longer
258
+ * than 2,000, all in code points.
259
+ * - Text and elements share Slack's 13,200 budget, so
260
+ * `descriptor.measure(markdown, actions)` counts the `actions` block as
261
+ * Slack stores it, with every non-ASCII unit at 6. A `value` near 2,000
262
+ * uses up the budget by itself. A `post` whose elements push it past the
263
+ * cap fails `TooLarge` with `msg_blocks_too_long`, and nothing is posted.
264
+ * The adapter never falls back to posting the text and adding the elements
265
+ * by `edit`. A caller can: `chat.update` had no 13,200 cap when tested,
266
+ * which Slack does not document.
267
+ *
268
+ * @stability unstable
269
+ * @category layers
270
+ * @since 4.1.5
271
+ */
272
+ export const layer = (options: {
273
+ readonly botToken: Redacted.Redacted
274
+ readonly teamId: string
275
+ }): Layer.Layer<SlackChat | SlackWebApi, never, HttpClient.HttpClient | Registry> =>
276
+ Layer.effect(
277
+ SlackChat,
278
+ Effect.gen(function*() {
279
+ const api = yield* SlackWebApi
280
+ const http = yield* HttpClient.HttpClient
281
+ const registry = yield* Registry
282
+ let cached: string | undefined
283
+ const botUserId: Effect.Effect<string, ChatError> = Effect.suspend(() => {
284
+ if (cached !== undefined) return Effect.succeed(cached)
285
+ return api.call("auth.test", {}).pipe(
286
+ Effect.mapError(Errors.withOp("botUserId")),
287
+ Effect.flatMap((answer) => {
288
+ const id = Json.string(answer, "user_id")
289
+ if (id === undefined) {
290
+ return Effect.fail(Errors.chatError("botUserId", Errors.invalidResponse(false, "missing_user_id")))
291
+ }
292
+ cached = id
293
+ return Effect.succeed(id)
294
+ })
295
+ )
296
+ })
297
+ const { adapter, answer, user } = Adapter.make({
298
+ api,
299
+ http,
300
+ botToken: options.botToken,
301
+ teamId: options.teamId,
302
+ botUserId,
303
+ attachFailed: (fields) => new SlackAttachFailed(fields)
304
+ })
305
+ yield* registry.register(adapter)
306
+ const interaction = Interactions.make({ api, teamId: options.teamId, answer })
307
+ return SlackChat.of({ teamId: options.teamId, botUserId, user, interaction })
308
+ })
309
+ ).pipe(Layer.provideMerge(WebApi.layer({ botToken: options.botToken })))
310
+
311
+ /**
312
+ * The `cause` of a `post` with files that failed `uncertain` with detail
313
+ * `attach_failed_message_left`.
314
+ *
315
+ * **Details**
316
+ *
317
+ * - The attach failed and the message could not be deleted. The message may
318
+ * still exist, with or without its files: an attach that timed out may
319
+ * have landed, and a delete that timed out may have too. `messageId` is
320
+ * that message and `fileIds` are its files, which are kept. `reason` is
321
+ * the attach's own.
322
+ * - Its `message` leaves the ids out.
323
+ *
324
+ * @stability unstable
325
+ * @category errors
326
+ * @since 4.1.5
327
+ */
328
+ export class SlackAttachFailed
329
+ extends Schema.TaggedError<SlackAttachFailed>("@effect/chat-slack/SlackChat/SlackAttachFailed")(
330
+ "SlackAttachFailed",
331
+ {
332
+ thread: ChatThread,
333
+ messageId: Schema.String,
334
+ fileIds: Schema.Array(Schema.String),
335
+ reason: ChatErrorReason
336
+ }
337
+ )
338
+ {
339
+ override get message(): string {
340
+ return `Slack did not attach the files and the message may be left: ${this.reason.message}`
341
+ }
342
+ }
343
+
344
+ /**
345
+ * The address of a Slack channel, direct conversation or thread:
346
+ * `{team}/{channel}`, or `{team}/{channel}/{threadTs}` for a thread.
347
+ *
348
+ * @stability unstable
349
+ * @category constructors
350
+ * @since 4.1.5
351
+ */
352
+ export const thread: (parts: {
353
+ readonly team: string
354
+ readonly channel: string
355
+ readonly threadTs?: string | undefined
356
+ }) => ChatThread = Address.thread
357
+
358
+ /**
359
+ * The parts of a Slack address, or `None` for another platform's or a
360
+ * malformed one.
361
+ *
362
+ * @stability unstable
363
+ * @category destructors
364
+ * @since 4.1.5
365
+ */
366
+ export const parts: (thread: ChatThread) => Option.Option<{
367
+ readonly team: string
368
+ readonly channel: string
369
+ readonly threadTs?: string | undefined
370
+ }> = Address.parts
371
+
372
+ /**
373
+ * `POST {path}`: the Events API webhook.
374
+ *
375
+ * **Details**
376
+ *
377
+ * - Checks the `v0` signature with the signing secret and a five minute
378
+ * window, then answers `url_verification`.
379
+ * - An envelope for another app, another workspace or of another type is
380
+ * answered 200 and dropped.
381
+ * - The events go through `normalize` to the `ChatHandler`, one at a time.
382
+ * - Answers 503, so Slack retries, when the handler fails `NotAccepted`,
383
+ * when the bot user can't be read, or when the request, from reading its
384
+ * body to the handler's return, takes longer than `deadline` (2.5 seconds
385
+ * by default). Each of the three is logged with its own message, the
386
+ * unreadable bot user as an error with its `ChatError` and the other two
387
+ * as warnings.
388
+ * - Answers 413 past `maxBodyBytes` (1 MiB by default), and for a body that
389
+ * can't be read, before the signature is checked. `maxBodyBytes` must be
390
+ * a non-negative safe integer; another value is a defect when the layer is
391
+ * built.
392
+ * - Slack redelivers on a timeout or an error, so an event can arrive twice.
393
+ * `ChatEvent.dedupeKey` gives the two deliveries equal keys.
394
+ *
395
+ * Signature checks use the required `Mac` service. Provide
396
+ * `NodeCrypto.layerMac`, `BunCrypto.layerMac`, `DenoCrypto.layerMac`,
397
+ * `BrowserCrypto.layerMac`, or `Mac.layerWebCrypto` with
398
+ * `SecureRandom.layerWebCrypto` for other runtimes such as Workers.
399
+ * Key construction failures are configuration defects; verification errors
400
+ * fail the signature check (401).
401
+ *
402
+ * @stability unstable
403
+ * @category layers
404
+ * @since 4.1.5
405
+ */
406
+ export const layerWebhook = (options: {
407
+ readonly path: `/${string}`
408
+ readonly signingSecret: Redacted.Redacted
409
+ readonly appId: string
410
+ readonly deadline?: Duration.Duration | undefined
411
+ readonly maxBodyBytes?: number | undefined
412
+ }): Layer.Layer<never, never, HttpRouter.HttpRouter | SlackChat | ChatHandler | Mac.Mac> =>
413
+ HttpRouter.use(Effect.fnUntraced(function*(router) {
414
+ const slack = yield* SlackChat
415
+ const handler = yield* ChatHandler
416
+ const verify = yield* Webhook.makeVerifier(options.signingSecret)
417
+ const webhookOptions: Webhook.Options = {
418
+ verify,
419
+ appId: options.appId,
420
+ teamId: slack.teamId,
421
+ botUserId: slack.botUserId,
422
+ handle: handler.handle,
423
+ deadline: options.deadline ?? Duration.millis(2500),
424
+ maxBodySize: ByteSize.bytes(options.maxBodyBytes ?? Webhook.defaultMaxBodyBytes)
425
+ }
426
+ yield* router.add("POST", options.path, (request) => Webhook.handleRequest(request, webhookOptions))
427
+ }))
428
+
429
+ /**
430
+ * `POST {path}`: the Interactivity Request URL, which Slack posts
431
+ * form-encoded and separately from the Events API.
432
+ *
433
+ * **Details**
434
+ *
435
+ * - Checks the `v0` signature as `layerWebhook` does, decodes the form's
436
+ * `payload` and drops one for another app with a 200.
437
+ * - It is also the Request URL of a slash command. A command's form has no
438
+ * `payload` field and has a `command` field, which is how the route tells
439
+ * the two apart. Its fields go to `SlackChat.interaction` as one object,
440
+ * after the same signature and app checks.
441
+ * - Hands the payload to `SlackChat.interaction` with `deadline` (2.5
442
+ * seconds by default). Its body is the response, and `Late` is answered
443
+ * with a 503, so the modal stays open with Slack's own error.
444
+ * - Answers 413 past `maxBodyBytes`, as `layerWebhook` does.
445
+ * - Slack never redelivers an interaction, so a click or submit that is not
446
+ * answered in time is lost. A user can submit again, as a new request.
447
+ *
448
+ * Signature checks use the required `Mac` service. Provide
449
+ * `NodeCrypto.layerMac`, `BunCrypto.layerMac`, `DenoCrypto.layerMac`,
450
+ * `BrowserCrypto.layerMac`, or `Mac.layerWebCrypto` with
451
+ * `SecureRandom.layerWebCrypto` for other runtimes such as Workers.
452
+ * Key construction failures are configuration defects; verification errors
453
+ * fail the signature check (401).
454
+ *
455
+ * @stability unstable
456
+ * @category layers
457
+ * @since 4.1.5
458
+ */
459
+ export const layerInteractivity = (options: {
460
+ readonly path: `/${string}`
461
+ readonly signingSecret: Redacted.Redacted
462
+ readonly appId: string
463
+ readonly deadline?: Duration.Duration | undefined
464
+ readonly maxBodyBytes?: number | undefined
465
+ }): Layer.Layer<never, never, HttpRouter.HttpRouter | SlackChat | ChatInteraction.Handler | Mac.Mac> =>
466
+ HttpRouter.use(Effect.fnUntraced(function*(router) {
467
+ const slack = yield* SlackChat
468
+ const handler = yield* ChatInteraction.Handler
469
+ const verify = yield* Webhook.makeVerifier(options.signingSecret)
470
+ const interactivityOptions: Webhook.InteractivityOptions = {
471
+ verify,
472
+ appId: options.appId,
473
+ interaction: (payload, interactionOptions) =>
474
+ Effect.provideService(slack.interaction(payload, interactionOptions), ChatInteraction.Handler, handler),
475
+ deadline: options.deadline ?? Interactions.defaultDeadline,
476
+ maxBodySize: ByteSize.bytes(options.maxBodyBytes ?? Webhook.defaultMaxBodyBytes)
477
+ }
478
+ yield* router.add("POST", options.path, (request) => Webhook.handleInteractivity(request, interactivityOptions))
479
+ }))
480
+
481
+ /**
482
+ * The normaliser behind `SlackChat.interaction`.
483
+ *
484
+ * **Details**
485
+ *
486
+ * - Pure: takes the decoded `payload` of a `block_actions` or
487
+ * `view_submission` request, or the fields of a slash command.
488
+ * - None for any other payload, and for one that is not from an element
489
+ * this adapter built: a block of the consumer's own, a link button, or a
490
+ * view the adapter did not open.
491
+ * - Every command gives a `CommandInvoked`, known or not: the registry
492
+ * decides that later. `id` is `command` less its slash, `text` is `text`
493
+ * or the empty string, and the thread is the channel's.
494
+ * - A submit's thread and message are those of the click that opened the
495
+ * modal, which the adapter packed into `private_metadata` beside the
496
+ * consumer's metadata. A modal a command opened has no message, so its
497
+ * submit has no `messageId`.
498
+ * - The team in an address is `context.teamId`. `raw` is the payload
499
+ * without its verification `token`. A command's holds its `response_url`,
500
+ * so it is a credential for 30 minutes.
501
+ *
502
+ * @stability unstable
503
+ * @category normalization
504
+ * @since 4.1.5
505
+ */
506
+ export const normalizeInteraction: (
507
+ payload: unknown,
508
+ context: { readonly teamId: string }
509
+ ) => Option.Option<ChatInteraction.Interaction> = Interactions.normalize
510
+
511
+ /**
512
+ * The normaliser, for Socket Mode or a consumer's own transport.
513
+ *
514
+ * **Details**
515
+ *
516
+ * - Pure: takes an `event_callback` envelope, gives zero or more events.
517
+ * - An envelope for another workspace gives none. The team in an address is
518
+ * the workspace, from the envelope's `team_id` or `authorizations`.
519
+ * - `message` and `app_mention` for one message give equal events. An
520
+ * `app_mention` that carries `edited` gives none.
521
+ * - A message subtype other than `file_share`, `thread_broadcast`,
522
+ * `bot_message` and `me_message` gives none.
523
+ * - Mentions come from the message's `rich_text` block when it has one,
524
+ * and only for elements whose token is in `text`, since Slack decides a
525
+ * mention from `text`. Without a `rich_text` block they come from `text`
526
+ * outside code.
527
+ * - The bot's own messages with a `rich_text` block read back with `text`
528
+ * rendered from the blocks as Markdown, whole and with its newlines, as
529
+ * the stored `text` the adapter sent may be cut. Everyone else's `text`
530
+ * is Slack's field as stored.
531
+ * - `agent_session_stopped` gives a `StopRequested`.
532
+ * - `raw` is the envelope without its verification `token`.
533
+ *
534
+ * @stability unstable
535
+ * @category normalization
536
+ * @since 4.1.5
537
+ */
538
+ export const normalize: (
539
+ envelope: unknown,
540
+ context: { readonly teamId: string; readonly botUserId: string }
541
+ ) => ReadonlyArray<ChatEvent> = Normalize.normalize
542
+
543
+ /**
544
+ * Slack options for every write inside an effect.
545
+ *
546
+ * @stability unstable
547
+ * @category models
548
+ * @since 4.1.5
549
+ */
550
+ export interface SlackPostOptions {
551
+ /** Which mention tokens may notify. Default: none. */
552
+ readonly notify?: {
553
+ readonly users?: ReadonlyArray<string> | undefined
554
+ readonly groups?: ReadonlyArray<string> | undefined
555
+ readonly broadcast?: boolean | undefined
556
+ } | undefined
557
+ /**
558
+ * Link and media previews. Default false, which sends `unfurl_links` and
559
+ * `unfurl_media` both false; true sends both true.
560
+ *
561
+ * **Details**
562
+ *
563
+ * - It applies to `post` only: `chat.update` has no unfurl parameter.
564
+ * An edit that adds a link gets no preview either way, which a live
565
+ * check confirmed, so a post-then-edit stream never unfurls.
566
+ * - Slack disables unfurling in streaming messages, so it does nothing on
567
+ * a native stream.
568
+ */
569
+ readonly unfurl?: boolean | undefined
570
+ /** Default true where the workspace supports it. */
571
+ readonly nativeStream?: boolean | undefined
572
+ /** For a Connect channel, where the recipient is on another team. */
573
+ readonly recipientTeamId?: string | undefined
574
+ /** The agent session status at a normal end of a native stream. Default `active`. */
575
+ readonly sessionStatusAtEnd?: "active" | "processing" | "suspended" | "closed" | undefined
576
+ }
577
+
578
+ /**
579
+ * Scoped Slack options for every write inside `effect`. Nested calls merge,
580
+ * the inner one winning field by field.
581
+ *
582
+ * @stability unstable
583
+ * @category combinators
584
+ * @since 4.1.5
585
+ */
586
+ export const withPostOptions: {
587
+ /**
588
+ * Scoped Slack options for every write inside `effect`. Nested calls merge,
589
+ * the inner one winning field by field.
590
+ *
591
+ * @stability unstable
592
+ * @category combinators
593
+ * @since 4.1.5
594
+ */
595
+ (options: SlackPostOptions): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>
596
+ /**
597
+ * Scoped Slack options for every write inside `effect`. Nested calls merge,
598
+ * the inner one winning field by field.
599
+ *
600
+ * @stability unstable
601
+ * @category combinators
602
+ * @since 4.1.5
603
+ */
604
+ <A, E, R>(effect: Effect.Effect<A, E, R>, options: SlackPostOptions): Effect.Effect<A, E, R>
605
+ } = dual(
606
+ 2,
607
+ <A, E, R>(effect: Effect.Effect<A, E, R>, options: SlackPostOptions): Effect.Effect<A, E, R> =>
608
+ Effect.updateService(effect, CurrentPostOptions, (current) => ({ ...current, ...options }))
609
+ )
610
+
611
+ /**
612
+ * A Slack emoji name, with or without colons and with at most one skin tone
613
+ * suffix (`+1::skin-tone-4`), as Unicode. `None` for a name the table
614
+ * doesn't know, such as a custom emoji, and for a name with two tones.
615
+ *
616
+ * @stability unstable
617
+ * @category emoji
618
+ * @since 4.1.5
619
+ */
620
+ export const emojiFromName = (name: string): Option.Option<string> => Option.fromUndefinedOr(Emoji.fromName(name))
621
+
622
+ /**
623
+ * An emoji as its Slack name, without colons.
624
+ *
625
+ * @stability unstable
626
+ * @category emoji
627
+ * @since 4.1.5
628
+ */
629
+ export const emojiToName = (emoji: string): Option.Option<string> => Option.fromUndefinedOr(Emoji.toName(emoji))
630
+
631
+ /**
632
+ * Reads one Slack mention token, such as `<@U123>`, `<!subteam^S123|@team>`,
633
+ * `<#C123|name>` or `<!here>`, for `ChatTest.checkMessage`,
634
+ * `ChatTest.checkEvent` and `ChatTest.conformance`.
635
+ *
636
+ * @stability unstable
637
+ * @category testing
638
+ * @since 4.1.5
639
+ */
640
+ export const parseMention: ParseMention = (slice) => Option.fromUndefinedOr(Mentions.parseToken(slice))