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