@effect-uai/core 0.17.0 → 0.19.0-dev-20261109183959

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 (218) hide show
  1. package/README.md +5 -5
  2. package/dist/Content-D_Qfn8Ja.d.mts +48 -0
  3. package/dist/Content-D_Qfn8Ja.d.mts.map +1 -0
  4. package/dist/File-B923KvZ9.d.mts +46 -0
  5. package/dist/File-B923KvZ9.d.mts.map +1 -0
  6. package/dist/{Image-Cv6iBLTy.d.mts → Image-Bzc1H_UK.d.mts} +19 -8
  7. package/dist/Image-Bzc1H_UK.d.mts.map +1 -0
  8. package/dist/{Items-C7MyrYPX.d.mts → Items-Bvx8s9QH.d.mts} +109 -16
  9. package/dist/Items-Bvx8s9QH.d.mts.map +1 -0
  10. package/dist/{Loop-ChpaO-ya.d.mts → Loop-CeA0AelN.d.mts} +7 -6
  11. package/dist/Loop-CeA0AelN.d.mts.map +1 -0
  12. package/dist/Tool-Bkryw6-h.d.mts +206 -0
  13. package/dist/Tool-Bkryw6-h.d.mts.map +1 -0
  14. package/dist/ToolEvent-9inLx5cI.d.mts +22 -0
  15. package/dist/ToolEvent-9inLx5cI.d.mts.map +1 -0
  16. package/dist/ToolOutput-BNTIQgGB.d.mts +151 -0
  17. package/dist/ToolOutput-BNTIQgGB.d.mts.map +1 -0
  18. package/dist/Toolkit-D2VGeD5R.d.mts +212 -0
  19. package/dist/Toolkit-D2VGeD5R.d.mts.map +1 -0
  20. package/dist/browser/BrowserTool.d.mts +84 -22
  21. package/dist/browser/BrowserTool.d.mts.map +1 -1
  22. package/dist/browser/BrowserTool.mjs +5 -0
  23. package/dist/browser/BrowserTool.mjs.map +1 -1
  24. package/dist/capabilities/Capabilities.d.mts +1 -1
  25. package/dist/decision-model/Decision.test.mjs +4 -4
  26. package/dist/dist-B5K-y4Be.mjs +191 -0
  27. package/dist/dist-B5K-y4Be.mjs.map +1 -0
  28. package/dist/dist-CorQTQL-.mjs +1533 -0
  29. package/dist/dist-CorQTQL-.mjs.map +1 -0
  30. package/dist/dist-DNeuh84d.mjs +7 -0
  31. package/dist/dist-DNeuh84d.mjs.map +1 -0
  32. package/dist/dist-DzeSyeYF.mjs +10253 -0
  33. package/dist/dist-DzeSyeYF.mjs.map +1 -0
  34. package/dist/domain/File.d.mts +2 -0
  35. package/dist/domain/File.mjs +51 -0
  36. package/dist/domain/File.mjs.map +1 -0
  37. package/dist/domain/Image.d.mts +2 -2
  38. package/dist/domain/Image.mjs +12 -2
  39. package/dist/domain/Image.mjs.map +1 -1
  40. package/dist/domain/Items.d.mts +2 -2
  41. package/dist/domain/Items.mjs +65 -4
  42. package/dist/domain/Items.mjs.map +1 -1
  43. package/dist/domain/Realtime.d.mts +72 -490
  44. package/dist/domain/Realtime.d.mts.map +1 -1
  45. package/dist/domain/Research.d.mts +1 -1
  46. package/dist/domain/Transcript.test.mjs +3 -3
  47. package/dist/domain/Turn.d.mts +57 -262
  48. package/dist/domain/Turn.d.mts.map +1 -1
  49. package/dist/domain/Turn.mjs +1 -1
  50. package/dist/domain/Turn.test.mjs +2 -2
  51. package/dist/embedding-model/Embedding.d.mts +1 -1
  52. package/dist/embedding-model/EmbeddingModel.test.mjs +2 -2
  53. package/dist/embedding-model/EmbeddingModel.test.mjs.map +1 -1
  54. package/dist/image-generator/ImageGenerator.d.mts +10 -66
  55. package/dist/image-generator/ImageGenerator.d.mts.map +1 -1
  56. package/dist/index.C4tKZ0yW-LuFnBtmu.mjs +7042 -0
  57. package/dist/index.C4tKZ0yW-LuFnBtmu.mjs.map +1 -0
  58. package/dist/index.d.mts +10 -9
  59. package/dist/index.mjs +7 -6
  60. package/dist/language-model/LanguageModel.d.mts +2 -2
  61. package/dist/language-model/LanguageModel.test.mjs +2 -2
  62. package/dist/loop/Loop.d.mts +1 -1
  63. package/dist/loop/Loop.mjs.map +1 -1
  64. package/dist/loop/Loop.test.mjs +3 -3
  65. package/dist/math/Probability.test.mjs +2 -2
  66. package/dist/messenger/Messenger.d.mts +43 -289
  67. package/dist/messenger/Messenger.d.mts.map +1 -1
  68. package/dist/messenger/MessengerAdapter.test.mjs +3 -3
  69. package/dist/music-generator/MusicGenerator.test.mjs +3 -3
  70. package/dist/observability/Metrics.d.mts +1 -1
  71. package/dist/observability/Metrics.test.mjs +3 -3
  72. package/dist/observability/Telemetry.d.mts +1 -1
  73. package/dist/observability/Telemetry.mjs +1 -1
  74. package/dist/observability/Telemetry.mjs.map +1 -1
  75. package/dist/observability/Telemetry.test.mjs +4 -4
  76. package/dist/observability/Telemetry.test.mjs.map +1 -1
  77. package/dist/realtime/RealtimeSession.d.mts +1 -1
  78. package/dist/realtime/RealtimeSession.test.mjs +4 -4
  79. package/dist/retry/Retry.test.mjs +2 -2
  80. package/dist/sandbox/Sandbox.d.mts +32 -237
  81. package/dist/sandbox/Sandbox.d.mts.map +1 -1
  82. package/dist/speech-synthesizer/SpeechSynthesizer.test.mjs +3 -3
  83. package/dist/streaming/JSONL.test.mjs +2 -2
  84. package/dist/streaming/Multipart.d.mts +1 -1
  85. package/dist/streaming/Multipart.mjs +3 -2
  86. package/dist/streaming/Multipart.mjs.map +1 -1
  87. package/dist/streaming/Multipart.test.mjs +28 -0
  88. package/dist/streaming/Multipart.test.mjs.map +1 -0
  89. package/dist/streaming/SSE.d.mts +1 -1
  90. package/dist/streaming/SSE.mjs +2 -2
  91. package/dist/streaming/SSE.mjs.map +1 -1
  92. package/dist/streaming/SSE.test.mjs +2 -2
  93. package/dist/streaming/Settle.test.mjs +3 -3
  94. package/dist/streaming/WebSocketSession.d.mts +5 -3
  95. package/dist/streaming/WebSocketSession.d.mts.map +1 -1
  96. package/dist/streaming/WebSocketSession.mjs +22 -10
  97. package/dist/streaming/WebSocketSession.mjs.map +1 -1
  98. package/dist/streaming/WebSocketSession.test.mjs +41 -5
  99. package/dist/streaming/WebSocketSession.test.mjs.map +1 -1
  100. package/dist/structured-format/StructuredFormat.mjs.map +1 -1
  101. package/dist/structured-format/StructuredFormat.test.mjs +2 -2
  102. package/dist/testing/FakeWebSocket.d.mts +5 -1
  103. package/dist/testing/FakeWebSocket.d.mts.map +1 -1
  104. package/dist/testing/FakeWebSocket.mjs +12 -6
  105. package/dist/testing/FakeWebSocket.mjs.map +1 -1
  106. package/dist/testing/MockMessenger.d.mts +19 -134
  107. package/dist/testing/MockMessenger.d.mts.map +1 -1
  108. package/dist/testing/MockProvider.d.mts +1 -1
  109. package/dist/testing/MockSandbox.d.mts +65 -446
  110. package/dist/testing/MockSandbox.d.mts.map +1 -1
  111. package/dist/tool/Content.d.mts +2 -0
  112. package/dist/tool/Content.mjs +46 -0
  113. package/dist/tool/Content.mjs.map +1 -0
  114. package/dist/tool/Content.test.d.mts +1 -0
  115. package/dist/tool/Content.test.mjs +48 -0
  116. package/dist/tool/Content.test.mjs.map +1 -0
  117. package/dist/tool/HistoryCheck.d.mts +6 -15
  118. package/dist/tool/HistoryCheck.d.mts.map +1 -1
  119. package/dist/tool/HistoryCheck.mjs +10 -24
  120. package/dist/tool/HistoryCheck.mjs.map +1 -1
  121. package/dist/tool/Tool.d.mts +2 -2
  122. package/dist/tool/Tool.mjs +55 -130
  123. package/dist/tool/Tool.mjs.map +1 -1
  124. package/dist/tool/Tool.test.mjs +222 -178
  125. package/dist/tool/Tool.test.mjs.map +1 -1
  126. package/dist/tool/ToolDecision.d.mts +164 -0
  127. package/dist/tool/ToolDecision.d.mts.map +1 -0
  128. package/dist/tool/ToolDecision.mjs +146 -0
  129. package/dist/tool/ToolDecision.mjs.map +1 -0
  130. package/dist/tool/ToolDecision.test.d.mts +1 -0
  131. package/dist/tool/ToolDecision.test.mjs +330 -0
  132. package/dist/tool/ToolDecision.test.mjs.map +1 -0
  133. package/dist/tool/ToolEvent.d.mts +2 -2
  134. package/dist/tool/ToolEvent.mjs +2 -34
  135. package/dist/tool/ToolEvent.mjs.map +1 -1
  136. package/dist/tool/ToolOutput.d.mts +2 -0
  137. package/dist/tool/ToolOutput.mjs +128 -0
  138. package/dist/tool/ToolOutput.mjs.map +1 -0
  139. package/dist/tool/ToolOutput.test.d.mts +1 -0
  140. package/dist/tool/ToolOutput.test.mjs +153 -0
  141. package/dist/tool/ToolOutput.test.mjs.map +1 -0
  142. package/dist/tool/Toolkit.d.mts +2 -2
  143. package/dist/tool/Toolkit.mjs +230 -165
  144. package/dist/tool/Toolkit.mjs.map +1 -1
  145. package/dist/tool/Toolkit.test.mjs +433 -391
  146. package/dist/tool/Toolkit.test.mjs.map +1 -1
  147. package/dist/transcriber/Transcriber.test.mjs +3 -3
  148. package/dist/web-read/WebReadTool.d.mts +2 -2
  149. package/dist/web-read/WebReadTool.mjs +1 -0
  150. package/dist/web-read/WebReadTool.mjs.map +1 -1
  151. package/dist/web-search/WebSearchTool.d.mts +2 -2
  152. package/dist/web-search/WebSearchTool.mjs +1 -0
  153. package/dist/web-search/WebSearchTool.mjs.map +1 -1
  154. package/package.json +18 -10
  155. package/src/browser/BrowserTool.ts +5 -0
  156. package/src/domain/File.ts +79 -0
  157. package/src/domain/Image.ts +14 -4
  158. package/src/domain/Items.ts +39 -3
  159. package/src/embedding-model/EmbeddingModel.test.ts +2 -2
  160. package/src/index.ts +3 -2
  161. package/src/loop/Loop.ts +25 -14
  162. package/src/observability/Telemetry.test.ts +1 -1
  163. package/src/observability/Telemetry.ts +2 -2
  164. package/src/streaming/Multipart.test.ts +26 -0
  165. package/src/streaming/Multipart.ts +6 -5
  166. package/src/streaming/SSE.ts +2 -2
  167. package/src/streaming/WebSocketSession.test.ts +54 -2
  168. package/src/streaming/WebSocketSession.ts +27 -6
  169. package/src/structured-format/StructuredFormat.ts +1 -1
  170. package/src/testing/FakeWebSocket.ts +21 -6
  171. package/src/tool/Content.test.ts +40 -0
  172. package/src/tool/Content.ts +38 -0
  173. package/src/tool/HistoryCheck.ts +21 -26
  174. package/src/tool/Tool.test.ts +240 -241
  175. package/src/tool/Tool.ts +204 -309
  176. package/src/tool/ToolDecision.test.ts +301 -0
  177. package/src/tool/ToolDecision.ts +360 -0
  178. package/src/tool/ToolEvent.ts +21 -41
  179. package/src/tool/ToolOutput.test.ts +132 -0
  180. package/src/tool/ToolOutput.ts +198 -0
  181. package/src/tool/Toolkit.test.ts +594 -454
  182. package/src/tool/Toolkit.ts +631 -356
  183. package/src/web-read/WebReadTool.ts +2 -1
  184. package/src/web-search/WebSearchTool.ts +2 -1
  185. package/dist/Image-Cv6iBLTy.d.mts.map +0 -1
  186. package/dist/Items-C7MyrYPX.d.mts.map +0 -1
  187. package/dist/Loop-ChpaO-ya.d.mts.map +0 -1
  188. package/dist/Tool-BF78QWtn.d.mts +0 -314
  189. package/dist/Tool-BF78QWtn.d.mts.map +0 -1
  190. package/dist/ToolEvent-Di4a723B.d.mts +0 -144
  191. package/dist/ToolEvent-Di4a723B.d.mts.map +0 -1
  192. package/dist/ToolResult-BsYQRjmW.d.mts +0 -152
  193. package/dist/ToolResult-BsYQRjmW.d.mts.map +0 -1
  194. package/dist/Toolkit-tlL0F2YR.d.mts +0 -193
  195. package/dist/Toolkit-tlL0F2YR.d.mts.map +0 -1
  196. package/dist/dist-BaenoU1A.mjs +0 -145
  197. package/dist/dist-BaenoU1A.mjs.map +0 -1
  198. package/dist/dist-nohcnkD6.mjs +0 -182
  199. package/dist/dist-nohcnkD6.mjs.map +0 -1
  200. package/dist/magic-string.es-CB2hOw9v.mjs +0 -1014
  201. package/dist/magic-string.es-CB2hOw9v.mjs.map +0 -1
  202. package/dist/test.DNmyFkvJ-YPzDR0Co.mjs +0 -10254
  203. package/dist/test.DNmyFkvJ-YPzDR0Co.mjs.map +0 -1
  204. package/dist/tool/Approval.d.mts +0 -113
  205. package/dist/tool/Approval.d.mts.map +0 -1
  206. package/dist/tool/Approval.mjs +0 -80
  207. package/dist/tool/Approval.mjs.map +0 -1
  208. package/dist/tool/Approval.test.mjs +0 -371
  209. package/dist/tool/Approval.test.mjs.map +0 -1
  210. package/dist/tool/ToolResult.d.mts +0 -2
  211. package/dist/tool/ToolResult.mjs +0 -85
  212. package/dist/tool/ToolResult.mjs.map +0 -1
  213. package/dist/utils-CiH_DjFW.mjs +0 -3918
  214. package/dist/utils-CiH_DjFW.mjs.map +0 -1
  215. package/src/tool/Approval.test.ts +0 -400
  216. package/src/tool/Approval.ts +0 -181
  217. package/src/tool/ToolResult.ts +0 -114
  218. /package/dist/{tool/Approval.test.d.mts → streaming/Multipart.test.d.mts} +0 -0
@@ -1,6 +1,6 @@
1
1
  import { fromBytes, toBytes } from "./SSE.mjs";
2
- import { m as it, o as describe } from "../utils-CiH_DjFW.mjs";
3
- import { n as globalExpect } from "../test.DNmyFkvJ-YPzDR0Co.mjs";
2
+ import { b as it, m as describe } from "../dist-DzeSyeYF.mjs";
3
+ import { n as globalExpect } from "../index.C4tKZ0yW-LuFnBtmu.mjs";
4
4
  import { Cause, Deferred, Effect, Exit, Fiber, Result, Stream } from "effect";
5
5
  //#region src/streaming/SSE.test.ts
6
6
  const enc = new TextEncoder();
@@ -1,7 +1,7 @@
1
1
  import { drainBurst, onQuiet, settleBurst } from "./Settle.mjs";
2
- import { o as describe } from "../utils-CiH_DjFW.mjs";
3
- import { n as globalExpect } from "../test.DNmyFkvJ-YPzDR0Co.mjs";
4
- import { t as it } from "../dist-nohcnkD6.mjs";
2
+ import { m as describe } from "../dist-DzeSyeYF.mjs";
3
+ import { n as globalExpect } from "../index.C4tKZ0yW-LuFnBtmu.mjs";
4
+ import { t as it } from "../dist-B5K-y4Be.mjs";
5
5
  import { Effect, Fiber, Option, Queue, Ref, Stream } from "effect";
6
6
  import { TestClock } from "effect/testing";
7
7
  //#region src/streaming/Settle.test.ts
@@ -1,8 +1,8 @@
1
1
  import { t as AiError } from "../AiError-DvhLIbmd.mjs";
2
2
  import { Cause, Duration, Effect, Queue, Schema, Scope } from "effect";
3
- import * as Socket from "effect/unstable/socket/Socket";
3
+ import * as Socket from "effect/socket/Socket";
4
4
  declare namespace WebSocketSession_d_exports {
5
- export { OpenOptions, WebSocketSession, open, redactUrl, toAiError };
5
+ export { OpenOptions, WebSocketSession, isCleanClose, open, redactUrl, toAiError };
6
6
  }
7
7
  type WebSocketSession<A> = {
8
8
  /** Fails `Unavailable` once the socket is closed. */
@@ -25,6 +25,8 @@ type OpenOptions<A, I> = {
25
25
  */
26
26
  declare const redactUrl: (text: string) => string;
27
27
  declare const toAiError: (provider: string) => (error: Socket.SocketError) => AiError;
28
+ /** Effect's `Socket` fails on every close, clean or not. */
29
+ declare const isCleanClose: (error: Socket.SocketError) => boolean;
28
30
  /**
29
31
  * Connect for the lifetime of the surrounding `Scope`. The reader runs in a
30
32
  * forked fiber; a dirty close reaches the consumer as a failed queue rather
@@ -32,5 +34,5 @@ declare const toAiError: (provider: string) => (error: Socket.SocketError) => Ai
32
34
  */
33
35
  declare const open: <A, I>(options: OpenOptions<A, I>) => Effect.Effect<WebSocketSession<A>, AiError, Scope.Scope | Socket.WebSocketConstructor>;
34
36
  //#endregion
35
- export { OpenOptions, WebSocketSession, open, redactUrl, WebSocketSession_d_exports as t, toAiError };
37
+ export { OpenOptions, WebSocketSession, isCleanClose, open, redactUrl, WebSocketSession_d_exports as t, toAiError };
36
38
  //# sourceMappingURL=WebSocketSession.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"WebSocketSession.d.mts","names":[],"sources":["../../src/streaming/WebSocketSession.ts"],"mappings":";;;;;;KAuBY,iBAAiB;;WAElB,OAAO,kBAAkB,OAAO,aAAa;;WAE7C,QAAQ,MAAM,QAAQ,GAAG,UAAkB,MAAM;;KAGhD,YAAY,GAAG;WAChB;WACA;;WAEA,QAAQ,OAAO,MAAM,GAAG;WACxB,cAAc,SAAS;WACvB;;;;;;;cAiBE,YAAS;cAeT,YAAS,sBACH,OACT,OAAO,gBAAc;;;;;;cAsBlB,OAAQ,GAAG,GAAC,SACd,YAAY,GAAG,OACvB,OAAO,OAAO,iBAAiB,IAAI,SAAiB,MAAM,QAAQ,OAAO"}
1
+ {"version":3,"file":"WebSocketSession.d.mts","names":[],"sources":["../../src/streaming/WebSocketSession.ts"],"mappings":";;;;;;KAyBY,iBAAiB;;WAElB,OAAO,kBAAkB,OAAO,aAAa;;WAE7C,QAAQ,MAAM,QAAQ,GAAG,UAAkB,MAAM;;KAGhD,YAAY,GAAG;WAChB;WACA;;WAEA,QAAQ,OAAO,MAAM,GAAG;WACxB,cAAc,SAAS;WACvB;;;;;;;cAiBE,YAAS;cAeT,YAAS,sBACH,OACT,OAAO,gBAAc;;cAqBlB,eAAY,OAAW,OAAO;;;;;;cAQ9B,OAAQ,GAAG,GAAC,SACd,YAAY,GAAG,OACvB,OAAO,OAAO,iBAAiB,IAAI,SAAiB,MAAM,QAAQ,OAAO"}
@@ -1,8 +1,8 @@
1
1
  import { n as __exportAll } from "../rolldown-runtime-EAsCxrDo.mjs";
2
2
  import { AuthFailed, Timeout, Unavailable } from "../domain/AiError.mjs";
3
3
  import { parseSafe } from "./JSONL.mjs";
4
- import { Cause, Effect, Match, Option, Predicate, Queue, Schema } from "effect";
5
- import * as Socket from "effect/unstable/socket/Socket";
4
+ import { Cause, Effect, Match, Option, Predicate, Queue, Ref, Schema, Stream } from "effect";
5
+ import * as Socket from "effect/socket/Socket";
6
6
  //#region src/streaming/WebSocketSession.ts
7
7
  /**
8
8
  * One JSON-over-WebSocket session: connect, read decoded frames off a queue,
@@ -13,6 +13,7 @@ import * as Socket from "effect/unstable/socket/Socket";
13
13
  * own copies of this.
14
14
  */
15
15
  var WebSocketSession_exports = /* @__PURE__ */ __exportAll({
16
+ isCleanClose: () => isCleanClose,
16
17
  open: () => open,
17
18
  redactUrl: () => redactUrl,
18
19
  toAiError: () => toAiError
@@ -50,6 +51,14 @@ const toAiError = (provider) => (error) => {
50
51
  raw
51
52
  })));
52
53
  };
54
+ /** Normal closure, going away, and no status code. */
55
+ const cleanCloseCodes = /* @__PURE__ */ new Set([
56
+ 1e3,
57
+ 1001,
58
+ 1005
59
+ ]);
60
+ /** Effect's `Socket` fails on every close, clean or not. */
61
+ const isCleanClose = (error) => error.reason._tag === "SocketCloseError" && cleanCloseCodes.has(error.reason.code);
53
62
  /**
54
63
  * Connect for the lifetime of the surrounding `Scope`. The reader runs in a
55
64
  * forked fiber; a dirty close reaches the consumer as a failed queue rather
@@ -58,12 +67,14 @@ const toAiError = (provider) => (error) => {
58
67
  const open = (options) => Effect.gen(function* () {
59
68
  const asAiError = toAiError(options.provider);
60
69
  const decode = Schema.decodeUnknownEffect(options.schema);
61
- const socket = yield* Socket.makeWebSocket(options.url, {
62
- closeCodeIsError: (code) => code !== 1e3 && code !== 1001 && code !== 1005,
63
- ...options.openTimeout !== void 0 && { openTimeout: options.openTimeout }
64
- });
70
+ const socket = yield* Socket.makeWebSocket(options.url, { ...options.openTimeout !== void 0 && { openTimeout: options.openTimeout } });
65
71
  const frames = yield* Queue.bounded(options.capacity ?? 64);
66
- const write = yield* socket.writer;
72
+ const { write } = yield* socket.writer;
73
+ const ended = yield* Ref.make(false);
74
+ const closed = new Unavailable({
75
+ provider: options.provider,
76
+ raw: "socket closed"
77
+ });
67
78
  const onFrame = (raw) => Effect.gen(function* () {
68
79
  const json = yield* parseSafe(raw);
69
80
  if (json === void 0) return;
@@ -74,16 +85,17 @@ const open = (options) => Effect.gen(function* () {
74
85
  }
75
86
  yield* Queue.offer(frames, decoded.value);
76
87
  });
77
- yield* socket.runString(onFrame).pipe(Effect.mapError(asAiError), Effect.matchCauseEffect({
88
+ yield* Stream.fromPull(Socket.readerString(socket)).pipe(Stream.scoped, Stream.catchIf(isCleanClose, () => Stream.empty), Stream.runForEach(onFrame), Effect.mapError(asAiError), Effect.ensuring(Ref.set(ended, true)), Effect.matchCauseEffect({
78
89
  onFailure: (cause) => Cause.hasFails(cause) ? Queue.failCause(frames, cause) : Queue.end(frames),
79
90
  onSuccess: () => Queue.end(frames)
80
91
  }), Effect.forkScoped);
92
+ const send = (frame) => Effect.flatMap(Ref.get(ended), (isEnded) => isEnded ? Effect.fail(closed) : Effect.mapError(write(frame), asAiError));
81
93
  return {
82
- send: (frame) => write(frame).pipe(Effect.mapError(asAiError)),
94
+ send,
83
95
  frames
84
96
  };
85
97
  });
86
98
  //#endregion
87
- export { open, redactUrl, WebSocketSession_exports as t, toAiError };
99
+ export { isCleanClose, open, redactUrl, WebSocketSession_exports as t, toAiError };
88
100
 
89
101
  //# sourceMappingURL=WebSocketSession.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"WebSocketSession.mjs","names":["AiError.Timeout","AiError.AuthFailed","AiError.Unavailable","JSONL.parseSafe"],"sources":["../../src/streaming/WebSocketSession.ts"],"sourcesContent":["/**\n * One JSON-over-WebSocket session: connect, read decoded frames off a queue,\n * write frames back.\n *\n * For duplex protocols where the caller drives the conversation frame by\n * frame. The stream-shaped adapters (realtime STT and TTS) still carry their\n * own copies of this.\n */\nimport {\n Cause,\n type Duration,\n Effect,\n Match,\n Option,\n Predicate,\n Queue,\n Schema,\n type Scope,\n} from \"effect\"\nimport * as Socket from \"effect/unstable/socket/Socket\"\nimport * as AiError from \"../domain/AiError.js\"\nimport * as JSONL from \"./JSONL.js\"\n\nexport type WebSocketSession<A> = {\n /** Fails `Unavailable` once the socket is closed. */\n readonly send: (frame: string) => Effect.Effect<void, AiError.AiError>\n /** Ends when the socket closes cleanly, fails when it does not. */\n readonly frames: Queue.Dequeue<A, AiError.AiError | Cause.Done>\n}\n\nexport type OpenOptions<A, I> = {\n readonly url: string\n readonly provider: string\n /** Frames that do not decode are dropped, and logged at debug level. */\n readonly schema: Schema.Codec<A, I>\n readonly openTimeout?: Duration.Input\n readonly capacity?: number\n}\n\n/**\n * The cause of a failed open is a DOM `ErrorEvent`, not an `Error`, and its\n * `message` is a prototype getter, so a structural decode does not see it.\n */\nconst describeCause = (cause: unknown): string =>\n Predicate.hasProperty(cause, \"message\") && Predicate.isString(cause.message)\n ? cause.message\n : String(cause)\n\n/**\n * Some wires authenticate with a key in the query string, and some runtimes\n * name the socket URL in their open error (Bun does). Everything taken off a\n * socket error goes through this.\n */\nexport const redactUrl = (text: string): string =>\n text.replace(/(\\b(?:wss?|https?):\\/\\/[^\\s\"']*?)\\?[^\\s\"']*/gi, \"$1?<redacted>\")\n\nconst detailOf = Match.type<Socket.SocketError[\"reason\"]>().pipe(\n Match.tag(\"SocketCloseError\", (reason) => reason.message),\n Match.orElse((reason) => describeCause(reason.cause)),\n)\n\n/** Never the `SocketError` itself: callers print `raw` with `Cause.pretty`. */\nconst rawOf = (error: Socket.SocketError): string =>\n redactUrl(`${error.reason._tag}: ${detailOf(error.reason)}`)\n\n/** A rejected WS upgrade surfaces only as prose, so the status is read from it. */\nconst isAuthRejection = (text: string): boolean => /\\b40[13]\\b/.test(text)\n\nexport const toAiError =\n (provider: string) =>\n (error: Socket.SocketError): AiError.AiError => {\n const raw = rawOf(error)\n return Match.value(error.reason).pipe(\n Match.tag(\"SocketOpenError\", (reason) =>\n Match.value(reason.kind).pipe(\n Match.when(\"Timeout\", (): AiError.AiError => new AiError.Timeout({ provider, raw })),\n Match.orElse((): AiError.AiError =>\n isAuthRejection(describeCause(reason.cause))\n ? new AiError.AuthFailed({ provider, subtype: \"auth\", raw })\n : new AiError.Unavailable({ provider, raw }),\n ),\n ),\n ),\n Match.orElse((): AiError.AiError => new AiError.Unavailable({ provider, raw })),\n )\n }\n\n/**\n * Connect for the lifetime of the surrounding `Scope`. The reader runs in a\n * forked fiber; a dirty close reaches the consumer as a failed queue rather\n * than a clean end.\n */\nexport const open = <A, I>(\n options: OpenOptions<A, I>,\n): Effect.Effect<WebSocketSession<A>, AiError.AiError, Scope.Scope | Socket.WebSocketConstructor> =>\n Effect.gen(function* () {\n const asAiError = toAiError(options.provider)\n const decode = Schema.decodeUnknownEffect(options.schema)\n const socket = yield* Socket.makeWebSocket(options.url, {\n // Effect's Socket treats every close code as an error by default.\n closeCodeIsError: (code) => code !== 1000 && code !== 1001 && code !== 1005,\n ...(options.openTimeout !== undefined && { openTimeout: options.openTimeout }),\n })\n const frames = yield* Queue.bounded<A, AiError.AiError | Cause.Done>(options.capacity ?? 64)\n const write = yield* socket.writer\n\n const onFrame = (raw: string) =>\n Effect.gen(function* () {\n const json = yield* JSONL.parseSafe(raw)\n if (json === undefined) return\n const decoded = yield* decode(json).pipe(Effect.option)\n if (Option.isNone(decoded)) {\n yield* Effect.logDebug(`[${options.provider}] dropped frame`, { frame: json })\n return\n }\n yield* Queue.offer(frames, decoded.value)\n })\n\n yield* socket.runString(onFrame).pipe(\n Effect.mapError(asAiError),\n // `Queue.end` on a clean close so the consumer drains what is queued;\n // a failure must not arrive looking like the end of the conversation.\n Effect.matchCauseEffect({\n onFailure: (cause) =>\n Cause.hasFails(cause) ? Queue.failCause(frames, cause) : Queue.end(frames),\n onSuccess: () => Queue.end(frames),\n }),\n Effect.forkScoped,\n )\n\n return { send: (frame: string) => write(frame).pipe(Effect.mapError(asAiError)), frames }\n })\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA2CA,MAAM,iBAAiB,UACrB,UAAU,YAAY,OAAO,SAAS,KAAK,UAAU,SAAS,MAAM,OAAO,IACvE,MAAM,UACN,OAAO,KAAK;;;;;;AAOlB,MAAa,aAAa,SACxB,KAAK,QAAQ,iDAAiD,eAAe;AAE/E,MAAM,WAAW,MAAM,KAAmC,CAAC,CAAC,KAC1D,MAAM,IAAI,qBAAqB,WAAW,OAAO,OAAO,GACxD,MAAM,QAAQ,WAAW,cAAc,OAAO,KAAK,CAAC,CACtD;;AAGA,MAAM,SAAS,UACb,UAAU,GAAG,MAAM,OAAO,KAAK,IAAI,SAAS,MAAM,MAAM,GAAG;;AAG7D,MAAM,mBAAmB,SAA0B,aAAa,KAAK,IAAI;AAEzE,MAAa,aACV,cACA,UAA+C;CAC9C,MAAM,MAAM,MAAM,KAAK;CACvB,OAAO,MAAM,MAAM,MAAM,MAAM,CAAC,CAAC,KAC/B,MAAM,IAAI,oBAAoB,WAC5B,MAAM,MAAM,OAAO,IAAI,CAAC,CAAC,KACvB,MAAM,KAAK,iBAAkC,IAAIA,QAAgB;EAAE;EAAU;CAAI,C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,CAAC,GACD,OAAO,UACT;CAEA,OAAO;EAAE,OAAO,UAAkB,MAAM,KAAK,CAAC,CAAC,KAAK,OAAO,SAAS,SAAS,CAAC;EAAG;CAAO;AAC1F,CAAC"}
1
+ {"version":3,"file":"WebSocketSession.mjs","names":["AiError.Timeout","AiError.AuthFailed","AiError.Unavailable","JSONL.parseSafe"],"sources":["../../src/streaming/WebSocketSession.ts"],"sourcesContent":["/**\n * One JSON-over-WebSocket session: connect, read decoded frames off a queue,\n * write frames back.\n *\n * For duplex protocols where the caller drives the conversation frame by\n * frame. The stream-shaped adapters (realtime STT and TTS) still carry their\n * own copies of this.\n */\nimport {\n Cause,\n type Duration,\n Effect,\n Match,\n Option,\n Predicate,\n Queue,\n Ref,\n Schema,\n type Scope,\n Stream,\n} from \"effect\"\nimport * as Socket from \"effect/socket/Socket\"\nimport * as AiError from \"../domain/AiError.js\"\nimport * as JSONL from \"./JSONL.js\"\n\nexport type WebSocketSession<A> = {\n /** Fails `Unavailable` once the socket is closed. */\n readonly send: (frame: string) => Effect.Effect<void, AiError.AiError>\n /** Ends when the socket closes cleanly, fails when it does not. */\n readonly frames: Queue.Dequeue<A, AiError.AiError | Cause.Done>\n}\n\nexport type OpenOptions<A, I> = {\n readonly url: string\n readonly provider: string\n /** Frames that do not decode are dropped, and logged at debug level. */\n readonly schema: Schema.Codec<A, I>\n readonly openTimeout?: Duration.Input\n readonly capacity?: number\n}\n\n/**\n * The cause of a failed open is a DOM `ErrorEvent`, not an `Error`, and its\n * `message` is a prototype getter, so a structural decode does not see it.\n */\nconst describeCause = (cause: unknown): string =>\n Predicate.hasProperty(cause, \"message\") && Predicate.isString(cause.message)\n ? cause.message\n : String(cause)\n\n/**\n * Some wires authenticate with a key in the query string, and some runtimes\n * name the socket URL in their open error (Bun does). Everything taken off a\n * socket error goes through this.\n */\nexport const redactUrl = (text: string): string =>\n text.replace(/(\\b(?:wss?|https?):\\/\\/[^\\s\"']*?)\\?[^\\s\"']*/gi, \"$1?<redacted>\")\n\nconst detailOf = Match.type<Socket.SocketError[\"reason\"]>().pipe(\n Match.tag(\"SocketCloseError\", (reason) => reason.message),\n Match.orElse((reason) => describeCause(reason.cause)),\n)\n\n/** Never the `SocketError` itself: callers print `raw` with `Cause.pretty`. */\nconst rawOf = (error: Socket.SocketError): string =>\n redactUrl(`${error.reason._tag}: ${detailOf(error.reason)}`)\n\n/** A rejected WS upgrade surfaces only as prose, so the status is read from it. */\nconst isAuthRejection = (text: string): boolean => /\\b40[13]\\b/.test(text)\n\nexport const toAiError =\n (provider: string) =>\n (error: Socket.SocketError): AiError.AiError => {\n const raw = rawOf(error)\n return Match.value(error.reason).pipe(\n Match.tag(\"SocketOpenError\", (reason) =>\n Match.value(reason.kind).pipe(\n Match.when(\"Timeout\", (): AiError.AiError => new AiError.Timeout({ provider, raw })),\n Match.orElse((): AiError.AiError =>\n isAuthRejection(describeCause(reason.cause))\n ? new AiError.AuthFailed({ provider, subtype: \"auth\", raw })\n : new AiError.Unavailable({ provider, raw }),\n ),\n ),\n ),\n Match.orElse((): AiError.AiError => new AiError.Unavailable({ provider, raw })),\n )\n }\n\n/** Normal closure, going away, and no status code. */\nconst cleanCloseCodes: ReadonlySet<number> = new Set([1000, 1001, 1005])\n\n/** Effect's `Socket` fails on every close, clean or not. */\nexport const isCleanClose = (error: Socket.SocketError): boolean =>\n error.reason._tag === \"SocketCloseError\" && cleanCloseCodes.has(error.reason.code)\n\n/**\n * Connect for the lifetime of the surrounding `Scope`. The reader runs in a\n * forked fiber; a dirty close reaches the consumer as a failed queue rather\n * than a clean end.\n */\nexport const open = <A, I>(\n options: OpenOptions<A, I>,\n): Effect.Effect<WebSocketSession<A>, AiError.AiError, Scope.Scope | Socket.WebSocketConstructor> =>\n Effect.gen(function* () {\n const asAiError = toAiError(options.provider)\n const decode = Schema.decodeUnknownEffect(options.schema)\n const socket = yield* Socket.makeWebSocket(options.url, {\n ...(options.openTimeout !== undefined && { openTimeout: options.openTimeout }),\n })\n const frames = yield* Queue.bounded<A, AiError.AiError | Cause.Done>(options.capacity ?? 64)\n const { write } = yield* socket.writer\n // The writer waits for the next connection rather than failing, so a send\n // after the reader ends has to be refused here.\n const ended = yield* Ref.make(false)\n const closed = new AiError.Unavailable({ provider: options.provider, raw: \"socket closed\" })\n\n const onFrame = (raw: string) =>\n Effect.gen(function* () {\n const json = yield* JSONL.parseSafe(raw)\n if (json === undefined) return\n const decoded = yield* decode(json).pipe(Effect.option)\n if (Option.isNone(decoded)) {\n yield* Effect.logDebug(`[${options.provider}] dropped frame`, { frame: json })\n return\n }\n yield* Queue.offer(frames, decoded.value)\n })\n\n yield* Stream.fromPull(Socket.readerString(socket)).pipe(\n Stream.scoped,\n Stream.catchIf(isCleanClose, () => Stream.empty),\n Stream.runForEach(onFrame),\n Effect.mapError(asAiError),\n // Set before `frames` ends, so a send after the last frame already fails.\n Effect.ensuring(Ref.set(ended, true)),\n // `Queue.end` on a clean close so the consumer drains what is queued;\n // a failure must not arrive looking like the end of the conversation.\n Effect.matchCauseEffect({\n onFailure: (cause) =>\n Cause.hasFails(cause) ? Queue.failCause(frames, cause) : Queue.end(frames),\n onSuccess: () => Queue.end(frames),\n }),\n Effect.forkScoped,\n )\n\n const send = (frame: string): Effect.Effect<void, AiError.AiError> =>\n Effect.flatMap(Ref.get(ended), (isEnded) =>\n isEnded ? Effect.fail(closed) : Effect.mapError(write(frame), asAiError),\n )\n\n return { send, frames }\n })\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA6CA,MAAM,iBAAiB,UACrB,UAAU,YAAY,OAAO,SAAS,KAAK,UAAU,SAAS,MAAM,OAAO,IACvE,MAAM,UACN,OAAO,KAAK;;;;;;AAOlB,MAAa,aAAa,SACxB,KAAK,QAAQ,iDAAiD,eAAe;AAE/E,MAAM,WAAW,MAAM,KAAmC,CAAC,CAAC,KAC1D,MAAM,IAAI,qBAAqB,WAAW,OAAO,OAAO,GACxD,MAAM,QAAQ,WAAW,cAAc,OAAO,KAAK,CAAC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AQ;EAAU,KAAK;CAAgB,CAAC;CAE3F,MAAM,WAAW,QACf,OAAO,IAAI,aAAa;EACtB,MAAM,OAAO,OAAOC,UAAgB,GAAG;EACvC,IAAI,SAAS,KAAA,GAAW;EACxB,MAAM,UAAU,OAAO,OAAO,IAAI,CAAC,CAAC,KAAK,OAAO,MAAM;EACtD,IAAI,OAAO,OAAO,OAAO,GAAG;GAC1B,OAAO,OAAO,SAAS,IAAI,QAAQ,SAAS,kBAAkB,EAAE,OAAO,KAAK,CAAC;GAC7E;EACF;EACA,OAAO,MAAM,MAAM,QAAQ,QAAQ,KAAK;CAC1C,CAAC;CAEH,OAAO,OAAO,SAAS,OAAO,aAAa,MAAM,CAAC,CAAC,CAAC,KAClD,OAAO,QACP,OAAO,QAAQ,oBAAoB,OAAO,KAAK,GAC/C,OAAO,WAAW,OAAO,GACzB,OAAO,SAAS,SAAS,GAEzB,OAAO,SAAS,IAAI,IAAI,OAAO,IAAI,CAAC,GAGpC,OAAO,iBAAiB;EACtB,YAAY,UACV,MAAM,SAAS,KAAK,IAAI,MAAM,UAAU,QAAQ,KAAK,IAAI,MAAM,IAAI,MAAM;EAC3E,iBAAiB,MAAM,IAAI,MAAM;CACnC,CAAC,GACD,OAAO,UACT;CAEA,MAAM,QAAQ,UACZ,OAAO,QAAQ,IAAI,IAAI,KAAK,IAAI,YAC9B,UAAU,OAAO,KAAK,MAAM,IAAI,OAAO,SAAS,MAAM,KAAK,GAAG,SAAS,CACzE;CAEF,OAAO;EAAE;EAAM;CAAO;AACxB,CAAC"}
@@ -1,9 +1,11 @@
1
1
  import { describe } from "../domain/AiError.mjs";
2
- import { toAiError } from "./WebSocketSession.mjs";
3
- import { o as describe$1 } from "../utils-CiH_DjFW.mjs";
4
- import { n as globalExpect } from "../test.DNmyFkvJ-YPzDR0Co.mjs";
5
- import { t as it } from "../dist-nohcnkD6.mjs";
6
- import * as Socket from "effect/unstable/socket/Socket";
2
+ import { open, toAiError } from "./WebSocketSession.mjs";
3
+ import { m as describe$1 } from "../dist-DzeSyeYF.mjs";
4
+ import { n as globalExpect } from "../index.C4tKZ0yW-LuFnBtmu.mjs";
5
+ import { t as it } from "../dist-B5K-y4Be.mjs";
6
+ import { make } from "../testing/FakeWebSocket.mjs";
7
+ import { Effect, Exit, Pull, Queue, Schema } from "effect";
8
+ import * as Socket from "effect/socket/Socket";
7
9
  //#region src/streaming/WebSocketSession.test.ts
8
10
  const KEY = "AIzaSyEXAMPLEKEY";
9
11
  const URL = `wss://generativelanguage.googleapis.com/ws/BidiGenerateContent?key=${KEY}`;
@@ -45,6 +47,40 @@ describe$1("WebSocketSession errors", () => {
45
47
  globalExpect(ended._tag).toBe("Unavailable");
46
48
  });
47
49
  });
50
+ const Frame = Schema.Struct({ n: Schema.Number });
51
+ const session = (server) => open({
52
+ url: "wss://example.test",
53
+ provider: "test",
54
+ schema: Frame
55
+ }).pipe(Effect.provide(server.layer));
56
+ describe$1("WebSocketSession lifetime", () => {
57
+ it.live("writes a reply to a frame before the next one arrives", () => Effect.gen(function* () {
58
+ const server = yield* make({ greeting: [{ n: 1 }] });
59
+ const { send, frames } = yield* session(server);
60
+ const first = yield* Queue.take(frames);
61
+ yield* send(JSON.stringify({ n: first.n + 1 }));
62
+ yield* Effect.sleep("5 millis");
63
+ globalExpect(yield* server.sent).toEqual([{ n: 2 }]);
64
+ }).pipe(Effect.scoped));
65
+ it.live("ends the frames on a clean close, and refuses a send after it", () => Effect.gen(function* () {
66
+ const server = yield* make({ greeting: [{ n: 1 }] });
67
+ const { send, frames } = yield* session(server);
68
+ yield* Queue.take(frames);
69
+ yield* server.close(1e3);
70
+ const end = yield* Effect.exit(Queue.take(frames));
71
+ const late = yield* Effect.exit(send(JSON.stringify({ n: 2 })));
72
+ globalExpect(Exit.isFailure(end) && Pull.isDoneCause(end.cause)).toBe(true);
73
+ globalExpect(Exit.isFailure(late) && JSON.stringify(late)).toContain("Unavailable");
74
+ }).pipe(Effect.scoped));
75
+ it.live("fails the frames on a dirty close", () => Effect.gen(function* () {
76
+ const server = yield* make({ greeting: [{ n: 1 }] });
77
+ const { frames } = yield* session(server);
78
+ yield* Queue.take(frames);
79
+ yield* server.close(1011);
80
+ const end = yield* Effect.exit(Queue.take(frames));
81
+ globalExpect(JSON.stringify(end)).toContain("Unavailable");
82
+ }).pipe(Effect.scoped));
83
+ });
48
84
  //#endregion
49
85
  export {};
50
86
 
@@ -1 +1 @@
1
- {"version":3,"file":"WebSocketSession.test.mjs","names":["describe","AiError.describe"],"sources":["../../src/streaming/WebSocketSession.test.ts"],"sourcesContent":["import { describe, it } from \"@effect/vitest\"\nimport * as Socket from \"effect/unstable/socket/Socket\"\nimport { expect } from \"vitest\"\nimport * as AiError from \"../domain/AiError.js\"\nimport { toAiError } from \"./WebSocketSession.js\"\n\nconst KEY = \"AIzaSyEXAMPLEKEY\"\nconst URL = `wss://generativelanguage.googleapis.com/ws/BidiGenerateContent?key=${KEY}`\n\n/**\n * What Bun hands the `error` listener when the upgrade is rejected: the whole\n * socket URL, in prose, on a prototype getter. Node and Deno say less, but the\n * adapter cannot know which runtime it is on.\n */\nclass BunErrorEvent {\n get message(): string {\n return `WebSocket connection to '${URL}' failed: Connection ended`\n }\n}\n\n/** Deno names the status but not the URL, also on a prototype getter. */\nclass DenoErrorEvent {\n constructor(private readonly detail: string) {}\n get message(): string {\n return `NetworkError: failed to connect to WebSocket: ${this.detail}`\n }\n}\n\nconst openFailure = (cause: unknown) =>\n new Socket.SocketError({ reason: new Socket.SocketOpenError({ kind: \"Unknown\", cause }) })\n\ndescribe(\"WebSocketSession errors\", () => {\n it(\"keeps the key out of the error a rejected upgrade produces\", () => {\n const error = toAiError(\"google\")(openFailure(new BunErrorEvent()))\n\n expect(JSON.stringify(error)).not.toContain(KEY)\n expect(AiError.describe(error)).not.toContain(KEY)\n // The host is still there: an error that says nothing is its own problem.\n expect(JSON.stringify(error)).toContain(\"generativelanguage.googleapis.com\")\n })\n\n it(\"reads the rejected status out of the prose, wherever the runtime put it\", () => {\n // Deno's wording. The status is the only hint a rejected upgrade gives.\n const forbidden = toAiError(\"google\")(\n openFailure(new DenoErrorEvent(\"Invalid status code: 403\")),\n )\n const ended = toAiError(\"google\")(openFailure(new BunErrorEvent()))\n\n expect(forbidden._tag).toBe(\"AuthFailed\")\n expect(ended._tag).toBe(\"Unavailable\")\n })\n})\n"],"mappings":";;;;;;;AAMA,MAAM,MAAM;AACZ,MAAM,MAAM,sEAAsE;;;;;;AAOlF,IAAM,gBAAN,MAAoB;CAClB,IAAI,UAAkB;EACpB,OAAO,4BAA4B,IAAI;CACzC;AACF;;AAGA,IAAM,iBAAN,MAAqB;CACU;CAA7B,YAAY,QAAiC;EAAhB,KAAA,SAAA;CAAiB;CAC9C,IAAI,UAAkB;EACpB,OAAO,iDAAiD,KAAK;CAC/D;AACF;AAEA,MAAM,eAAe,UACnB,IAAI,OAAO,YAAY,EAAE,QAAQ,IAAI,OAAO,gBAAgB;CAAE,MAAM;CAAW;AAAM,CAAC,EAAE,CAAC;AAE3FA,WAAS,iCAAiC;CACxC,GAAG,oEAAoE;EACrE,MAAM,QAAQ,UAAU,QAAQ,CAAC,CAAC,YAAY,IAAI,cAAc,CAAC,CAAC;EAElE,aAAO,KAAK,UAAU,KAAK,CAAC,CAAC,CAAC,IAAI,UAAU,GAAG;EAC/C,aAAOC,SAAiB,KAAK,CAAC,CAAC,CAAC,IAAI,UAAU,GAAG;EAEjD,aAAO,KAAK,UAAU,KAAK,CAAC,CAAC,CAAC,UAAU,mCAAmC;CAC7E,CAAC;CAED,GAAG,iFAAiF;EAElF,MAAM,YAAY,UAAU,QAAQ,CAAC,CACnC,YAAY,IAAI,eAAe,0BAA0B,CAAC,CAC5D;EACA,MAAM,QAAQ,UAAU,QAAQ,CAAC,CAAC,YAAY,IAAI,cAAc,CAAC,CAAC;EAElE,aAAO,UAAU,IAAI,CAAC,CAAC,KAAK,YAAY;EACxC,aAAO,MAAM,IAAI,CAAC,CAAC,KAAK,aAAa;CACvC,CAAC;AACH,CAAC"}
1
+ {"version":3,"file":"WebSocketSession.test.mjs","names":["describe","AiError.describe","FakeWebSocket.make"],"sources":["../../src/streaming/WebSocketSession.test.ts"],"sourcesContent":["import { describe, it } from \"@effect/vitest\"\nimport { Effect, Exit, Pull, Queue, Schema } from \"effect\"\nimport * as Socket from \"effect/socket/Socket\"\nimport { expect } from \"vitest\"\nimport * as AiError from \"../domain/AiError.js\"\nimport * as FakeWebSocket from \"../testing/FakeWebSocket.js\"\nimport { open, toAiError } from \"./WebSocketSession.js\"\n\nconst KEY = \"AIzaSyEXAMPLEKEY\"\nconst URL = `wss://generativelanguage.googleapis.com/ws/BidiGenerateContent?key=${KEY}`\n\n/**\n * What Bun hands the `error` listener when the upgrade is rejected: the whole\n * socket URL, in prose, on a prototype getter. Node and Deno say less, but the\n * adapter cannot know which runtime it is on.\n */\nclass BunErrorEvent {\n get message(): string {\n return `WebSocket connection to '${URL}' failed: Connection ended`\n }\n}\n\n/** Deno names the status but not the URL, also on a prototype getter. */\nclass DenoErrorEvent {\n constructor(private readonly detail: string) {}\n get message(): string {\n return `NetworkError: failed to connect to WebSocket: ${this.detail}`\n }\n}\n\nconst openFailure = (cause: unknown) =>\n new Socket.SocketError({ reason: new Socket.SocketOpenError({ kind: \"Unknown\", cause }) })\n\ndescribe(\"WebSocketSession errors\", () => {\n it(\"keeps the key out of the error a rejected upgrade produces\", () => {\n const error = toAiError(\"google\")(openFailure(new BunErrorEvent()))\n\n expect(JSON.stringify(error)).not.toContain(KEY)\n expect(AiError.describe(error)).not.toContain(KEY)\n // The host is still there: an error that says nothing is its own problem.\n expect(JSON.stringify(error)).toContain(\"generativelanguage.googleapis.com\")\n })\n\n it(\"reads the rejected status out of the prose, wherever the runtime put it\", () => {\n // Deno's wording. The status is the only hint a rejected upgrade gives.\n const forbidden = toAiError(\"google\")(\n openFailure(new DenoErrorEvent(\"Invalid status code: 403\")),\n )\n const ended = toAiError(\"google\")(openFailure(new BunErrorEvent()))\n\n expect(forbidden._tag).toBe(\"AuthFailed\")\n expect(ended._tag).toBe(\"Unavailable\")\n })\n})\n\nconst Frame = Schema.Struct({ n: Schema.Number })\n\nconst session = (server: FakeWebSocket.FakeWebSocketServer) =>\n open({ url: \"wss://example.test\", provider: \"test\", schema: Frame }).pipe(\n Effect.provide(server.layer),\n )\n\ndescribe(\"WebSocketSession lifetime\", () => {\n it.live(\"writes a reply to a frame before the next one arrives\", () =>\n Effect.gen(function* () {\n const server = yield* FakeWebSocket.make({ greeting: [{ n: 1 }] })\n const { send, frames } = yield* session(server)\n\n const first = yield* Queue.take(frames)\n yield* send(JSON.stringify({ n: first.n + 1 }))\n yield* Effect.sleep(\"5 millis\")\n\n expect(yield* server.sent).toEqual([{ n: 2 }])\n }).pipe(Effect.scoped),\n )\n\n it.live(\"ends the frames on a clean close, and refuses a send after it\", () =>\n Effect.gen(function* () {\n const server = yield* FakeWebSocket.make({ greeting: [{ n: 1 }] })\n const { send, frames } = yield* session(server)\n\n yield* Queue.take(frames)\n yield* server.close(1000)\n const end = yield* Effect.exit(Queue.take(frames))\n const late = yield* Effect.exit(send(JSON.stringify({ n: 2 })))\n\n expect(Exit.isFailure(end) && Pull.isDoneCause(end.cause)).toBe(true)\n expect(Exit.isFailure(late) && JSON.stringify(late)).toContain(\"Unavailable\")\n }).pipe(Effect.scoped),\n )\n\n it.live(\"fails the frames on a dirty close\", () =>\n Effect.gen(function* () {\n const server = yield* FakeWebSocket.make({ greeting: [{ n: 1 }] })\n const { frames } = yield* session(server)\n\n yield* Queue.take(frames)\n yield* server.close(1011)\n const end = yield* Effect.exit(Queue.take(frames))\n\n expect(JSON.stringify(end)).toContain(\"Unavailable\")\n }).pipe(Effect.scoped),\n )\n})\n"],"mappings":";;;;;;;;;AAQA,MAAM,MAAM;AACZ,MAAM,MAAM,sEAAsE;;;;;;AAOlF,IAAM,gBAAN,MAAoB;CAClB,IAAI,UAAkB;EACpB,OAAO,4BAA4B,IAAI;CACzC;AACF;;AAGA,IAAM,iBAAN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U,GAAG,CAAC,CAAC,CAAC,UAAU,aAAa;CACrD,CAAC,CAAC,CAAC,KAAK,OAAO,MAAM,CACvB;AACF,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"StructuredFormat.mjs","names":[],"sources":["../../src/structured-format/StructuredFormat.ts"],"sourcesContent":["import type { StandardJSONSchemaV1, StandardSchemaV1 } from \"@standard-schema/spec\"\nimport { Data, Effect, Match, Result, Schema, Stream, pipe } from \"effect\"\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Cross-validator schema constraint for structured outputs. Any schema\n * implementing both Standard Schema (runtime validation) and Standard\n * JSON Schema (wire encoding) works directly: Zod 4+, Valibot, ArkType,\n * and Effect Schema after `fromEffectSchema`.\n */\nexport type StructuredSchema<Output = unknown> = StandardSchemaV1<unknown, Output> &\n StandardJSONSchemaV1<unknown, Output>\n\n/**\n * A schema-bound output the user wants the model to produce. Pairs the\n * cross-validator schema with metadata providers need (name, description,\n * strict-mode flag).\n */\nexport type StructuredFormat<A> = {\n readonly name: string\n readonly description?: string\n readonly schema: StructuredSchema<A>\n /**\n * Provider strict-mode flag. OpenAI, Anthropic, and Mistral honour it\n * (constrained decoding); other providers ignore.\n */\n readonly strict?: boolean\n}\n\n/** A single path-scoped validation problem. Library-agnostic shape. */\nexport type DecodeIssue = {\n readonly path: ReadonlyArray<string | number>\n readonly message: string\n}\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\n\n/**\n * Schema validation failed. `raw` is the original text (or stringified\n * value) that failed; `issues` is a flat list of per-field problems.\n */\nexport class StructuredDecodeError extends Data.TaggedError(\"StructuredDecodeError\")<{\n readonly raw: string\n readonly issues: ReadonlyArray<DecodeIssue>\n}> {}\n\n/**\n * `JSON.parse` threw on a string that was supposed to be JSON. Distinct\n * from `StructuredDecodeError`: the bytes weren't even JSON.\n */\nexport class JsonParseError extends Data.TaggedError(\"StructuredJsonParseError\")<{\n readonly raw: string\n readonly cause: unknown\n}> {}\n\n// ---------------------------------------------------------------------------\n// Constructors\n// ---------------------------------------------------------------------------\n\n/**\n * Wrap an Effect `Schema` as a `StructuredFormat`. Effect Schema doesn't\n * natively implement Standard Schema; this helper installs the\n * `~standard` and JSON Schema interfaces.\n */\nexport const fromEffectSchema = <S extends Schema.Codec<any, any, never, any>>(\n schema: S,\n options?: {\n readonly name?: string\n readonly description?: string\n readonly strict?: boolean\n },\n): StructuredFormat<S[\"Type\"]> => ({\n name: options?.name ?? \"output\",\n schema: Schema.toStandardJSONSchemaV1(Schema.toStandardSchemaV1(schema)),\n ...(options?.description !== undefined && {\n description: options.description,\n }),\n ...(options?.strict !== undefined && { strict: options.strict }),\n})\n\n// ---------------------------------------------------------------------------\n// Standard Schema → DecodeIssue\n// ---------------------------------------------------------------------------\n\nconst propertyKeyToScalar = Match.type<PropertyKey>().pipe(\n Match.when(Match.string, (s) => s),\n Match.when(Match.number, (n) => n),\n Match.when(Match.symbol, (s) => s.toString()),\n Match.exhaustive,\n)\n\nconst segmentToKey = Match.type<PropertyKey | StandardSchemaV1.PathSegment>().pipe(\n Match.when(Match.string, (s) => s),\n Match.when(Match.number, (n) => n),\n Match.when(Match.symbol, (s) => s.toString()),\n Match.orElse((segment) => propertyKeyToScalar(segment.key)),\n)\n\nconst issueToDecode = (issue: StandardSchemaV1.Issue): DecodeIssue => ({\n path: (issue.path ?? []).map(segmentToKey),\n message: issue.message,\n})\n\n// ---------------------------------------------------------------------------\n// Decoding\n// ---------------------------------------------------------------------------\n\n/**\n * Validate an `unknown` against the format's schema. Returns the typed\n * value or a `StructuredDecodeError`. Standard Schema's `validate` may\n * be async; this function handles both sync and async results.\n */\nexport const decode =\n <A>(format: StructuredFormat<A>) =>\n (raw: unknown): Effect.Effect<A, StructuredDecodeError> =>\n pipe(\n Effect.promise(async () => format.schema[\"~standard\"].validate(raw)),\n Effect.flatMap((result) =>\n result.issues === undefined\n ? Effect.succeed(result.value)\n : Effect.fail(\n new StructuredDecodeError({\n raw: typeof raw === \"string\" ? raw : JSON.stringify(raw),\n issues: result.issues.map(issueToDecode),\n }),\n ),\n ),\n )\n\n/**\n * Parse a JSON string then validate against the format's schema. Two\n * failure modes: `JsonParseError` (bytes weren't JSON) and\n * `StructuredDecodeError` (JSON didn't match the schema).\n */\nexport const parseJson =\n <A>(format: StructuredFormat<A>) =>\n (raw: string): Effect.Effect<A, JsonParseError | StructuredDecodeError> =>\n pipe(\n Effect.try({\n // Validation runs through Standard Schema (Zod / Valibot / Effect), not\n // Effect Schema, so its JSON codecs don't apply here; and JSON.parse is\n // a separate step on purpose, to surface JsonParseError distinctly.\n // @effect-diagnostics-next-line effect/preferSchemaOverJson:off\n try: () => JSON.parse(raw),\n catch: (cause) => new JsonParseError({ raw, cause }),\n }),\n Effect.flatMap(decode(format)),\n )\n\n/**\n * Stream operator: each input string is JSON-parsed and validated.\n * Failures surface in the stream's failure channel, distinguished by tag.\n */\nexport const decodeJsonLines =\n <A>(format: StructuredFormat<A>) =>\n <E, R>(\n self: Stream.Stream<string, E, R>,\n ): Stream.Stream<A, E | JsonParseError | StructuredDecodeError, R> =>\n self.pipe(Stream.mapEffect(parseJson(format)))\n\n/**\n * Like {@link decodeJsonLines}, but each line yields a `Result` instead of\n * failing the stream. Use when one bad line shouldn't abort the rest —\n * log-and-continue, or partial-recovery with a corrective re-prompt.\n * Upstream errors (the input stream's own `E`) still propagate normally.\n */\nexport const decodeJsonLinesRecoverable =\n <A>(format: StructuredFormat<A>) =>\n <E, R>(\n self: Stream.Stream<string, E, R>,\n ): Stream.Stream<Result.Result<A, JsonParseError | StructuredDecodeError>, E, R> =>\n self.pipe(Stream.mapEffect((line) => Effect.result(parseJson(format)(line))))\n"],"mappings":";;;;;;;;;;;;;;;;AA8CA,IAAa,wBAAb,cAA2C,KAAK,YAAY,uBAAuB,CAAC,CAGjF,CAAC;;;;;AAMJ,IAAa,iBAAb,cAAoC,KAAK,YAAY,0BAA0B,CAAC,CAG7E,CAAC;;;;;;AA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EAAK;CAAM,CAAC;AACrD,CAAC,GACD,OAAO,QAAQ,OAAO,MAAM,CAAC,CAC/B;;;;;AAMJ,MAAa,mBACP,YAEF,SAEA,KAAK,KAAK,OAAO,UAAU,UAAU,MAAM,CAAC,CAAC;;;;;;;AAQjD,MAAa,8BACP,YAEF,SAEA,KAAK,KAAK,OAAO,WAAW,SAAS,OAAO,OAAO,UAAU,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC"}
1
+ {"version":3,"file":"StructuredFormat.mjs","names":[],"sources":["../../src/structured-format/StructuredFormat.ts"],"sourcesContent":["import type { StandardJSONSchemaV1, StandardSchemaV1 } from \"@standard-schema/spec\"\nimport { Data, Effect, Match, Result, Schema, Stream, pipe } from \"effect\"\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Cross-validator schema constraint for structured outputs. Any schema\n * implementing both Standard Schema (runtime validation) and Standard\n * JSON Schema (wire encoding) works directly: Zod 4+, Valibot, ArkType,\n * and Effect Schema after `fromEffectSchema`.\n */\nexport type StructuredSchema<Output = unknown> = StandardSchemaV1<unknown, Output> &\n StandardJSONSchemaV1<unknown, Output>\n\n/**\n * A schema-bound output the user wants the model to produce. Pairs the\n * cross-validator schema with metadata providers need (name, description,\n * strict-mode flag).\n */\nexport type StructuredFormat<A> = {\n readonly name: string\n readonly description?: string\n readonly schema: StructuredSchema<A>\n /**\n * Provider strict-mode flag. OpenAI, Anthropic, and Mistral honour it\n * (constrained decoding); other providers ignore.\n */\n readonly strict?: boolean\n}\n\n/** A single path-scoped validation problem. Library-agnostic shape. */\nexport type DecodeIssue = {\n readonly path: ReadonlyArray<string | number>\n readonly message: string\n}\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\n\n/**\n * Schema validation failed. `raw` is the original text (or stringified\n * value) that failed; `issues` is a flat list of per-field problems.\n */\nexport class StructuredDecodeError extends Data.TaggedError(\"StructuredDecodeError\")<{\n readonly raw: string\n readonly issues: ReadonlyArray<DecodeIssue>\n}> {}\n\n/**\n * `JSON.parse` threw on a string that was supposed to be JSON. Distinct\n * from `StructuredDecodeError`: the bytes weren't even JSON.\n */\nexport class JsonParseError extends Data.TaggedError(\"StructuredJsonParseError\")<{\n readonly raw: string\n readonly cause: unknown\n}> {}\n\n// ---------------------------------------------------------------------------\n// Constructors\n// ---------------------------------------------------------------------------\n\n/**\n * Wrap an Effect `Schema` as a `StructuredFormat`. Effect Schema doesn't\n * natively implement Standard Schema; this helper installs the\n * `~standard` and JSON Schema interfaces.\n */\nexport const fromEffectSchema = <S extends Schema.Codec<any, any, never, any>>(\n schema: S,\n options?: {\n readonly name?: string\n readonly description?: string\n readonly strict?: boolean\n },\n): StructuredFormat<S[\"Type\"]> => ({\n name: options?.name ?? \"output\",\n schema: Schema.toStandardJSONSchemaV1(Schema.toStandardSchemaV1(schema)),\n ...(options?.description !== undefined && {\n description: options.description,\n }),\n ...(options?.strict !== undefined && { strict: options.strict }),\n})\n\n// ---------------------------------------------------------------------------\n// Standard Schema → DecodeIssue\n// ---------------------------------------------------------------------------\n\nconst propertyKeyToScalar = Match.type<PropertyKey>().pipe(\n Match.when(Match.string, (s) => s),\n Match.when(Match.number, (n) => n),\n Match.when(Match.symbol, (s) => s.toString()),\n Match.exhaustive,\n)\n\nconst segmentToKey = Match.type<PropertyKey | StandardSchemaV1.PathSegment>().pipe(\n Match.when(Match.string, (s) => s),\n Match.when(Match.number, (n) => n),\n Match.when(Match.symbol, (s) => s.toString()),\n Match.orElse((segment) => propertyKeyToScalar(segment.key)),\n)\n\nconst issueToDecode = (issue: StandardSchemaV1.Issue): DecodeIssue => ({\n path: (issue.path ?? []).map(segmentToKey),\n message: issue.message,\n})\n\n// ---------------------------------------------------------------------------\n// Decoding\n// ---------------------------------------------------------------------------\n\n/**\n * Validate an `unknown` against the format's schema. Returns the typed\n * value or a `StructuredDecodeError`. Standard Schema's `validate` may\n * be async; this function handles both sync and async results.\n */\nexport const decode =\n <A>(format: StructuredFormat<A>) =>\n (raw: unknown): Effect.Effect<A, StructuredDecodeError> =>\n pipe(\n Effect.promise(async () => format.schema[\"~standard\"].validate(raw)),\n Effect.flatMap((result) =>\n result.issues === undefined\n ? Effect.succeed(result.value)\n : Effect.fail(\n new StructuredDecodeError({\n raw: typeof raw === \"string\" ? raw : JSON.stringify(raw),\n issues: result.issues.map(issueToDecode),\n }),\n ),\n ),\n )\n\n/**\n * Parse a JSON string then validate against the format's schema. Two\n * failure modes: `JsonParseError` (bytes weren't JSON) and\n * `StructuredDecodeError` (JSON didn't match the schema).\n */\nexport const parseJson =\n <A>(format: StructuredFormat<A>) =>\n (raw: string): Effect.Effect<A, JsonParseError | StructuredDecodeError> =>\n pipe(\n Effect.try({\n // Validation runs through Standard Schema (Zod / Valibot / Effect), not\n // Effect Schema, so its JSON codecs don't apply here; and JSON.parse is\n // a separate step on purpose, to surface JsonParseError distinctly.\n // @effect-diagnostics-next-linepreferSchemaOverJson:off\n try: () => JSON.parse(raw),\n catch: (cause) => new JsonParseError({ raw, cause }),\n }),\n Effect.flatMap(decode(format)),\n )\n\n/**\n * Stream operator: each input string is JSON-parsed and validated.\n * Failures surface in the stream's failure channel, distinguished by tag.\n */\nexport const decodeJsonLines =\n <A>(format: StructuredFormat<A>) =>\n <E, R>(\n self: Stream.Stream<string, E, R>,\n ): Stream.Stream<A, E | JsonParseError | StructuredDecodeError, R> =>\n self.pipe(Stream.mapEffect(parseJson(format)))\n\n/**\n * Like {@link decodeJsonLines}, but each line yields a `Result` instead of\n * failing the stream. Use when one bad line shouldn't abort the rest —\n * log-and-continue, or partial-recovery with a corrective re-prompt.\n * Upstream errors (the input stream's own `E`) still propagate normally.\n */\nexport const decodeJsonLinesRecoverable =\n <A>(format: StructuredFormat<A>) =>\n <E, R>(\n self: Stream.Stream<string, E, R>,\n ): Stream.Stream<Result.Result<A, JsonParseError | StructuredDecodeError>, E, R> =>\n self.pipe(Stream.mapEffect((line) => Effect.result(parseJson(format)(line))))\n"],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AQ,OAAO,OAAO,IAAI,aAAa;AACzC,CAAC,CACH,CACN,CACF;;;;;;AAOJ,MAAa,aACP,YACH,QACC,KACE,OAAO,IAAI;CAKT,WAAW,KAAK,MAAM,GAAG;CACzB,QAAQ,UAAU,IAAI,eAAe;EAAE;EAAK;CAAM,CAAC;AACrD,CAAC,GACD,OAAO,QAAQ,OAAO,MAAM,CAAC,CAC/B;;;;;AAMJ,MAAa,mBACP,YAEF,SAEA,KAAK,KAAK,OAAO,UAAU,UAAU,MAAM,CAAC,CAAC;;;;;;;AAQjD,MAAa,8BACP,YAEF,SAEA,KAAK,KAAK,OAAO,WAAW,SAAS,OAAO,OAAO,UAAU,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC"}
@@ -1,6 +1,6 @@
1
1
  import { JsonParseError, StructuredDecodeError, decodeJsonLines, decodeJsonLinesRecoverable, fromEffectSchema } from "./StructuredFormat.mjs";
2
- import { m as it, o as describe } from "../utils-CiH_DjFW.mjs";
3
- import { n as globalExpect } from "../test.DNmyFkvJ-YPzDR0Co.mjs";
2
+ import { b as it, m as describe } from "../dist-DzeSyeYF.mjs";
3
+ import { n as globalExpect } from "../index.C4tKZ0yW-LuFnBtmu.mjs";
4
4
  import { Effect, Exit, Filter, Result, Schema, Stream } from "effect";
5
5
  //#region src/structured-format/StructuredFormat.test.ts
6
6
  const Item = Schema.Struct({
@@ -1,9 +1,13 @@
1
1
  import { Effect, Layer, Scope } from "effect";
2
- import * as Socket from "effect/unstable/socket/Socket";
2
+ import * as Socket from "effect/socket/Socket";
3
3
  //#region src/testing/FakeWebSocket.d.ts
4
4
  type FakeWebSocketServer = {
5
5
  /** Every frame the client has sent, JSON-parsed, oldest first. */
6
6
  readonly sent: Effect.Effect<ReadonlyArray<unknown>>;
7
+ /** Wait until the client has sent at least `count` frames. */
8
+ readonly awaitSent: (count: number) => Effect.Effect<void>;
9
+ /** Wait until the client has subscribed and the greeting has landed. */
10
+ readonly greeted: Effect.Effect<void>;
7
11
  /** Deliver one frame to the client. */
8
12
  readonly push: (frame: unknown) => Effect.Effect<void>;
9
13
  /** Close the socket. 1000, 1001 and 1005 are the clean codes. */
@@ -1 +1 @@
1
- {"version":3,"file":"FakeWebSocket.d.mts","names":[],"sources":["../../src/testing/FakeWebSocket.ts"],"mappings":";;;KAeY;;WAED,MAAM,OAAO,OAAO;;WAEpB,OAAO,mBAAmB,OAAO;;WAEjC,QAAQ,kBAAkB,OAAO;;WAEjC,SAAS,OAAO;;WAEhB,OAAO,MAAM,MAAM,OAAO;;KAGzB;;WAED,WAAW;;WAEX,SAAS,mBAAmB,OAAO,OAAO;;cAWxC,OAAI,UACL,yBACT,OAAO,OAAO,4BAA4B,MAAM"}
1
+ {"version":3,"file":"FakeWebSocket.d.mts","names":[],"sources":["../../src/testing/FakeWebSocket.ts"],"mappings":";;;KAeY;;WAED,MAAM,OAAO,OAAO;;WAEpB,YAAY,kBAAkB,OAAO;;WAErC,SAAS,OAAO;;WAEhB,OAAO,mBAAmB,OAAO;;WAEjC,QAAQ,kBAAkB,OAAO;;WAEjC,SAAS,OAAO;;WAEhB,OAAO,MAAM,MAAM,OAAO;;KAGzB;;WAED,WAAW;;WAEX,SAAS,mBAAmB,OAAO,OAAO;;cAWxC,OAAI,UACL,yBACT,OAAO,OAAO,4BAA4B,MAAM"}
@@ -1,5 +1,5 @@
1
- import { Effect, Layer, Queue, Ref, Stream } from "effect";
2
- import * as Socket from "effect/unstable/socket/Socket";
1
+ import { Deferred, Effect, Layer, Queue, Stream, SubscriptionRef } from "effect";
2
+ import * as Socket from "effect/socket/Socket";
3
3
  //#region src/testing/FakeWebSocket.ts
4
4
  /**
5
5
  * An in-memory WebSocket for testing socket adapters without a server.
@@ -19,7 +19,8 @@ const CLOSED = 3;
19
19
  const soon = (run) => void Promise.resolve().then(run);
20
20
  const make = (options) => Effect.gen(function* () {
21
21
  const inbound = yield* Queue.unbounded();
22
- const sent = yield* Ref.make([]);
22
+ const sent = yield* SubscriptionRef.make([]);
23
+ const greeted = yield* Deferred.make();
23
24
  const wiring = {
24
25
  listeners: {},
25
26
  readyState: OPEN,
@@ -37,7 +38,7 @@ const make = (options) => Effect.gen(function* () {
37
38
  });
38
39
  };
39
40
  yield* Stream.fromQueue(inbound).pipe(Stream.runForEach((frame) => Effect.gen(function* () {
40
- yield* Ref.update(sent, (frames) => [...frames, frame]);
41
+ yield* SubscriptionRef.update(sent, (frames) => [...frames, frame]);
41
42
  const answer = yield* options?.reply?.(frame) ?? Effect.succeed([]);
42
43
  yield* deliver(answer);
43
44
  })), Effect.forkScoped);
@@ -52,7 +53,10 @@ const make = (options) => Effect.gen(function* () {
52
53
  };
53
54
  if (type === "message" && !wiring.greeted) {
54
55
  wiring.greeted = true;
55
- soon(() => deliverSync(options?.greeting ?? []));
56
+ soon(() => {
57
+ deliverSync(options?.greeting ?? []);
58
+ Deferred.doneUnsafe(greeted, Effect.void);
59
+ });
56
60
  }
57
61
  },
58
62
  removeEventListener: (type, fn) => {
@@ -66,7 +70,9 @@ const make = (options) => Effect.gen(function* () {
66
70
  };
67
71
  const connect = () => socket;
68
72
  return {
69
- sent: Ref.get(sent),
73
+ sent: SubscriptionRef.get(sent),
74
+ awaitSent: (count) => SubscriptionRef.changes(sent).pipe(Stream.filter((frames) => frames.length >= count), Stream.take(1), Stream.runDrain),
75
+ greeted: Deferred.await(greeted),
70
76
  push: (frame) => deliver([frame]),
71
77
  close: (code = 1e3) => Effect.sync(() => shutdown(code)),
72
78
  connect,
@@ -1 +1 @@
1
- {"version":3,"file":"FakeWebSocket.mjs","names":[],"sources":["../../src/testing/FakeWebSocket.ts"],"sourcesContent":["/**\n * An in-memory WebSocket for testing socket adapters without a server.\n *\n * Provide `layer` in place of the real `Socket.WebSocketConstructor` and the\n * adapter runs end to end: its own connect, handshake, decode and teardown.\n * The test plays the other end with `reply`, `push`, `close` and `sent`.\n *\n * Client frames land on a queue, so the scripted server is a forked fiber and\n * `reply` is a real Effect. What stays imperative is the listener table the\n * shim registers, since `Socket.makeWebSocket` drives it with plain callbacks.\n * The shim is a plain object, so nothing here touches a platform global.\n */\nimport { Effect, Layer, Queue, Ref, type Scope, Stream } from \"effect\"\nimport * as Socket from \"effect/unstable/socket/Socket\"\n\nexport type FakeWebSocketServer = {\n /** Every frame the client has sent, JSON-parsed, oldest first. */\n readonly sent: Effect.Effect<ReadonlyArray<unknown>>\n /** Deliver one frame to the client. */\n readonly push: (frame: unknown) => Effect.Effect<void>\n /** Close the socket. 1000, 1001 and 1005 are the clean codes. */\n readonly close: (code?: number) => Effect.Effect<void>\n /** Hand this to an adapter that takes a socket constructor directly. */\n readonly connect: Socket.WebSocketConstructor[\"Service\"]\n /** Provide this in place of the real constructor. */\n readonly layer: Layer.Layer<Socket.WebSocketConstructor>\n}\n\nexport type FakeWebSocketOptions = {\n /** Pushed once the client subscribes, for a protocol whose server speaks first. */\n readonly greeting?: ReadonlyArray<unknown>\n /** How the server answers each client frame. */\n readonly reply?: (frame: unknown) => Effect.Effect<ReadonlyArray<unknown>>\n}\n\ntype Listener = (event: any) => void\n\nconst OPEN = 1\nconst CLOSED = 3\n\n/** Run after the current call unwinds, so the client is never re-entered. */\nconst soon = (run: () => void): void => void Promise.resolve().then(run)\n\nexport const make = (\n options?: FakeWebSocketOptions,\n): Effect.Effect<FakeWebSocketServer, never, Scope.Scope> =>\n Effect.gen(function* () {\n const inbound = yield* Queue.unbounded<unknown>()\n const sent = yield* Ref.make<ReadonlyArray<unknown>>([])\n\n const wiring = {\n listeners: {} as Record<string, ReadonlyArray<Listener>>,\n readyState: OPEN,\n greeted: false,\n }\n\n const emit = (type: string, event: unknown): void =>\n (wiring.listeners[type] ?? []).forEach((listener) => listener(event))\n\n const deliverSync = (frames: ReadonlyArray<unknown>): void =>\n frames.forEach((f) => emit(\"message\", { data: JSON.stringify(f) }))\n\n const deliver = (frames: ReadonlyArray<unknown>): Effect.Effect<void> =>\n Effect.sync(() => deliverSync(frames))\n\n const shutdown = (code: number): void => {\n if (wiring.readyState === CLOSED) return\n wiring.readyState = CLOSED\n emit(\"close\", { code, reason: \"\" })\n }\n\n // The scripted server. Answers land on their own turn, like a real one.\n yield* Stream.fromQueue(inbound).pipe(\n Stream.runForEach((frame) =>\n Effect.gen(function* () {\n yield* Ref.update(sent, (frames) => [...frames, frame])\n const answer = yield* options?.reply?.(frame) ?? Effect.succeed([])\n yield* deliver(answer)\n }),\n ),\n Effect.forkScoped,\n )\n\n const socket = {\n get readyState() {\n return wiring.readyState\n },\n addEventListener: (type: string, fn: Listener): void => {\n wiring.listeners = {\n ...wiring.listeners,\n [type]: [...(wiring.listeners[type] ?? []), fn],\n }\n // The greeting waits for a subscriber before it lands.\n if (type === \"message\" && !wiring.greeted) {\n wiring.greeted = true\n soon(() => deliverSync(options?.greeting ?? []))\n }\n },\n removeEventListener: (type: string, fn: Listener): void => {\n wiring.listeners = {\n ...wiring.listeners,\n [type]: (wiring.listeners[type] ?? []).filter((l) => l !== fn),\n }\n },\n // Safe from a synchronous callback, and no runtime needed.\n send: (data: string): void => void Queue.offerUnsafe(inbound, JSON.parse(data)),\n close: (code = 1000): void => shutdown(code),\n }\n\n const connect: Socket.WebSocketConstructor[\"Service\"] = () =>\n socket as unknown as globalThis.WebSocket\n\n return {\n sent: Ref.get(sent),\n push: (frame) => deliver([frame]),\n close: (code = 1000) => Effect.sync(() => shutdown(code)),\n connect,\n layer: Layer.succeed(Socket.WebSocketConstructor, connect),\n }\n })\n"],"mappings":";;;;;;;;;;;;;;;AAqCA,MAAM,OAAO;AACb,MAAM,SAAS;;AAGf,MAAM,QAAQ,QAA0B,KAAK,QAAQ,QAAQ,CAAC,CAAC,KAAK,GAAG;AAEvE,MAAa,QACX,YAEA,OAAO,IAAI,aAAa;CACtB,MAAM,UAAU,OAAO,MAAM,UAAmB;CAChD,MAAM,OAAO,OAAO,IAAI,KAA6B,CAAC,CAAC;CAEvD,MAAM,SAAS;EACb,WAAW,CAAC;EACZ,YAAY;EACZ,SAAS;CACX;CAEA,MAAM,QAAQ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gBACJ;CAEF,OAAO;EACL,MAAM,IAAI,IAAI,IAAI;EAClB,OAAO,UAAU,QAAQ,CAAC,KAAK,CAAC;EAChC,QAAQ,OAAO,QAAS,OAAO,WAAW,SAAS,IAAI,CAAC;EACxD;EACA,OAAO,MAAM,QAAQ,OAAO,sBAAsB,OAAO;CAC3D;AACF,CAAC"}
1
+ {"version":3,"file":"FakeWebSocket.mjs","names":[],"sources":["../../src/testing/FakeWebSocket.ts"],"sourcesContent":["/**\n * An in-memory WebSocket for testing socket adapters without a server.\n *\n * Provide `layer` in place of the real `Socket.WebSocketConstructor` and the\n * adapter runs end to end: its own connect, handshake, decode and teardown.\n * The test plays the other end with `reply`, `push`, `close` and `sent`.\n *\n * Client frames land on a queue, so the scripted server is a forked fiber and\n * `reply` is a real Effect. What stays imperative is the listener table the\n * shim registers, since `Socket.makeWebSocket` drives it with plain callbacks.\n * The shim is a plain object, so nothing here touches a platform global.\n */\nimport { Deferred, Effect, Layer, Queue, type Scope, Stream, SubscriptionRef } from \"effect\"\nimport * as Socket from \"effect/socket/Socket\"\n\nexport type FakeWebSocketServer = {\n /** Every frame the client has sent, JSON-parsed, oldest first. */\n readonly sent: Effect.Effect<ReadonlyArray<unknown>>\n /** Wait until the client has sent at least `count` frames. */\n readonly awaitSent: (count: number) => Effect.Effect<void>\n /** Wait until the client has subscribed and the greeting has landed. */\n readonly greeted: Effect.Effect<void>\n /** Deliver one frame to the client. */\n readonly push: (frame: unknown) => Effect.Effect<void>\n /** Close the socket. 1000, 1001 and 1005 are the clean codes. */\n readonly close: (code?: number) => Effect.Effect<void>\n /** Hand this to an adapter that takes a socket constructor directly. */\n readonly connect: Socket.WebSocketConstructor[\"Service\"]\n /** Provide this in place of the real constructor. */\n readonly layer: Layer.Layer<Socket.WebSocketConstructor>\n}\n\nexport type FakeWebSocketOptions = {\n /** Pushed once the client subscribes, for a protocol whose server speaks first. */\n readonly greeting?: ReadonlyArray<unknown>\n /** How the server answers each client frame. */\n readonly reply?: (frame: unknown) => Effect.Effect<ReadonlyArray<unknown>>\n}\n\ntype Listener = (event: any) => void\n\nconst OPEN = 1\nconst CLOSED = 3\n\n/** Run after the current call unwinds, so the client is never re-entered. */\nconst soon = (run: () => void): void => void Promise.resolve().then(run)\n\nexport const make = (\n options?: FakeWebSocketOptions,\n): Effect.Effect<FakeWebSocketServer, never, Scope.Scope> =>\n Effect.gen(function* () {\n const inbound = yield* Queue.unbounded<unknown>()\n const sent = yield* SubscriptionRef.make<ReadonlyArray<unknown>>([])\n const greeted = yield* Deferred.make<void>()\n\n const wiring = {\n listeners: {} as Record<string, ReadonlyArray<Listener>>,\n readyState: OPEN,\n greeted: false,\n }\n\n const emit = (type: string, event: unknown): void =>\n (wiring.listeners[type] ?? []).forEach((listener) => listener(event))\n\n const deliverSync = (frames: ReadonlyArray<unknown>): void =>\n frames.forEach((f) => emit(\"message\", { data: JSON.stringify(f) }))\n\n const deliver = (frames: ReadonlyArray<unknown>): Effect.Effect<void> =>\n Effect.sync(() => deliverSync(frames))\n\n const shutdown = (code: number): void => {\n if (wiring.readyState === CLOSED) return\n wiring.readyState = CLOSED\n emit(\"close\", { code, reason: \"\" })\n }\n\n // The scripted server. Answers land on their own turn, like a real one.\n yield* Stream.fromQueue(inbound).pipe(\n Stream.runForEach((frame) =>\n Effect.gen(function* () {\n yield* SubscriptionRef.update(sent, (frames) => [...frames, frame])\n const answer = yield* options?.reply?.(frame) ?? Effect.succeed([])\n yield* deliver(answer)\n }),\n ),\n Effect.forkScoped,\n )\n\n const socket = {\n get readyState() {\n return wiring.readyState\n },\n addEventListener: (type: string, fn: Listener): void => {\n wiring.listeners = {\n ...wiring.listeners,\n [type]: [...(wiring.listeners[type] ?? []), fn],\n }\n // The greeting waits for a subscriber before it lands.\n if (type === \"message\" && !wiring.greeted) {\n wiring.greeted = true\n soon(() => {\n deliverSync(options?.greeting ?? [])\n Deferred.doneUnsafe(greeted, Effect.void)\n })\n }\n },\n removeEventListener: (type: string, fn: Listener): void => {\n wiring.listeners = {\n ...wiring.listeners,\n [type]: (wiring.listeners[type] ?? []).filter((l) => l !== fn),\n }\n },\n // Safe from a synchronous callback, and no runtime needed.\n send: (data: string): void => void Queue.offerUnsafe(inbound, JSON.parse(data)),\n close: (code = 1000): void => shutdown(code),\n }\n\n const connect: Socket.WebSocketConstructor[\"Service\"] = () =>\n socket as unknown as globalThis.WebSocket\n\n return {\n sent: SubscriptionRef.get(sent),\n awaitSent: (count) =>\n SubscriptionRef.changes(sent).pipe(\n Stream.filter((frames) => frames.length >= count),\n Stream.take(1),\n Stream.runDrain,\n ),\n greeted: Deferred.await(greeted),\n push: (frame) => deliver([frame]),\n close: (code = 1000) => Effect.sync(() => shutdown(code)),\n connect,\n layer: Layer.succeed(Socket.WebSocketConstructor, connect),\n }\n })\n"],"mappings":";;;;;;;;;;;;;;;AAyCA,MAAM,OAAO;AACb,MAAM,SAAS;;AAGf,MAAM,QAAQ,QAA0B,KAAK,QAAQ,QAAQ,CAAC,CAAC,KAAK,GAAG;AAEvE,MAAa,QACX,YAEA,OAAO,IAAI,aAAa;CACtB,MAAM,UAAU,OAAO,MAAM,UAAmB;CAChD,MAAM,OAAO,OAAO,gBAAgB,KAA6B,CAAC,CAAC;CACnE,MAAM,UAAU,OAAO,SAAS,KAAW;CAE3C,MAAM,SAAS;EACb,WAAW,CAAC;EACZ,YAAY;EACZ,SAAS;CACX;CAEA,MAAM,QAAQ,MAAc,WACzB,OAAO,UAAU,SAAS,CAAC,EAAA,CAAG,SAAS,aAAa,SAAS,KAAK,CAAC;CAEtE,MAAM,eAAe,WACnB,OAAO,SAAS,MAAM,KAAK,WAAW,EAAE,MAAM,KAAK,UAAU,CAAC,EAAE,CAAC,CAAC;CAEpE,MAAM,WAAW,WACf,OAAO,WAAW,YAAY,MAAM,CAAC;CAEvC,MAAM,YAAY,SAAuB;EACvC,IAAI,OAAO,eAAe,QAAQ;EAClC,OAAO,aAAa;EACpB,KAAK,SAAS;GAAE;GAAM,QAAQ;EAAG,C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CAAC;EACxD;EACA,OAAO,MAAM,QAAQ,OAAO,sBAAsB,OAAO;CAC3D;AACF,CAAC"}
@@ -28,140 +28,25 @@ type Call = Data.TaggedEnum<{
28
28
  readonly conversation: ConversationRef;
29
29
  };
30
30
  }>;
31
- declare const Call: {
32
- readonly $is: <Tag extends "Edit" | "Post" | "React" | "TypingStart" | "TypingStop">(tag: Tag) => (u: unknown) => u is Extract<{
33
- readonly _tag: "Edit";
34
- readonly message: MessageRef;
35
- readonly next: Outbound;
36
- }, {
37
- readonly _tag: Tag;
38
- }> | Extract<{
39
- readonly _tag: "Post";
40
- readonly conversation: ConversationRef;
41
- readonly message: Outbound;
42
- }, {
43
- readonly _tag: Tag;
44
- }> | Extract<{
45
- readonly _tag: "React";
46
- readonly message: MessageRef;
47
- readonly emoji: string;
48
- }, {
49
- readonly _tag: Tag;
50
- }> | Extract<{
51
- readonly _tag: "TypingStart";
52
- readonly conversation: ConversationRef;
53
- }, {
54
- readonly _tag: Tag;
55
- }> | Extract<{
56
- readonly _tag: "TypingStop";
57
- readonly conversation: ConversationRef;
58
- }, {
59
- readonly _tag: Tag;
60
- }>;
61
- readonly $match: {
62
- <Cases extends { readonly [Tag in "Edit" | "Post" | "React" | "TypingStart" | "TypingStop"]: (args: Extract<{
63
- readonly _tag: "Edit";
64
- readonly message: MessageRef;
65
- readonly next: Outbound;
66
- } | {
67
- readonly _tag: "Post";
68
- readonly conversation: ConversationRef;
69
- readonly message: Outbound;
70
- } | {
71
- readonly _tag: "React";
72
- readonly message: MessageRef;
73
- readonly emoji: string;
74
- } | {
75
- readonly _tag: "TypingStart";
76
- readonly conversation: ConversationRef;
77
- } | {
78
- readonly _tag: "TypingStop";
79
- readonly conversation: ConversationRef;
80
- }, {
81
- readonly _tag: Tag;
82
- }>) => any; }>(cases: Cases): (value: {
83
- readonly _tag: "Edit";
84
- readonly message: MessageRef;
85
- readonly next: Outbound;
86
- } | {
87
- readonly _tag: "Post";
88
- readonly conversation: ConversationRef;
89
- readonly message: Outbound;
90
- } | {
91
- readonly _tag: "React";
92
- readonly message: MessageRef;
93
- readonly emoji: string;
94
- } | {
95
- readonly _tag: "TypingStart";
96
- readonly conversation: ConversationRef;
97
- } | {
98
- readonly _tag: "TypingStop";
99
- readonly conversation: ConversationRef;
100
- }) => import("effect/Unify").Unify<ReturnType<Cases["Edit" | "Post" | "React" | "TypingStart" | "TypingStop"]>>;
101
- <Cases extends { readonly [Tag in "Edit" | "Post" | "React" | "TypingStart" | "TypingStop"]: (args: Extract<{
102
- readonly _tag: "Edit";
103
- readonly message: MessageRef;
104
- readonly next: Outbound;
105
- } | {
106
- readonly _tag: "Post";
107
- readonly conversation: ConversationRef;
108
- readonly message: Outbound;
109
- } | {
110
- readonly _tag: "React";
111
- readonly message: MessageRef;
112
- readonly emoji: string;
113
- } | {
114
- readonly _tag: "TypingStart";
115
- readonly conversation: ConversationRef;
116
- } | {
117
- readonly _tag: "TypingStop";
118
- readonly conversation: ConversationRef;
119
- }, {
120
- readonly _tag: Tag;
121
- }>) => any; }>(value: {
122
- readonly _tag: "Edit";
123
- readonly message: MessageRef;
124
- readonly next: Outbound;
125
- } | {
126
- readonly _tag: "Post";
127
- readonly conversation: ConversationRef;
128
- readonly message: Outbound;
129
- } | {
130
- readonly _tag: "React";
131
- readonly message: MessageRef;
132
- readonly emoji: string;
133
- } | {
134
- readonly _tag: "TypingStart";
135
- readonly conversation: ConversationRef;
136
- } | {
137
- readonly _tag: "TypingStop";
138
- readonly conversation: ConversationRef;
139
- }, cases: Cases): import("effect/Unify").Unify<ReturnType<Cases["Edit" | "Post" | "React" | "TypingStart" | "TypingStop"]>>;
140
- };
141
- readonly Edit: Data.TaggedEnum.ConstructorFrom<{
142
- readonly _tag: "Edit";
143
- readonly message: MessageRef;
144
- readonly next: Outbound;
145
- }, "_tag">;
146
- readonly Post: Data.TaggedEnum.ConstructorFrom<{
147
- readonly _tag: "Post";
148
- readonly conversation: ConversationRef;
149
- readonly message: Outbound;
150
- }, "_tag">;
151
- readonly React: Data.TaggedEnum.ConstructorFrom<{
152
- readonly _tag: "React";
153
- readonly message: MessageRef;
154
- readonly emoji: string;
155
- }, "_tag">;
156
- readonly TypingStart: Data.TaggedEnum.ConstructorFrom<{
157
- readonly _tag: "TypingStart";
158
- readonly conversation: ConversationRef;
159
- }, "_tag">;
160
- readonly TypingStop: Data.TaggedEnum.ConstructorFrom<{
161
- readonly _tag: "TypingStop";
162
- readonly conversation: ConversationRef;
163
- }, "_tag">;
164
- };
31
+ declare const Call: Data.TaggedEnum.Constructor<{
32
+ readonly _tag: "Edit";
33
+ readonly message: MessageRef;
34
+ readonly next: Outbound;
35
+ } | {
36
+ readonly _tag: "Post";
37
+ readonly conversation: ConversationRef;
38
+ readonly message: Outbound;
39
+ } | {
40
+ readonly _tag: "React";
41
+ readonly message: MessageRef;
42
+ readonly emoji: string;
43
+ } | {
44
+ readonly _tag: "TypingStart";
45
+ readonly conversation: ConversationRef;
46
+ } | {
47
+ readonly _tag: "TypingStop";
48
+ readonly conversation: ConversationRef;
49
+ }>;
165
50
  type MockMessengerRecorder = {
166
51
  readonly calls: ReadonlyArray<Call>;
167
52
  };
@@ -1 +1 @@
1
- {"version":3,"file":"MockMessenger.d.mts","names":[],"sources":["../../src/testing/MockMessenger.ts"],"mappings":";;;;;;;;;;KA4BY,OAAO,KAAK;EACtB;aAAiB,cAAc;aAA0B,SAAS;;EAClE;aAAiB,SAAS;aAAqB,MAAM;;EACrD;aAAkB,SAAS;aAAqB;;EAChD;aAAwB,cAAc;;EACtC;aAAuB,cAAc;;;cAG1B;;;aANe,SAAA;aAA2B,MAAA;;;;;aADtB,cAAA;aAAmC,SAAA;;;;;aAEvC,SAAA;aAA4B;;;;;aACjB,cAAA;;;;;aACD,cAAA;;;;;;;eAHX,SAAA;eAA2B,MAAA;;;eADtB,cAAA;eAAmC,SAAA;;;eAEvC,SAAA;eAA4B;;;eACjB,cAAA;;;eACD,cAAA;;;;;;;;;;;;;;;;;;;;;;;;eAHX,SAAA;eAA2B,MAAA;;;eADtB,cAAA;eAAmC,SAAA;;;eAEvC,SAAA;eAA4B;;;eACjB,cAAA;;;eACD,cAAA;;;;;;;;;;;;;;;;;;;;;;;;;aAHX,SAAA;aAA2B,MAAA;;;;aADtB,cAAA;aAAmC,SAAA;;;;aAEvC,SAAA;aAA4B;;;;aACjB,cAAA;;;;aACD,cAAA;;;KAK3B;WACD,OAAO,cAAc;;KAOpB;;WAED,SAAS,OAAO,OAAO,cAAc;WACrC,SAAS;;;;;WAKT,WAAW,cAAc;;WAEzB,gBAAgB;;;cAoFd,QAAK,SAAY;;;;;cAMjB,OAAI,SAAY"}
1
+ {"version":3,"file":"MockMessenger.d.mts","names":[],"sources":["../../src/testing/MockMessenger.ts"],"mappings":";;;;;;;;;;KA4BY,OAAO,KAAK;EACtB;aAAiB,cAAc;aAA0B,SAAS;;EAClE;aAAiB,SAAS;aAAqB,MAAM;;EACrD;aAAkB,SAAS;aAAqB;;EAChD;aAAwB,cAAc;;EACtC;aAAuB,cAAc;;;cAG1B,MAAI,KAAA,WAAA;;WANW,SAAA;WAA2B,MAAA;;;WADtB,cAAA;WAAmC,SAAA;;;WAEvC,SAAA;WAA4B;;;WACjB,cAAA;;;WACD,cAAA;;KAK3B;WACD,OAAO,cAAc;;KAOpB;;WAED,SAAS,OAAO,OAAO,cAAc;WACrC,SAAS;;;;;WAKT,WAAW,cAAc;;WAEzB,gBAAgB;;;cAoFd,QAAK,SAAY;;;;;cAMjB,OAAI,SAAY"}
@@ -1,4 +1,4 @@
1
- import { o as HistoryItem } from "../Items-C7MyrYPX.mjs";
1
+ import { o as HistoryItem } from "../Items-Bvx8s9QH.mjs";
2
2
  import { Turn } from "../domain/Turn.mjs";
3
3
  import { LanguageModel, LanguageModelService } from "../language-model/LanguageModel.mjs";
4
4
  import { Duration, Effect, Layer } from "effect";