@effect/chat-slack 0.0.0 → 4.1.6

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 +47 -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/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 +62 -1
  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,961 @@
1
+ import {
2
+ type ChatAdapter,
3
+ type Descriptor,
4
+ type File,
5
+ type Posted,
6
+ retrySafe,
7
+ type ThreadInfo
8
+ } from "effect/chat/ChatAdapter"
9
+ import {
10
+ type ChatError,
11
+ type ChatErrorReason,
12
+ fileRefused,
13
+ interactionExpired,
14
+ NotFound,
15
+ TooLarge,
16
+ Unknown,
17
+ Unsupported
18
+ } from "effect/chat/ChatError"
19
+ import type { Defer, Visibility } from "effect/chat/ChatInteraction"
20
+ import type { ChatMessage } from "effect/chat/ChatMessage"
21
+ import type { ChatThread } from "effect/chat/ChatThread"
22
+ import type { Action } from "effect/chat/ChatUi"
23
+ import * as Clock from "effect/Clock"
24
+ import * as DateTime from "effect/DateTime"
25
+ import * as Duration from "effect/Duration"
26
+ import * as Effect from "effect/Effect"
27
+ import type * as HttpClient from "effect/http/HttpClient"
28
+ import * as HttpClientRequest from "effect/http/HttpClientRequest"
29
+ import * as Option from "effect/Option"
30
+ import * as Redacted from "effect/Redacted"
31
+ import * as Result from "effect/Result"
32
+ import type * as Schema from "effect/Schema"
33
+ import * as Stream from "effect/Stream"
34
+ import * as Str from "effect/String"
35
+ import type { SlackUser } from "../SlackChat.ts"
36
+ import type { SlackWebApi } from "../SlackWebApi.ts"
37
+ import * as Address from "./address.ts"
38
+ import * as Errors from "./errors.ts"
39
+ import * as Escape from "./escape.ts"
40
+ import * as Interactions from "./interactions.ts"
41
+ import { isObject, type JsonObject, object, parse, string } from "./json.ts"
42
+ import * as Length from "./length.ts"
43
+ import * as Normalize from "./normalize.ts"
44
+ import { CurrentPostOptions, type SessionStatus } from "./options.ts"
45
+ import * as Text from "./text.ts"
46
+
47
+ type Json = Schema.Json
48
+
49
+ /** @internal */
50
+ export const descriptor: Descriptor = {
51
+ platform: Address.platform,
52
+ capabilities: new Set([
53
+ "edit",
54
+ "delete",
55
+ "fetchMessage",
56
+ "history",
57
+ "download",
58
+ "files",
59
+ "startThread",
60
+ "getThread",
61
+ "opener",
62
+ "getUser",
63
+ "nativeStream",
64
+ "buttons",
65
+ "selects",
66
+ "modals",
67
+ "modalErrors",
68
+ "commands",
69
+ "ephemeral"
70
+ ]),
71
+ measure: Length.measure,
72
+ limits: {
73
+ messageLength: Length.messageLength,
74
+ filesPerMessage: 10,
75
+ uploadBytes: 1024 * 1024 * 1024,
76
+ minWriteInterval: Duration.seconds(1),
77
+ streamLength: Length.messageLength,
78
+ streamAge: Duration.minutes(10),
79
+ followUpAge: Duration.minutes(30),
80
+ ...Interactions.limits
81
+ }
82
+ }
83
+
84
+ const pageSize = 200
85
+
86
+ /**
87
+ * The hosts a command's `response_url` may point at. A deferral is data that
88
+ * may have crossed a queue, so the adapter posts only to Slack.
89
+ */
90
+ const isSlackHost = (host: string): boolean =>
91
+ host === "slack.com" || host.endsWith(".slack.com") || host === "slack-gov.com" || host.endsWith(".slack-gov.com")
92
+
93
+ /**
94
+ * What a spent `response_url` answers, as plain text with a 404: `used_url`
95
+ * after five posts, `expired_url` after 30 minutes. Recorded in EFF-3802.
96
+ * The same strings in a JSON `error`, and a 410, are from Slack's docs and
97
+ * were never seen; they stay mapped.
98
+ */
99
+ const spentResponseUrl = new Set(["expired_url", "used_url"])
100
+
101
+ /** The `response_type` of a command's answer. */
102
+ const responseType = (visibility: Visibility) => visibility === "ephemeral" ? "ephemeral" : "in_channel"
103
+
104
+ /** The bound on each call of a file post from `chat.postMessage` on: the post, each attach and the rollback. */
105
+ const fileCallTimeout = Duration.seconds(30)
106
+
107
+ /**
108
+ * The bound on the whole attach: every attempt, the waits between them and
109
+ * the pacing after a 429. Past it the post is rolled back, however long a
110
+ * `Retry-After` asked for.
111
+ */
112
+ const attachDeadline = Duration.minutes(1)
113
+
114
+ /** Codes on `chat.startStream` that mean the feature is off for this thread. */
115
+ const streamUnsupported = new Set(["channel_type_not_supported", "feature_disabled", "not_allowed_token_type"])
116
+
117
+ /** Floor between two edits to one message: the spec's starting number, provisional until measured. */
118
+ const editIntervalMillis = 3_000
119
+
120
+ /** How long a reply's backoff is kept after its last write. */
121
+ const paceIdleMillis = 15 * 60 * 1000
122
+
123
+ /** A reply's pace after a 429, shared by every message the reply writes. */
124
+ interface Backoff {
125
+ intervalMillis: number
126
+ nextAt: number
127
+ lastWrite: number
128
+ }
129
+
130
+ interface StreamState {
131
+ readonly escape: Escape.State
132
+ /** The Markdown the stream took, held tails left out. */
133
+ readonly markdown: string
134
+ /** What its start and appends sent. */
135
+ readonly sent: string
136
+ readonly stopped: boolean
137
+ /**
138
+ * False while an append is in flight, and after one failed in a way the
139
+ * layer repairs: an append cut off or failed `uncertain` may have landed,
140
+ * and the repair edit rewrites the message itself.
141
+ */
142
+ readonly settled: boolean
143
+ /** Whether the cleanup edit has run or been skipped. */
144
+ readonly cleaned: boolean
145
+ /** Whether the session status at the end has been set, for a stream stopped by the user. */
146
+ readonly ended: boolean
147
+ }
148
+
149
+ /** The state of an open, unstopped stream that has sent `sent` for `markdown`. */
150
+ const openStream = (escape: Escape.State, markdown: string, sent: string): StreamState => ({
151
+ escape,
152
+ markdown,
153
+ sent,
154
+ stopped: false,
155
+ settled: true,
156
+ cleaned: false,
157
+ ended: false
158
+ })
159
+
160
+ const hasDetail = (code: string) => (error: ChatError): boolean => error.reason.detail === code
161
+
162
+ const userName = (user: JsonObject): string => {
163
+ const profile = object(user, "profile")
164
+ return string(profile, "display_name") ?? string(profile, "real_name") ?? string(user, "real_name") ??
165
+ string(user, "name") ?? string(user, "id") ?? ""
166
+ }
167
+
168
+ /** @internal */
169
+ export const make = (options: {
170
+ readonly api: SlackWebApi["Service"]
171
+ readonly http: HttpClient.HttpClient
172
+ readonly botToken: Redacted.Redacted
173
+ readonly teamId: string
174
+ readonly botUserId: Effect.Effect<string, ChatError>
175
+ /** Builds the `SlackAttachFailed` cause, which lives in the public module. */
176
+ readonly attachFailed: (fields: {
177
+ readonly thread: ChatThread
178
+ readonly messageId: string
179
+ readonly fileIds: ReadonlyArray<string>
180
+ readonly reason: ChatErrorReason
181
+ }) => unknown
182
+ }) => {
183
+ const { api, teamId } = options
184
+ const streams = new Map<string, StreamState>()
185
+ let declaredAgent = true
186
+
187
+ const fail = (op: string, reason: ChatErrorReason) => Effect.fail(Errors.chatError(op, reason))
188
+
189
+ /** Refuses elements Slack would refuse, or that the adapter could not tell from a consumer's. */
190
+ const checkActions = (op: string, actions: ReadonlyArray<Action>) => {
191
+ const refusal = Interactions.checkActions(actions)
192
+ return refusal === undefined ? Effect.void : fail(op, refusal)
193
+ }
194
+
195
+ /**
196
+ * The pace of the writes that grow one reply: stream appends, the starts
197
+ * of its later parts, and edits.
198
+ *
199
+ * - Edits to one message are at least `editIntervalMillis` apart.
200
+ * - After a 429, the next write waits for the retry-after, and each later
201
+ * write waits twice the interval it waited before, for the rest of the
202
+ * reply. The backoff is keyed by message and shared: a stream started
203
+ * with `continues` takes the backoff of the message it continues, and a
204
+ * stop with `end: "done"` drops it.
205
+ * - Each attempt reads the pace afresh, so a write retried after a 429
206
+ * waits for it.
207
+ */
208
+ const backoffs = new Map<string, Backoff>()
209
+ const nextEdit = new Map<string, number>()
210
+
211
+ const evict = (now: number) => {
212
+ if (nextEdit.size >= 64) { for (const [key, at] of nextEdit) if (at <= now) nextEdit.delete(key) }
213
+ if (backoffs.size >= 64) {
214
+ for (const [key, backoff] of backoffs) if (backoff.lastWrite < now - paceIdleMillis) backoffs.delete(key)
215
+ }
216
+ }
217
+
218
+ const paced = <A>(
219
+ messageId: string,
220
+ write: Effect.Effect<A, ChatError>,
221
+ kind: "edit" | "stream"
222
+ ): Effect.Effect<A, ChatError> =>
223
+ Effect.gen(function*() {
224
+ const at = Math.max(backoffs.get(messageId)?.nextAt ?? 0, kind === "edit" ? nextEdit.get(messageId) ?? 0 : 0)
225
+ const wait = at - (yield* Clock.currentTimeMillis)
226
+ if (wait > 0) yield* Effect.sleep(Duration.millis(wait))
227
+ return yield* write.pipe(
228
+ Effect.tap(() =>
229
+ Effect.map(Clock.currentTimeMillis, (now) => {
230
+ evict(now)
231
+ const backoff = backoffs.get(messageId)
232
+ if (backoff !== undefined) {
233
+ backoff.nextAt = now + backoff.intervalMillis
234
+ backoff.lastWrite = now
235
+ }
236
+ if (kind === "edit") nextEdit.set(messageId, now + editIntervalMillis)
237
+ })
238
+ ),
239
+ Effect.tapError((error) =>
240
+ error.reason._tag !== "RateLimited" ? Effect.void : Effect.map(Clock.currentTimeMillis, (now) => {
241
+ evict(now)
242
+ const base = kind === "edit" ? editIntervalMillis : Duration.toMillis(descriptor.limits.minWriteInterval)
243
+ const backoff = backoffs.get(messageId) ?? { intervalMillis: base, nextAt: now, lastWrite: now }
244
+ backoff.intervalMillis *= 2
245
+ const retryAfter = error.retryAfter
246
+ backoff.nextAt = now + (retryAfter === undefined ? backoff.intervalMillis : Duration.toMillis(retryAfter))
247
+ backoff.lastWrite = now
248
+ backoffs.set(messageId, backoff)
249
+ })
250
+ )
251
+ )
252
+ })
253
+
254
+ const call = (
255
+ op: string,
256
+ method: string,
257
+ body: Readonly<Record<string, unknown>>,
258
+ callOptions?: { readonly write?: boolean | undefined; readonly retry?: boolean | undefined }
259
+ ) => api.call(method, body, callOptions).pipe(Effect.mapError(Errors.withOp(op)))
260
+
261
+ const resolve = (op: string, thread: ChatThread): Effect.Effect<Address.Parts, ChatError> => {
262
+ const parts = Address.parts(thread)
263
+ return Option.isSome(parts) && parts.value.team === teamId
264
+ ? Effect.succeed(parts.value)
265
+ : fail(op, Errors.invalidRequest("invalid_thread"))
266
+ }
267
+
268
+ const tsOf = (op: string, write: boolean) => (answer: Json): Effect.Effect<string, ChatError> => {
269
+ const ts = string(answer, "ts")
270
+ return ts === undefined ? fail(op, Errors.invalidResponse(write, "missing_ts")) : Effect.succeed(ts)
271
+ }
272
+
273
+ /**
274
+ * Refuses text past 12,000 code points as sent, which Slack would refuse
275
+ * with `msg_too_long`. Slack's second count, with emoji as shortcodes, is
276
+ * left to Slack: `measure` only bounds it from above, because entities,
277
+ * code and Markdown markers render shorter than they are sent. Its refusal
278
+ * maps to `TooLarge` and leaves nothing behind.
279
+ */
280
+ const checkSent = (op: string, sent: string): Effect.Effect<void, ChatError> =>
281
+ Length.codePoints(sent) > Length.messageLength
282
+ ? fail(op, new TooLarge({ subject: "text", detail: "msg_too_long" }))
283
+ : Effect.void
284
+
285
+ /**
286
+ * The body of a post or an update: the Markdown as one `markdown` block,
287
+ * and a `text` the adapter builds, cut to the call's budget. Slack decides
288
+ * mentions from `text`, and builds one with every token intact when none
289
+ * is sent, so `markdown_text` is never used on these two calls.
290
+ */
291
+ const messageContent = Effect.fnUntraced(
292
+ function*(op: string, body: Text.Body) {
293
+ yield* checkSent(op, body.sent)
294
+ if (body.text === "" && !Text.hasActions(body)) return yield* fail(op, Errors.invalidRequest("no_text"))
295
+ if (body.dropped > 0) yield* Effect.annotateCurrentSpan("slack.text.dropped_tokens", body.dropped)
296
+ return { blocks: body.blocks, text: body.text }
297
+ }
298
+ )
299
+
300
+ const messages = (answer: Json): ReadonlyArray<Json> =>
301
+ isObject(answer) && Array.isArray(answer.messages) ? answer.messages : []
302
+
303
+ const nextCursor = (answer: Json): Option.Option<string> =>
304
+ Option.fromUndefinedOr(string(object(answer, "response_metadata"), "next_cursor"))
305
+
306
+ /** One message by ts, in or out of a thread, as Slack stores it. */
307
+ const fetchRaw = (op: string, channel: string, ts: string): Effect.Effect<Json, ChatError> =>
308
+ call(op, "conversations.replies", { channel, ts, latest: ts, oldest: ts, inclusive: true, limit: 2 }).pipe(
309
+ Effect.flatMap((answer) => {
310
+ const found = messages(answer).find((message) => isObject(message) && message.ts === ts)
311
+ return found === undefined ? fail(op, Errors.notFound("message_not_found")) : Effect.succeed(found)
312
+ })
313
+ )
314
+
315
+ const fetchMessage = Effect.fnUntraced(function*(op: string, thread: ChatThread, messageId: string) {
316
+ const parts = yield* resolve(op, thread)
317
+ const botUserId = yield* options.botUserId
318
+ const raw = yield* fetchRaw(op, parts.channel, messageId)
319
+ const message = Normalize.message(raw, { team: teamId, channel: parts.channel, botUserId })
320
+ return message === undefined ? yield* fail(op, Errors.notFound("not_a_message")) : message
321
+ })
322
+
323
+ const sessionStatus = (channel: string, threadTs: string, status: SessionStatus): Effect.Effect<void> =>
324
+ declaredAgent
325
+ ? call("nativeStream.stop", "agents.sessions.setStatus", { channel_id: channel, thread_ts: threadTs, status }, {
326
+ write: true,
327
+ retry: false
328
+ }).pipe(
329
+ Effect.asVoid,
330
+ Effect.catch((error) => {
331
+ if (hasDetail("not_authorized")(error)) declaredAgent = false
332
+ return Effect.logDebug("agents.sessions.setStatus failed", error)
333
+ })
334
+ )
335
+ : Effect.void
336
+
337
+ // Files
338
+
339
+ /** A `denied` failure of an upload call refused a file. */
340
+ const refused = (error: ChatError): ChatError =>
341
+ error.reason.retry === "denied" ? Errors.chatError(error.op, Errors.fileRefused(error.reason)) : error
342
+
343
+ const stage = (file: File): Effect.Effect<{ readonly id: string; readonly title: string }, ChatError> =>
344
+ Effect.gen(function*() {
345
+ const answer = yield* call("post", "files.getUploadURLExternal", {
346
+ filename: file.name,
347
+ length: file.content.length
348
+ })
349
+ const uploadUrl = string(answer, "upload_url")
350
+ const fileId = string(answer, "file_id")
351
+ if (uploadUrl === undefined || fileId === undefined) {
352
+ return yield* fail("post", Errors.invalidResponse(false, "missing_upload_url"))
353
+ }
354
+ // Staging posts nothing, so every failure here is safe to retry.
355
+ const response = yield* options.http.execute(
356
+ HttpClientRequest.post(uploadUrl).pipe(HttpClientRequest.bodyUint8Array(file.content, file.contentType))
357
+ ).pipe(Effect.mapError((error) => Errors.chatError("post", Errors.transport(false, "upload_failed", error))))
358
+ if (response.status < 200 || response.status >= 300) {
359
+ return yield* fail("post", Errors.reasonForStatus(response.status, { write: false }))
360
+ }
361
+ return { id: fileId, title: file.name }
362
+ }).pipe(Effect.mapError(refused))
363
+
364
+ /** One call of the post, the attach or the rollback, cut off after `fileCallTimeout`. */
365
+ const bounded = <A>(effect: Effect.Effect<A, ChatError>, onTimeout: ChatErrorReason): Effect.Effect<A, ChatError> =>
366
+ Effect.timeoutOrElse(effect, { duration: fileCallTimeout, orElse: () => fail("post", onTimeout) })
367
+
368
+ /**
369
+ * Upload, post, then attach. The files are completed with no channel, so
370
+ * nothing is visible until `chat.postMessage`, and `chat.update` with
371
+ * `file_ids` attaches them. Both calls send the same body, with `text` under
372
+ * the update budget, so `text` never changes between them.
373
+ *
374
+ * From the post on, the route runs uninterruptible, with a timeout on each
375
+ * call and `attachDeadline` on the attach as a whole, retries and waits
376
+ * included. The attach replaces the file list, so it is retried. When it
377
+ * still fails, the message is deleted and then the files, best effort. If
378
+ * the delete fails or times out, the message may be left, with or without
379
+ * its files, and the post fails `uncertain` with a `SlackAttachFailed` as
380
+ * its cause. The files are kept so the ids it carries still mean something.
381
+ */
382
+ const postFiles = Effect.fnUntraced(function*(
383
+ thread: ChatThread,
384
+ parts: Address.Parts,
385
+ markdown: string,
386
+ files: ReadonlyArray<File>,
387
+ actions: ReadonlyArray<Action>,
388
+ notify: Escape.Notify,
389
+ unfurl: boolean
390
+ ) {
391
+ if (
392
+ files.length > descriptor.limits.filesPerMessage ||
393
+ files.some((file) => file.content.length > descriptor.limits.uploadBytes)
394
+ ) {
395
+ return yield* fail("post", new TooLarge({ subject: "files", detail: fileRefused }))
396
+ }
397
+ const content = Text.body(markdown, notify, Text.updateBudget)
398
+ const body = yield* messageContent(
399
+ "post",
400
+ Text.withActions(
401
+ content.text === "" ? Text.placeholder(files.map((file) => file.name), Text.updateBudget) : content,
402
+ actions
403
+ )
404
+ )
405
+ const staged = yield* Effect.forEach(files, stage)
406
+ yield* call("post", "files.completeUploadExternal", { files: staged }).pipe(Effect.mapError(refused))
407
+ const fileIds = staged.map((file) => file.id)
408
+ const channel = parts.channel
409
+
410
+ return yield* Effect.uninterruptible(Effect.gen(function*() {
411
+ const removeFiles = bounded(
412
+ Effect.forEach(fileIds, (file) => call("post", "files.delete", { file }, { write: true }).pipe(Effect.ignore), {
413
+ concurrency: "unbounded",
414
+ discard: true
415
+ }),
416
+ Errors.transport(true, "timeout")
417
+ ).pipe(Effect.ignore)
418
+ const ts = yield* bounded(
419
+ call("post", "chat.postMessage", {
420
+ channel,
421
+ thread_ts: parts.threadTs,
422
+ ...body,
423
+ unfurl_links: unfurl,
424
+ unfurl_media: unfurl
425
+ }, { write: true }).pipe(Effect.flatMap(tsOf("post", true))),
426
+ Errors.transport(true, "timeout")
427
+ ).pipe(Effect.tapError(() => removeFiles))
428
+ const posted: Posted = { id: ts, thread, timestamp: Normalize.timestamp(ts) }
429
+
430
+ const attached = yield* retrySafe(paced(
431
+ ts,
432
+ bounded(
433
+ call("post", "chat.update", { channel, ts, ...body, file_ids: fileIds }, { write: false, retry: false }),
434
+ Errors.transport(false, "timeout")
435
+ ),
436
+ "edit"
437
+ )).pipe(
438
+ Effect.timeoutOrElse({
439
+ duration: attachDeadline,
440
+ orElse: () => fail("post", Errors.transport(false, "attach_deadline"))
441
+ }),
442
+ Effect.result
443
+ )
444
+ if (Result.isSuccess(attached)) return posted
445
+
446
+ const error = attached.failure
447
+ yield* Effect.annotateCurrentSpan("slack.attach.failed", error.reason._tag)
448
+ const deleted = yield* bounded(
449
+ call("post", "chat.delete", { channel, ts }, { write: true }),
450
+ Errors.transport(true, "timeout")
451
+ ).pipe(Effect.result)
452
+ if (Result.isSuccess(deleted)) {
453
+ yield* removeFiles
454
+ return yield* Effect.fail(refused(error))
455
+ }
456
+ return yield* fail(
457
+ "post",
458
+ new Unknown({
459
+ detail: "attach_failed_message_left",
460
+ cause: options.attachFailed({ thread, messageId: ts, fileIds, reason: error.reason })
461
+ })
462
+ )
463
+ }))
464
+ })
465
+
466
+ // History
467
+
468
+ const page = (op: string, method: string, body: Record<string, unknown>) => (cursor: string | undefined) =>
469
+ call(op, method, { ...body, cursor }).pipe(
470
+ Effect.map((answer) => [messages(answer), nextCursor(answer)] as const)
471
+ )
472
+
473
+ const history: ChatAdapter["history"] = (thread, { direction, from }) =>
474
+ Stream.unwrap(Effect.gen(function*() {
475
+ const parts = yield* resolve("history", thread)
476
+ const botUserId = yield* options.botUserId
477
+ const context = { team: teamId, channel: parts.channel, botUserId }
478
+ const after = (message: ChatMessage) =>
479
+ from === undefined ||
480
+ (direction === "forward"
481
+ ? Address.compareTs(message.id, from) > 0
482
+ : Address.compareTs(message.id, from) < 0)
483
+ const normalized = (raw: Stream.Stream<Json, ChatError>) =>
484
+ raw.pipe(
485
+ Stream.map((message) => Normalize.message(message, context)),
486
+ Stream.filter((message): message is ChatMessage => message !== undefined && after(message))
487
+ )
488
+ const reversed = (stream: Stream.Stream<ChatMessage, ChatError>) =>
489
+ Stream.unwrap(Effect.map(Stream.runCollect(stream), (all) => Stream.fromIterable(Array.from(all).reverse())))
490
+ const bound = from === undefined ? {} : direction === "forward" ? { oldest: from } : { latest: from }
491
+ if (parts.threadTs !== undefined) {
492
+ // Oldest first, from the thread's start. Slack puts the opener on every page.
493
+ const threadTs = parts.threadTs
494
+ const replies = page("history", "conversations.replies", {
495
+ channel: parts.channel,
496
+ ts: threadTs,
497
+ limit: pageSize,
498
+ ...bound
499
+ })
500
+ const stream = normalized(
501
+ Stream.paginate(undefined as string | undefined, (cursor) =>
502
+ Effect.map(replies(cursor), ([found, next]) =>
503
+ [
504
+ cursor === undefined
505
+ ? found
506
+ : found.filter((message) => !(isObject(message) && message.ts === threadTs)),
507
+ next
508
+ ] as const))
509
+ )
510
+ return direction === "forward" ? stream : reversed(stream)
511
+ }
512
+ // Newest first. A reply broadcast to the channel is the thread's.
513
+ const stream = normalized(
514
+ Stream.paginate(
515
+ undefined as string | undefined,
516
+ page("history", "conversations.history", { channel: parts.channel, limit: pageSize, ...bound })
517
+ )
518
+ ).pipe(Stream.filter((message) => message.thread.id === thread.id))
519
+ return direction === "backward" ? stream : reversed(stream)
520
+ }))
521
+
522
+ // Native stream
523
+
524
+ /**
525
+ * The cleanup edit: once a stream is closed, a message whose appends
526
+ * differ from what the block path would send is rewritten once as blocks
527
+ * plus `text`, which takes out the zero-width spaces. It carries no
528
+ * `actions`, since the stop never does.
529
+ *
530
+ * It is skipped when the block would pass 12,000 and when the edit fails,
531
+ * leaving the characters, failing nothing and saying so on the span. A
532
+ * message whose last append is unsettled is left to the layer's repair,
533
+ * which rewrites it, so it gets no second edit. An allowed token in the
534
+ * message does not skip it: an edit that keeps a real mention sends no
535
+ * second push (EFF-3740).
536
+ *
537
+ * An interrupted cleanup leaves the message marked not cleaned, so the
538
+ * stop the layer's finaliser sends again runs it again.
539
+ */
540
+ const cleanupEdit = Effect.fnUntraced(function*(
541
+ op: string,
542
+ channel: string,
543
+ messageId: string,
544
+ state: StreamState,
545
+ notify: Escape.Notify
546
+ ) {
547
+ const block = Escape.escape(state.markdown, notify, { flush: true }).sent
548
+ if (block === state.sent) return
549
+ const skip = (reason: string) => Effect.annotateCurrentSpan("slack.stream.cleanup", reason)
550
+ if (!state.settled) return yield* skip("unsettled")
551
+ const body = Text.body(state.markdown, notify, Text.updateBudget)
552
+ if (Length.codePoints(body.sent) > Length.messageLength) return yield* skip("too_long")
553
+ if (body.dropped > 0) yield* Effect.annotateCurrentSpan("slack.text.dropped_tokens", body.dropped)
554
+ const edited = yield* paced(
555
+ messageId,
556
+ call(op, "chat.update", { channel, ts: messageId, blocks: body.blocks, text: body.text }, {
557
+ write: true,
558
+ retry: false
559
+ }),
560
+ "edit"
561
+ ).pipe(Effect.result)
562
+ yield* Effect.annotateCurrentSpan("slack.stream.cleanup", Result.isSuccess(edited) ? "edited" : "failed")
563
+ })
564
+
565
+ /**
566
+ * Moves the agent session of a stopped stream off `processing`, once. It is
567
+ * marked only after the call, so an interrupted one runs again on the stop
568
+ * the layer's finaliser sends.
569
+ */
570
+ const endSession = (
571
+ channel: string,
572
+ threadTs: string | undefined,
573
+ messageId: string,
574
+ status: SessionStatus
575
+ ): Effect.Effect<void> =>
576
+ Effect.suspend(() => {
577
+ if (threadTs === undefined || streams.get(messageId)?.ended === true) return Effect.void
578
+ return Effect.andThen(
579
+ sessionStatus(channel, threadTs, status),
580
+ Effect.sync(() => {
581
+ const state = streams.get(messageId)
582
+ if (state !== undefined) streams.set(messageId, { ...state, ended: true })
583
+ })
584
+ )
585
+ })
586
+
587
+ const cleanup = (op: string, channel: string, messageId: string, notify: Escape.Notify): Effect.Effect<void> =>
588
+ Effect.suspend(() => {
589
+ const state = streams.get(messageId)
590
+ if (state === undefined || state.cleaned) return Effect.void
591
+ return Effect.andThen(
592
+ cleanupEdit(op, channel, messageId, state, notify),
593
+ Effect.sync(() => void streams.set(messageId, { ...state, cleaned: true }))
594
+ )
595
+ })
596
+
597
+ const nativeStream: NonNullable<ChatAdapter["nativeStream"]> = {
598
+ start: Effect.fnUntraced(function*(thread, start) {
599
+ const op = "nativeStream.start"
600
+ const postOptions = yield* CurrentPostOptions
601
+ if (postOptions.nativeStream === false) {
602
+ return yield* fail(op, new Unsupported({ capability: "nativeStream", detail: "disabled" }))
603
+ }
604
+ const parts = yield* resolve(op, thread)
605
+ if (parts.threadTs === undefined || start.recipient === undefined || start.replyTo !== undefined) {
606
+ return yield* fail(op, new Unsupported({ capability: "nativeStream" }))
607
+ }
608
+ const escaped = Escape.escapeStream(start.markdown, postOptions.notify ?? {}, { flush: true })
609
+ // Slack blanks a message whose surrogate pair is split across two appends.
610
+ const sent = Str.toWellFormed(escaped.sent)
611
+ yield* checkSent(op, sent)
612
+ const startCall = call(op, "chat.startStream", {
613
+ channel: parts.channel,
614
+ thread_ts: parts.threadTs,
615
+ recipient_user_id: start.recipient,
616
+ recipient_team_id: postOptions.recipientTeamId ?? parts.team,
617
+ markdown_text: sent === "" ? undefined : sent
618
+ }, { write: true, retry: false }).pipe(
619
+ Effect.catchIf(
620
+ (error) => error.reason.detail !== undefined && streamUnsupported.has(error.reason.detail),
621
+ (error) =>
622
+ fail(
623
+ op,
624
+ new Unsupported({
625
+ capability: "nativeStream",
626
+ ...(error.reason.detail === undefined ? {} : { detail: error.reason.detail }),
627
+ cause: error
628
+ })
629
+ )
630
+ )
631
+ )
632
+ // A later part of a reply goes at the reply's pace, and keeps it.
633
+ const continues = start.continues
634
+ const answer = yield* (continues === undefined ? startCall : paced(continues, startCall, "stream"))
635
+ const ts = yield* tsOf(op, true)(answer)
636
+ const backoff = continues === undefined ? undefined : backoffs.get(continues)
637
+ if (backoff !== undefined) backoffs.set(ts, backoff)
638
+ streams.set(ts, openStream(escaped.state, start.markdown, sent))
639
+ return { id: ts, thread, timestamp: Normalize.timestamp(ts) }
640
+ }),
641
+ append: Effect.fnUntraced(function*(thread, messageId, markdown, appendOptions) {
642
+ const op = "nativeStream.append"
643
+ const parts = yield* resolve(op, thread)
644
+ const postOptions = yield* CurrentPostOptions
645
+ const state = streams.get(messageId) ?? openStream(Escape.initialState, "", "")
646
+ const flush = appendOptions?.flush === true
647
+ // A trailing high surrogate waits for its other half.
648
+ const input = !flush && /[\ud800-\udbff]$/.test(markdown) ? markdown.slice(0, -1) : markdown
649
+ const escaped = Escape.escapeStream(input, postOptions.notify ?? {}, { state: state.escape, flush })
650
+ const held = markdown.length - escaped.consumed
651
+ if (escaped.sent === "") return { state: "open" as const, held }
652
+ const sent = Str.toWellFormed(escaped.sent)
653
+ yield* checkSent(op, state.sent + sent)
654
+ const unsettle = Effect.sync(() => streams.set(messageId, { ...state, settled: false }))
655
+ return yield* paced(
656
+ messageId,
657
+ Effect.andThen(
658
+ unsettle,
659
+ call(op, "chat.appendStream", { channel: parts.channel, ts: messageId, markdown_text: sent }, {
660
+ write: true,
661
+ retry: false
662
+ })
663
+ ),
664
+ "stream"
665
+ ).pipe(
666
+ Effect.map(() => {
667
+ streams.set(
668
+ messageId,
669
+ openStream(escaped.state, state.markdown + input.slice(0, escaped.consumed), state.sent + sent)
670
+ )
671
+ return { state: "open" as const, held }
672
+ }),
673
+ Effect.catchIf(
674
+ hasDetail("message_not_in_streaming_state"),
675
+ () =>
676
+ Effect.sync(() => {
677
+ // The layer carries on by editing the message, and sends no stop.
678
+ streams.delete(messageId)
679
+ return { state: "closed" as const, held: 0 }
680
+ })
681
+ ),
682
+ // Slack closed the stream and the reply ends stopped. The layer sends no stop after this, so the
683
+ // cleanup and the session status go here.
684
+ Effect.catchIf(
685
+ hasDetail("stopped_by_user"),
686
+ () =>
687
+ Effect.sync(() => streams.set(messageId, { ...state, stopped: true })).pipe(
688
+ Effect.andThen(cleanup(op, parts.channel, messageId, postOptions.notify ?? {})),
689
+ Effect.andThen(
690
+ endSession(parts.channel, parts.threadTs, messageId, postOptions.sessionStatusAtEnd ?? "active")
691
+ ),
692
+ Effect.as({ state: "stopped" as const, held: 0 })
693
+ )
694
+ ),
695
+ Effect.tapError((error) =>
696
+ Effect.sync(() => {
697
+ if (error.retry === "denied") streams.set(messageId, state)
698
+ })
699
+ )
700
+ )
701
+ }),
702
+ stop: Effect.fnUntraced(function*(thread, messageId, stopOptions) {
703
+ const op = "nativeStream.stop"
704
+ const parts = yield* resolve(op, thread)
705
+ const postOptions = yield* CurrentPostOptions
706
+ const state = streams.get(messageId)
707
+ // A rotating stop keeps the reply's backoff for its next part.
708
+ const backoff = backoffs.get(messageId)
709
+ if (backoff !== undefined && stopOptions.end === "done") {
710
+ for (const [key, value] of backoffs) if (value === backoff) backoffs.delete(key)
711
+ }
712
+ const status = stopOptions.end === "rotating" ? "processing" : postOptions.sessionStatusAtEnd
713
+ const body = { channel: parts.channel, ts: messageId }
714
+ const stop = status === undefined || !declaredAgent
715
+ ? call(op, "chat.stopStream", body, { write: true, retry: false })
716
+ : call(op, "chat.stopStream", { ...body, session_status: status }, { write: true, retry: false }).pipe(
717
+ Effect.catchIf(hasDetail("not_authorized"), () => {
718
+ declaredAgent = false
719
+ return call(op, "chat.stopStream", body, { write: true, retry: false })
720
+ })
721
+ )
722
+ const answer = yield* stop.pipe(
723
+ Effect.catchIf(hasDetail("message_not_in_streaming_state"), () => Effect.succeed(undefined))
724
+ )
725
+ const stopped = state?.stopped === true || string(answer, "result_status") === "stopped_by_user" ||
726
+ string(object(object(answer, "message"), "ai_context"), "result_status") === "stopped_by_user"
727
+ // Remember stopped_by_user across interruptions, even if a retry finds no open stream.
728
+ const current = streams.get(messageId)
729
+ if (stopped && current !== undefined) streams.set(messageId, { ...current, stopped: true })
730
+ yield* cleanup(op, parts.channel, messageId, postOptions.notify ?? {})
731
+ if (stopped && stopOptions.end === "done") {
732
+ yield* endSession(parts.channel, parts.threadTs, messageId, postOptions.sessionStatusAtEnd ?? "active")
733
+ }
734
+ // Retain stream state until cleanup and session completion finish.
735
+ streams.delete(messageId)
736
+ return { stopped }
737
+ })
738
+ }
739
+
740
+ // Users
741
+
742
+ const user = (id: string): Effect.Effect<SlackUser, ChatError> =>
743
+ call("user", "users.info", { user: id }).pipe(
744
+ Effect.flatMap((answer) => {
745
+ const raw = object(answer, "user")
746
+ const userId = string(raw, "id")
747
+ if (raw === undefined || userId === undefined) {
748
+ return fail("user", Errors.invalidResponse(false, "missing_user"))
749
+ }
750
+ const userTeam = string(raw, "team_id") ?? teamId
751
+ return Effect.succeed<SlackUser>({
752
+ id: userId,
753
+ teamId: userTeam,
754
+ name: userName(raw),
755
+ isBot: raw.is_bot === true,
756
+ isRestricted: raw.is_restricted === true,
757
+ isUltraRestricted: raw.is_ultra_restricted === true,
758
+ isStranger: raw.is_stranger === true || (userTeam !== teamId && raw.enterprise_user === undefined),
759
+ deleted: raw.deleted === true,
760
+ raw
761
+ })
762
+ })
763
+ )
764
+
765
+ /** A `bot_message` author is a bot id, which `users.info` answers with `NotFound`. */
766
+ const getUser: ChatAdapter["getUser"] = Effect.fnUntraced(function*(id) {
767
+ const botUserId = yield* options.botUserId
768
+ const found = yield* user(id).pipe(Effect.mapError(Errors.withOp("getUser")))
769
+ return { id: found.id, name: found.name, isBot: found.isBot, isSelf: found.id === botUserId, raw: found.raw }
770
+ })
771
+
772
+ /**
773
+ * The body of a command's answer, `Respond` or `followUp`: what a `post`
774
+ * of the same content sends with the default post options, after the same
775
+ * checks, with its `response_type`. `withPostOptions` does not reach it,
776
+ * so it notifies nobody and unfurls nothing.
777
+ */
778
+ const answer = Effect.fnUntraced(function*(
779
+ op: string,
780
+ content: { readonly markdown: string; readonly actions?: ReadonlyArray<Action> | undefined },
781
+ visibility: Visibility
782
+ ) {
783
+ const actions = content.actions ?? []
784
+ yield* checkActions(op, actions)
785
+ const body = yield* messageContent(op, Text.body(content.markdown, {}, Text.postBudget, actions))
786
+ return { response_type: responseType(visibility), ...body, unfurl_links: false, unfurl_media: false }
787
+ })
788
+
789
+ const responseUrl = (op: string, deferred: Defer): Effect.Effect<URL, ChatError> => {
790
+ const raw = deferred.command.raw
791
+ const value = string(raw, "response_url")
792
+ const url = value === undefined || !URL.canParse(value) ? undefined : new URL(value)
793
+ return url !== undefined && url.protocol === "https:" && isSlackHost(url.hostname)
794
+ ? Effect.succeed(url)
795
+ : fail(op, Errors.invalidRequest("invalid_response_url"))
796
+ }
797
+
798
+ /**
799
+ * One POST to the command's `response_url`, never retried. A spent URL is
800
+ * `NotFound` with detail `interaction_expired`.
801
+ */
802
+ const followUp: ChatAdapter["followUp"] = Effect.fnUntraced(function*(deferred, content) {
803
+ const op = "followUp"
804
+ const url = yield* responseUrl(op, deferred)
805
+ const body = yield* answer(op, content, deferred.visibility)
806
+ const response = yield* options.http.execute(
807
+ HttpClientRequest.post(url).pipe(HttpClientRequest.bodyJsonUnsafe(body))
808
+ ).pipe(Effect.mapError((error) => Errors.chatError(op, Errors.transport(true, error.reason._tag, error))))
809
+ if (response.status >= 200 && response.status < 300) return
810
+ const text = yield* Effect.orElseSucceed(response.text, () => "")
811
+ const parsed = parse(text)
812
+ const code = parsed === undefined
813
+ ? text.trim() === "" ? undefined : text.trim()
814
+ : string(parsed, "error")
815
+ if (response.status === 404 || response.status === 410 || (code !== undefined && spentResponseUrl.has(code))) {
816
+ return yield* fail(
817
+ op,
818
+ new NotFound({ detail: interactionExpired, ...(code === undefined ? {} : { cause: code }) })
819
+ )
820
+ }
821
+ return yield* fail(op, Errors.reasonForStatus(response.status, { write: true, cause: code }))
822
+ })
823
+
824
+ const adapter: ChatAdapter = {
825
+ descriptor,
826
+ nativeStream,
827
+ followUp,
828
+ post: Effect.fnUntraced(function*(thread, content) {
829
+ const parts = yield* resolve("post", thread)
830
+ if (content.replyTo !== undefined) return yield* fail("post", new Unsupported({ capability: "replyTo" }))
831
+ const actions = content.actions ?? []
832
+ yield* checkActions("post", actions)
833
+ const postOptions = yield* CurrentPostOptions
834
+ const notify = postOptions.notify ?? {}
835
+ const unfurl = postOptions.unfurl === true
836
+ if (content.files !== undefined && content.files.length > 0) {
837
+ return yield* postFiles(thread, parts, content.markdown, content.files, actions, notify, unfurl)
838
+ }
839
+ const body = yield* messageContent("post", Text.body(content.markdown, notify, Text.postBudget, actions))
840
+ const ts = yield* call("post", "chat.postMessage", {
841
+ channel: parts.channel,
842
+ thread_ts: parts.threadTs,
843
+ ...body,
844
+ unfurl_links: unfurl,
845
+ unfurl_media: unfurl
846
+ }, { write: true }).pipe(Effect.flatMap(tsOf("post", true)))
847
+ return { id: ts, thread, timestamp: Normalize.timestamp(ts) }
848
+ }),
849
+ edit: Effect.fnUntraced(function*(thread, messageId, content) {
850
+ const parts = yield* resolve("edit", thread)
851
+ const actions = content.actions ?? []
852
+ yield* checkActions("edit", actions)
853
+ const postOptions = yield* CurrentPostOptions
854
+ const body = yield* messageContent(
855
+ "edit",
856
+ Text.body(content.markdown, postOptions.notify ?? {}, Text.updateBudget, actions)
857
+ )
858
+ yield* retrySafe(paced(
859
+ messageId,
860
+ call("edit", "chat.update", { channel: parts.channel, ts: messageId, ...body }, {
861
+ write: true,
862
+ retry: false
863
+ }),
864
+ "edit"
865
+ ))
866
+ }),
867
+ delete: Effect.fnUntraced(function*(thread, messageId) {
868
+ const parts = yield* resolve("delete", thread)
869
+ const body = { channel: parts.channel, ts: messageId }
870
+ yield* call("delete", "chat.delete", body, { write: true }).pipe(
871
+ // Slack refuses to delete an open stream: stop it, then delete.
872
+ Effect.catchIf(
873
+ hasDetail("cant_delete_message"),
874
+ (error) =>
875
+ call("delete", "chat.stopStream", body, { write: true, retry: false }).pipe(
876
+ Effect.matchEffect({
877
+ onFailure: () => Effect.fail(error),
878
+ onSuccess: () => {
879
+ streams.delete(messageId)
880
+ return call("delete", "chat.delete", body, { write: true })
881
+ }
882
+ })
883
+ )
884
+ )
885
+ )
886
+ }),
887
+ fetchMessage: (thread, messageId) => fetchMessage("fetchMessage", thread, messageId),
888
+ history,
889
+ download: (thread, attachment, { maxBytes }) =>
890
+ Stream.unwrap(Effect.gen(function*() {
891
+ const op = "download"
892
+ yield* resolve(op, thread)
893
+ const tooLarge = Errors.chatError(op, new TooLarge({ subject: "files", detail: "max_bytes" }))
894
+ if (attachment.size !== undefined && attachment.size > maxBytes) return yield* Effect.fail(tooLarge)
895
+ const answer = yield* call(op, "files.info", { file: attachment.id })
896
+ const file = object(answer, "file")
897
+ const url = string(file, "url_private_download") ?? string(file, "url_private")
898
+ if (url === undefined) return yield* fail(op, Errors.invalidResponse(false, "missing_url"))
899
+ const response = yield* options.http.execute(
900
+ HttpClientRequest.get(url).pipe(HttpClientRequest.bearerToken(Redacted.value(options.botToken)))
901
+ ).pipe(Effect.mapError((error) => Errors.chatError(op, Errors.transport(false, error.reason._tag, error))))
902
+ if (response.status < 200 || response.status >= 300) {
903
+ return yield* fail(op, Errors.reasonForStatus(response.status, { write: false }))
904
+ }
905
+ let received = 0
906
+ return response.stream.pipe(
907
+ Stream.mapError((error) => Errors.chatError(op, Errors.transport(false, error.reason._tag, error))),
908
+ Stream.mapEffect((chunk) => {
909
+ received += chunk.length
910
+ return received > maxBytes ? Effect.fail(tooLarge) : Effect.succeed(chunk)
911
+ })
912
+ )
913
+ })),
914
+ startThread: (thread, messageId) =>
915
+ resolve("startThread", thread).pipe(
916
+ Effect.map((parts) =>
917
+ parts.threadTs === undefined
918
+ ? Address.thread({ team: parts.team, channel: parts.channel, threadTs: messageId })
919
+ : thread
920
+ )
921
+ ),
922
+ getThread: Effect.fnUntraced(function*(thread) {
923
+ const parts = yield* resolve("getThread", thread)
924
+ const answer = yield* call("getThread", "conversations.info", { channel: parts.channel })
925
+ const channel = object(answer, "channel")
926
+ if (channel === undefined) return yield* fail("getThread", Errors.invalidResponse(false, "missing_channel"))
927
+ const direct = channel.is_im === true || channel.is_mpim === true
928
+ const topicValue = string(object(channel, "topic"), "value")
929
+ const name = direct ? undefined : string(channel, "name")
930
+ const created = channel.created
931
+ const createdAt = parts.threadTs !== undefined
932
+ ? Normalize.timestamp(parts.threadTs)
933
+ : typeof created === "number" && Number.isFinite(created)
934
+ ? DateTime.makeUnsafe(created * 1000)
935
+ : undefined
936
+ return {
937
+ thread,
938
+ kind: parts.threadTs !== undefined ? "thread" : direct ? "direct" : "channel",
939
+ ...(parts.threadTs === undefined && name !== undefined ? { name } : {}),
940
+ ...(parts.threadTs === undefined && topicValue !== undefined ? { topic: topicValue } : {}),
941
+ ...(parts.threadTs === undefined
942
+ ? {}
943
+ : { parent: Address.thread({ team: parts.team, channel: parts.channel }) }),
944
+ ...(createdAt === undefined ? {} : { createdAt }),
945
+ raw: channel
946
+ } satisfies ThreadInfo
947
+ }),
948
+ opener: Effect.fnUntraced(function*(thread) {
949
+ const parts = yield* resolve("opener", thread)
950
+ if (parts.threadTs === undefined) return Option.none()
951
+ const channelAddress = Address.thread({ team: parts.team, channel: parts.channel })
952
+ return yield* fetchMessage("opener", channelAddress, parts.threadTs).pipe(
953
+ Effect.map(Option.some),
954
+ Effect.catchIf((error) => error.reason._tag === "NotFound", () => Effect.succeed(Option.none()))
955
+ )
956
+ }),
957
+ getUser
958
+ }
959
+
960
+ return { adapter, user, answer }
961
+ }