effect 4.1.4 → 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 (723) hide show
  1. package/THIRD_PARTY_NOTICES.md +88 -0
  2. package/ai-docs/package.json +2 -2
  3. package/dist/Arbitrary.d.ts +44 -2
  4. package/dist/Arbitrary.d.ts.map +1 -1
  5. package/dist/Arbitrary.js +9 -1
  6. package/dist/Arbitrary.js.map +1 -1
  7. package/dist/BigInt.d.ts +200 -1
  8. package/dist/BigInt.d.ts.map +1 -1
  9. package/dist/BigInt.js +105 -9
  10. package/dist/BigInt.js.map +1 -1
  11. package/dist/Cache.d.ts.map +1 -1
  12. package/dist/Cache.js +4 -2
  13. package/dist/Cache.js.map +1 -1
  14. package/dist/Cause.d.ts +3 -3
  15. package/dist/Cause.js +1 -1
  16. package/dist/Chunk.d.ts +5 -0
  17. package/dist/Chunk.d.ts.map +1 -1
  18. package/dist/Chunk.js +7 -2
  19. package/dist/Chunk.js.map +1 -1
  20. package/dist/Clock.d.ts +5 -2
  21. package/dist/Clock.d.ts.map +1 -1
  22. package/dist/Clock.js +2 -1
  23. package/dist/Clock.js.map +1 -1
  24. package/dist/Codegen.d.ts +295 -0
  25. package/dist/Codegen.d.ts.map +1 -0
  26. package/dist/Codegen.js +521 -0
  27. package/dist/Codegen.js.map +1 -0
  28. package/dist/Config.d.ts +31 -2
  29. package/dist/Config.d.ts.map +1 -1
  30. package/dist/Config.js +12 -1
  31. package/dist/Config.js.map +1 -1
  32. package/dist/ConfigProvider.d.ts +11 -1
  33. package/dist/ConfigProvider.d.ts.map +1 -1
  34. package/dist/ConfigProvider.js +17 -6
  35. package/dist/ConfigProvider.js.map +1 -1
  36. package/dist/Effect.d.ts +869 -109
  37. package/dist/Effect.d.ts.map +1 -1
  38. package/dist/Effect.js +400 -47
  39. package/dist/Effect.js.map +1 -1
  40. package/dist/Equivalence.d.ts +11 -9
  41. package/dist/Equivalence.d.ts.map +1 -1
  42. package/dist/Equivalence.js +15 -12
  43. package/dist/Equivalence.js.map +1 -1
  44. package/dist/Fiber.d.ts +58 -8
  45. package/dist/Fiber.d.ts.map +1 -1
  46. package/dist/Fiber.js +28 -4
  47. package/dist/Fiber.js.map +1 -1
  48. package/dist/FiberHandle.d.ts +81 -10
  49. package/dist/FiberHandle.d.ts.map +1 -1
  50. package/dist/FiberHandle.js +40 -8
  51. package/dist/FiberHandle.js.map +1 -1
  52. package/dist/FiberMap.d.ts +80 -10
  53. package/dist/FiberMap.d.ts.map +1 -1
  54. package/dist/FiberMap.js +37 -6
  55. package/dist/FiberMap.js.map +1 -1
  56. package/dist/FiberSet.d.ts +93 -8
  57. package/dist/FiberSet.d.ts.map +1 -1
  58. package/dist/FiberSet.js +46 -4
  59. package/dist/FiberSet.js.map +1 -1
  60. package/dist/Formatter.d.ts +2 -0
  61. package/dist/Formatter.d.ts.map +1 -1
  62. package/dist/Formatter.js +2 -0
  63. package/dist/Formatter.js.map +1 -1
  64. package/dist/LayerMap.d.ts +12 -3
  65. package/dist/LayerMap.d.ts.map +1 -1
  66. package/dist/LayerMap.js +12 -2
  67. package/dist/LayerMap.js.map +1 -1
  68. package/dist/LayerRef.d.ts +2 -2
  69. package/dist/Match.d.ts +12 -0
  70. package/dist/Match.d.ts.map +1 -1
  71. package/dist/Match.js +16 -0
  72. package/dist/Match.js.map +1 -1
  73. package/dist/Metric.js +1 -1
  74. package/dist/Metric.js.map +1 -1
  75. package/dist/Option.d.ts +4 -1
  76. package/dist/Option.d.ts.map +1 -1
  77. package/dist/Option.js +6 -2
  78. package/dist/Option.js.map +1 -1
  79. package/dist/Order.d.ts +7 -5
  80. package/dist/Order.d.ts.map +1 -1
  81. package/dist/Order.js +7 -2
  82. package/dist/Order.js.map +1 -1
  83. package/dist/Pool.d.ts +4 -3
  84. package/dist/Pool.d.ts.map +1 -1
  85. package/dist/Pool.js +21 -18
  86. package/dist/Pool.js.map +1 -1
  87. package/dist/Predicate.d.ts +4 -1
  88. package/dist/Predicate.d.ts.map +1 -1
  89. package/dist/Predicate.js +5 -1
  90. package/dist/Predicate.js.map +1 -1
  91. package/dist/Queue.d.ts +69 -22
  92. package/dist/Queue.d.ts.map +1 -1
  93. package/dist/Queue.js +40 -18
  94. package/dist/Queue.js.map +1 -1
  95. package/dist/Rational.d.ts +179 -0
  96. package/dist/Rational.d.ts.map +1 -1
  97. package/dist/Rational.js +63 -0
  98. package/dist/Rational.js.map +1 -1
  99. package/dist/Request.d.ts +20 -0
  100. package/dist/Request.d.ts.map +1 -1
  101. package/dist/Request.js +20 -0
  102. package/dist/Request.js.map +1 -1
  103. package/dist/Result.d.ts +3 -1
  104. package/dist/Result.d.ts.map +1 -1
  105. package/dist/Result.js +5 -2
  106. package/dist/Result.js.map +1 -1
  107. package/dist/Schema.d.ts +49 -19
  108. package/dist/Schema.d.ts.map +1 -1
  109. package/dist/Schema.js +44 -27
  110. package/dist/Schema.js.map +1 -1
  111. package/dist/SchemaAST.d.ts.map +1 -1
  112. package/dist/SchemaAST.js +11 -4
  113. package/dist/SchemaAST.js.map +1 -1
  114. package/dist/SchemaGetter.d.ts +5 -6
  115. package/dist/SchemaGetter.d.ts.map +1 -1
  116. package/dist/SchemaGetter.js +14 -10
  117. package/dist/SchemaGetter.js.map +1 -1
  118. package/dist/SchemaRepresentation.d.ts +19 -64
  119. package/dist/SchemaRepresentation.d.ts.map +1 -1
  120. package/dist/SchemaRepresentation.js +1 -28
  121. package/dist/SchemaRepresentation.js.map +1 -1
  122. package/dist/SchemaTransformation.d.ts +11 -10
  123. package/dist/SchemaTransformation.d.ts.map +1 -1
  124. package/dist/SchemaTransformation.js +12 -11
  125. package/dist/SchemaTransformation.js.map +1 -1
  126. package/dist/Scope.d.ts +12 -6
  127. package/dist/Scope.d.ts.map +1 -1
  128. package/dist/Scope.js +12 -6
  129. package/dist/Scope.js.map +1 -1
  130. package/dist/ScopedCache.d.ts.map +1 -1
  131. package/dist/ScopedCache.js +2 -1
  132. package/dist/ScopedCache.js.map +1 -1
  133. package/dist/Semaphore.d.ts.map +1 -1
  134. package/dist/Semaphore.js +18 -4
  135. package/dist/Semaphore.js.map +1 -1
  136. package/dist/Stream.d.ts.map +1 -1
  137. package/dist/Stream.js +55 -14
  138. package/dist/Stream.js.map +1 -1
  139. package/dist/String.d.ts +57 -3
  140. package/dist/String.d.ts.map +1 -1
  141. package/dist/String.js +62 -4
  142. package/dist/String.js.map +1 -1
  143. package/dist/Struct.d.ts +135 -1
  144. package/dist/Struct.d.ts.map +1 -1
  145. package/dist/Struct.js +64 -5
  146. package/dist/Struct.js.map +1 -1
  147. package/dist/TextDiff.d.ts +105 -0
  148. package/dist/TextDiff.d.ts.map +1 -1
  149. package/dist/TextDiff.js +137 -24
  150. package/dist/TextDiff.js.map +1 -1
  151. package/dist/TxPriorityQueue.js +2 -2
  152. package/dist/TxPriorityQueue.js.map +1 -1
  153. package/dist/ai/LanguageModel.d.ts.map +1 -1
  154. package/dist/ai/LanguageModel.js +1 -1
  155. package/dist/ai/LanguageModel.js.map +1 -1
  156. package/dist/ai/McpSchema.d.ts +88 -88
  157. package/dist/ai/McpSchema.d.ts.map +1 -1
  158. package/dist/ai/McpServer.d.ts +47 -2
  159. package/dist/ai/McpServer.d.ts.map +1 -1
  160. package/dist/ai/McpServer.js +135 -16
  161. package/dist/ai/McpServer.js.map +1 -1
  162. package/dist/ai/Tool.d.ts +3 -2
  163. package/dist/ai/Tool.d.ts.map +1 -1
  164. package/dist/ai/Tool.js +3 -2
  165. package/dist/ai/Tool.js.map +1 -1
  166. package/dist/ai/Toolkit.d.ts.map +1 -1
  167. package/dist/ai/Toolkit.js +5 -1
  168. package/dist/ai/Toolkit.js.map +1 -1
  169. package/dist/chat/Chat.d.ts +90 -0
  170. package/dist/chat/Chat.d.ts.map +1 -0
  171. package/dist/chat/Chat.js +127 -0
  172. package/dist/chat/Chat.js.map +1 -0
  173. package/dist/chat/ChatAdapter.d.ts +386 -0
  174. package/dist/chat/ChatAdapter.d.ts.map +1 -0
  175. package/dist/chat/ChatAdapter.js +110 -0
  176. package/dist/chat/ChatAdapter.js.map +1 -0
  177. package/dist/chat/ChatError.d.ts +500 -0
  178. package/dist/chat/ChatError.d.ts.map +1 -0
  179. package/dist/chat/ChatError.js +521 -0
  180. package/dist/chat/ChatError.js.map +1 -0
  181. package/dist/chat/ChatEvent.d.ts +321 -0
  182. package/dist/chat/ChatEvent.d.ts.map +1 -0
  183. package/dist/chat/ChatEvent.js +163 -0
  184. package/dist/chat/ChatEvent.js.map +1 -0
  185. package/dist/chat/ChatHandler.d.ts +81 -0
  186. package/dist/chat/ChatHandler.d.ts.map +1 -0
  187. package/dist/chat/ChatHandler.js +85 -0
  188. package/dist/chat/ChatHandler.js.map +1 -0
  189. package/dist/chat/ChatInteraction.d.ts +1519 -0
  190. package/dist/chat/ChatInteraction.d.ts.map +1 -0
  191. package/dist/chat/ChatInteraction.js +1052 -0
  192. package/dist/chat/ChatInteraction.js.map +1 -0
  193. package/dist/chat/ChatMarkdown.d.ts +280 -0
  194. package/dist/chat/ChatMarkdown.d.ts.map +1 -0
  195. package/dist/chat/ChatMarkdown.js +1172 -0
  196. package/dist/chat/ChatMarkdown.js.map +1 -0
  197. package/dist/chat/ChatMessage.d.ts +224 -0
  198. package/dist/chat/ChatMessage.d.ts.map +1 -0
  199. package/dist/chat/ChatMessage.js +172 -0
  200. package/dist/chat/ChatMessage.js.map +1 -0
  201. package/dist/chat/ChatTest.d.ts +407 -0
  202. package/dist/chat/ChatTest.d.ts.map +1 -0
  203. package/dist/chat/ChatTest.js +2145 -0
  204. package/dist/chat/ChatTest.js.map +1 -0
  205. package/dist/chat/ChatThread.d.ts +92 -0
  206. package/dist/chat/ChatThread.d.ts.map +1 -0
  207. package/dist/chat/ChatThread.js +116 -0
  208. package/dist/chat/ChatThread.js.map +1 -0
  209. package/dist/chat/ChatUi.d.ts +362 -0
  210. package/dist/chat/ChatUi.d.ts.map +1 -0
  211. package/dist/chat/ChatUi.js +209 -0
  212. package/dist/chat/ChatUi.js.map +1 -0
  213. package/dist/chat/index.d.ts +60 -0
  214. package/dist/chat/index.d.ts.map +1 -0
  215. package/dist/chat/index.js +61 -0
  216. package/dist/chat/index.js.map +1 -0
  217. package/dist/chat/internal/retries.d.ts +2 -0
  218. package/dist/chat/internal/retries.d.ts.map +1 -0
  219. package/dist/chat/internal/retries.js +7 -0
  220. package/dist/chat/internal/retries.js.map +1 -0
  221. package/dist/cli/CliOutput.d.ts.map +1 -1
  222. package/dist/cli/CliOutput.js +6 -7
  223. package/dist/cli/CliOutput.js.map +1 -1
  224. package/dist/cli/Command.d.ts +20 -2
  225. package/dist/cli/Command.d.ts.map +1 -1
  226. package/dist/cli/Command.js +4 -0
  227. package/dist/cli/Command.js.map +1 -1
  228. package/dist/cli/Prompt.d.ts +5 -6
  229. package/dist/cli/Prompt.d.ts.map +1 -1
  230. package/dist/cli/Prompt.js +9 -4
  231. package/dist/cli/Prompt.js.map +1 -1
  232. package/dist/cli/internal/command.d.ts +1 -1
  233. package/dist/cli/internal/command.d.ts.map +1 -1
  234. package/dist/cli/internal/config.d.ts +1 -1
  235. package/dist/cli/internal/config.d.ts.map +1 -1
  236. package/dist/cli/internal/config.js +3 -3
  237. package/dist/cli/internal/config.js.map +1 -1
  238. package/dist/cluster/ClusterCron.d.ts +21 -1
  239. package/dist/cluster/ClusterCron.d.ts.map +1 -1
  240. package/dist/cluster/ClusterCron.js +24 -6
  241. package/dist/cluster/ClusterCron.js.map +1 -1
  242. package/dist/cluster/ClusterWorkflowEngine.d.ts.map +1 -1
  243. package/dist/cluster/ClusterWorkflowEngine.js +30 -22
  244. package/dist/cluster/ClusterWorkflowEngine.js.map +1 -1
  245. package/dist/cluster/Sharding.d.ts.map +1 -1
  246. package/dist/cluster/Sharding.js +15 -3
  247. package/dist/cluster/Sharding.js.map +1 -1
  248. package/dist/cluster/ShardingConfig.d.ts +6 -0
  249. package/dist/cluster/ShardingConfig.d.ts.map +1 -1
  250. package/dist/cluster/ShardingConfig.js.map +1 -1
  251. package/dist/cluster/SqlMessageStorage.d.ts.map +1 -1
  252. package/dist/cluster/SqlMessageStorage.js +13 -15
  253. package/dist/cluster/SqlMessageStorage.js.map +1 -1
  254. package/dist/cluster/SqlRunnerStorage.d.ts.map +1 -1
  255. package/dist/cluster/SqlRunnerStorage.js +18 -8
  256. package/dist/cluster/SqlRunnerStorage.js.map +1 -1
  257. package/dist/cluster/internal/entityManager.js +12 -8
  258. package/dist/cluster/internal/entityManager.js.map +1 -1
  259. package/dist/cluster/internal/entityReaper.js +1 -1
  260. package/dist/cluster/internal/entityReaper.js.map +1 -1
  261. package/dist/crypto/Kdf.d.ts +2 -1
  262. package/dist/crypto/Kdf.d.ts.map +1 -1
  263. package/dist/crypto/Kdf.js +2 -1
  264. package/dist/crypto/Kdf.js.map +1 -1
  265. package/dist/crypto/Password.d.ts +162 -0
  266. package/dist/crypto/Password.d.ts.map +1 -0
  267. package/dist/crypto/Password.js +217 -0
  268. package/dist/crypto/Password.js.map +1 -0
  269. package/dist/crypto/index.d.ts +5 -0
  270. package/dist/crypto/index.d.ts.map +1 -1
  271. package/dist/crypto/index.js +5 -0
  272. package/dist/crypto/index.js.map +1 -1
  273. package/dist/encoding/Base64.d.ts +63 -0
  274. package/dist/encoding/Base64.d.ts.map +1 -1
  275. package/dist/encoding/Base64.js +77 -0
  276. package/dist/encoding/Base64.js.map +1 -1
  277. package/dist/encoding/Base64Url.d.ts +1 -0
  278. package/dist/encoding/Base64Url.d.ts.map +1 -1
  279. package/dist/encoding/Base64Url.js +1 -0
  280. package/dist/encoding/Base64Url.js.map +1 -1
  281. package/dist/encoding/Csv.d.ts.map +1 -1
  282. package/dist/encoding/Csv.js +44 -16
  283. package/dist/encoding/Csv.js.map +1 -1
  284. package/dist/encoding/Hex.d.ts +5 -0
  285. package/dist/encoding/Hex.d.ts.map +1 -1
  286. package/dist/encoding/Hex.js +5 -0
  287. package/dist/encoding/Hex.js.map +1 -1
  288. package/dist/encoding/SchemaBinary.d.ts.map +1 -1
  289. package/dist/encoding/SchemaBinary.js +13 -124
  290. package/dist/encoding/SchemaBinary.js.map +1 -1
  291. package/dist/encoding/Sse.d.ts +1 -0
  292. package/dist/encoding/Sse.d.ts.map +1 -1
  293. package/dist/encoding/Sse.js +7 -5
  294. package/dist/encoding/Sse.js.map +1 -1
  295. package/dist/encoding/Xml.d.ts +117 -11
  296. package/dist/encoding/Xml.d.ts.map +1 -1
  297. package/dist/encoding/Xml.js +332 -42
  298. package/dist/encoding/Xml.js.map +1 -1
  299. package/dist/eventlog/EventJournal.d.ts.map +1 -1
  300. package/dist/eventlog/EventJournal.js +3 -8
  301. package/dist/eventlog/EventJournal.js.map +1 -1
  302. package/dist/eventlog/SqlEventLogServerEncrypted.js +6 -8
  303. package/dist/eventlog/SqlEventLogServerEncrypted.js.map +1 -1
  304. package/dist/http/FindMyWay/internal/router.js +163 -116
  305. package/dist/http/FindMyWay/internal/router.js.map +1 -1
  306. package/dist/http/FindMyWay.d.ts +99 -0
  307. package/dist/http/FindMyWay.d.ts.map +1 -1
  308. package/dist/http/FindMyWay.js +39 -0
  309. package/dist/http/FindMyWay.js.map +1 -1
  310. package/dist/http/HttpClient.d.ts.map +1 -1
  311. package/dist/http/HttpClient.js +1 -1
  312. package/dist/http/HttpClient.js.map +1 -1
  313. package/dist/http/HttpMiddleware.d.ts.map +1 -1
  314. package/dist/http/HttpMiddleware.js +15 -8
  315. package/dist/http/HttpMiddleware.js.map +1 -1
  316. package/dist/http/HttpRouter.d.ts +49 -1
  317. package/dist/http/HttpRouter.d.ts.map +1 -1
  318. package/dist/http/HttpRouter.js +70 -20
  319. package/dist/http/HttpRouter.js.map +1 -1
  320. package/dist/http/HttpServerResponse.d.ts.map +1 -1
  321. package/dist/http/HttpServerResponse.js +24 -58
  322. package/dist/http/HttpServerResponse.js.map +1 -1
  323. package/dist/http/Mime.d.ts.map +1 -1
  324. package/dist/http/Mime.js +3 -2
  325. package/dist/http/Mime.js.map +1 -1
  326. package/dist/http/internal/compression.d.ts.map +1 -1
  327. package/dist/http/internal/compression.js +2 -2
  328. package/dist/http/internal/compression.js.map +1 -1
  329. package/dist/http/internal/mediaType.d.ts.map +1 -0
  330. package/dist/{http-api → http}/internal/mediaType.js +4 -0
  331. package/dist/{http-api → http}/internal/mediaType.js.map +1 -1
  332. package/dist/http/internal/redactedPath.d.ts +2 -0
  333. package/dist/http/internal/redactedPath.d.ts.map +1 -0
  334. package/dist/http/internal/redactedPath.js +138 -0
  335. package/dist/http/internal/redactedPath.js.map +1 -0
  336. package/dist/http/internal/requestState.js +1 -0
  337. package/dist/http/internal/requestState.js.map +1 -1
  338. package/dist/http-api/HttpApi.d.ts +13 -2
  339. package/dist/http-api/HttpApi.d.ts.map +1 -1
  340. package/dist/http-api/HttpApi.js +16 -2
  341. package/dist/http-api/HttpApi.js.map +1 -1
  342. package/dist/http-api/HttpApiBuilder.d.ts.map +1 -1
  343. package/dist/http-api/HttpApiBuilder.js +3 -2
  344. package/dist/http-api/HttpApiBuilder.js.map +1 -1
  345. package/dist/http-api/HttpApiClient.d.ts.map +1 -1
  346. package/dist/http-api/HttpApiClient.js +6 -6
  347. package/dist/http-api/HttpApiClient.js.map +1 -1
  348. package/dist/http-api/HttpApiEndpoint.d.ts.map +1 -1
  349. package/dist/http-api/HttpApiEndpoint.js +1 -1
  350. package/dist/http-api/HttpApiEndpoint.js.map +1 -1
  351. package/dist/http-api/HttpApiScalar.d.ts +4 -0
  352. package/dist/http-api/HttpApiScalar.d.ts.map +1 -1
  353. package/dist/http-api/HttpApiScalar.js +10 -1
  354. package/dist/http-api/HttpApiScalar.js.map +1 -1
  355. package/dist/http-api/HttpApiSchema.d.ts.map +1 -1
  356. package/dist/http-api/HttpApiSchema.js +1 -1
  357. package/dist/http-api/HttpApiSchema.js.map +1 -1
  358. package/dist/http-api/OpenApi.d.ts +2 -0
  359. package/dist/http-api/OpenApi.d.ts.map +1 -1
  360. package/dist/http-api/internal/httpApiScalar.js +5 -2
  361. package/dist/http-api/internal/httpApiScalar.js.map +1 -1
  362. package/dist/index.d.ts +5 -0
  363. package/dist/index.d.ts.map +1 -1
  364. package/dist/index.js +5 -0
  365. package/dist/index.js.map +1 -1
  366. package/dist/internal/arbitrary/model.js +0 -5
  367. package/dist/internal/arbitrary/model.js.map +1 -1
  368. package/dist/internal/arbitrary/regexp.js +2 -1
  369. package/dist/internal/arbitrary/regexp.js.map +1 -1
  370. package/dist/internal/arbitrary/runner.d.ts.map +1 -1
  371. package/dist/internal/arbitrary/runner.js +21 -16
  372. package/dist/internal/arbitrary/runner.js.map +1 -1
  373. package/dist/internal/arbitrary/schema.js +140 -23
  374. package/dist/internal/arbitrary/schema.js.map +1 -1
  375. package/dist/internal/codegen.d.ts +2 -0
  376. package/dist/internal/codegen.d.ts.map +1 -0
  377. package/dist/internal/codegen.js +59 -0
  378. package/dist/internal/codegen.js.map +1 -0
  379. package/dist/internal/core.js +3 -3
  380. package/dist/internal/core.js.map +1 -1
  381. package/dist/internal/dateTime.js +26 -12
  382. package/dist/internal/dateTime.js.map +1 -1
  383. package/dist/internal/effect.js +21 -7
  384. package/dist/internal/effect.js.map +1 -1
  385. package/dist/internal/hashMap.js +7 -7
  386. package/dist/internal/hashMap.js.map +1 -1
  387. package/dist/internal/matcher.js +2 -1
  388. package/dist/internal/matcher.js.map +1 -1
  389. package/dist/internal/record.js +18 -4
  390. package/dist/internal/record.js.map +1 -1
  391. package/dist/internal/result.js +1 -1
  392. package/dist/internal/result.js.map +1 -1
  393. package/dist/internal/schema/codeExpression.d.ts +4 -0
  394. package/dist/internal/schema/codeExpression.d.ts.map +1 -0
  395. package/dist/internal/schema/codeExpression.js +179 -0
  396. package/dist/internal/schema/codeExpression.js.map +1 -0
  397. package/dist/internal/schema/codeImports.d.ts +8 -0
  398. package/dist/internal/schema/codeImports.d.ts.map +1 -0
  399. package/dist/internal/schema/codeImports.js +135 -0
  400. package/dist/internal/schema/codeImports.js.map +1 -0
  401. package/dist/internal/schema/codeTokens.d.ts +8 -0
  402. package/dist/internal/schema/codeTokens.d.ts.map +1 -0
  403. package/dist/internal/schema/codeTokens.js +17 -0
  404. package/dist/internal/schema/codeTokens.js.map +1 -0
  405. package/dist/internal/schema/passthrough.d.ts +2 -0
  406. package/dist/internal/schema/passthrough.d.ts.map +1 -0
  407. package/dist/internal/schema/passthrough.js +8 -0
  408. package/dist/internal/schema/passthrough.js.map +1 -0
  409. package/dist/internal/schema/schemaCodegen.d.ts +2 -0
  410. package/dist/internal/schema/schemaCodegen.d.ts.map +1 -0
  411. package/dist/internal/schema/schemaCodegen.js +377 -0
  412. package/dist/internal/schema/schemaCodegen.js.map +1 -0
  413. package/dist/internal/schema/toJsonSchemaDocument.js +11 -4
  414. package/dist/internal/schema/toJsonSchemaDocument.js.map +1 -1
  415. package/dist/internal/trie.js +51 -64
  416. package/dist/internal/trie.js.map +1 -1
  417. package/dist/internal/utf8.d.ts +2 -0
  418. package/dist/internal/utf8.d.ts.map +1 -0
  419. package/dist/internal/utf8.js +151 -0
  420. package/dist/internal/utf8.js.map +1 -0
  421. package/dist/internal/version.js +1 -1
  422. package/dist/jose/Jwks.d.ts +13 -0
  423. package/dist/jose/Jwks.d.ts.map +1 -1
  424. package/dist/jose/Jwks.js +10 -2
  425. package/dist/jose/Jwks.js.map +1 -1
  426. package/dist/observability/OtlpExporter.d.ts.map +1 -1
  427. package/dist/observability/OtlpExporter.js +12 -10
  428. package/dist/observability/OtlpExporter.js.map +1 -1
  429. package/dist/observability/OtlpLogger.d.ts.map +1 -1
  430. package/dist/observability/OtlpLogger.js +5 -3
  431. package/dist/observability/OtlpLogger.js.map +1 -1
  432. package/dist/observability/internal/otlpProtobuf.d.ts +4 -2
  433. package/dist/observability/internal/otlpProtobuf.d.ts.map +1 -1
  434. package/dist/observability/internal/otlpProtobuf.js +238 -156
  435. package/dist/observability/internal/otlpProtobuf.js.map +1 -1
  436. package/dist/persistence/PersistedQueue.d.ts.map +1 -1
  437. package/dist/persistence/PersistedQueue.js +20 -3
  438. package/dist/persistence/PersistedQueue.js.map +1 -1
  439. package/dist/protobuf/ProtobufDescriptor.d.ts +377 -0
  440. package/dist/protobuf/ProtobufDescriptor.d.ts.map +1 -0
  441. package/dist/protobuf/ProtobufDescriptor.js +135 -0
  442. package/dist/protobuf/ProtobufDescriptor.js.map +1 -0
  443. package/dist/protobuf/ProtobufDescriptorProto.d.ts +2083 -0
  444. package/dist/protobuf/ProtobufDescriptorProto.d.ts.map +1 -0
  445. package/dist/protobuf/ProtobufDescriptorProto.js +2674 -0
  446. package/dist/protobuf/ProtobufDescriptorProto.js.map +1 -0
  447. package/dist/protobuf/ProtobufMessage.d.ts +183 -0
  448. package/dist/protobuf/ProtobufMessage.d.ts.map +1 -0
  449. package/dist/protobuf/ProtobufMessage.js +232 -0
  450. package/dist/protobuf/ProtobufMessage.js.map +1 -0
  451. package/dist/protobuf/ProtobufReader.d.ts +350 -0
  452. package/dist/protobuf/ProtobufReader.d.ts.map +1 -0
  453. package/dist/protobuf/ProtobufReader.js +698 -0
  454. package/dist/protobuf/ProtobufReader.js.map +1 -0
  455. package/dist/protobuf/ProtobufWriter.d.ts +224 -0
  456. package/dist/protobuf/ProtobufWriter.d.ts.map +1 -0
  457. package/dist/protobuf/ProtobufWriter.js +483 -0
  458. package/dist/protobuf/ProtobufWriter.js.map +1 -0
  459. package/dist/protobuf/index.d.ts +30 -0
  460. package/dist/protobuf/index.d.ts.map +1 -0
  461. package/dist/protobuf/index.js +31 -0
  462. package/dist/protobuf/index.js.map +1 -0
  463. package/dist/protobuf/internal/binary.d.ts +2 -0
  464. package/dist/protobuf/internal/binary.d.ts.map +1 -0
  465. package/dist/protobuf/internal/binary.js +966 -0
  466. package/dist/protobuf/internal/binary.js.map +1 -0
  467. package/dist/protobuf/internal/resolve.d.ts +2 -0
  468. package/dist/protobuf/internal/resolve.d.ts.map +1 -0
  469. package/dist/protobuf/internal/resolve.js +463 -0
  470. package/dist/protobuf/internal/resolve.js.map +1 -0
  471. package/dist/protobuf/internal/wireType.d.ts +2 -0
  472. package/dist/protobuf/internal/wireType.d.ts.map +1 -0
  473. package/dist/protobuf/internal/wireType.js +10 -0
  474. package/dist/protobuf/internal/wireType.js.map +1 -0
  475. package/dist/reactivity/AsyncResult.d.ts +3 -0
  476. package/dist/reactivity/AsyncResult.d.ts.map +1 -1
  477. package/dist/reactivity/AsyncResult.js +4 -1
  478. package/dist/reactivity/AsyncResult.js.map +1 -1
  479. package/dist/reactivity/Atom.d.ts +10 -4
  480. package/dist/reactivity/Atom.d.ts.map +1 -1
  481. package/dist/reactivity/Atom.js +38 -13
  482. package/dist/reactivity/Atom.js.map +1 -1
  483. package/dist/reactivity/AtomHttpApi.d.ts +5 -0
  484. package/dist/reactivity/AtomHttpApi.d.ts.map +1 -1
  485. package/dist/reactivity/AtomHttpApi.js +5 -1
  486. package/dist/reactivity/AtomHttpApi.js.map +1 -1
  487. package/dist/reactivity/AtomRegistry.js +13 -0
  488. package/dist/reactivity/AtomRegistry.js.map +1 -1
  489. package/dist/reactivity/AtomRpc.d.ts +5 -0
  490. package/dist/reactivity/AtomRpc.d.ts.map +1 -1
  491. package/dist/reactivity/AtomRpc.js +6 -1
  492. package/dist/reactivity/AtomRpc.js.map +1 -1
  493. package/dist/rpc/Rpc.d.ts +25 -0
  494. package/dist/rpc/Rpc.d.ts.map +1 -1
  495. package/dist/rpc/Rpc.js +18 -0
  496. package/dist/rpc/Rpc.js.map +1 -1
  497. package/dist/rpc/RpcClient.d.ts.map +1 -1
  498. package/dist/rpc/RpcClient.js +38 -21
  499. package/dist/rpc/RpcClient.js.map +1 -1
  500. package/dist/rpc/RpcGroup.d.ts +5 -0
  501. package/dist/rpc/RpcGroup.d.ts.map +1 -1
  502. package/dist/rpc/RpcGroup.js.map +1 -1
  503. package/dist/rpc/RpcMiddleware.d.ts +9 -0
  504. package/dist/rpc/RpcMiddleware.d.ts.map +1 -1
  505. package/dist/rpc/RpcMiddleware.js.map +1 -1
  506. package/dist/rpc/RpcSerialization.d.ts +7 -1
  507. package/dist/rpc/RpcSerialization.d.ts.map +1 -1
  508. package/dist/rpc/RpcSerialization.js +22 -5
  509. package/dist/rpc/RpcSerialization.js.map +1 -1
  510. package/dist/rpc/RpcServer.d.ts.map +1 -1
  511. package/dist/rpc/RpcServer.js +33 -18
  512. package/dist/rpc/RpcServer.js.map +1 -1
  513. package/dist/schema/SchemaCompiler/runtime.js +2 -1
  514. package/dist/schema/SchemaCompiler/runtime.js.map +1 -1
  515. package/dist/schema/VariantSchema.d.ts +10 -2
  516. package/dist/schema/VariantSchema.d.ts.map +1 -1
  517. package/dist/schema/VariantSchema.js +7 -1
  518. package/dist/schema/VariantSchema.js.map +1 -1
  519. package/dist/socket/Socket.d.ts +24 -10
  520. package/dist/socket/Socket.d.ts.map +1 -1
  521. package/dist/socket/Socket.js +52 -17
  522. package/dist/socket/Socket.js.map +1 -1
  523. package/dist/sql/Migrator.d.ts +3 -0
  524. package/dist/sql/Migrator.d.ts.map +1 -1
  525. package/dist/sql/Migrator.js +10 -1
  526. package/dist/sql/Migrator.js.map +1 -1
  527. package/dist/sql/SqlModel.d.ts.map +1 -1
  528. package/dist/sql/SqlModel.js +1 -0
  529. package/dist/sql/SqlModel.js.map +1 -1
  530. package/dist/testing/TestConsole.d.ts +96 -0
  531. package/dist/testing/TestConsole.d.ts.map +1 -1
  532. package/dist/testing/TestConsole.js +78 -6
  533. package/dist/testing/TestConsole.js.map +1 -1
  534. package/dist/testing/TestSchema.d.ts +5 -1
  535. package/dist/testing/TestSchema.d.ts.map +1 -1
  536. package/dist/testing/TestSchema.js +7 -2
  537. package/dist/testing/TestSchema.js.map +1 -1
  538. package/dist/workers/SharedMemory.d.ts +115 -0
  539. package/dist/workers/SharedMemory.d.ts.map +1 -0
  540. package/dist/workers/SharedMemory.js +149 -0
  541. package/dist/workers/SharedMemory.js.map +1 -0
  542. package/dist/workers/Transferable.d.ts.map +1 -1
  543. package/dist/workers/Transferable.js +1 -4
  544. package/dist/workers/Transferable.js.map +1 -1
  545. package/dist/workers/index.d.ts +5 -0
  546. package/dist/workers/index.d.ts.map +1 -1
  547. package/dist/workers/index.js +5 -0
  548. package/dist/workers/index.js.map +1 -1
  549. package/dist/workflow/WorkflowEngine.d.ts.map +1 -1
  550. package/dist/workflow/WorkflowEngine.js +3 -1
  551. package/dist/workflow/WorkflowEngine.js.map +1 -1
  552. package/package.json +7 -4
  553. package/src/Arbitrary.ts +60 -3
  554. package/src/BigInt.ts +247 -9
  555. package/src/Cache.ts +4 -2
  556. package/src/Cause.ts +3 -3
  557. package/src/Chunk.ts +7 -3
  558. package/src/Clock.ts +5 -2
  559. package/src/Codegen.ts +741 -0
  560. package/src/Config.ts +35 -4
  561. package/src/ConfigProvider.ts +24 -7
  562. package/src/Effect.ts +871 -109
  563. package/src/Equivalence.ts +16 -13
  564. package/src/Fiber.ts +58 -8
  565. package/src/FiberHandle.ts +86 -12
  566. package/src/FiberMap.ts +83 -10
  567. package/src/FiberSet.ts +96 -8
  568. package/src/Formatter.ts +2 -0
  569. package/src/LayerMap.ts +14 -4
  570. package/src/LayerRef.ts +2 -2
  571. package/src/Match.ts +16 -0
  572. package/src/Metric.ts +1 -1
  573. package/src/Option.ts +9 -5
  574. package/src/Order.ts +9 -4
  575. package/src/Pool.ts +22 -17
  576. package/src/Predicate.ts +7 -3
  577. package/src/Queue.ts +84 -31
  578. package/src/Rational.ts +198 -0
  579. package/src/Request.ts +20 -0
  580. package/src/Result.ts +9 -6
  581. package/src/Schema.ts +69 -32
  582. package/src/SchemaAST.ts +15 -4
  583. package/src/SchemaGetter.ts +17 -10
  584. package/src/SchemaRepresentation.ts +19 -74
  585. package/src/SchemaTransformation.ts +12 -11
  586. package/src/Scope.ts +12 -6
  587. package/src/ScopedCache.ts +2 -1
  588. package/src/Semaphore.ts +18 -4
  589. package/src/Stream.ts +66 -20
  590. package/src/String.ts +83 -6
  591. package/src/Struct.ts +138 -5
  592. package/src/TextDiff.ts +186 -30
  593. package/src/TxPriorityQueue.ts +2 -2
  594. package/src/ai/LanguageModel.ts +2 -1
  595. package/src/ai/McpServer.ts +145 -22
  596. package/src/ai/Tool.ts +3 -2
  597. package/src/ai/Toolkit.ts +3 -1
  598. package/src/chat/Chat.ts +164 -0
  599. package/src/chat/ChatAdapter.ts +444 -0
  600. package/src/chat/ChatError.ts +684 -0
  601. package/src/chat/ChatEvent.ts +221 -0
  602. package/src/chat/ChatHandler.ts +102 -0
  603. package/src/chat/ChatInteraction.ts +1979 -0
  604. package/src/chat/ChatMarkdown.ts +1406 -0
  605. package/src/chat/ChatMessage.ts +213 -0
  606. package/src/chat/ChatTest.ts +2606 -0
  607. package/src/chat/ChatThread.ts +132 -0
  608. package/src/chat/ChatUi.ts +320 -0
  609. package/src/chat/index.ts +72 -0
  610. package/src/chat/internal/retries.ts +7 -0
  611. package/src/cli/CliOutput.ts +4 -5
  612. package/src/cli/Command.ts +20 -2
  613. package/src/cli/Prompt.ts +15 -9
  614. package/src/cli/internal/config.ts +8 -8
  615. package/src/cluster/ClusterCron.ts +33 -10
  616. package/src/cluster/ClusterWorkflowEngine.ts +42 -23
  617. package/src/cluster/Sharding.ts +17 -3
  618. package/src/cluster/ShardingConfig.ts +3 -0
  619. package/src/cluster/SqlMessageStorage.ts +16 -20
  620. package/src/cluster/SqlRunnerStorage.ts +21 -8
  621. package/src/cluster/internal/entityManager.ts +19 -10
  622. package/src/cluster/internal/entityReaper.ts +1 -1
  623. package/src/crypto/Kdf.ts +2 -1
  624. package/src/crypto/Password.ts +258 -0
  625. package/src/crypto/index.ts +6 -0
  626. package/src/encoding/Base64.ts +79 -0
  627. package/src/encoding/Base64Url.ts +1 -0
  628. package/src/encoding/Csv.ts +47 -20
  629. package/src/encoding/Hex.ts +5 -0
  630. package/src/encoding/SchemaBinary.ts +13 -79
  631. package/src/encoding/Sse.ts +7 -5
  632. package/src/encoding/Xml.ts +394 -47
  633. package/src/eventlog/EventJournal.ts +3 -8
  634. package/src/eventlog/SqlEventLogServerEncrypted.ts +9 -9
  635. package/src/http/FindMyWay/internal/router.ts +181 -129
  636. package/src/http/FindMyWay.ts +106 -0
  637. package/src/http/HttpClient.ts +2 -1
  638. package/src/http/HttpMiddleware.ts +22 -9
  639. package/src/http/HttpRouter.ts +84 -20
  640. package/src/http/HttpServerResponse.ts +33 -61
  641. package/src/http/Mime.ts +3 -2
  642. package/src/http/internal/compression.ts +2 -2
  643. package/src/{http-api → http}/internal/mediaType.ts +4 -0
  644. package/src/http/internal/redactedPath.ts +144 -0
  645. package/src/http/internal/requestState.ts +2 -0
  646. package/src/http-api/HttpApi.ts +25 -2
  647. package/src/http-api/HttpApiBuilder.ts +5 -2
  648. package/src/http-api/HttpApiClient.ts +10 -6
  649. package/src/http-api/HttpApiEndpoint.ts +1 -1
  650. package/src/http-api/HttpApiScalar.ts +9 -1
  651. package/src/http-api/HttpApiSchema.ts +1 -1
  652. package/src/http-api/OpenApi.ts +2 -0
  653. package/src/http-api/internal/httpApiScalar.ts +5 -1
  654. package/src/index.ts +6 -0
  655. package/src/internal/arbitrary/model.ts +3 -9
  656. package/src/internal/arbitrary/regexp.ts +3 -1
  657. package/src/internal/arbitrary/runner.ts +28 -14
  658. package/src/internal/arbitrary/schema.ts +140 -35
  659. package/src/internal/codegen.ts +53 -0
  660. package/src/internal/core.ts +3 -3
  661. package/src/internal/dateTime.ts +30 -13
  662. package/src/internal/effect.ts +25 -9
  663. package/src/internal/hashMap.ts +8 -7
  664. package/src/internal/matcher.ts +2 -1
  665. package/src/internal/record.ts +19 -4
  666. package/src/internal/result.ts +1 -1
  667. package/src/internal/schema/codeExpression.ts +179 -0
  668. package/src/internal/schema/codeImports.ts +142 -0
  669. package/src/internal/schema/codeTokens.ts +39 -0
  670. package/src/internal/schema/passthrough.ts +8 -0
  671. package/src/internal/schema/schemaCodegen.ts +543 -0
  672. package/src/internal/schema/toJsonSchemaDocument.ts +13 -4
  673. package/src/internal/trie.ts +46 -60
  674. package/src/internal/utf8.ts +106 -0
  675. package/src/internal/version.ts +1 -1
  676. package/src/jose/Jwks.ts +23 -4
  677. package/src/observability/OtlpExporter.ts +12 -10
  678. package/src/observability/OtlpLogger.ts +5 -3
  679. package/src/observability/internal/otlpProtobuf.ts +386 -457
  680. package/src/persistence/PersistedQueue.ts +21 -4
  681. package/src/protobuf/ProtobufDescriptor.ts +503 -0
  682. package/src/protobuf/ProtobufDescriptorProto.ts +3611 -0
  683. package/src/protobuf/ProtobufMessage.ts +277 -0
  684. package/src/protobuf/ProtobufReader.ts +756 -0
  685. package/src/protobuf/ProtobufWriter.ts +530 -0
  686. package/src/protobuf/index.ts +36 -0
  687. package/src/protobuf/internal/binary.ts +1215 -0
  688. package/src/protobuf/internal/resolve.ts +533 -0
  689. package/src/protobuf/internal/wireType.ts +9 -0
  690. package/src/reactivity/AsyncResult.ts +6 -1
  691. package/src/reactivity/Atom.ts +55 -16
  692. package/src/reactivity/AtomHttpApi.ts +10 -1
  693. package/src/reactivity/AtomRegistry.ts +16 -0
  694. package/src/reactivity/AtomRpc.ts +11 -1
  695. package/src/rpc/Rpc.ts +31 -0
  696. package/src/rpc/RpcClient.ts +30 -21
  697. package/src/rpc/RpcGroup.ts +5 -0
  698. package/src/rpc/RpcMiddleware.ts +9 -0
  699. package/src/rpc/RpcSerialization.ts +26 -6
  700. package/src/rpc/RpcServer.ts +33 -20
  701. package/src/schema/SchemaCompiler/runtime.ts +2 -3
  702. package/src/schema/VariantSchema.ts +12 -4
  703. package/src/socket/Socket.ts +67 -20
  704. package/src/sql/Migrator.ts +8 -1
  705. package/src/sql/SqlModel.ts +4 -0
  706. package/src/testing/TestConsole.ts +119 -9
  707. package/src/testing/TestSchema.ts +8 -3
  708. package/src/workers/SharedMemory.ts +227 -0
  709. package/src/workers/Transferable.ts +1 -5
  710. package/src/workers/index.ts +6 -0
  711. package/src/workflow/WorkflowEngine.ts +3 -1
  712. package/dist/http-api/internal/mediaType.d.ts.map +0 -1
  713. package/dist/internal/schema/toCodeDocument.d.ts +0 -2
  714. package/dist/internal/schema/toCodeDocument.d.ts.map +0 -1
  715. package/dist/internal/schema/toCodeDocument.js +0 -447
  716. package/dist/internal/schema/toCodeDocument.js.map +0 -1
  717. package/dist/observability/internal/protobuf.d.ts +0 -2
  718. package/dist/observability/internal/protobuf.d.ts.map +0 -1
  719. package/dist/observability/internal/protobuf.js +0 -169
  720. package/dist/observability/internal/protobuf.js.map +0 -1
  721. package/src/internal/schema/toCodeDocument.ts +0 -578
  722. package/src/observability/internal/protobuf.ts +0 -225
  723. /package/dist/{http-api → http}/internal/mediaType.d.ts +0 -0
@@ -0,0 +1,1406 @@
1
+ /**
2
+ * Posting long and streamed Markdown through `Chat`.
3
+ *
4
+ * `post` splits Markdown that outgrows one message into parts at block
5
+ * boundaries. `stream` writes a stream of Markdown deltas as it arrives, by
6
+ * the adapter's native stream when it has one, otherwise by posting and then
7
+ * editing, and on an adapter without `edit` by posting each part once. Both
8
+ * sit above the adapter ops and use one splitter.
9
+ *
10
+ * **Example** (Streaming a reply)
11
+ *
12
+ * ```ts
13
+ * import { Effect, Stream } from "effect"
14
+ * import { ChatMarkdown, ChatThread } from "effect/chat"
15
+ *
16
+ * const reply = (deltas: Stream.Stream<string>) =>
17
+ * Effect.gen(function*() {
18
+ * const result = yield* ChatMarkdown.stream(ChatThread.make("slack", "T1/C1"), deltas)
19
+ * return result.parts.map((part) => part.messageId)
20
+ * })
21
+ * ```
22
+ *
23
+ * @stability unstable
24
+ * @since 4.1.5
25
+ */
26
+ import * as Cause from "../Cause.ts"
27
+ import * as Clock from "../Clock.ts"
28
+ import * as Data from "../Data.ts"
29
+ import type * as DateTime from "../DateTime.ts"
30
+ import * as Duration from "../Duration.ts"
31
+ import * as Effect from "../Effect.ts"
32
+ import * as Exit from "../Exit.ts"
33
+ import * as Fiber from "../Fiber.ts"
34
+ import * as Latch from "../Latch.ts"
35
+ import * as Option from "../Option.ts"
36
+ import * as Scope from "../Scope.ts"
37
+ import * as Stream from "../Stream.ts"
38
+ import * as Chat from "./Chat.ts"
39
+ import type { Descriptor, File, NativeStream, Posted } from "./ChatAdapter.ts"
40
+ import { Registry } from "./ChatAdapter.ts"
41
+ import { ChatError, fileRefused, TooLarge } from "./ChatError.ts"
42
+ import type { ReplyTo } from "./ChatMessage.ts"
43
+ import type { ChatThread } from "./ChatThread.ts"
44
+ import type { Action } from "./ChatUi.ts"
45
+
46
+ /**
47
+ * One message a call created.
48
+ *
49
+ * **Details**
50
+ *
51
+ * - `markdown` is the Markdown as it went out, with a reopened or closed code
52
+ * fence and a consumer's unattached note included. It is empty for the
53
+ * overflow file.
54
+ * - `text` is the slice of the input the part carries, without anything the
55
+ * layer added. The `text` of every part, in order, is the input.
56
+ * - `transport` is `post` for a part from `post` and for a streamed part
57
+ * posted once to an adapter without `edit`, `edit` for a streamed part
58
+ * written by post-then-edit and `native` for one written by the adapter's
59
+ * native stream, even if it was finished by an edit.
60
+ *
61
+ * @stability unstable
62
+ * @category models
63
+ * @since 4.1.5
64
+ */
65
+ export interface Part {
66
+ readonly messageId: string
67
+ readonly timestamp: DateTime.Utc
68
+ readonly markdown: string
69
+ readonly text: string
70
+ readonly kind: "text" | "overflowFile"
71
+ readonly transport: "post" | "edit" | "native"
72
+ }
73
+
74
+ /**
75
+ * What a call posted.
76
+ *
77
+ * **Details**
78
+ *
79
+ * - `parts` is empty when the input was empty: nothing is posted.
80
+ * - `stopped` means a user clicked stop on this reply (Slack's stop button).
81
+ * It can be true with the whole text delivered, when the consumer ignored
82
+ * the click. It is always false from `post`.
83
+ *
84
+ * @stability unstable
85
+ * @category models
86
+ * @since 4.1.5
87
+ */
88
+ export interface Result {
89
+ readonly parts: ReadonlyArray<Part>
90
+ readonly stopped: boolean
91
+ }
92
+
93
+ /**
94
+ * Error for a call that did not deliver its whole input.
95
+ *
96
+ * **Details**
97
+ *
98
+ * - `posted` is text the platform confirmed, `uncertain` is text sent in a
99
+ * write that failed `uncertain` and was never confirmed since, and
100
+ * `remaining` was never sent. The `text` of `posted`, then `uncertain`,
101
+ * then `remaining` is the input, with nothing in two of them.
102
+ * - `remainingFence` is set when `remaining` starts inside a code fence:
103
+ * the line that opened it, with its info string. Text sent later starts
104
+ * with that line and a newline, then `remaining`.
105
+ * - `cause` is a `ChatError` from a write, the upstream's error `E`, or
106
+ * `Overflow` when the input outgrew `maxParts` and the overflow file.
107
+ *
108
+ * **Gotchas**
109
+ *
110
+ * It is not a `Schema.TaggedError`: it is generic in `E` and carries
111
+ * message text. `message` and `toJSON` leave the text out.
112
+ *
113
+ * @stability unstable
114
+ * @category errors
115
+ * @since 4.1.5
116
+ */
117
+ export class ChatMarkdownError<E = never> extends Data.TaggedError("ChatMarkdownError")<{
118
+ readonly posted: ReadonlyArray<Part>
119
+ readonly remaining: string
120
+ readonly remainingFence?: string | undefined
121
+ readonly uncertain?: string | undefined
122
+ readonly cause:
123
+ | { readonly _tag: "Chat"; readonly error: ChatError }
124
+ | { readonly _tag: "Upstream"; readonly error: E }
125
+ | { readonly _tag: "Overflow" }
126
+ }> {
127
+ override get message(): string {
128
+ const cause = this.cause._tag === "Chat" ? "Chat(" + this.cause.error.reason._tag + ")" : this.cause._tag
129
+ return "ChatMarkdown failed after " + this.posted.length + " part(s): " + cause
130
+ }
131
+
132
+ /**
133
+ * The error without its message text.
134
+ */
135
+ override toJSON(): unknown {
136
+ return {
137
+ _tag: this._tag,
138
+ posted: this.posted.map((part) => ({ messageId: part.messageId, kind: part.kind, transport: part.transport })),
139
+ cause: this.cause._tag === "Chat" ? { _tag: "Chat", error: this.cause.error.toJSON() } : { _tag: this.cause._tag }
140
+ }
141
+ }
142
+ }
143
+
144
+ /**
145
+ * The options `post` and `stream` share.
146
+ *
147
+ * **Details**
148
+ *
149
+ * - `replyTo` applies to the first part.
150
+ * - `maxParts` defaults to 5, a provisional number. Past it, `overflow`
151
+ * decides: `fail`, the default, or `{ file }`, which sends the rest as one
152
+ * trailing file message that does not count against `maxParts`.
153
+ * - `minWriteInterval` is the floor between two writes. It defaults to the
154
+ * adapter's `limits.minWriteInterval`.
155
+ * - `onPart` runs for every message the call creates, the overflow file
156
+ * included, uninterruptibly once its post returns, so an interrupt can
157
+ * neither lose an id nor post the message twice. It has to be quick.
158
+ *
159
+ * @stability unstable
160
+ * @category models
161
+ * @since 4.1.5
162
+ */
163
+ export interface Options<R> {
164
+ readonly replyTo?: ReplyTo | undefined
165
+ readonly maxParts?: number | undefined
166
+ readonly overflow?: "fail" | { readonly file: { readonly name: string } } | undefined
167
+ readonly minWriteInterval?: Duration.Duration | undefined
168
+ readonly onPart?: ((part: Part) => Effect.Effect<void, never, R>) | undefined
169
+ }
170
+
171
+ // -----------------------------------------------------------------------------
172
+ // Markdown scanning
173
+ // -----------------------------------------------------------------------------
174
+
175
+ interface Fence {
176
+ readonly marker: string
177
+ readonly line: string
178
+ }
179
+
180
+ interface Line {
181
+ /** The index after the line's newline. */
182
+ readonly end: number
183
+ /** The fence open after the line. */
184
+ readonly fence: Fence | undefined
185
+ /** The line closes a fence. */
186
+ readonly closed: boolean
187
+ /** A part can end after this line: it is outside a fence, and blank or closing a fence. */
188
+ readonly boundary: boolean
189
+ }
190
+
191
+ const fencePattern = /^ {0,3}(`{3,}|~{3,})(.*)$/
192
+
193
+ const fenceAfter = (
194
+ fence: Fence | undefined,
195
+ line: string
196
+ ): { readonly fence: Fence | undefined; readonly closed: boolean } => {
197
+ const match = fencePattern.exec(line)
198
+ if (match === null) return { fence, closed: false }
199
+ const marker = match[1]
200
+ if (fence === undefined) {
201
+ return marker[0] === "`" && match[2].includes("`")
202
+ ? { fence, closed: false }
203
+ : { fence: { marker, line: line.trimStart() }, closed: false }
204
+ }
205
+ return marker[0] === fence.marker[0] && marker.length >= fence.marker.length && match[2].trim() === ""
206
+ ? { fence: undefined, closed: true }
207
+ : { fence, closed: false }
208
+ }
209
+
210
+ /**
211
+ * The lines of `text`, read from a state of `fence`. Only complete lines
212
+ * count, unless `complete` says the text is finished.
213
+ */
214
+ const scanLines = (text: string, fence: Fence | undefined, complete: boolean): Array<Line> => {
215
+ const lines: Array<Line> = []
216
+ let start = 0
217
+ while (start < text.length) {
218
+ const newline = text.indexOf("\n", start)
219
+ if (newline === -1 && !complete) break
220
+ const end = newline === -1 ? text.length : newline + 1
221
+ const line = text.slice(start, newline === -1 ? text.length : newline).replace(/\r$/, "")
222
+ const step = fenceAfter(fence, line)
223
+ fence = step.fence
224
+ lines.push({
225
+ end,
226
+ fence,
227
+ closed: step.closed,
228
+ boundary: fence === undefined && (step.closed || line.trim() === "")
229
+ })
230
+ start = end
231
+ }
232
+ return lines
233
+ }
234
+
235
+ const fenceAt = (lines: ReadonlyArray<Line>, initial: Fence | undefined, index: number): Fence | undefined => {
236
+ let fence = initial
237
+ for (const line of lines) {
238
+ if (line.end > index) break
239
+ fence = line.fence
240
+ }
241
+ return fence
242
+ }
243
+
244
+ const closing = (fence: Fence | undefined, markdown: string): string =>
245
+ fence === undefined ? "" : (markdown === "" || markdown.endsWith("\n") ? "" : "\n") + fence.marker
246
+
247
+ const reopening = (fence: Fence | undefined): string => fence === undefined ? "" : fence.line + "\n"
248
+
249
+ const isBlank = (text: string) => text.trim() === ""
250
+
251
+ /** Markdown for `text` written as a whole message: an open fence is closed. */
252
+ const render = (prefix: string, text: string, fence: Fence | undefined): string => {
253
+ const markdown = prefix + text
254
+ return markdown + closing(fenceAt(scanLines(text, fence, true), fence, text.length), markdown)
255
+ }
256
+
257
+ /**
258
+ * Where to cut `text` so that `prefix`, the cut text and a closing fence
259
+ * measure at most `room`: prefer a fitting block boundary, else cut after
260
+ * the last line, else after the last whitespace, else at the last character.
261
+ * Never inside a grapheme cluster, and never at 0.
262
+ */
263
+ const fitCut = (
264
+ measure: (markdown: string) => number,
265
+ text: string,
266
+ fence: Fence | undefined,
267
+ prefix: string,
268
+ room: number
269
+ ): number => {
270
+ const lines = scanLines(text, fence, false)
271
+ const size = (cut: number) => {
272
+ const markdown = prefix + text.slice(0, cut)
273
+ return measure(markdown + closing(fenceAt(lines, fence, cut), markdown))
274
+ }
275
+ const fits = (cut: number) => size(cut) <= room
276
+ let low = 0
277
+ let high = text.length
278
+ while (low < high) {
279
+ const middle = Math.ceil((low + high) / 2)
280
+ if (fits(middle)) low = middle
281
+ else high = middle - 1
282
+ }
283
+ const most = low
284
+ // Closing a fence removes the synthetic suffix. Look ahead two real closes
285
+ // beyond the estimate, farthest first, to bound the extra measurements.
286
+ const closes = lines.filter((line) => line.closed && line.end > most).slice(0, 2)
287
+ const candidates = closes.map((line) => line.end).reverse()
288
+ for (let i = lines.length - 1; i >= 0; i--) {
289
+ if (lines[i].boundary && lines[i].end <= most) candidates.push(lines[i].end)
290
+ }
291
+ for (let i = lines.length - 1; i >= 0; i--) {
292
+ if (lines[i].end <= most) candidates.push(lines[i].end)
293
+ }
294
+ for (let i = most - 1; i > 0; i--) {
295
+ if (/\s/.test(text[i])) {
296
+ candidates.push(i + 1)
297
+ break
298
+ }
299
+ }
300
+ candidates.push(most)
301
+ const clusters = graphemes(text)
302
+ for (const candidate of candidates) {
303
+ const cut = clusterStart(clusters, text, candidate)
304
+ if (cut > 0 && fits(cut)) return cut
305
+ }
306
+ // Not even one cluster fits: the cut goes after the first one, and the write fails `TooLarge`.
307
+ return clusterStart(clusters, text, most) || clusterEnd(clusters, 0)
308
+ }
309
+
310
+ let segmenter: Intl.Segmenter | undefined
311
+
312
+ /** The grapheme clusters of `text`. `Intl.Segmenter` is created on first use. */
313
+ const graphemes = (text: string): Intl.Segments =>
314
+ (segmenter ??= new Intl.Segmenter(undefined, { granularity: "grapheme" })).segment(text)
315
+
316
+ /** The grapheme cluster boundary at or before `cut`. */
317
+ const clusterStart = (clusters: Intl.Segments, text: string, cut: number): number =>
318
+ cut <= 0 || cut >= text.length ? cut : clusters.containing(cut)!.index
319
+
320
+ /** The end of the grapheme cluster that contains `index`. */
321
+ const clusterEnd = (clusters: Intl.Segments, index: number): number => {
322
+ const cluster = clusters.containing(index)!
323
+ return cluster.index + cluster.segment.length
324
+ }
325
+
326
+ /** Where the last grapheme cluster of `text` that is not whitespace starts, or -1 for blank text. */
327
+ const lastContentStart = (text: string): number => {
328
+ const end = text.trimEnd().length
329
+ return end === 0 ? -1 : graphemes(text).containing(end - 1)!.index
330
+ }
331
+
332
+ /** Past this many held characters, a held line is released up to its last whitespace. */
333
+ const holdLimit = 300
334
+
335
+ /**
336
+ * What an append may send of `pending` before the input is finished: up to
337
+ * the last complete line, unless inside a code fence.
338
+ */
339
+ const releasable = (pending: string, fence: Fence | undefined): string => {
340
+ const lines = scanLines(pending, fence, false)
341
+ const complete = lines.length === 0 ? 0 : lines[lines.length - 1].end
342
+ if (complete === pending.length) return pending
343
+ if (fenceAt(lines, fence, complete) === undefined) {
344
+ const tail = pending.slice(complete)
345
+ if (tail.length <= holdLimit) return pending.slice(0, complete)
346
+ const space = tail.search(/\s\S*$/)
347
+ if (space !== -1) return pending.slice(0, complete + space + 1)
348
+ }
349
+ // The next delta may still extend the trailing cluster, even inside a fence.
350
+ // A split surrogate may complete a code point that extends the preceding cluster.
351
+ const text = /[\ud800-\udbff]$/.test(pending) ? pending.slice(0, -1) : pending
352
+ let last = 0
353
+ for (const cluster of graphemes(text)) last = cluster.index
354
+ return pending.slice(0, last)
355
+ }
356
+
357
+ const utf8Length = (text: string): number => {
358
+ let bytes = 0
359
+ for (let i = 0; i < text.length; i++) {
360
+ const code = text.charCodeAt(i)
361
+ bytes += code < 0x80 ? 1 : code < 0x800 ? 2 : code >= 0xd800 && code <= 0xdfff ? 2 : 3
362
+ }
363
+ return bytes
364
+ }
365
+
366
+ // -----------------------------------------------------------------------------
367
+ // the reply
368
+ // -----------------------------------------------------------------------------
369
+
370
+ const defaultMaxParts = 5
371
+ /** Consecutive `retry` failures of appends on one stream before the repair. Provisional. */
372
+ const appendRetryLimit = 3
373
+ /** A native stream rolls over at the next block boundary past this share of `streamLength`. */
374
+ const softShare = 0.85
375
+ /** A native stream rotates once it is this share of `streamAge` old. */
376
+ const ageShare = 0.8
377
+ /** How long finishing a failed or interrupted reply may take. */
378
+ const finishTimeout = Duration.seconds(5)
379
+
380
+ type FailureCause<E> = ChatMarkdownError<E>["cause"]
381
+
382
+ interface Current {
383
+ readonly start: number
384
+ readonly fence: Fence | undefined
385
+ readonly prefix: string
386
+ readonly transport: Part["transport"]
387
+ /** Appending to an open native stream. */
388
+ native: boolean
389
+ posted: Posted | undefined
390
+ /** The input index the platform confirmed up to. */
391
+ confirmed: number
392
+ /** The input index a write that failed `uncertain` reached. */
393
+ uncertain: number
394
+ /** Native: the input index appended up to. */
395
+ sent: number
396
+ /** The input length when this part was last written. */
397
+ attempted: number
398
+ /** The Markdown the platform last confirmed. */
399
+ markdown: string
400
+ startedAt: number
401
+ retries: number
402
+ /** A stop to send, and what follows it. Kept until the platform answers, so a stop cut off is sent again. */
403
+ closing: Closing | undefined
404
+ /** A user clicked stop during a repair: the part is written up to here, then the reply ends. */
405
+ stoppedAt: number | undefined
406
+ }
407
+
408
+ interface Closing {
409
+ readonly end: "done" | "rotating"
410
+ readonly onStop: (stopped: boolean) => void
411
+ }
412
+
413
+ interface ReplyOptions<E, R, R2> extends Options<R2> {
414
+ readonly thread: ChatThread
415
+ readonly initial: string
416
+ readonly deltas?: Stream.Stream<string, E, R> | undefined
417
+ readonly descriptor: Descriptor
418
+ readonly chat: Chat.Chat["Service"]
419
+ readonly native?: NativeStream | undefined
420
+ readonly recipient?: string | undefined
421
+ readonly files?: ReadonlyArray<File> | undefined
422
+ readonly actions?: ReadonlyArray<Action> | undefined
423
+ readonly unattachedNote?: ((files: ReadonlyArray<File>) => string) | undefined
424
+ }
425
+
426
+ const firstError = <A>(exit: Exit.Exit<A, ChatError>): ChatError | undefined =>
427
+ Option.getOrUndefined(Exit.findErrorOption(exit))
428
+
429
+ /** Whether a write was cut off before the platform answered. */
430
+ const unanswered = <A>(exit: Exit.Exit<A, ChatError>): boolean =>
431
+ Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)
432
+
433
+ /** Whether the adapter guarantees the files were refused and nothing remains posted. */
434
+ const isFileRefusal = <A>(exit: Exit.Exit<A, ChatError>): boolean => {
435
+ const reason = firstError(exit)?.reason
436
+ return reason?.retry === "denied" && reason.detail === fileRefused
437
+ }
438
+
439
+ const reply = <E, R, R2>(options: ReplyOptions<E, R, R2>): Effect.Effect<Result, ChatMarkdownError<E>, R | R2> =>
440
+ Effect.suspend(() => {
441
+ const { chat, descriptor, thread } = options
442
+ const measure = descriptor.measure
443
+ const limits = descriptor.limits
444
+ const interval = Duration.toMillis(options.minWriteInterval ?? limits.minWriteInterval)
445
+ let maxParts = Math.max(1, options.maxParts ?? defaultMaxParts)
446
+ const overflow = options.overflow ?? "fail"
447
+ const streamLength = Math.min(limits.streamLength ?? limits.messageLength, limits.messageLength)
448
+ const streamAge = limits.streamAge === undefined ? undefined : Duration.toMillis(limits.streamAge)
449
+ const onPart = options.onPart ?? (() => Effect.void)
450
+ const native = options.native
451
+ const latch = Latch.makeUnsafe(false)
452
+ /** Opens when the upstream fails, which ends the loop even while a write is in flight. */
453
+ const upstreamFailed = Latch.makeUnsafe(false)
454
+ /** Holds the write fibers, so they outlive the loop and the finalizer can wait for them. */
455
+ const writes = Scope.makeUnsafe()
456
+
457
+ let input = options.initial
458
+ let upstream: Exit.Exit<void, E> | undefined = options.deltas === undefined ? Exit.void : undefined
459
+ let state: { readonly _tag: "Running" } | { readonly _tag: "Done"; readonly stopped: boolean } | {
460
+ readonly _tag: "Failed"
461
+ readonly cause: FailureCause<E>
462
+ } = { _tag: "Running" }
463
+ let finishing = false
464
+ let nativeAllowed = native !== undefined && options.recipient !== undefined
465
+ /** Without `edit`, a streamed part is posted once, when it is final. */
466
+ const buffered = options.deltas !== undefined && !descriptor.capabilities.has("edit")
467
+ let renderedNatively = false
468
+ let lastWrite = Number.NEGATIVE_INFINITY
469
+ let retryAt: number | undefined
470
+ let overflowStart: number | undefined
471
+ let overflowBytes = 0
472
+ let overflowUncertain = false
473
+ let overflowFilesRefused = false
474
+ let note: string | undefined
475
+ const parts: Array<Part> = []
476
+
477
+ const isRunning = () => state._tag === "Running"
478
+ const fail = (cause: FailureCause<E>) => {
479
+ if (isRunning()) state = { _tag: "Failed", cause }
480
+ }
481
+ const failChat = (error: ChatError) => fail({ _tag: "Chat", error })
482
+ const done = (stopped: boolean) => {
483
+ if (isRunning()) state = { _tag: "Done", stopped }
484
+ }
485
+
486
+ const newPart = (start: number, fence: Fence | undefined): Current => ({
487
+ start,
488
+ fence,
489
+ prefix: reopening(fence),
490
+ transport: options.deltas === undefined ? "post" : nativeAllowed ? "native" : buffered ? "post" : "edit",
491
+ native: nativeAllowed,
492
+ posted: undefined,
493
+ confirmed: start,
494
+ uncertain: start,
495
+ sent: start,
496
+ attempted: -1,
497
+ markdown: "",
498
+ startedAt: 0,
499
+ retries: 0,
500
+ closing: undefined,
501
+ stoppedAt: undefined
502
+ })
503
+
504
+ let current = newPart(0, undefined)
505
+
506
+ const partOf = (
507
+ posted: Posted,
508
+ markdown: string,
509
+ text: string,
510
+ kind: Part["kind"],
511
+ transport: Part["transport"]
512
+ ): Part => ({ messageId: posted.id, timestamp: posted.timestamp, markdown, text, kind, transport })
513
+
514
+ const toPart = (part: Current, posted: Posted, markdown: string, end: number): Part =>
515
+ partOf(posted, markdown, input.slice(part.start, end), "text", part.transport)
516
+
517
+ /** Only the reply's first message replies to `replyTo`. */
518
+ const firstReplyTo = () => parts.length === 0 && options.replyTo !== undefined ? { replyTo: options.replyTo } : {}
519
+
520
+ /** The open fence at `index` of the input, read from the current part's complete lines. */
521
+ const fenceAtInput = (part: Current, index: number): Fence | undefined => {
522
+ const text = input.slice(part.start, index)
523
+ return fenceAt(scanLines(text, part.fence, false), part.fence, text.length)
524
+ }
525
+
526
+ const now = Clock.currentTimeMillis
527
+
528
+ /** Waits for the floor since the previous write returned. */
529
+ const pace: Effect.Effect<void> = Effect.flatMap(now, (time) => {
530
+ const wait = lastWrite + interval - time
531
+ return wait > 0 ? Effect.sleep(Duration.millis(wait)) : Effect.void
532
+ })
533
+ const wrote = Effect.flatMap(now, (time) => Effect.sync(() => void (lastWrite = time)))
534
+
535
+ /**
536
+ * Sends an edit or a stop after the floor. Both are safe to send again, so
537
+ * they stay interruptible. `commit` records the answer, or that there was
538
+ * none, before an interrupt can land.
539
+ */
540
+ const write = <A>(
541
+ effect: Effect.Effect<A, ChatError>,
542
+ commit: (exit: Exit.Exit<A, ChatError>) => void
543
+ ): Effect.Effect<void> =>
544
+ Effect.andThen(
545
+ pace,
546
+ Effect.uninterruptibleMask((restore) =>
547
+ Effect.exit(restore(effect)).pipe(
548
+ Effect.ensuring(wrote),
549
+ Effect.flatMap((exit) => Effect.sync(() => commit(exit)))
550
+ )
551
+ )
552
+ )
553
+
554
+ /** The post, start or append in flight. */
555
+ let inflight: Fiber.Fiber<unknown> | undefined
556
+
557
+ /**
558
+ * Sends a post, a start or an append after the floor. Sending one again
559
+ * could repeat text, so neither an interrupt of the reply nor a failure of
560
+ * the upstream cuts it off: it runs in a fiber of its own, outside the
561
+ * loop, which commits the answer, and the finalizer waits for it. Only the
562
+ * finish timeout cuts it off, and `commit` then records that there was no
563
+ * answer.
564
+ */
565
+ const send = <A>(
566
+ effect: Effect.Effect<A, ChatError>,
567
+ commit: (exit: Exit.Exit<A, ChatError>, time: number) => Effect.Effect<void, never, R2>
568
+ ): Effect.Effect<Exit.Exit<A, ChatError>, never, R2> =>
569
+ Effect.andThen(
570
+ pace,
571
+ Effect.uninterruptibleMask((restore) =>
572
+ Effect.forkIn(
573
+ Effect.uninterruptibleMask((restoreRequest) =>
574
+ Effect.exit(restoreRequest(effect)).pipe(
575
+ Effect.ensuring(wrote),
576
+ Effect.tap((exit) => Effect.flatMap(now, (time) => commit(exit, time))),
577
+ Effect.ensuring(Effect.sync(() => void (inflight = undefined)))
578
+ )
579
+ ),
580
+ writes
581
+ ).pipe(Effect.flatMap((fiber) => {
582
+ inflight = fiber
583
+ return restore(Fiber.join(fiber))
584
+ }))
585
+ )
586
+ )
587
+
588
+ /**
589
+ * Creates a message, records it and runs `onPart` for it, in one commit,
590
+ * so an interrupt can neither lose an id nor make the finalizer create the
591
+ * message again.
592
+ */
593
+ const create = (
594
+ effect: Effect.Effect<Posted, ChatError>,
595
+ part: (posted: Posted) => Part,
596
+ commit: (exit: Exit.Exit<Posted, ChatError>, time: number) => void
597
+ ): Effect.Effect<Exit.Exit<Posted, ChatError>, never, R2> =>
598
+ send(effect, (exit, time) => {
599
+ commit(exit, time)
600
+ return Exit.isSuccess(exit) ? onPart(part(exit.value)) : Effect.void
601
+ })
602
+
603
+ const finishPart = (end: number) => {
604
+ const part = current
605
+ parts.push(toPart(part, part.posted!, part.markdown, end))
606
+ current = newPart(end, fenceAtInput(part, end))
607
+ if (parts.length >= maxParts) {
608
+ overflowStart = end
609
+ overflowBytes = utf8Length(input.slice(end))
610
+ }
611
+ }
612
+
613
+ /** Ends the reply. Blank text left over is given to the last part, since it can't be posted alone. */
614
+ const finishReply = (from: number) => {
615
+ const rest = input.slice(from)
616
+ const last = parts.length - 1
617
+ if (rest !== "" && last >= 0) parts[last] = { ...parts[last], text: parts[last].text + rest }
618
+ done(false)
619
+ }
620
+
621
+ const hasFiles = (options.files?.length ?? 0) > 0
622
+ const actions = options.actions ?? []
623
+ const hasActions = actions.length > 0
624
+ /** What the reply's last part costs, measured with the actions it carries. */
625
+ const measureLast = hasActions ? (markdown: string) => measure(markdown, actions) : measure
626
+ /** The last part takes the files and the actions. */
627
+ const hasExtras = hasFiles || hasActions
628
+ /**
629
+ * Set when not even the text's last grapheme cluster fits beside the
630
+ * actions: the text is posted without them, and the files and the
631
+ * actions follow in a message of their own.
632
+ */
633
+ let extrasAlone = false
634
+ /** Whether the note posted on its own takes the actions. */
635
+ let noteActions = false
636
+ /** Set when the actions fit beside neither the text nor the note: they follow in a message of their own. */
637
+ let actionsAfter = false
638
+
639
+ // --- post-then-edit --------------------------------------------------------
640
+
641
+ /**
642
+ * Writes the current part as `input[start, end)`. `last` marks the part's
643
+ * final write, and `withFiles` the reply's last part, which takes the files.
644
+ */
645
+ const writeEdit = (end: number, last: boolean, withFiles: boolean): Effect.Effect<void, never, R2> =>
646
+ Effect.suspend(() => {
647
+ const part = current
648
+ const markdown = render(part.prefix, input.slice(part.start, end), part.fence)
649
+ part.attempted = input.length
650
+ if (part.posted === undefined) return postPart(part, end, markdown, withFiles && hasExtras)
651
+ if (part.confirmed === end && part.markdown === markdown) return Effect.void
652
+ const edit = chat.edit(thread, part.posted.id, { markdown })
653
+ return write(last ? edit : Chat.withoutRetries(edit), (exit) => {
654
+ if (Exit.isSuccess(exit)) {
655
+ part.confirmed = part.uncertain = end
656
+ part.markdown = markdown
657
+ return
658
+ }
659
+ // Cut off, so it may have landed. The finalizer edits again.
660
+ if (unanswered(exit)) part.uncertain = Math.max(part.uncertain, end)
661
+ const error = firstError(exit)
662
+ if (error === undefined) return
663
+ if (error.retry === "uncertain") part.uncertain = Math.max(part.uncertain, end)
664
+ if (last || error.retry === "denied") failChat(error)
665
+ })
666
+ })
667
+
668
+ const postPart = (
669
+ part: Current,
670
+ end: number,
671
+ markdown: string,
672
+ withFiles: boolean
673
+ ): Effect.Effect<void, never, R2> => {
674
+ const files = withFiles && hasFiles ? options.files! : undefined
675
+ const unattachedNote = files === undefined ? undefined : options.unattachedNote
676
+ const withActions = withFiles && hasActions
677
+ const settle = (exit: Exit.Exit<Posted, ChatError>, markdown: string) => {
678
+ if (Exit.isSuccess(exit)) {
679
+ part.posted = exit.value
680
+ part.markdown = markdown
681
+ part.confirmed = part.uncertain = end
682
+ return
683
+ }
684
+ if (unanswered(exit)) part.uncertain = end
685
+ const error = firstError(exit)
686
+ if (error === undefined) return
687
+ if (error.retry === "uncertain") part.uncertain = end
688
+ failChat(error)
689
+ }
690
+ const attempt = (
691
+ markdown: string,
692
+ files: ReadonlyArray<File> | undefined,
693
+ fallback: boolean,
694
+ withActions: boolean
695
+ ) =>
696
+ create(
697
+ chat.post(thread, {
698
+ markdown,
699
+ ...firstReplyTo(),
700
+ ...(files === undefined ? {} : { files }),
701
+ ...(withActions ? { actions } : {})
702
+ }),
703
+ (posted) => toPart(part, posted, markdown, end),
704
+ (exit) => {
705
+ // Left unsettled: the post goes out again without the files.
706
+ if (fallback && isFileRefusal(exit)) return
707
+ settle(exit, markdown)
708
+ }
709
+ )
710
+ const withoutFiles = () => {
711
+ // Replace refused files with the unattached note.
712
+ const text = unattachedNote!(files!)
713
+ if (measureLast(markdown + text) <= limits.messageLength) {
714
+ return Effect.asVoid(attempt(markdown + text, undefined, false, withActions))
715
+ }
716
+ // The note is the last message now, so it takes the actions, or they follow it on their own.
717
+ noteActions = withActions && measure(text, actions) <= limits.messageLength
718
+ actionsAfter = withActions && !noteActions
719
+ // With no text to post, this part is the note.
720
+ if (isBlank(markdown)) return Effect.asVoid(attempt(text, undefined, false, noteActions))
721
+ note = text
722
+ return Effect.asVoid(attempt(markdown, undefined, false, false))
723
+ }
724
+ if (overflowFilesRefused && files !== undefined) return withoutFiles()
725
+ return Effect.flatMap(
726
+ attempt(markdown, files, unattachedNote !== undefined, withActions),
727
+ (exit) => unattachedNote !== undefined && isFileRefusal(exit) ? withoutFiles() : Effect.void
728
+ )
729
+ }
730
+
731
+ /** Posts a message after the text that is not part of it: the unattached note, or the actions alone. */
732
+ const postAfter = (text: string, withActions: boolean): Effect.Effect<void, never, R2> => {
733
+ const part = (posted: Posted) => partOf(posted, text, "", "text", "post")
734
+ const post = chat.post(thread, { markdown: text, ...(withActions ? { actions } : {}) })
735
+ return Effect.flatMap(
736
+ create(post, part, (exit) => {
737
+ if (Exit.isSuccess(exit)) return void parts.push(part(exit.value))
738
+ const error = firstError(exit)
739
+ if (error !== undefined) failChat(error)
740
+ }),
741
+ () => isRunning() ? finishAfter : Effect.void
742
+ )
743
+ }
744
+
745
+ /**
746
+ * Ends the reply once the text is posted: the unattached note that did
747
+ * not fit the last part follows, then the actions when they fit beside
748
+ * neither. The actions' message counts against `maxParts`, and with no
749
+ * part left the reply fails `Overflow`.
750
+ */
751
+ const finishAfter: Effect.Effect<void, never, R2> = Effect.suspend(() => {
752
+ if (note !== undefined) {
753
+ const text = note
754
+ note = undefined
755
+ return postAfter(text, noteActions)
756
+ }
757
+ if (actionsAfter) {
758
+ actionsAfter = false
759
+ if (parts.length >= maxParts) {
760
+ fail({ _tag: "Overflow" })
761
+ return Effect.void
762
+ }
763
+ return postAfter("", true)
764
+ }
765
+ done(false)
766
+ return Effect.void
767
+ })
768
+
769
+ /**
770
+ * Posts the files and the actions in a message of their own, after the
771
+ * text. It counts against `maxParts`, and there is no text left to put in
772
+ * an overflow file, so with no part left the reply fails `Overflow`.
773
+ */
774
+ const postExtras: Effect.Effect<void, never, R2> = Effect.suspend(() => {
775
+ extrasAlone = false
776
+ if (parts.length >= maxParts) {
777
+ fail({ _tag: "Overflow" })
778
+ return Effect.void
779
+ }
780
+ const part = newPart(input.length, undefined)
781
+ current = part
782
+ return Effect.flatMap(postPart(part, input.length, "", true), () => {
783
+ if (!isRunning()) return Effect.void
784
+ finishPart(input.length)
785
+ return finishAfter
786
+ })
787
+ })
788
+
789
+ const stepEdit = (final: boolean): Effect.Effect<void, never, R2> =>
790
+ Effect.suspend(() => {
791
+ const part = current
792
+ if (part.stoppedAt !== undefined) {
793
+ // A user clicked stop during a repair: settle what was sent, then end the reply.
794
+ return Effect.map(writeEdit(part.stoppedAt, false, false), () => {
795
+ if (!isRunning()) return
796
+ finishPart(part.confirmed)
797
+ done(true)
798
+ })
799
+ }
800
+ const body = input.slice(part.start)
801
+ if (part.posted === undefined && isBlank(body) && !(final && hasExtras && parts.length === 0)) {
802
+ if (final) finishReply(part.start)
803
+ return Effect.void
804
+ }
805
+ const end = (last: boolean): Effect.Effect<void, never, R2> => {
806
+ if (!last || !isRunning()) return Effect.void
807
+ return extrasAlone ? postExtras : finishAfter
808
+ }
809
+ const cutAt = (cut: number): Effect.Effect<void, never, R2> => {
810
+ // Only blank text follows the cut: this is the last part, so it takes the files, the actions and that text.
811
+ const last = final && isBlank(input.slice(cut))
812
+ return Effect.flatMap(writeEdit(cut, true, last && !extrasAlone), () => {
813
+ if (!isRunning()) return Effect.void
814
+ finishPart(last ? input.length : cut)
815
+ return end(last)
816
+ })
817
+ }
818
+ /** A cut that would end the reply has to leave room for the actions. */
819
+ const lastFits = (cut: number) =>
820
+ !final || !hasActions || extrasAlone || !isBlank(input.slice(cut)) ||
821
+ measureLast(render(part.prefix, input.slice(part.start, cut), part.fence)) <= limits.messageLength
822
+ const cut = measure(render(part.prefix, body, part.fence)) > limits.messageLength
823
+ ? part.start + fitCut(measure, body, part.fence, part.prefix, limits.messageLength)
824
+ : input.length
825
+ if (!lastFits(cut)) {
826
+ // Reserve the last grapheme for a part with actions. If they cannot
827
+ // fit together, send the actions in their own message.
828
+ const keep = lastContentStart(body)
829
+ const tailStart = part.start + keep
830
+ const tailFence = fenceAtInput(part, tailStart)
831
+ const tail = render(reopening(tailFence), input.slice(tailStart), tailFence)
832
+ if (keep > 0 && measureLast(tail) <= limits.messageLength) {
833
+ return cutAt(
834
+ part.start + fitCut(measure, body.slice(0, keep), part.fence, part.prefix, limits.messageLength)
835
+ )
836
+ }
837
+ extrasAlone = true
838
+ }
839
+ if (cut < input.length) return cutAt(cut)
840
+ if (buffered && !final) {
841
+ // Nothing to post until the part is final: it rolls over or the reply ends.
842
+ part.attempted = input.length
843
+ return Effect.void
844
+ }
845
+ return Effect.flatMap(writeEdit(input.length, final, final && !extrasAlone), () => {
846
+ if (final && isRunning()) finishPart(input.length)
847
+ return end(final)
848
+ })
849
+ })
850
+
851
+ // --- native ----------------------------------------------------------------
852
+
853
+ /** Sends the stop the current part is closing with. A stop carries no text, so its failures are ignored. */
854
+ const sendStop = (part: Current, closing: Closing): Effect.Effect<void> =>
855
+ write(native!.stop(thread, part.posted!.id, { end: closing.end }), (exit) => {
856
+ // Cut off, so the stream may still be open. The finalizer sends the stop again.
857
+ if (unanswered(exit)) return
858
+ part.closing = undefined
859
+ part.native = false
860
+ closing.onStop(Exit.isSuccess(exit) && exit.value.stopped)
861
+ })
862
+
863
+ /** Ends a native part at `end` once its stop is answered. The reply ends when `last`, or when a user had clicked stop. */
864
+ const rollNative = (part: Current, end: number, last: boolean) => {
865
+ part.closing = {
866
+ end: last ? "done" : "rotating",
867
+ onStop: (stopped) => {
868
+ finishPart(end)
869
+ if (stopped) done(true)
870
+ else if (last) finishReply(end)
871
+ }
872
+ }
873
+ }
874
+
875
+ /**
876
+ * Stops the stream and carries on by post-then-edit: the next edit writes
877
+ * the part's whole known text, the chunk that failed included.
878
+ */
879
+ const repair = (part: Current) => {
880
+ part.closing = {
881
+ end: "rotating",
882
+ onStop: (stopped) => {
883
+ part.attempted = -1
884
+ if (stopped) part.stoppedAt = Math.max(part.uncertain, part.sent)
885
+ }
886
+ }
887
+ }
888
+
889
+ const startNative = (final: boolean): Effect.Effect<void, never, R2> =>
890
+ Effect.suspend(() => {
891
+ const part = current
892
+ const pending = input.slice(part.start)
893
+ const text = final ? pending : releasable(pending, part.fence)
894
+ if (isBlank(text)) {
895
+ if (final) finishReply(part.start)
896
+ return Effect.void
897
+ }
898
+ part.attempted = input.length
899
+ // Measured with the closing fence, so a start leaves room to close it.
900
+ const whole = render(part.prefix, text, part.fence)
901
+ const cut = measure(whole) > streamLength
902
+ ? fitCut(measure, text, part.fence, part.prefix, streamLength)
903
+ : text.length
904
+ const end = part.start + cut
905
+ const roll = cut < text.length
906
+ const markdown = roll || final ? render(part.prefix, text.slice(0, cut), part.fence) : part.prefix + text
907
+ return Effect.asVoid(
908
+ create(
909
+ native!.start(thread, {
910
+ markdown,
911
+ ...firstReplyTo(),
912
+ ...(parts.length === 0 ? {} : { continues: parts[parts.length - 1].messageId }),
913
+ recipient: options.recipient
914
+ }),
915
+ (posted) => toPart(part, posted, markdown, end),
916
+ (exit, time) => {
917
+ if (Exit.isSuccess(exit)) {
918
+ renderedNatively = true
919
+ part.posted = exit.value
920
+ part.markdown = markdown
921
+ part.confirmed = part.uncertain = part.sent = end
922
+ part.startedAt = time
923
+ if (roll || final) rollNative(part, end, !roll)
924
+ return
925
+ }
926
+ if (unanswered(exit)) part.uncertain = end
927
+ const error = firstError(exit)
928
+ if (error === undefined) return
929
+ if (error.reason._tag === "Unsupported" && !renderedNatively) {
930
+ nativeAllowed = false
931
+ current = newPart(part.start, part.fence)
932
+ return
933
+ }
934
+ if (error.retry === "uncertain") part.uncertain = end
935
+ failChat(error)
936
+ }
937
+ )
938
+ )
939
+ })
940
+
941
+ /**
942
+ * What the next append sends, and whether the part ends after it. Every
943
+ * append leaves room to close the code fence it ends in, so a part that
944
+ * rolls over on length always ends with its fence closed. `rotate` sends
945
+ * just that closing fence, for a stream about to rotate on age.
946
+ */
947
+ const nextAppend = (part: Current, final: boolean, rotate: boolean) => {
948
+ const pending = input.slice(part.sent)
949
+ const fence = fenceAtInput(part, part.sent)
950
+ const lines = scanLines(pending, fence, false)
951
+ const size = (text: string) => measure(part.markdown + text)
952
+ const closeAt = (piece: string) => closing(fenceAt(lines, fence, piece.length), part.markdown + piece)
953
+ const closeOnly = { piece: "", extra: closeAt(""), roll: true }
954
+ if (rotate) return closeOnly
955
+ const soft = softShare * streamLength
956
+ const piece = final ? pending : releasable(pending, fence)
957
+ const reserve = final
958
+ ? closing(fenceAt(scanLines(pending, fence, true), fence, pending.length), part.markdown + pending)
959
+ : closeAt(piece)
960
+ const extra = final ? reserve : ""
961
+ if (size(piece + reserve) <= soft) return { piece, extra, roll: false }
962
+ for (const line of lines) {
963
+ if (!line.boundary || line.end > piece.length) continue
964
+ const measured = size(pending.slice(0, line.end))
965
+ if (measured > streamLength) break
966
+ if (measured >= soft) return { piece: pending.slice(0, line.end), extra: "", roll: true }
967
+ }
968
+ if (size(piece + reserve) <= streamLength) return { piece, extra, roll: false }
969
+ const cut = pending.slice(0, fitCut(measure, pending, fence, part.markdown, streamLength))
970
+ // Not even the smallest cut fits with its closing fence: send just the closing fence.
971
+ return size(cut + closeAt(cut)) <= streamLength ? { piece: cut, extra: closeAt(cut), roll: true } : closeOnly
972
+ }
973
+
974
+ /**
975
+ * Appends the next piece. What follows, a rollover, a repair or a retry,
976
+ * is recorded in the commit, so an interrupt can't lose it.
977
+ */
978
+ const appendNative = (final: boolean, rotate: boolean): Effect.Effect<void, never, R2> =>
979
+ Effect.suspend(() => {
980
+ const part = current
981
+ const { extra, piece, roll } = nextAppend(part, final, rotate)
982
+ if (piece === "" && extra === "") {
983
+ if (roll || final) rollNative(part, part.sent, !roll)
984
+ return Effect.void
985
+ }
986
+ part.attempted = input.length
987
+ const markdown = piece + extra
988
+ const commit = (
989
+ exit: Exit.Exit<{ readonly state: string; readonly held: number }, ChatError>,
990
+ time: number
991
+ ) => {
992
+ if (Exit.isSuccess(exit)) {
993
+ const { held, state } = exit.value
994
+ if (state === "stopped") {
995
+ part.native = false
996
+ finishPart(part.sent)
997
+ done(true)
998
+ } else if (state === "closed") {
999
+ part.native = false
1000
+ part.attempted = -1
1001
+ } else {
1002
+ const added = Math.max(0, markdown.length - held)
1003
+ part.retries = 0
1004
+ part.sent += Math.min(piece.length, added)
1005
+ part.confirmed = part.uncertain = part.sent
1006
+ part.markdown += markdown.slice(0, added)
1007
+ if (roll || (final && part.sent === input.length)) rollNative(part, part.sent, !roll)
1008
+ }
1009
+ return
1010
+ }
1011
+ // Cut off by the finish timeout, so it may have landed.
1012
+ if (unanswered(exit)) {
1013
+ part.uncertain = part.sent + piece.length
1014
+ return
1015
+ }
1016
+ const error = firstError(exit)
1017
+ if (error === undefined) return
1018
+ if (error.reason._tag === "TooLarge") {
1019
+ // Retry the chunk in the next part.
1020
+ rollNative(part, part.sent, false)
1021
+ } else if (error.retry === "retry") {
1022
+ part.retries++
1023
+ if (part.retries >= appendRetryLimit) repair(part)
1024
+ else retryAt = time + (error.retryAfter === undefined ? interval : Duration.toMillis(error.retryAfter))
1025
+ } else if (error.retry === "uncertain") {
1026
+ part.uncertain = part.sent + piece.length
1027
+ repair(part)
1028
+ } else {
1029
+ failChat(error)
1030
+ part.closing = { end: "done", onStop: () => {} }
1031
+ }
1032
+ }
1033
+ return Effect.asVoid(
1034
+ send(
1035
+ native!.append(thread, part.posted!.id, markdown, { flush: final || roll }),
1036
+ (exit, time) => Effect.sync(() => commit(exit, time))
1037
+ )
1038
+ )
1039
+ })
1040
+
1041
+ const stepNative = (final: boolean): Effect.Effect<void, never, R2> =>
1042
+ Effect.suspend(() => {
1043
+ const part = current
1044
+ if (part.posted === undefined) return startNative(final)
1045
+ if (final || streamAge === undefined) return appendNative(final, false)
1046
+ return Effect.flatMap(now, (time) => appendNative(final, time - part.startedAt >= ageShare * streamAge))
1047
+ })
1048
+
1049
+ // --- overflow --------------------------------------------------------------
1050
+
1051
+ const stepOverflow = (final: boolean): Effect.Effect<void, never, R2> =>
1052
+ Effect.suspend(() => {
1053
+ const start = overflowStart!
1054
+ const rest = input.slice(start)
1055
+ if (isBlank(rest)) {
1056
+ if (final) finishReply(start)
1057
+ return Effect.void
1058
+ }
1059
+ if (overflow === "fail" || overflowBytes > limits.uploadBytes) {
1060
+ fail({ _tag: "Overflow" })
1061
+ return Effect.void
1062
+ }
1063
+ // The upload is skipped when the reply failed or was interrupted.
1064
+ if (!final || finishing) {
1065
+ if (finishing) done(false)
1066
+ return Effect.void
1067
+ }
1068
+ const file: File = {
1069
+ name: overflow.file.name,
1070
+ contentType: "text/markdown",
1071
+ content: new TextEncoder().encode(rest)
1072
+ }
1073
+ const part = (markdown: string) => (posted: Posted) => partOf(posted, markdown, rest, "overflowFile", "post")
1074
+ // Attach consumer files to the final message.
1075
+ const attempt = (markdown: string, files: ReadonlyArray<File>, fallback: boolean) =>
1076
+ create(
1077
+ chat.post(thread, { markdown, files: [file, ...files], ...(hasActions ? { actions } : {}) }),
1078
+ part(markdown),
1079
+ (exit) => {
1080
+ if (Exit.isSuccess(exit)) {
1081
+ parts.push(part(markdown)(exit.value))
1082
+ overflowStart = input.length
1083
+ return done(false)
1084
+ }
1085
+ if (fallback && isFileRefusal(exit)) return
1086
+ if (unanswered(exit)) overflowUncertain = true
1087
+ const error = firstError(exit)
1088
+ if (error === undefined) return
1089
+ overflowUncertain = error.retry === "uncertain"
1090
+ failChat(error)
1091
+ }
1092
+ )
1093
+ const files = options.files ?? []
1094
+ const unattachedNote = files.length === 0 ? undefined : options.unattachedNote
1095
+ return Effect.asVoid(Effect.map(attempt("", files, unattachedNote !== undefined), (exit) => {
1096
+ if (unattachedNote === undefined || !isFileRefusal(exit)) return
1097
+ // The overflow file was refused too. Drain the remaining text through
1098
+ // the normal splitter, without files or another maxParts overflow.
1099
+ overflowFilesRefused = true
1100
+ overflowStart = undefined
1101
+ maxParts = Infinity
1102
+ nativeAllowed = false
1103
+ current.native = false
1104
+ }))
1105
+ })
1106
+
1107
+ // --- the loop --------------------------------------------------------------
1108
+
1109
+ /** Whether there is a write to make. A stop is sent even after the reply failed. */
1110
+ const active = () => isRunning() || current.closing !== undefined
1111
+
1112
+ const hasWork = (): boolean => {
1113
+ if (!isRunning() || upstream !== undefined || current.closing !== undefined) return true
1114
+ if (overflowStart !== undefined) {
1115
+ return !isBlank(input.slice(overflowStart)) && (overflow === "fail" || overflowBytes > limits.uploadBytes)
1116
+ }
1117
+ const part = current
1118
+ if (input.length <= part.attempted) return false
1119
+ if (!part.native) return !isBlank(input.slice(part.start))
1120
+ return part.posted === undefined
1121
+ ? !isBlank(releasable(input.slice(part.start), part.fence))
1122
+ : releasable(input.slice(part.sent), fenceAtInput(part, part.sent)) !== ""
1123
+ }
1124
+
1125
+ /** Waits until there is something to write, or a retry is due. */
1126
+ const awaitWork: Effect.Effect<void> = Effect.suspend(() => {
1127
+ if (retryAt !== undefined) {
1128
+ const at = retryAt
1129
+ retryAt = undefined
1130
+ return Effect.flatMap(now, (time) => time < at ? Effect.sleep(Duration.millis(at - time)) : Effect.void)
1131
+ }
1132
+ if (hasWork()) return Effect.void
1133
+ latch.closeUnsafe()
1134
+ return Effect.andThen(latch.await, awaitWork)
1135
+ })
1136
+
1137
+ const step = (final: boolean): Effect.Effect<void, never, R2> => {
1138
+ const closing = current.closing
1139
+ if (closing !== undefined) return sendStop(current, closing)
1140
+ if (overflowStart !== undefined) return stepOverflow(final)
1141
+ return current.native ? stepNative(final) : stepEdit(final)
1142
+ }
1143
+
1144
+ const loop: Effect.Effect<void, never, R2> = Effect.suspend(() =>
1145
+ active() ?
1146
+ Effect.flatMap(awaitWork, () => {
1147
+ if (!active()) return Effect.void
1148
+ if (current.closing === undefined && upstream !== undefined && Exit.isFailure(upstream)) return Effect.void
1149
+ // The write takes whatever arrived while it waited for the floor.
1150
+ return Effect.andThen(pace, Effect.suspend(() => step(upstream !== undefined))).pipe(Effect.andThen(loop))
1151
+ }) :
1152
+ Effect.void
1153
+ )
1154
+
1155
+ /** Writes what was received as the end of the reply, closing an open fence, within a short timeout. */
1156
+ const finish: Effect.Effect<void, never, R2> = Effect.suspend(() => {
1157
+ finishing = true
1158
+ const drain: Effect.Effect<void, never, R2> = Effect.suspend(() =>
1159
+ active() ? Effect.andThen(step(true), drain) : Effect.void
1160
+ )
1161
+ // A write in flight commits first. Interruptible, so the timeout can cut it short in the interrupt finalizer.
1162
+ const awaitInflight = Effect.suspend(() => inflight === undefined ? Effect.void : Fiber.await(inflight))
1163
+ return Effect.timeoutOption(Effect.interruptible(Effect.andThen(awaitInflight, drain)), finishTimeout).pipe(
1164
+ Effect.andThen(Effect.suspend(() => inflight === undefined ? Effect.void : Fiber.interrupt(inflight))),
1165
+ Effect.asVoid
1166
+ )
1167
+ })
1168
+
1169
+ const toError = (cause: FailureCause<E>): ChatMarkdownError<E> => {
1170
+ const posted = parts.slice()
1171
+ let uncertain = ""
1172
+ let from: number
1173
+ if (overflowStart !== undefined) {
1174
+ from = overflowStart
1175
+ if (overflowUncertain) {
1176
+ uncertain = input.slice(from)
1177
+ from = input.length
1178
+ }
1179
+ } else {
1180
+ const part = current
1181
+ if (part.posted !== undefined) posted.push(toPart(part, part.posted, part.markdown, part.confirmed))
1182
+ from = Math.max(part.confirmed, part.uncertain)
1183
+ uncertain = input.slice(part.confirmed, from)
1184
+ }
1185
+ // Read from the start of the input, so it holds whichever part the cut fell in.
1186
+ const fence = from === input.length
1187
+ ? undefined
1188
+ : fenceAt(scanLines(input.slice(0, from), undefined, false), undefined, from)
1189
+ return new ChatMarkdownError<E>({
1190
+ posted,
1191
+ remaining: input.slice(from),
1192
+ ...(fence === undefined ? {} : { remainingFence: fence.line }),
1193
+ ...(uncertain === "" ? {} : { uncertain }),
1194
+ cause
1195
+ })
1196
+ }
1197
+
1198
+ const consume: Effect.Effect<void, never, R> = options.deltas === undefined
1199
+ ? Effect.void
1200
+ : Effect.flatMap(
1201
+ Effect.exit(Stream.runForEach(options.deltas, (chunk) =>
1202
+ Effect.sync(() => {
1203
+ input += chunk
1204
+ if (overflowStart !== undefined) overflowBytes += utf8Length(chunk)
1205
+ latch.openUnsafe()
1206
+ }))),
1207
+ (exit) =>
1208
+ Effect.sync(() => {
1209
+ upstream = exit
1210
+ latch.openUnsafe()
1211
+ if (Exit.isFailure(exit)) upstreamFailed.openUnsafe()
1212
+ })
1213
+ )
1214
+
1215
+ return Effect.gen(function*() {
1216
+ const fiber = yield* Effect.forkChild(consume)
1217
+ // A failed upstream ends the loop at once, so the finish timeout starts even while a write is in flight.
1218
+ yield* Effect.onInterrupt(
1219
+ Effect.raceFirst(loop, upstreamFailed.await),
1220
+ () => Effect.andThen(Fiber.interrupt(fiber), finish)
1221
+ )
1222
+ yield* Fiber.interrupt(fiber)
1223
+ if (upstream !== undefined && Exit.isFailure(upstream) && (isRunning() || state._tag === "Done")) {
1224
+ const cause = upstream.cause
1225
+ state = { _tag: "Running" }
1226
+ yield* finish
1227
+ const error = Cause.findErrorOption(cause)
1228
+ if (Option.isNone(error)) return yield* Effect.failCause(cause as Cause.Cause<never>)
1229
+ state = { _tag: "Failed", cause: { _tag: "Upstream", error: error.value } }
1230
+ } else if (current.closing !== undefined || inflight !== undefined) {
1231
+ // The reply failed already, and the race cut off its stop or write. The finish sends only that stop,
1232
+ // within the timeout, since a failed reply writes no more text, and keeps the error it failed with.
1233
+ yield* finish
1234
+ }
1235
+ yield* Effect.annotateCurrentSpan("chat.markdown.transport", renderedNatively ? "native" : current.transport)
1236
+ if (state._tag === "Failed") return yield* Effect.fail(toError(state.cause))
1237
+ return { parts, stopped: state._tag === "Done" && state.stopped }
1238
+ }).pipe(Effect.ensuring(Scope.close(writes, Exit.void)))
1239
+ })
1240
+
1241
+ // -----------------------------------------------------------------------------
1242
+ // the calls
1243
+ // -----------------------------------------------------------------------------
1244
+
1245
+ /**
1246
+ * Posts Markdown of any length, split into as many messages as it needs.
1247
+ *
1248
+ * **Details**
1249
+ *
1250
+ * - A part ends at a block boundary: after a blank line or a closed code
1251
+ * fence. A block too long for one message is cut at a line, closing the code
1252
+ * fence it is in and reopening it in the next part. Length is measured with
1253
+ * the adapter's `measure`.
1254
+ * - Each part is posted once and never edited. Parts are paced by
1255
+ * `minWriteInterval`.
1256
+ * - `files` go with the last part, or with the overflow file when there is
1257
+ * one. Blank text after the last cut stays with the last part.
1258
+ * - With `unattachedNote`, a post with files that fails `denied` with
1259
+ * detail `file_refused` is tried once more without them, ending in the note,
1260
+ * or followed by the note when it does not fit. Any failure of that post
1261
+ * fails the call. Without `unattachedNote` the first failure fails the
1262
+ * call. If the overflow file is refused too, the remaining text is split
1263
+ * into messages beyond `maxParts`, without files and ending in the note.
1264
+ * An `uncertain` failure records the part in `uncertain` and posts no note.
1265
+ * - `actions` go with the last part too, which is cut so that
1266
+ * `measure(part, actions) <= limits.messageLength`. The parts before it
1267
+ * are filled without room for them. When not even the text's last grapheme
1268
+ * cluster fits beside the actions, the files and the actions go in a
1269
+ * message of their own after the text. Either can add a part, which counts
1270
+ * against `maxParts`. When `measure("", actions)` is already over, the
1271
+ * call fails `TooLarge` before anything is posted.
1272
+ * - An unattached note posted on its own takes the actions. When they don't
1273
+ * fit beside it, they follow it in a message of their own, which counts
1274
+ * against `maxParts`.
1275
+ * - A `TooLarge` without detail `file_refused` fails the call, even with
1276
+ * `subject: "files"` or text that measured as fitting. Fallback requires
1277
+ * `denied` plus `file_refused`; `subject` never controls it.
1278
+ * - An empty input posts nothing and succeeds with no parts, unless there are
1279
+ * files or actions, which then go out in a message of their own.
1280
+ *
1281
+ * **Gotchas**
1282
+ *
1283
+ * A failure in the middle leaves the parts already posted in place. The error
1284
+ * says what was posted and what was not.
1285
+ *
1286
+ * @stability unstable
1287
+ * @category constructors
1288
+ * @since 4.1.5
1289
+ */
1290
+ export const post = <R = never>(
1291
+ thread: ChatThread,
1292
+ markdown: string,
1293
+ options?: Options<R> & {
1294
+ readonly files?: ReadonlyArray<File> | undefined
1295
+ readonly actions?: ReadonlyArray<Action> | undefined
1296
+ readonly unattachedNote?: ((files: ReadonlyArray<File>) => string) | undefined
1297
+ }
1298
+ ): Effect.Effect<Result, ChatMarkdownError, Chat.Chat | R> =>
1299
+ Effect.gen(function*() {
1300
+ const chat = yield* Chat.Chat
1301
+ const failed = (error: ChatError) =>
1302
+ new ChatMarkdownError<never>({ posted: [], remaining: markdown, cause: { _tag: "Chat", error } })
1303
+ const descriptor = yield* Effect.mapError(chat.descriptor(thread.platform), failed)
1304
+ const actions = options?.actions ?? []
1305
+ if (actions.length > 0 && descriptor.measure("", actions) > descriptor.limits.messageLength) {
1306
+ return yield* Effect.fail(failed(
1307
+ new ChatError({
1308
+ platform: thread.platform,
1309
+ op: "post",
1310
+ reason: new TooLarge({ detail: "actions_too_long" })
1311
+ })
1312
+ ))
1313
+ }
1314
+ return yield* reply<never, never, R>({ ...options, thread, initial: markdown, descriptor, chat })
1315
+ }).pipe(Effect.withSpan("ChatMarkdown.post", { attributes: { "chat.platform": thread.platform } }))
1316
+
1317
+ /**
1318
+ * Writes a stream of Markdown deltas as one reply, as the text arrives.
1319
+ *
1320
+ * **Details**
1321
+ *
1322
+ * - With a `recipient` and an adapter that has a native stream, the reply is
1323
+ * written by native appends. Otherwise, or when the first native start fails
1324
+ * with `Unsupported`, it posts and then edits. The result and the span say
1325
+ * which ran.
1326
+ * - On an adapter without `edit` the reply is buffered instead: each part is
1327
+ * posted once, when it rolls over or the reply ends, with transport
1328
+ * `post`. Nothing shows until then. An upstream failure or an interrupt
1329
+ * posts what was received, as above.
1330
+ * - Text that outgrows a message rolls over into a new one at a block
1331
+ * boundary, and each new message counts against `maxParts`. A native stream
1332
+ * rolls over at the next block boundary past 85% of `limits.streamLength`,
1333
+ * and rotates once it is 80% of `limits.streamAge` old. Every append leaves
1334
+ * room to close the code fence it ends in, and a rollover or rotation closes
1335
+ * it.
1336
+ * - Writes are paced by `minWriteInterval`, on `Clock`. The next write is
1337
+ * scheduled only after the previous one returns, and takes all the text that
1338
+ * arrived meanwhile.
1339
+ * - An append holds back the unfinished last line, unless inside a code fence.
1340
+ * An edit closes an open code fence.
1341
+ * - An intermediate edit that fails `retry` or `uncertain` is dropped, since
1342
+ * the next edit carries the whole text. A `denied` failure, and any failure
1343
+ * of a post or of a part's last edit, fails the reply.
1344
+ * - A native append that fails `retry` is tried again after its
1345
+ * `retryAfter`, or the write interval, whether or not new text arrived.
1346
+ * Three in a row, or one `uncertain` failure, stop the stream, edit the part
1347
+ * to its whole known text, the failed chunk included, and carry on by
1348
+ * post-then-edit. `TooLarge` starts the next part with the chunk.
1349
+ * - `Result.stopped` is true when a user clicked stop on the reply. The
1350
+ * upstream is then interrupted.
1351
+ * - When the upstream fails or the call is interrupted, what was received is
1352
+ * written out, with an open code fence closed, within a short timeout, and
1353
+ * left posted. The timeout starts at once, even while a write is in
1354
+ * flight. A post, start or append in flight is not cut off by the failure
1355
+ * or the interrupt, since sending it again could repeat text: the finalizer
1356
+ * waits for it, then sends what follows, a stop cut off by the interrupt
1357
+ * included. Only the timeout cuts a write off, and its text is then
1358
+ * reported as `uncertain`.
1359
+ *
1360
+ * **Gotchas**
1361
+ *
1362
+ * - There are no files: post them after the result, when it is known whether
1363
+ * the reply stopped.
1364
+ * - There are no actions either. Add them after the result with
1365
+ * `chat.edit(thread, last.messageId, { markdown: last.markdown, actions })`,
1366
+ * where `last` is the final entry of `Result.parts`. Without `edit` they
1367
+ * can't be added to the reply: post them in a message of their own with
1368
+ * `chat.post(thread, { markdown, actions })`.
1369
+ * - To stop a reply, end `deltas` with `Stream.interruptWhen` or
1370
+ * `Stream.haltWhen`, so a `Result` still comes back. Interrupting the call
1371
+ * leaves only the ids collected through `onPart`.
1372
+ * - Native writes go to the adapter through the `Registry`, so a layer that
1373
+ * wraps `Chat` does not see them.
1374
+ * - A native part that is rolled over on `TooLarge` can end inside an open
1375
+ * code fence, since it can no longer be appended to. The next part reopens
1376
+ * the fence.
1377
+ *
1378
+ * @stability unstable
1379
+ * @category constructors
1380
+ * @since 4.1.5
1381
+ */
1382
+ export const stream = <E, R, R2 = never>(
1383
+ thread: ChatThread,
1384
+ deltas: Stream.Stream<string, E, R>,
1385
+ options?: Options<R2> & {
1386
+ readonly recipient?: string | undefined
1387
+ }
1388
+ ): Effect.Effect<Result, ChatMarkdownError<E>, Chat.Chat | Registry | R | R2> =>
1389
+ Effect.gen(function*() {
1390
+ const chat = yield* Chat.Chat
1391
+ const registry = yield* Registry
1392
+ const adapter = yield* Effect.mapError(
1393
+ registry.get(thread.platform),
1394
+ (error) => new ChatMarkdownError<E>({ posted: [], remaining: "", cause: { _tag: "Chat", error } })
1395
+ )
1396
+ const native = adapter.descriptor.capabilities.has("nativeStream") ? adapter.nativeStream : undefined
1397
+ return yield* reply<E, R, R2>({
1398
+ ...options,
1399
+ thread,
1400
+ initial: "",
1401
+ deltas,
1402
+ descriptor: adapter.descriptor,
1403
+ chat,
1404
+ native
1405
+ })
1406
+ }).pipe(Effect.withSpan("ChatMarkdown.stream", { attributes: { "chat.platform": thread.platform } }))