@effect-uai/core 0.11.0 → 0.12.1
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.
- package/dist/{AiError-Bf1pq4BB.d.mts → AiError-eLV9t1lU.d.mts} +12 -16
- package/dist/AiError-eLV9t1lU.d.mts.map +1 -0
- package/dist/{Audio-CR7CSljJ.d.mts → Audio-60lKKHxS.d.mts} +4 -5
- package/dist/Audio-60lKKHxS.d.mts.map +1 -0
- package/dist/{Image-C4vuBmu0.d.mts → Image-BK8-4H6s.d.mts} +12 -14
- package/dist/Image-BK8-4H6s.d.mts.map +1 -0
- package/dist/{Items-BWNu6VGp.d.mts → Items-SfUabNuB.d.mts} +92 -81
- package/dist/Items-SfUabNuB.d.mts.map +1 -0
- package/dist/{Loop-D8nWpowc.d.mts → Loop-B54AB1ME.d.mts} +19 -21
- package/dist/Loop-B54AB1ME.d.mts.map +1 -0
- package/dist/{Media-D_CpcM1Z.d.mts → Media-DwgpifPD.d.mts} +1 -1
- package/dist/Media-DwgpifPD.d.mts.map +1 -0
- package/dist/{SandboxError-CIrVDOMV.d.mts → SandboxError-BN8b28Bh.d.mts} +11 -15
- package/dist/SandboxError-BN8b28Bh.d.mts.map +1 -0
- package/dist/{StructuredFormat-DHaUJBdd.d.mts → StructuredFormat-BlZhyOsi.d.mts} +3 -7
- package/dist/StructuredFormat-BlZhyOsi.d.mts.map +1 -0
- package/dist/{Tool-CXFHCQrT.d.mts → Tool-DE-rnvkw.d.mts} +5 -8
- package/dist/Tool-DE-rnvkw.d.mts.map +1 -0
- package/dist/{ToolEvent-nVijCrvm.d.mts → ToolEvent-D99MGQYH.d.mts} +56 -63
- package/dist/ToolEvent-D99MGQYH.d.mts.map +1 -0
- package/dist/{ToolResult-CQqKkcDa.d.mts → ToolResult-Cj8ChodL.d.mts} +49 -54
- package/dist/ToolResult-Cj8ChodL.d.mts.map +1 -0
- package/dist/{Toolkit-BYPwwu-j.d.mts → Toolkit-BEZrNPTI.d.mts} +13 -16
- package/dist/Toolkit-BEZrNPTI.d.mts.map +1 -0
- package/dist/browser/Browser.d.mts +11 -7
- package/dist/browser/Browser.d.mts.map +1 -1
- package/dist/browser/Browser.mjs +1 -1
- package/dist/browser/Browser.mjs.map +1 -1
- package/dist/browser/BrowserError.d.mts +9 -13
- package/dist/browser/BrowserError.d.mts.map +1 -1
- package/dist/browser/BrowserError.mjs +1 -1
- package/dist/browser/BrowserError.mjs.map +1 -1
- package/dist/browser/BrowserTool.d.mts +33 -36
- package/dist/browser/BrowserTool.d.mts.map +1 -1
- package/dist/browser/BrowserTool.mjs +1 -1
- package/dist/browser/BrowserTool.mjs.map +1 -1
- package/dist/capabilities/Capabilities.d.mts +8 -6
- package/dist/capabilities/Capabilities.d.mts.map +1 -1
- package/dist/capabilities/Capabilities.mjs +1 -1
- package/dist/capabilities/Capabilities.mjs.map +1 -1
- package/dist/dist-BaenoU1A.mjs +145 -0
- package/dist/dist-BaenoU1A.mjs.map +1 -0
- package/dist/{dist-C0m0QnUP.mjs → dist-nohcnkD6.mjs} +16 -15
- package/dist/dist-nohcnkD6.mjs.map +1 -0
- package/dist/domain/AiError.d.mts +1 -1
- package/dist/domain/AiError.mjs +1 -1
- package/dist/domain/AiError.mjs.map +1 -1
- package/dist/domain/Audio.d.mts +1 -1
- package/dist/domain/Audio.mjs +1 -1
- package/dist/domain/Citation.d.mts +0 -2
- package/dist/domain/Citation.d.mts.map +1 -1
- package/dist/domain/Citation.mjs +1 -1
- package/dist/domain/Image.d.mts +1 -1
- package/dist/domain/Image.mjs +1 -1
- package/dist/domain/Image.mjs.map +1 -1
- package/dist/domain/Items.d.mts +1 -1
- package/dist/domain/Items.mjs +16 -2
- package/dist/domain/Items.mjs.map +1 -1
- package/dist/domain/Media.d.mts +1 -1
- package/dist/domain/Media.mjs +1 -1
- package/dist/domain/Music.d.mts +18 -11
- package/dist/domain/Music.d.mts.map +1 -1
- package/dist/domain/Music.mjs +1 -1
- package/dist/domain/Music.mjs.map +1 -1
- package/dist/domain/Research.d.mts +3 -4
- package/dist/domain/Research.d.mts.map +1 -1
- package/dist/domain/Research.mjs +1 -1
- package/dist/domain/Transcript.d.mts +2 -3
- package/dist/domain/Transcript.d.mts.map +1 -1
- package/dist/domain/Transcript.mjs +1 -1
- package/dist/domain/Turn.d.mts +144 -164
- package/dist/domain/Turn.d.mts.map +1 -1
- package/dist/domain/Turn.mjs +1 -1
- package/dist/domain/Turn.mjs.map +1 -1
- package/dist/domain/Turn.test.d.mts +1 -1
- package/dist/domain/Turn.test.mjs +28 -18
- package/dist/domain/Turn.test.mjs.map +1 -1
- package/dist/embedding-model/Embedding.d.mts +1 -3
- package/dist/embedding-model/Embedding.d.mts.map +1 -1
- package/dist/embedding-model/Embedding.mjs +1 -1
- package/dist/embedding-model/EmbeddingModel.d.mts +1 -3
- package/dist/embedding-model/EmbeddingModel.d.mts.map +1 -1
- package/dist/embedding-model/EmbeddingModel.mjs +1 -1
- package/dist/embedding-model/EmbeddingModel.mjs.map +1 -1
- package/dist/embedding-model/EmbeddingModel.test.d.mts +1 -1
- package/dist/embedding-model/EmbeddingModel.test.mjs +14 -9
- package/dist/embedding-model/EmbeddingModel.test.mjs.map +1 -1
- package/dist/index.d.mts +12 -12
- package/dist/job/Job.d.mts +4 -4
- package/dist/job/Job.d.mts.map +1 -1
- package/dist/job/Job.mjs +1 -1
- package/dist/job/Job.mjs.map +1 -1
- package/dist/language-model/LanguageModel.d.mts +4 -6
- package/dist/language-model/LanguageModel.d.mts.map +1 -1
- package/dist/language-model/LanguageModel.mjs +1 -1
- package/dist/language-model/LanguageModel.mjs.map +1 -1
- package/dist/language-model/LanguageModel.test.d.mts +1 -1
- package/dist/language-model/LanguageModel.test.mjs +6 -3
- package/dist/language-model/LanguageModel.test.mjs.map +1 -1
- package/dist/loop/Loop.d.mts +1 -1
- package/dist/loop/Loop.mjs +1 -1
- package/dist/loop/Loop.mjs.map +1 -1
- package/dist/loop/Loop.test.d.mts +1 -1
- package/dist/loop/Loop.test.mjs +60 -34
- package/dist/loop/Loop.test.mjs.map +1 -1
- package/dist/{magic-string.es-Dk-MMA0F.mjs → magic-string.es-CB2hOw9v.mjs} +14 -13
- package/dist/{magic-string.es-Dk-MMA0F.mjs.map → magic-string.es-CB2hOw9v.mjs.map} +1 -1
- package/dist/math/Vector.d.mts +0 -2
- package/dist/math/Vector.d.mts.map +1 -1
- package/dist/math/Vector.mjs +1 -1
- package/dist/math/Vector.mjs.map +1 -1
- package/dist/music-generator/MusicGenerator.d.mts +2 -4
- package/dist/music-generator/MusicGenerator.d.mts.map +1 -1
- package/dist/music-generator/MusicGenerator.mjs +1 -1
- package/dist/music-generator/MusicGenerator.mjs.map +1 -1
- package/dist/music-generator/MusicGenerator.test.d.mts +1 -1
- package/dist/music-generator/MusicGenerator.test.mjs +19 -10
- package/dist/music-generator/MusicGenerator.test.mjs.map +1 -1
- package/dist/observability/Metrics.d.mts +21 -10
- package/dist/observability/Metrics.d.mts.map +1 -1
- package/dist/observability/Metrics.mjs +31 -8
- package/dist/observability/Metrics.mjs.map +1 -1
- package/dist/observability/Metrics.test.d.mts +1 -1
- package/dist/observability/Metrics.test.mjs +87 -23
- package/dist/observability/Metrics.test.mjs.map +1 -1
- package/dist/observability/Telemetry.d.mts +2 -3
- package/dist/observability/Telemetry.d.mts.map +1 -1
- package/dist/observability/Telemetry.mjs +1 -1
- package/dist/observability/Telemetry.mjs.map +1 -1
- package/dist/observability/Telemetry.test.d.mts +1 -1
- package/dist/observability/Telemetry.test.mjs +15 -7
- package/dist/observability/Telemetry.test.mjs.map +1 -1
- package/dist/research/DeepResearch.d.mts +1 -3
- package/dist/research/DeepResearch.d.mts.map +1 -1
- package/dist/research/DeepResearch.mjs +1 -1
- package/dist/research/DeepResearch.mjs.map +1 -1
- package/dist/retry/Retry.d.mts +4 -8
- package/dist/retry/Retry.d.mts.map +1 -1
- package/dist/retry/Retry.mjs +31 -2
- package/dist/retry/Retry.mjs.map +1 -1
- package/dist/retry/Retry.test.d.mts +1 -1
- package/dist/retry/Retry.test.mjs +6 -3
- package/dist/retry/Retry.test.mjs.map +1 -1
- package/dist/sandbox/Memory.d.mts +0 -2
- package/dist/sandbox/Memory.d.mts.map +1 -1
- package/dist/sandbox/Memory.mjs +4 -4
- package/dist/sandbox/Memory.mjs.map +1 -1
- package/dist/sandbox/Sandbox.d.mts +144 -156
- package/dist/sandbox/Sandbox.d.mts.map +1 -1
- package/dist/sandbox/Sandbox.mjs +1 -1
- package/dist/sandbox/Sandbox.mjs.map +1 -1
- package/dist/sandbox/SandboxError.d.mts +1 -1
- package/dist/sandbox/SandboxError.mjs +1 -1
- package/dist/sandbox/SandboxError.mjs.map +1 -1
- package/dist/sandbox/SandboxImage.d.mts +0 -2
- package/dist/sandbox/SandboxImage.d.mts.map +1 -1
- package/dist/sandbox/SandboxImage.mjs +1 -1
- package/dist/sandbox/SandboxImage.mjs.map +1 -1
- package/dist/sandbox/SandboxNetwork.d.mts +0 -2
- package/dist/sandbox/SandboxNetwork.d.mts.map +1 -1
- package/dist/sandbox/SandboxNetwork.mjs +1 -1
- package/dist/sandbox/SandboxNetwork.mjs.map +1 -1
- package/dist/speech-synthesizer/SpeechSynthesizer.d.mts +8 -7
- package/dist/speech-synthesizer/SpeechSynthesizer.d.mts.map +1 -1
- package/dist/speech-synthesizer/SpeechSynthesizer.mjs +1 -1
- package/dist/speech-synthesizer/SpeechSynthesizer.mjs.map +1 -1
- package/dist/speech-synthesizer/SpeechSynthesizer.test.d.mts +1 -1
- package/dist/speech-synthesizer/SpeechSynthesizer.test.mjs +31 -16
- package/dist/speech-synthesizer/SpeechSynthesizer.test.mjs.map +1 -1
- package/dist/streaming/JSONL.d.mts +1 -5
- package/dist/streaming/JSONL.d.mts.map +1 -1
- package/dist/streaming/JSONL.mjs +1 -1
- package/dist/streaming/JSONL.mjs.map +1 -1
- package/dist/streaming/JSONL.test.d.mts +1 -1
- package/dist/streaming/JSONL.test.mjs +16 -8
- package/dist/streaming/JSONL.test.mjs.map +1 -1
- package/dist/streaming/Lines.d.mts +0 -2
- package/dist/streaming/Lines.d.mts.map +1 -1
- package/dist/streaming/Lines.mjs +1 -1
- package/dist/streaming/Lines.mjs.map +1 -1
- package/dist/streaming/SSE.d.mts +0 -2
- package/dist/streaming/SSE.d.mts.map +1 -1
- package/dist/streaming/SSE.mjs +1 -1
- package/dist/streaming/SSE.mjs.map +1 -1
- package/dist/streaming/SSE.test.d.mts +1 -1
- package/dist/streaming/SSE.test.mjs +34 -17
- package/dist/streaming/SSE.test.mjs.map +1 -1
- package/dist/structured-format/StructuredFormat.d.mts +1 -1
- package/dist/structured-format/StructuredFormat.mjs +1 -1
- package/dist/structured-format/StructuredFormat.mjs.map +1 -1
- package/dist/structured-format/StructuredFormat.test.d.mts +1 -1
- package/dist/structured-format/StructuredFormat.test.mjs +7 -4
- package/dist/structured-format/StructuredFormat.test.mjs.map +1 -1
- package/dist/{dist-CcRV3-A5.mjs → test.DNmyFkvJ-YPzDR0Co.mjs} +1644 -5172
- package/dist/test.DNmyFkvJ-YPzDR0Co.mjs.map +1 -0
- package/dist/testing/MockMusicGenerator.d.mts +4 -3
- package/dist/testing/MockMusicGenerator.d.mts.map +1 -1
- package/dist/testing/MockMusicGenerator.mjs.map +1 -1
- package/dist/testing/MockProvider.d.mts +1 -2
- package/dist/testing/MockProvider.d.mts.map +1 -1
- package/dist/testing/MockProvider.mjs.map +1 -1
- package/dist/testing/MockSandbox.d.mts +256 -290
- package/dist/testing/MockSandbox.d.mts.map +1 -1
- package/dist/testing/MockSandbox.mjs.map +1 -1
- package/dist/testing/MockSpeechSynthesizer.d.mts +10 -6
- package/dist/testing/MockSpeechSynthesizer.d.mts.map +1 -1
- package/dist/testing/MockSpeechSynthesizer.mjs.map +1 -1
- package/dist/testing/MockTranscriber.d.mts +3 -2
- package/dist/testing/MockTranscriber.d.mts.map +1 -1
- package/dist/testing/MockTranscriber.mjs.map +1 -1
- package/dist/tool/Approval.d.mts +31 -36
- package/dist/tool/Approval.d.mts.map +1 -1
- package/dist/tool/Approval.mjs +1 -1
- package/dist/tool/Approval.mjs.map +1 -1
- package/dist/tool/Approval.test.d.mts +1 -1
- package/dist/tool/Approval.test.mjs +37 -24
- package/dist/tool/Approval.test.mjs.map +1 -1
- package/dist/tool/HistoryCheck.d.mts +2 -4
- package/dist/tool/HistoryCheck.d.mts.map +1 -1
- package/dist/tool/HistoryCheck.mjs +1 -1
- package/dist/tool/HistoryCheck.mjs.map +1 -1
- package/dist/tool/Tool.d.mts +1 -1
- package/dist/tool/Tool.mjs +4 -4
- package/dist/tool/Tool.mjs.map +1 -1
- package/dist/tool/Tool.test.d.mts +1 -1
- package/dist/tool/Tool.test.mjs +23 -11
- package/dist/tool/Tool.test.mjs.map +1 -1
- package/dist/tool/ToolEvent.d.mts +1 -1
- package/dist/tool/ToolEvent.mjs +1 -1
- package/dist/tool/ToolEvent.mjs.map +1 -1
- package/dist/tool/ToolResult.d.mts +1 -1
- package/dist/tool/ToolResult.mjs +1 -1
- package/dist/tool/ToolResult.mjs.map +1 -1
- package/dist/tool/Toolkit.d.mts +1 -1
- package/dist/tool/Toolkit.mjs +4 -3
- package/dist/tool/Toolkit.mjs.map +1 -1
- package/dist/tool/Toolkit.test.d.mts +1 -1
- package/dist/tool/Toolkit.test.mjs +40 -21
- package/dist/tool/Toolkit.test.mjs.map +1 -1
- package/dist/transcriber/Transcriber.d.mts +6 -6
- package/dist/transcriber/Transcriber.d.mts.map +1 -1
- package/dist/transcriber/Transcriber.mjs +1 -1
- package/dist/transcriber/Transcriber.mjs.map +1 -1
- package/dist/transcriber/Transcriber.test.d.mts +1 -1
- package/dist/transcriber/Transcriber.test.mjs +20 -10
- package/dist/transcriber/Transcriber.test.mjs.map +1 -1
- package/dist/utils-CiH_DjFW.mjs +3918 -0
- package/dist/utils-CiH_DjFW.mjs.map +1 -0
- package/dist/web-read/WebRead.d.mts +15 -9
- package/dist/web-read/WebRead.d.mts.map +1 -1
- package/dist/web-read/WebRead.mjs +1 -1
- package/dist/web-read/WebRead.mjs.map +1 -1
- package/dist/web-read/WebReadTool.d.mts +4 -5
- package/dist/web-read/WebReadTool.d.mts.map +1 -1
- package/dist/web-read/WebReadTool.mjs +1 -1
- package/dist/web-read/WebReadTool.mjs.map +1 -1
- package/dist/web-search/WebSearch.d.mts +22 -13
- package/dist/web-search/WebSearch.d.mts.map +1 -1
- package/dist/web-search/WebSearch.mjs +1 -1
- package/dist/web-search/WebSearch.mjs.map +1 -1
- package/dist/web-search/WebSearchTool.d.mts +6 -6
- package/dist/web-search/WebSearchTool.d.mts.map +1 -1
- package/dist/web-search/WebSearchTool.mjs +1 -1
- package/dist/web-search/WebSearchTool.mjs.map +1 -1
- package/package.json +4 -4
- package/src/domain/Items.ts +18 -0
- package/src/loop/Loop.test.ts +13 -14
- package/src/loop/Loop.ts +74 -76
- package/src/observability/Metrics.test.ts +65 -0
- package/src/observability/Metrics.ts +53 -11
- package/src/retry/Retry.ts +44 -3
- package/src/testing/MockProvider.ts +8 -9
- package/src/tool/Tool.ts +13 -13
- package/dist/AiError-Bf1pq4BB.d.mts.map +0 -1
- package/dist/Audio-CR7CSljJ.d.mts.map +0 -1
- package/dist/Image-C4vuBmu0.d.mts.map +0 -1
- package/dist/Items-BWNu6VGp.d.mts.map +0 -1
- package/dist/Loop-D8nWpowc.d.mts.map +0 -1
- package/dist/Media-D_CpcM1Z.d.mts.map +0 -1
- package/dist/SandboxError-CIrVDOMV.d.mts.map +0 -1
- package/dist/StructuredFormat-DHaUJBdd.d.mts.map +0 -1
- package/dist/Tool-CXFHCQrT.d.mts.map +0 -1
- package/dist/ToolEvent-nVijCrvm.d.mts.map +0 -1
- package/dist/ToolResult-CQqKkcDa.d.mts.map +0 -1
- package/dist/Toolkit-BYPwwu-j.d.mts.map +0 -1
- package/dist/dist-C0m0QnUP.mjs.map +0 -1
- package/dist/dist-CcRV3-A5.mjs.map +0 -1
- /package/dist/{chunk-uyGKjUfl.mjs → rolldown-runtime-EAsCxrDo.mjs} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Metrics.test.mjs","names":["Arr"],"sources":["../../src/observability/Metrics.test.ts"],"sourcesContent":["import { describe, it } from \"@effect/vitest\"\nimport { Array as Arr, Duration, Effect, Fiber, Option, Stream } from \"effect\"\nimport * as TestClock from \"effect/testing/TestClock\"\nimport { expect } from \"vitest\"\nimport type { Usage } from \"../domain/Items.js\"\nimport { TurnEvent } from \"../domain/Turn.js\"\nimport {\n type MetricEvent,\n type Throughput,\n type TimeToCompletion,\n type TimeToFirstToken,\n type TokenTotals,\n computeThroughputTick,\n isMetricEvent,\n makeEvent,\n metricEvents,\n throughput,\n timeToCompletion,\n timeToFirstToken,\n tokenTotals,\n} from \"./Metrics.js\"\n\nconst turnComplete = (usage: Usage): TurnEvent =>\n TurnEvent.TurnComplete({ turn: { items: [], usage, stop_reason: \"stop\" } })\n\nconst text = (s: string): TurnEvent => TurnEvent.TextDelta({ text: s })\n\nconst samples = (events: ReadonlyArray<unknown>): ReadonlyArray<MetricEvent> =>\n events.filter(isMetricEvent)\n\nconst head = <A>(xs: ReadonlyArray<A>): A => Option.getOrThrow(Arr.head(xs))\n\nconst tagged = <T extends MetricEvent[\"_tag\"]>(\n events: ReadonlyArray<unknown>,\n tag: T,\n): ReadonlyArray<Extract<MetricEvent, { readonly _tag: T }>> =>\n samples(events).filter((e): e is Extract<MetricEvent, { readonly _tag: T }> => e._tag === tag)\n\n// A stream that emits each event after the given delay since the previous one.\nconst timed = <A>(steps: ReadonlyArray<readonly [Duration.Input, A]>): Stream.Stream<A> =>\n Stream.fromIterable(steps).pipe(\n Stream.mapEffect(([delay, ev]) => Effect.as(Effect.sleep(delay), ev)),\n )\n\n// Collect a metered stream while advancing the test clock by each step, so\n// every per-event clock read lands at a known virtual time.\nconst runTimed = <A>(\n metered: Stream.Stream<A>,\n steps: ReadonlyArray<Duration.Input>,\n): Effect.Effect<ReadonlyArray<A>> =>\n Effect.gen(function* () {\n const fiber = yield* Effect.forkChild(Stream.runCollect(metered))\n yield* Effect.forEach(steps, (step) => TestClock.adjust(step), { discard: true })\n return yield* Fiber.join(fiber)\n })\n\ndescribe(\"tokenTotals\", () => {\n it.effect(\"turn level: a single TurnComplete reports that generation's usage\", () =>\n Effect.gen(function* () {\n const stream = Stream.make(\n text(\"hi\"),\n turnComplete({ input_tokens: 100, output_tokens: 20, total_tokens: 120 }),\n )\n const out = yield* Stream.runCollect(stream.pipe(tokenTotals))\n const totals = tagged(out, \"TokenTotals\") as ReadonlyArray<TokenTotals>\n expect(totals).toHaveLength(1)\n expect(head(totals).turnIndex).toBe(0)\n expect(head(totals).usage.output_tokens).toBe(20)\n expect(head(totals).cumulative.output_tokens).toBe(20)\n }),\n )\n\n it.effect(\"loop level: cumulative sums across every turn, usage stays per-turn\", () =>\n Effect.gen(function* () {\n const stream = Stream.make(\n text(\"a\"),\n turnComplete({ input_tokens: 1000, output_tokens: 120 }),\n turnComplete({ input_tokens: 1300, output_tokens: 410 }),\n )\n const out = yield* Stream.runCollect(stream.pipe(tokenTotals))\n const totals = tagged(out, \"TokenTotals\") as ReadonlyArray<TokenTotals>\n expect(totals.map((t) => t.turnIndex)).toEqual([0, 1])\n expect(totals.map((t) => t.usage.output_tokens)).toEqual([120, 410])\n expect(totals.map((t) => t.cumulative.input_tokens)).toEqual([1000, 2300])\n expect(totals.map((t) => t.cumulative.output_tokens)).toEqual([120, 530])\n }),\n )\n\n it.effect(\"emits an incremental output_tokens counter measurement per turn\", () =>\n Effect.gen(function* () {\n const stream = Stream.make(turnComplete({ output_tokens: 7 }))\n const out = yield* Stream.runCollect(stream.pipe(tokenTotals))\n const m = head(samples(out)).measurements.find((m) => m.name === \"effect_uai_output_tokens\")\n expect(m).toEqual({ name: \"effect_uai_output_tokens\", kind: \"counter\", value: 7 })\n }),\n )\n})\n\ndescribe(\"timeToFirstToken\", () => {\n it.effect(\"fires on the first content delta, measured from request (stream init)\", () =>\n Effect.gen(function* () {\n const stream = timed<TurnEvent>([\n [\"300 millis\", text(\"hello\")],\n [\"700 millis\", turnComplete({})],\n ]).pipe(timeToFirstToken())\n const out = yield* runTimed(stream, [\"300 millis\", \"700 millis\"])\n const ttft = tagged(out, \"TimeToFirstToken\") as ReadonlyArray<TimeToFirstToken>\n expect(ttft).toHaveLength(1)\n expect(Duration.toMillis(head(ttft).elapsed)).toBe(300)\n expect(head(ttft).kind).toBe(\"text\")\n }),\n )\n\n it.effect(\"reports kind reasoning when reasoning arrives first\", () =>\n Effect.gen(function* () {\n const stream = timed<TurnEvent>([\n [\"120 millis\", TurnEvent.ReasoningDelta({ text: \"...\", kind: \"trace\" })],\n [\"80 millis\", text(\"answer\")],\n [\"50 millis\", turnComplete({})],\n ]).pipe(timeToFirstToken())\n const out = yield* runTimed(stream, [\"120 millis\", \"80 millis\", \"50 millis\"])\n const ttft = tagged(out, \"TimeToFirstToken\") as ReadonlyArray<TimeToFirstToken>\n expect(ttft).toHaveLength(1)\n expect(head(ttft).kind).toBe(\"reasoning\")\n expect(Duration.toMillis(head(ttft).elapsed)).toBe(120)\n }),\n )\n\n it.effect(\"loop level: one TTFT per turn, turnIndex increments\", () =>\n Effect.gen(function* () {\n const stream = timed<TurnEvent>([\n [\"200 millis\", text(\"a\")],\n [\"100 millis\", turnComplete({})],\n [\"300 millis\", text(\"b\")],\n [\"100 millis\", turnComplete({})],\n ]).pipe(timeToFirstToken())\n const out = yield* runTimed(stream, [\"200 millis\", \"100 millis\", \"300 millis\", \"100 millis\"])\n const ttft = tagged(out, \"TimeToFirstToken\") as ReadonlyArray<TimeToFirstToken>\n expect(ttft.map((t) => t.turnIndex)).toEqual([0, 1])\n // turn 0 from init; turn 1 from the previous TurnComplete (loop-scope approximation)\n expect(ttft.map((t) => Duration.toMillis(t.elapsed))).toEqual([200, 300])\n }),\n )\n})\n\ndescribe(\"timeToCompletion\", () => {\n it.effect(\"reports duration (request->complete) and generation (first token->complete)\", () =>\n Effect.gen(function* () {\n const stream = timed<TurnEvent>([\n [\"300 millis\", text(\"hi\")],\n [\"700 millis\", turnComplete({})],\n ]).pipe(timeToCompletion)\n const out = yield* runTimed(stream, [\"300 millis\", \"700 millis\"])\n const done = tagged(out, \"TimeToCompletion\") as ReadonlyArray<TimeToCompletion>\n expect(done).toHaveLength(1)\n expect(Duration.toMillis(head(done).duration)).toBe(1000)\n expect(Duration.toMillis(head(done).generation)).toBe(700)\n }),\n )\n})\n\ndescribe(\"computeThroughputTick\", () => {\n const base = {\n units: 0,\n lastUnits: 0,\n lastMillis: 0,\n firstMillis: Option.none<number>(),\n smoothed: Option.none<number>(),\n turnIndex: 0,\n }\n\n it(\"returns None before the first token\", () => {\n expect(Option.isNone(computeThroughputTick(base, 500, \"windowed\", undefined))).toBe(true)\n })\n\n it(\"windowed: rate is units in the last interval over that interval\", () => {\n const state = {\n ...base,\n units: 30,\n lastUnits: 10,\n lastMillis: 500,\n firstMillis: Option.some(100),\n }\n const r = computeThroughputTick(state, 1000, \"windowed\", undefined)\n // (30 - 10) units over (1000 - 500) ms = 40/s\n expect(Option.getOrThrow(r).rate).toBe(40)\n })\n\n it(\"cumulative: rate is total units over time since first token\", () => {\n const state = {\n ...base,\n units: 30,\n lastUnits: 10,\n lastMillis: 500,\n firstMillis: Option.some(100),\n }\n const r = computeThroughputTick(state, 1000, \"cumulative\", undefined)\n // 30 units over (1000 - 100) ms ~= 33.33/s\n expect(Option.getOrThrow(r).rate).toBeCloseTo(33.333, 2)\n })\n\n it(\"smooth: blends the instantaneous rate with the carried average\", () => {\n const state = {\n ...base,\n units: 20,\n lastUnits: 0,\n lastMillis: 0,\n firstMillis: Option.some(0),\n smoothed: Option.some(100),\n }\n // windowed instant = 20 units / 1000 ms = 20/s; smoothed = 0.5*20 + 0.5*100 = 60\n const r = computeThroughputTick(state, 1000, \"windowed\", 0.5)\n expect(Option.getOrThrow(r).rate).toBe(60)\n })\n})\n\ndescribe(\"throughput (metronome)\", () => {\n it.effect(\"emits a live char rate on the tick, over the elapsed window\", () =>\n Effect.gen(function* () {\n // 10 chars land at t=0; the source then stays open so the metronome can\n // tick. take(1) ends the stream on the first sample, so termination does\n // not depend on the source closing.\n const source = Stream.make(text(\"aaaaa\"), text(\"aaaaa\")).pipe(\n Stream.concat(timed<TurnEvent>([[\"10 seconds\", turnComplete({})]])),\n )\n const stream = source.pipe(\n throughput({ every: \"1 second\", unit: \"char\" }),\n metricEvents,\n Stream.take(1),\n )\n const out = yield* runTimed(stream, [\"1 second\"])\n const rates = out.filter((e): e is Throughput => e._tag === \"Throughput\")\n expect(rates).toHaveLength(1)\n expect(head(rates).unit).toBe(\"char\")\n expect(head(rates).turnIndex).toBe(0)\n // exact rate math is pinned by the computeThroughputTick tests; here we\n // only assert the metronome wired a positive char rate onto the tick.\n expect(head(rates).ratePerSecond).toBeGreaterThan(0)\n }),\n )\n})\n\ndescribe(\"custom events and helpers\", () => {\n it(\"makeEvent stamps the brand so isMetricEvent and the recorder see it\", () => {\n const ev = makeEvent({\n _tag: \"ToolLatency\",\n turnIndex: 0,\n measurements: [{ name: \"myapp_tool_latency\", kind: \"timer\", value: Duration.millis(42) }],\n })\n expect(isMetricEvent(ev)).toBe(true)\n expect(isMetricEvent(text(\"x\"))).toBe(false)\n expect(isMetricEvent(turnComplete({}))).toBe(false)\n })\n\n it.effect(\"metricEvents projects a mixed stream onto just the samples\", () =>\n Effect.gen(function* () {\n const stream = Stream.make(text(\"hi\"), turnComplete({ output_tokens: 3 })).pipe(\n tokenTotals,\n metricEvents,\n )\n const out = yield* Stream.runCollect(stream)\n expect(out.every(isMetricEvent)).toBe(true)\n expect(out.map((e) => e._tag)).toEqual([\"TokenTotals\"])\n }),\n )\n})\n"],"mappings":";;;;;;;AAsBA,MAAM,gBAAgB,UACpB,UAAU,aAAa,EAAE,MAAM;CAAE,OAAO,EAAE;CAAE;CAAO,aAAa;CAAQ,EAAE,CAAC;AAE7E,MAAM,QAAQ,MAAyB,UAAU,UAAU,EAAE,MAAM,GAAG,CAAC;AAEvE,MA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AAE,KAAK,CAAC,CAAC,QAAQ,CAAC,cAAc,CAAC;GACvD,CACH;EACD"}
|
|
1
|
+
{"version":3,"file":"Metrics.test.mjs","names":["Arr"],"sources":["../../src/observability/Metrics.test.ts"],"sourcesContent":["import { describe, it } from \"@effect/vitest\"\nimport { Array as Arr, Duration, Effect, Fiber, Option, Stream } from \"effect\"\nimport * as TestClock from \"effect/testing/TestClock\"\nimport { expect } from \"vitest\"\nimport type { Usage } from \"../domain/Items.js\"\nimport { TurnEvent } from \"../domain/Turn.js\"\nimport {\n type MetricEvent,\n type Throughput,\n type TimeToCompletion,\n type TimeToFirstToken,\n type TokenTotals,\n computeThroughputTick,\n isMetricEvent,\n makeEvent,\n metricEvents,\n throughput,\n timeToCompletion,\n timeToFirstToken,\n tokenTotals,\n} from \"./Metrics.js\"\n\nconst turnComplete = (usage: Usage): TurnEvent =>\n TurnEvent.TurnComplete({ turn: { items: [], usage, stop_reason: \"stop\" } })\n\nconst text = (s: string): TurnEvent => TurnEvent.TextDelta({ text: s })\n\nconst toolArgs = (s: string): TurnEvent =>\n TurnEvent.ToolCallArgsDelta({ call_id: \"call_1\", delta: s })\n\nconst samples = (events: ReadonlyArray<unknown>): ReadonlyArray<MetricEvent> =>\n events.filter(isMetricEvent)\n\nconst head = <A>(xs: ReadonlyArray<A>): A => Option.getOrThrow(Arr.head(xs))\n\nconst tagged = <T extends MetricEvent[\"_tag\"]>(\n events: ReadonlyArray<unknown>,\n tag: T,\n): ReadonlyArray<Extract<MetricEvent, { readonly _tag: T }>> =>\n samples(events).filter((e): e is Extract<MetricEvent, { readonly _tag: T }> => e._tag === tag)\n\n// A stream that emits each event after the given delay since the previous one.\nconst timed = <A>(steps: ReadonlyArray<readonly [Duration.Input, A]>): Stream.Stream<A> =>\n Stream.fromIterable(steps).pipe(\n Stream.mapEffect(([delay, ev]) => Effect.as(Effect.sleep(delay), ev)),\n )\n\n// Collect a metered stream while advancing the test clock by each step, so\n// every per-event clock read lands at a known virtual time.\nconst runTimed = <A>(\n metered: Stream.Stream<A>,\n steps: ReadonlyArray<Duration.Input>,\n): Effect.Effect<ReadonlyArray<A>> =>\n Effect.gen(function* () {\n const fiber = yield* Effect.forkChild(Stream.runCollect(metered))\n yield* Effect.forEach(steps, (step) => TestClock.adjust(step), { discard: true })\n return yield* Fiber.join(fiber)\n })\n\ndescribe(\"tokenTotals\", () => {\n it.effect(\"turn level: a single TurnComplete reports that generation's usage\", () =>\n Effect.gen(function* () {\n const stream = Stream.make(\n text(\"hi\"),\n turnComplete({ input_tokens: 100, output_tokens: 20, total_tokens: 120 }),\n )\n const out = yield* Stream.runCollect(stream.pipe(tokenTotals))\n const totals = tagged(out, \"TokenTotals\") as ReadonlyArray<TokenTotals>\n expect(totals).toHaveLength(1)\n expect(head(totals).turnIndex).toBe(0)\n expect(head(totals).usage.output_tokens).toBe(20)\n expect(head(totals).cumulative.output_tokens).toBe(20)\n }),\n )\n\n it.effect(\"loop level: cumulative sums across every turn, usage stays per-turn\", () =>\n Effect.gen(function* () {\n const stream = Stream.make(\n text(\"a\"),\n turnComplete({ input_tokens: 1000, output_tokens: 120 }),\n turnComplete({ input_tokens: 1300, output_tokens: 410 }),\n )\n const out = yield* Stream.runCollect(stream.pipe(tokenTotals))\n const totals = tagged(out, \"TokenTotals\") as ReadonlyArray<TokenTotals>\n expect(totals.map((t) => t.turnIndex)).toEqual([0, 1])\n expect(totals.map((t) => t.usage.output_tokens)).toEqual([120, 410])\n expect(totals.map((t) => t.cumulative.input_tokens)).toEqual([1000, 2300])\n expect(totals.map((t) => t.cumulative.output_tokens)).toEqual([120, 530])\n }),\n )\n\n it.effect(\"emits an incremental output_tokens counter measurement per turn\", () =>\n Effect.gen(function* () {\n const stream = Stream.make(turnComplete({ output_tokens: 7 }))\n const out = yield* Stream.runCollect(stream.pipe(tokenTotals))\n const m = head(samples(out)).measurements.find((m) => m.name === \"effect_uai_output_tokens\")\n expect(m).toEqual({ name: \"effect_uai_output_tokens\", kind: \"counter\", value: 7 })\n }),\n )\n\n it.effect(\"carries cache read and write tokens through usage and measurements\", () =>\n Effect.gen(function* () {\n const stream = Stream.make(\n turnComplete({\n input_tokens: 94,\n input_tokens_details: { cached_tokens: 31851, cache_write_tokens: 604 },\n }),\n turnComplete({ input_tokens: 6, input_tokens_details: { cached_tokens: 32000 } }),\n )\n const out = yield* Stream.runCollect(stream.pipe(tokenTotals))\n const totals = tagged(out, \"TokenTotals\") as ReadonlyArray<TokenTotals>\n expect(totals.map((t) => t.cumulative.input_tokens_details?.cache_write_tokens)).toEqual([\n 604, 604,\n ])\n expect(totals.map((t) => t.cumulative.input_tokens_details?.cached_tokens)).toEqual([\n 31851, 63851,\n ])\n const write = head(totals).measurements.find(\n (m) => m.name === \"effect_uai_cache_write_tokens\",\n )\n expect(write).toEqual({ name: \"effect_uai_cache_write_tokens\", kind: \"counter\", value: 604 })\n }),\n )\n})\n\ndescribe(\"timeToFirstToken\", () => {\n it.effect(\"fires on the first content delta, measured from request (stream init)\", () =>\n Effect.gen(function* () {\n const stream = timed<TurnEvent>([\n [\"300 millis\", text(\"hello\")],\n [\"700 millis\", turnComplete({})],\n ]).pipe(timeToFirstToken())\n const out = yield* runTimed(stream, [\"300 millis\", \"700 millis\"])\n const ttft = tagged(out, \"TimeToFirstToken\") as ReadonlyArray<TimeToFirstToken>\n expect(ttft).toHaveLength(1)\n expect(Duration.toMillis(head(ttft).elapsed)).toBe(300)\n expect(head(ttft).kind).toBe(\"text\")\n }),\n )\n\n it.effect(\"reports kind reasoning when reasoning arrives first\", () =>\n Effect.gen(function* () {\n const stream = timed<TurnEvent>([\n [\"120 millis\", TurnEvent.ReasoningDelta({ text: \"...\", kind: \"trace\" })],\n [\"80 millis\", text(\"answer\")],\n [\"50 millis\", turnComplete({})],\n ]).pipe(timeToFirstToken())\n const out = yield* runTimed(stream, [\"120 millis\", \"80 millis\", \"50 millis\"])\n const ttft = tagged(out, \"TimeToFirstToken\") as ReadonlyArray<TimeToFirstToken>\n expect(ttft).toHaveLength(1)\n expect(head(ttft).kind).toBe(\"reasoning\")\n expect(Duration.toMillis(head(ttft).elapsed)).toBe(120)\n }),\n )\n\n it.effect(\"loop level: one TTFT per turn, turnIndex increments\", () =>\n Effect.gen(function* () {\n const stream = timed<TurnEvent>([\n [\"200 millis\", text(\"a\")],\n [\"100 millis\", turnComplete({})],\n [\"300 millis\", text(\"b\")],\n [\"100 millis\", turnComplete({})],\n ]).pipe(timeToFirstToken())\n const out = yield* runTimed(stream, [\"200 millis\", \"100 millis\", \"300 millis\", \"100 millis\"])\n const ttft = tagged(out, \"TimeToFirstToken\") as ReadonlyArray<TimeToFirstToken>\n expect(ttft.map((t) => t.turnIndex)).toEqual([0, 1])\n // turn 0 from init; turn 1 from the previous TurnComplete (loop-scope approximation)\n expect(ttft.map((t) => Duration.toMillis(t.elapsed))).toEqual([200, 300])\n }),\n )\n})\n\ndescribe(\"timeToCompletion\", () => {\n it.effect(\"reports duration (request->complete) and generation (first token->complete)\", () =>\n Effect.gen(function* () {\n const stream = timed<TurnEvent>([\n [\"300 millis\", text(\"hi\")],\n [\"700 millis\", turnComplete({})],\n ]).pipe(timeToCompletion)\n const out = yield* runTimed(stream, [\"300 millis\", \"700 millis\"])\n const done = tagged(out, \"TimeToCompletion\") as ReadonlyArray<TimeToCompletion>\n expect(done).toHaveLength(1)\n expect(Duration.toMillis(head(done).duration)).toBe(1000)\n expect(Duration.toMillis(head(done).generation)).toBe(700)\n }),\n )\n})\n\ndescribe(\"computeThroughputTick\", () => {\n const base = {\n units: 0,\n lastUnits: 0,\n lastMillis: 0,\n firstMillis: Option.none<number>(),\n smoothed: Option.none<number>(),\n turnIndex: 0,\n }\n\n it(\"returns None before the first token\", () => {\n expect(Option.isNone(computeThroughputTick(base, 500, \"windowed\", undefined))).toBe(true)\n })\n\n it(\"windowed: rate is units in the last interval over that interval\", () => {\n const state = {\n ...base,\n units: 30,\n lastUnits: 10,\n lastMillis: 500,\n firstMillis: Option.some(100),\n }\n const r = computeThroughputTick(state, 1000, \"windowed\", undefined)\n // (30 - 10) units over (1000 - 500) ms = 40/s\n expect(Option.getOrThrow(r).rate).toBe(40)\n })\n\n it(\"cumulative: rate is total units over time since first token\", () => {\n const state = {\n ...base,\n units: 30,\n lastUnits: 10,\n lastMillis: 500,\n firstMillis: Option.some(100),\n }\n const r = computeThroughputTick(state, 1000, \"cumulative\", undefined)\n // 30 units over (1000 - 100) ms ~= 33.33/s\n expect(Option.getOrThrow(r).rate).toBeCloseTo(33.333, 2)\n })\n\n it(\"smooth: blends the instantaneous rate with the carried average\", () => {\n const state = {\n ...base,\n units: 20,\n lastUnits: 0,\n lastMillis: 0,\n firstMillis: Option.some(0),\n smoothed: Option.some(100),\n }\n // windowed instant = 20 units / 1000 ms = 20/s; smoothed = 0.5*20 + 0.5*100 = 60\n const r = computeThroughputTick(state, 1000, \"windowed\", 0.5)\n expect(Option.getOrThrow(r).rate).toBe(60)\n })\n})\n\ndescribe(\"throughput (metronome)\", () => {\n it.effect(\"emits a live char rate on the tick, over the elapsed window\", () =>\n Effect.gen(function* () {\n // 10 chars land at t=0; the source then stays open so the metronome can\n // tick. take(1) ends the stream on the first sample, so termination does\n // not depend on the source closing.\n const source = Stream.make(text(\"aaaaa\"), text(\"aaaaa\")).pipe(\n Stream.concat(timed<TurnEvent>([[\"10 seconds\", turnComplete({})]])),\n )\n const stream = source.pipe(\n throughput({ every: \"1 second\", unit: \"char\" }),\n metricEvents,\n Stream.take(1),\n )\n const out = yield* runTimed(stream, [\"1 second\"])\n const rates = out.filter((e): e is Throughput => e._tag === \"Throughput\")\n expect(rates).toHaveLength(1)\n expect(head(rates).unit).toBe(\"char\")\n expect(head(rates).turnIndex).toBe(0)\n // exact rate math is pinned by the computeThroughputTick tests; here we\n // only assert the metronome wired a positive char rate onto the tick.\n expect(head(rates).ratePerSecond).toBeGreaterThan(0)\n }),\n )\n\n it.effect(\"counts tool-call arguments: a turn with no prose still reports a rate\", () =>\n Effect.gen(function* () {\n // The shape of an agent turn that only calls tools. Before output deltas\n // were counted beyond TextDelta this measured 0 for the whole run.\n const source = Stream.make(toolArgs('{\"city\":'), toolArgs('\"Lisbon\"}')).pipe(\n Stream.concat(timed<TurnEvent>([[\"10 seconds\", turnComplete({})]])),\n )\n const stream = source.pipe(\n throughput({ every: \"1 second\", unit: \"char\" }),\n metricEvents,\n Stream.take(1),\n )\n const out = yield* runTimed(stream, [\"1 second\"])\n const rates = out.filter((e): e is Throughput => e._tag === \"Throughput\")\n expect(rates).toHaveLength(1)\n expect(head(rates).ratePerSecond).toBeGreaterThan(0)\n }),\n )\n\n // Runs on the real clock: this asserts an absence, so there is no sample to\n // wait for and the stream has to end by the source closing. Under TestClock\n // that path does not settle, because the metronome re-arms a sleep that no\n // remaining `adjust` resolves.\n it.live(\"ignores events that carry no generated output\", () =>\n Effect.gen(function* () {\n // ToolCallStart and UsageUpdate are turn bookkeeping, not output.\n const source = Stream.make(\n TurnEvent.ToolCallStart({ call_id: \"call_1\", name: \"get_weather\" }),\n TurnEvent.UsageUpdate({ usage: { output_tokens: 5 } }),\n ).pipe(Stream.concat(timed<TurnEvent>([[\"30 millis\", turnComplete({})]])))\n const stream = source.pipe(throughput({ every: \"10 millis\", unit: \"char\" }), metricEvents)\n const out = yield* Stream.runCollect(stream)\n // No output delta ever landed, so the accumulator never started and the\n // metronome ticks produce nothing.\n expect(out.filter((e): e is Throughput => e._tag === \"Throughput\")).toHaveLength(0)\n }),\n )\n})\n\ndescribe(\"custom events and helpers\", () => {\n it(\"makeEvent stamps the brand so isMetricEvent and the recorder see it\", () => {\n const ev = makeEvent({\n _tag: \"ToolLatency\",\n turnIndex: 0,\n measurements: [{ name: \"myapp_tool_latency\", kind: \"timer\", value: Duration.millis(42) }],\n })\n expect(isMetricEvent(ev)).toBe(true)\n expect(isMetricEvent(text(\"x\"))).toBe(false)\n expect(isMetricEvent(turnComplete({}))).toBe(false)\n })\n\n it.effect(\"metricEvents projects a mixed stream onto just the samples\", () =>\n Effect.gen(function* () {\n const stream = Stream.make(text(\"hi\"), turnComplete({ output_tokens: 3 })).pipe(\n tokenTotals,\n metricEvents,\n )\n const out = yield* Stream.runCollect(stream)\n expect(out.every(isMetricEvent)).toBe(true)\n expect(out.map((e) => e._tag)).toEqual([\"TokenTotals\"])\n }),\n )\n})\n"],"mappings":";;;;;;;;AAsBA,MAAM,gBAAgB,UACpB,UAAU,aAAa,EAAE,MAAM;CAAE,OAAO,CAAC;CAAG;CAAO,aAAa;AAAO,EAAE,CAAC;AAE5E,MAAM,QAAQ,MAAyB,UAAU,UAAU,EAAE,MAAM,EAAE,CAAC;AAEtE,MAAM,YAAY,MAChB,UAAU,kBAAkB;CAAE,SAAS;CAAU,OAAO;AAAE,CAAC;AAE7D,MAAM,WAAW,WACf,OAAO,OAAO,aAAa;AAE7B,MAAM,QAAW,OAA4B,OAAO,WAAWA,MAAI,KAAK,EAAE,CAAC;AAE3E,MAAM,UACJ,QACA,QAEA,QAAQ,MAAM,CAAC,CAAC,QAAQ,MAAuD,EAAE,SAAS,GAAG;AAG/F,MAAM,SAAY,UAChB,OAAO,aAAa,KAAK,CAAC,CAAC,KACzB,OAAO,WAAW,CAAC,OAAO,QAAQ,OAAO,GAAG,OAAO,MAAM,KAAK,GAAG,EAAE,CAAC,CACtE;AAIF,MAAM,YACJ,SACA,UAEA,OAAO,IAAI,aAAa;CACtB,MAAM,QAAQ,OAAO,OAAO,UAAU,OAAO,WAAW,OAAO,CAAC;CAChE,OAAO,OAAO,QAAQ,QAAQ,SAAS,UAAU,OAAO,IAAI,GAAG,EAAE,SAAS,KAAK,CAAC;CAChF,OAAO,OAAO,MAAM,KAAK,KAAK;AAChC,CAAC;AAEH,SAAS,qBAAqB;CAC5B,GAAG,OAAO,2EACR,OAAO,IAAI,aAAa;EACtB,MAAM,SAAS,OAAO,KACpB,KAAK,IAAI,GACT,aAAa;GAAE,cAAc;GAAK,eAAe;GAAI,cAAc;EAAI,CAAC,CAC1E;EACA,MAAM,MAAM,OAAO,OAAO,WA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GAAE,CAAC;EAC1F,CAAC;EACD,aAAO,cAAc,EAAE,CAAC,CAAC,CAAC,KAAK,IAAI;EACnC,aAAO,cAAc,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,KAAK;EAC3C,aAAO,cAAc,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,KAAK;CACpD,CAAC;CAED,GAAG,OAAO,oEACR,OAAO,IAAI,aAAa;EACtB,MAAM,SAAS,OAAO,KAAK,KAAK,IAAI,GAAG,aAAa,EAAE,eAAe,EAAE,CAAC,CAAC,CAAC,CAAC,KACzE,aACA,YACF;EACA,MAAM,MAAM,OAAO,OAAO,WAAW,MAAM;EAC3C,aAAO,IAAI,MAAM,aAAa,CAAC,CAAC,CAAC,KAAK,IAAI;EAC1C,aAAO,IAAI,KAAK,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,aAAa,CAAC;CACxD,CAAC,CACH;AACF,CAAC"}
|
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
import { Duration, Layer, Stream } from "effect";
|
|
2
2
|
import { HttpClient } from "effect/unstable/http";
|
|
3
|
-
|
|
4
|
-
//#region src/observability/Telemetry.d.ts
|
|
5
3
|
declare namespace Telemetry_d_exports {
|
|
6
4
|
export { LayerOtlpOptions, RecordOptions, layerOtlp, record };
|
|
7
5
|
}
|
|
8
6
|
type RecordOptions = {
|
|
9
|
-
/** Attributes applied to every recorded metric, e.g. `{ model, provider }`. */
|
|
7
|
+
/** Attributes applied to every recorded metric, e.g. `{ model, provider }`. */
|
|
8
|
+
readonly attributes?: Readonly<Record<string, string>>;
|
|
10
9
|
};
|
|
11
10
|
/**
|
|
12
11
|
* Record every measurement on every metric event into effect `Metric`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Telemetry.d.mts","names":[],"sources":["../../src/observability/Telemetry.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"Telemetry.d.mts","names":[],"sources":["../../src/observability/Telemetry.ts"],"mappings":";;;;;KAqDY;;WAED,aAAa,SAAS;;;;;;;;;;cAWpB,SAAM,UACN,mBACV,GAAG,GAAG,GAAC,MAAQ,OAAO,OAAO,GAAG,GAAG,OAAK,OAAO,OAAO,GAAG,GAAG;KASnD;WACD;WACA;aACE;aACA;;WAEF,iBAAiB,SAAS;;;;;;;;cASxB,YAAS,SACX,qBACR,MAAM,oBAAoB,WAAW"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as __exportAll } from "../
|
|
1
|
+
import { n as __exportAll } from "../rolldown-runtime-EAsCxrDo.mjs";
|
|
2
2
|
import { isMetricEvent } from "./Metrics.mjs";
|
|
3
3
|
import { Effect, Layer, Match, Metric, Stream } from "effect";
|
|
4
4
|
import { OtlpMetrics, OtlpSerialization } from "effect/unstable/observability";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Telemetry.mjs","names":[],"sources":["../../src/observability/Telemetry.ts"],"sourcesContent":["import { Duration, Effect, Layer, Match, Metric, Stream } from \"effect\"\nimport type { HttpClient } from \"effect/unstable/http\"\nimport { OtlpMetrics, OtlpSerialization } from \"effect/unstable/observability\"\nimport { isMetricEvent, type Measurement, type MetricEvent } from \"./Metrics.js\"\n\n// ---------------------------------------------------------------------------\n// The agnostic recorder\n// ---------------------------------------------------------------------------\n\n/**\n * Histogram bucket boundaries used for every histogram measurement (the only\n * built-in one is throughput). Custom histogram metrics share these; a metric\n * that needs bespoke boundaries can update its own instrument directly instead\n * of routing through `record`.\n */\nconst histogramBoundaries = Metric.exponentialBoundaries({ start: 1, factor: 2, count: 16 })\n\n/**\n * Build the effect `Metric` instrument a measurement maps to. Dispatches on\n * `kind`, never on the event `_tag`, so a new built-in or custom metric needs\n * no change here. Instruments dedupe by name in the global registry, so a fresh\n * instance per call accumulates onto the same series (no cache needed).\n */\nconst buildInstrument = (m: Measurement): Metric.Metric<any, any> =>\n Match.value(m.kind).pipe(\n Match.when(\"counter\", () => Metric.counter(m.name, { incremental: true })),\n Match.when(\"histogram\", () => Metric.histogram(m.name, { boundaries: histogramBoundaries })),\n Match.when(\"timer\", () => Metric.timer(m.name)),\n Match.when(\"gauge\", () => Metric.gauge(m.name)),\n Match.exhaustive,\n )\n\nconst mergeAttributes = (\n base: Readonly<Record<string, string>> | undefined,\n extra: Readonly<Record<string, string>> | undefined,\n): Readonly<Record<string, string>> | undefined =>\n base === undefined ? extra : extra === undefined ? base : { ...base, ...extra }\n\nconst recordEvent = (\n ev: MetricEvent,\n baseAttributes: Readonly<Record<string, string>> | undefined,\n): Effect.Effect<void> =>\n Effect.forEach(\n ev.measurements,\n (m) => {\n const attributes = mergeAttributes(baseAttributes, m.attributes)\n const base = buildInstrument(m)\n const instrument = attributes === undefined ? base : Metric.withAttributes(base, attributes)\n return Metric.update(instrument, m.value)\n },\n { discard: true },\n )\n\nexport type RecordOptions = {\n /** Attributes applied to every recorded metric, e.g. `{ model, provider }`. */\n readonly attributes?: Readonly<Record<string, string>>\n}\n\n/**\n * Record every measurement on every metric event into effect `Metric`\n * instruments, then pass events through unchanged. Matches events structurally\n * (`isMetricEvent`), so it records built-in and custom metrics alike, and\n * dispatches on `measurement.kind`, never on the event tag. Sits mid-pipeline\n * before the transport. Provide an OTLP (or Prometheus) layer to export the\n * instruments it populates.\n */\nexport const record =\n (options?: RecordOptions) =>\n <A, E, R>(self: Stream.Stream<A, E, R>): Stream.Stream<A, E, R> =>\n self.pipe(\n Stream.tap((ev) => (isMetricEvent(ev) ? recordEvent(ev, options?.attributes) : Effect.void)),\n )\n\n// ---------------------------------------------------------------------------\n// OTLP wiring\n// ---------------------------------------------------------------------------\n\nexport type LayerOtlpOptions = {\n readonly url: string\n readonly resource?: {\n readonly serviceName?: string\n readonly serviceVersion?: string\n }\n readonly exportInterval?: Duration.Input\n}\n\n/**\n * Convenience layer that exports recorded metrics over OTLP. Provides the JSON\n * serializer and leaves `HttpClient` as a requirement, so the platform's client\n * (FetchHttpClient, NodeHttpClient, ...) is provided at the edge. This keeps\n * the library platform-independent.\n */\nexport const layerOtlp = (\n options: LayerOtlpOptions,\n): Layer.Layer<never, never, HttpClient.HttpClient> =>\n OtlpMetrics.layer(options).pipe(Layer.provide(OtlpSerialization.layerJson))\n"],"mappings":";;;;;;;;;;;;;;;AAeA,MAAM,sBAAsB,OAAO,sBAAsB;CAAE,OAAO;CAAG,QAAQ;CAAG,OAAO;
|
|
1
|
+
{"version":3,"file":"Telemetry.mjs","names":[],"sources":["../../src/observability/Telemetry.ts"],"sourcesContent":["import { Duration, Effect, Layer, Match, Metric, Stream } from \"effect\"\nimport type { HttpClient } from \"effect/unstable/http\"\nimport { OtlpMetrics, OtlpSerialization } from \"effect/unstable/observability\"\nimport { isMetricEvent, type Measurement, type MetricEvent } from \"./Metrics.js\"\n\n// ---------------------------------------------------------------------------\n// The agnostic recorder\n// ---------------------------------------------------------------------------\n\n/**\n * Histogram bucket boundaries used for every histogram measurement (the only\n * built-in one is throughput). Custom histogram metrics share these; a metric\n * that needs bespoke boundaries can update its own instrument directly instead\n * of routing through `record`.\n */\nconst histogramBoundaries = Metric.exponentialBoundaries({ start: 1, factor: 2, count: 16 })\n\n/**\n * Build the effect `Metric` instrument a measurement maps to. Dispatches on\n * `kind`, never on the event `_tag`, so a new built-in or custom metric needs\n * no change here. Instruments dedupe by name in the global registry, so a fresh\n * instance per call accumulates onto the same series (no cache needed).\n */\nconst buildInstrument = (m: Measurement): Metric.Metric<any, any> =>\n Match.value(m.kind).pipe(\n Match.when(\"counter\", () => Metric.counter(m.name, { incremental: true })),\n Match.when(\"histogram\", () => Metric.histogram(m.name, { boundaries: histogramBoundaries })),\n Match.when(\"timer\", () => Metric.timer(m.name)),\n Match.when(\"gauge\", () => Metric.gauge(m.name)),\n Match.exhaustive,\n )\n\nconst mergeAttributes = (\n base: Readonly<Record<string, string>> | undefined,\n extra: Readonly<Record<string, string>> | undefined,\n): Readonly<Record<string, string>> | undefined =>\n base === undefined ? extra : extra === undefined ? base : { ...base, ...extra }\n\nconst recordEvent = (\n ev: MetricEvent,\n baseAttributes: Readonly<Record<string, string>> | undefined,\n): Effect.Effect<void> =>\n Effect.forEach(\n ev.measurements,\n (m) => {\n const attributes = mergeAttributes(baseAttributes, m.attributes)\n const base = buildInstrument(m)\n const instrument = attributes === undefined ? base : Metric.withAttributes(base, attributes)\n return Metric.update(instrument, m.value)\n },\n { discard: true },\n )\n\nexport type RecordOptions = {\n /** Attributes applied to every recorded metric, e.g. `{ model, provider }`. */\n readonly attributes?: Readonly<Record<string, string>>\n}\n\n/**\n * Record every measurement on every metric event into effect `Metric`\n * instruments, then pass events through unchanged. Matches events structurally\n * (`isMetricEvent`), so it records built-in and custom metrics alike, and\n * dispatches on `measurement.kind`, never on the event tag. Sits mid-pipeline\n * before the transport. Provide an OTLP (or Prometheus) layer to export the\n * instruments it populates.\n */\nexport const record =\n (options?: RecordOptions) =>\n <A, E, R>(self: Stream.Stream<A, E, R>): Stream.Stream<A, E, R> =>\n self.pipe(\n Stream.tap((ev) => (isMetricEvent(ev) ? recordEvent(ev, options?.attributes) : Effect.void)),\n )\n\n// ---------------------------------------------------------------------------\n// OTLP wiring\n// ---------------------------------------------------------------------------\n\nexport type LayerOtlpOptions = {\n readonly url: string\n readonly resource?: {\n readonly serviceName?: string\n readonly serviceVersion?: string\n }\n readonly exportInterval?: Duration.Input\n}\n\n/**\n * Convenience layer that exports recorded metrics over OTLP. Provides the JSON\n * serializer and leaves `HttpClient` as a requirement, so the platform's client\n * (FetchHttpClient, NodeHttpClient, ...) is provided at the edge. This keeps\n * the library platform-independent.\n */\nexport const layerOtlp = (\n options: LayerOtlpOptions,\n): Layer.Layer<never, never, HttpClient.HttpClient> =>\n OtlpMetrics.layer(options).pipe(Layer.provide(OtlpSerialization.layerJson))\n"],"mappings":";;;;;;;;;;;;;;;AAeA,MAAM,sBAAsB,OAAO,sBAAsB;CAAE,OAAO;CAAG,QAAQ;CAAG,OAAO;AAAG,CAAC;;;;;;;AAQ3F,MAAM,mBAAmB,MACvB,MAAM,MAAM,EAAE,IAAI,CAAC,CAAC,KAClB,MAAM,KAAK,iBAAiB,OAAO,QAAQ,EAAE,MAAM,EAAE,aAAa,KAAK,CAAC,CAAC,GACzE,MAAM,KAAK,mBAAmB,OAAO,UAAU,EAAE,MAAM,EAAE,YAAY,oBAAoB,CAAC,CAAC,GAC3F,MAAM,KAAK,eAAe,OAAO,MAAM,EAAE,IAAI,CAAC,GAC9C,MAAM,KAAK,eAAe,OAAO,MAAM,EAAE,IAAI,CAAC,GAC9C,MAAM,UACR;AAEF,MAAM,mBACJ,MACA,UAEA,SAAS,KAAA,IAAY,QAAQ,UAAU,KAAA,IAAY,OAAO;CAAE,GAAG;CAAM,GAAG;AAAM;AAEhF,MAAM,eACJ,IACA,mBAEA,OAAO,QACL,GAAG,eACF,MAAM;CACL,MAAM,aAAa,gBAAgB,gBAAgB,EAAE,UAAU;CAC/D,MAAM,OAAO,gBAAgB,CAAC;CAC9B,MAAM,aAAa,eAAe,KAAA,IAAY,OAAO,OAAO,eAAe,MAAM,UAAU;CAC3F,OAAO,OAAO,OAAO,YAAY,EAAE,KAAK;AAC1C,GACA,EAAE,SAAS,KAAK,CAClB;;;;;;;;;AAeF,MAAa,UACV,aACS,SACR,KAAK,KACH,OAAO,KAAK,OAAQ,cAAc,EAAE,IAAI,YAAY,IAAI,SAAS,UAAU,IAAI,OAAO,IAAK,CAC7F;;;;;;;AAqBJ,MAAa,aACX,YAEA,YAAY,MAAM,OAAO,CAAC,CAAC,KAAK,MAAM,QAAQ,kBAAkB,SAAS,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export {}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { makeEvent } from "./Metrics.mjs";
|
|
2
2
|
import { layerOtlp, record } from "./Telemetry.mjs";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import { o as describe } from "../utils-CiH_DjFW.mjs";
|
|
4
|
+
import { n as globalExpect } from "../test.DNmyFkvJ-YPzDR0Co.mjs";
|
|
5
|
+
import { t as it } from "../dist-nohcnkD6.mjs";
|
|
5
6
|
import { Array, Duration, Effect, Layer, Metric, Option, Ref, Stream } from "effect";
|
|
6
7
|
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
|
7
8
|
//#region src/observability/Telemetry.test.ts
|
|
@@ -20,7 +21,8 @@ describe("record", () => {
|
|
|
20
21
|
value: 5
|
|
21
22
|
}]);
|
|
22
23
|
yield* Stream.make(ev, ev).pipe(record(), Stream.runDrain);
|
|
23
|
-
const
|
|
24
|
+
const snap = yield* Metric.snapshot;
|
|
25
|
+
const c = findById(snap, "rec_counter");
|
|
24
26
|
globalExpect(c.type).toBe("Counter");
|
|
25
27
|
globalExpect(c.state.count).toBe(10);
|
|
26
28
|
})));
|
|
@@ -31,7 +33,8 @@ describe("record", () => {
|
|
|
31
33
|
value: Duration.millis(100)
|
|
32
34
|
}]);
|
|
33
35
|
yield* Stream.make(ev).pipe(record(), Stream.runDrain);
|
|
34
|
-
const
|
|
36
|
+
const snap = yield* Metric.snapshot;
|
|
37
|
+
const h = findById(snap, "rec_timer");
|
|
35
38
|
globalExpect(h.type).toBe("Histogram");
|
|
36
39
|
globalExpect(h.state.count).toBe(1);
|
|
37
40
|
})));
|
|
@@ -42,7 +45,9 @@ describe("record", () => {
|
|
|
42
45
|
value: 1
|
|
43
46
|
}]);
|
|
44
47
|
yield* Stream.make(ev).pipe(record({ attributes: { model: "test-model" } }), Stream.runDrain);
|
|
45
|
-
|
|
48
|
+
const snap = yield* Metric.snapshot;
|
|
49
|
+
const c = findById(snap, "rec_attr");
|
|
50
|
+
globalExpect(c.attributes).toMatchObject({ model: "test-model" });
|
|
46
51
|
})));
|
|
47
52
|
it.effect("records a custom metric with a novel name, unchanged recorder", () => isolated(Effect.gen(function* () {
|
|
48
53
|
const custom = makeEvent({
|
|
@@ -55,10 +60,13 @@ describe("record", () => {
|
|
|
55
60
|
}]
|
|
56
61
|
});
|
|
57
62
|
yield* Stream.make(custom).pipe(record(), Stream.runDrain);
|
|
58
|
-
|
|
63
|
+
const snap = yield* Metric.snapshot;
|
|
64
|
+
const c = findById(snap, "myapp_tool_latency_total");
|
|
65
|
+
globalExpect(c.state.count).toBe(3);
|
|
59
66
|
})));
|
|
60
67
|
it.effect("passes non-metric elements through untouched", () => isolated(Effect.gen(function* () {
|
|
61
|
-
|
|
68
|
+
const out = yield* Stream.make("a", "b", "c").pipe(record(), Stream.runCollect);
|
|
69
|
+
globalExpect(out).toEqual([
|
|
62
70
|
"a",
|
|
63
71
|
"b",
|
|
64
72
|
"c"
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Telemetry.test.mjs","names":["Arr"],"sources":["../../src/observability/Telemetry.test.ts"],"sourcesContent":["import { describe, it } from \"@effect/vitest\"\nimport { Array as Arr, Duration, Effect, Layer, Metric, Option, Ref, Stream } from \"effect\"\nimport { type HttpBody, HttpClient, HttpClientResponse } from \"effect/unstable/http\"\nimport { expect } from \"vitest\"\nimport { type Measurement, makeEvent } from \"./Metrics.js\"\nimport { layerOtlp, record } from \"./Telemetry.js\"\n\nconst event = (measurements: ReadonlyArray<Measurement>) =>\n makeEvent({ _tag: \"Test\", turnIndex: 0, measurements })\n\n// Each test gets a fresh registry so instruments do not leak across tests.\nconst isolated = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n Effect.provideService(self, Metric.MetricRegistry, new Map())\n\nconst findById = (snap: ReadonlyArray<Metric.Metric.Snapshot>, id: string) =>\n Option.getOrThrow(Arr.findFirst(snap, (s) => s.id === id))\n\ndescribe(\"record\", () => {\n it.effect(\"accumulates a counter measurement across events\", () =>\n isolated(\n Effect.gen(function* () {\n const ev = event([{ name: \"rec_counter\", kind: \"counter\", value: 5 }])\n yield* Stream.make(ev, ev).pipe(record(), Stream.runDrain)\n const snap = yield* Metric.snapshot\n const c = findById(snap, \"rec_counter\")\n expect(c.type).toBe(\"Counter\")\n expect((c.state as { readonly count: number }).count).toBe(10)\n }),\n ),\n )\n\n it.effect(\"records a timer measurement as a histogram observation\", () =>\n isolated(\n Effect.gen(function* () {\n const ev = event([{ name: \"rec_timer\", kind: \"timer\", value: Duration.millis(100) }])\n yield* Stream.make(ev).pipe(record(), Stream.runDrain)\n const snap = yield* Metric.snapshot\n const h = findById(snap, \"rec_timer\")\n expect(h.type).toBe(\"Histogram\")\n expect((h.state as { readonly count: number }).count).toBe(1)\n }),\n ),\n )\n\n it.effect(\"applies base attributes to every recorded metric\", () =>\n isolated(\n Effect.gen(function* () {\n const ev = event([{ name: \"rec_attr\", kind: \"counter\", value: 1 }])\n yield* Stream.make(ev).pipe(\n record({ attributes: { model: \"test-model\" } }),\n Stream.runDrain,\n )\n const snap = yield* Metric.snapshot\n const c = findById(snap, \"rec_attr\")\n expect(c.attributes).toMatchObject({ model: \"test-model\" })\n }),\n ),\n )\n\n it.effect(\"records a custom metric with a novel name, unchanged recorder\", () =>\n isolated(\n Effect.gen(function* () {\n // A user-defined event the recorder has never seen: still exported.\n const custom = makeEvent({\n _tag: \"ToolLatency\",\n turnIndex: 0,\n measurements: [{ name: \"myapp_tool_latency_total\", kind: \"counter\", value: 3 }],\n })\n yield* Stream.make(custom).pipe(record(), Stream.runDrain)\n const snap = yield* Metric.snapshot\n const c = findById(snap, \"myapp_tool_latency_total\")\n expect((c.state as { readonly count: number }).count).toBe(3)\n }),\n ),\n )\n\n it.effect(\"passes non-metric elements through untouched\", () =>\n isolated(\n Effect.gen(function* () {\n const out = yield* Stream.make(\"a\", \"b\", \"c\").pipe(record(), Stream.runCollect)\n expect(out).toEqual([\"a\", \"b\", \"c\"])\n }),\n ),\n )\n})\n\nconst bodyToString = (body: HttpBody.HttpBody): string =>\n body._tag === \"Uint8Array\" ? new TextDecoder().decode(body.body) : \"\"\n\ndescribe(\"layerOtlp\", () => {\n it.effect(\"exports recorded metrics over OTLP via a mock HttpClient\", () =>\n isolated(\n Effect.gen(function* () {\n const bodies = yield* Ref.make<ReadonlyArray<string>>([])\n const mockClient = HttpClient.make((request) =>\n Ref.update(bodies, (b) => [...b, bodyToString(request.body)]).pipe(\n Effect.as(HttpClientResponse.fromWeb(request, new Response(\"{}\", { status: 200 }))),\n ),\n )\n const clientLayer = Layer.succeed(HttpClient.HttpClient, mockClient)\n const ev = event([{ name: \"otlp_export_counter\", kind: \"counter\", value: 3 }])\n\n // Provide the OTLP layer scoped to the recording program. The exporter\n // flushes on scope close (interval is long, so we rely on the flush).\n yield* Stream.make(ev).pipe(\n record(),\n Stream.runDrain,\n Effect.provide(\n layerOtlp({\n url: \"http://localhost:4318/v1/metrics\",\n resource: { serviceName: \"test-service\" },\n exportInterval: \"10 minutes\",\n }).pipe(Layer.provide(clientLayer)),\n ),\n )\n\n const captured = yield* Ref.get(bodies)\n expect(captured.length).toBeGreaterThanOrEqual(1)\n expect(captured.join(\"\\n\")).toContain(\"otlp_export_counter\")\n }),\n ),\n )\n})\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"Telemetry.test.mjs","names":["Arr"],"sources":["../../src/observability/Telemetry.test.ts"],"sourcesContent":["import { describe, it } from \"@effect/vitest\"\nimport { Array as Arr, Duration, Effect, Layer, Metric, Option, Ref, Stream } from \"effect\"\nimport { type HttpBody, HttpClient, HttpClientResponse } from \"effect/unstable/http\"\nimport { expect } from \"vitest\"\nimport { type Measurement, makeEvent } from \"./Metrics.js\"\nimport { layerOtlp, record } from \"./Telemetry.js\"\n\nconst event = (measurements: ReadonlyArray<Measurement>) =>\n makeEvent({ _tag: \"Test\", turnIndex: 0, measurements })\n\n// Each test gets a fresh registry so instruments do not leak across tests.\nconst isolated = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n Effect.provideService(self, Metric.MetricRegistry, new Map())\n\nconst findById = (snap: ReadonlyArray<Metric.Metric.Snapshot>, id: string) =>\n Option.getOrThrow(Arr.findFirst(snap, (s) => s.id === id))\n\ndescribe(\"record\", () => {\n it.effect(\"accumulates a counter measurement across events\", () =>\n isolated(\n Effect.gen(function* () {\n const ev = event([{ name: \"rec_counter\", kind: \"counter\", value: 5 }])\n yield* Stream.make(ev, ev).pipe(record(), Stream.runDrain)\n const snap = yield* Metric.snapshot\n const c = findById(snap, \"rec_counter\")\n expect(c.type).toBe(\"Counter\")\n expect((c.state as { readonly count: number }).count).toBe(10)\n }),\n ),\n )\n\n it.effect(\"records a timer measurement as a histogram observation\", () =>\n isolated(\n Effect.gen(function* () {\n const ev = event([{ name: \"rec_timer\", kind: \"timer\", value: Duration.millis(100) }])\n yield* Stream.make(ev).pipe(record(), Stream.runDrain)\n const snap = yield* Metric.snapshot\n const h = findById(snap, \"rec_timer\")\n expect(h.type).toBe(\"Histogram\")\n expect((h.state as { readonly count: number }).count).toBe(1)\n }),\n ),\n )\n\n it.effect(\"applies base attributes to every recorded metric\", () =>\n isolated(\n Effect.gen(function* () {\n const ev = event([{ name: \"rec_attr\", kind: \"counter\", value: 1 }])\n yield* Stream.make(ev).pipe(\n record({ attributes: { model: \"test-model\" } }),\n Stream.runDrain,\n )\n const snap = yield* Metric.snapshot\n const c = findById(snap, \"rec_attr\")\n expect(c.attributes).toMatchObject({ model: \"test-model\" })\n }),\n ),\n )\n\n it.effect(\"records a custom metric with a novel name, unchanged recorder\", () =>\n isolated(\n Effect.gen(function* () {\n // A user-defined event the recorder has never seen: still exported.\n const custom = makeEvent({\n _tag: \"ToolLatency\",\n turnIndex: 0,\n measurements: [{ name: \"myapp_tool_latency_total\", kind: \"counter\", value: 3 }],\n })\n yield* Stream.make(custom).pipe(record(), Stream.runDrain)\n const snap = yield* Metric.snapshot\n const c = findById(snap, \"myapp_tool_latency_total\")\n expect((c.state as { readonly count: number }).count).toBe(3)\n }),\n ),\n )\n\n it.effect(\"passes non-metric elements through untouched\", () =>\n isolated(\n Effect.gen(function* () {\n const out = yield* Stream.make(\"a\", \"b\", \"c\").pipe(record(), Stream.runCollect)\n expect(out).toEqual([\"a\", \"b\", \"c\"])\n }),\n ),\n )\n})\n\nconst bodyToString = (body: HttpBody.HttpBody): string =>\n body._tag === \"Uint8Array\" ? new TextDecoder().decode(body.body) : \"\"\n\ndescribe(\"layerOtlp\", () => {\n it.effect(\"exports recorded metrics over OTLP via a mock HttpClient\", () =>\n isolated(\n Effect.gen(function* () {\n const bodies = yield* Ref.make<ReadonlyArray<string>>([])\n const mockClient = HttpClient.make((request) =>\n Ref.update(bodies, (b) => [...b, bodyToString(request.body)]).pipe(\n Effect.as(HttpClientResponse.fromWeb(request, new Response(\"{}\", { status: 200 }))),\n ),\n )\n const clientLayer = Layer.succeed(HttpClient.HttpClient, mockClient)\n const ev = event([{ name: \"otlp_export_counter\", kind: \"counter\", value: 3 }])\n\n // Provide the OTLP layer scoped to the recording program. The exporter\n // flushes on scope close (interval is long, so we rely on the flush).\n yield* Stream.make(ev).pipe(\n record(),\n Stream.runDrain,\n Effect.provide(\n layerOtlp({\n url: \"http://localhost:4318/v1/metrics\",\n resource: { serviceName: \"test-service\" },\n exportInterval: \"10 minutes\",\n }).pipe(Layer.provide(clientLayer)),\n ),\n )\n\n const captured = yield* Ref.get(bodies)\n expect(captured.length).toBeGreaterThanOrEqual(1)\n expect(captured.join(\"\\n\")).toContain(\"otlp_export_counter\")\n }),\n ),\n )\n})\n"],"mappings":";;;;;;;;AAOA,MAAM,SAAS,iBACb,UAAU;CAAE,MAAM;CAAQ,WAAW;CAAG;AAAa,CAAC;AAGxD,MAAM,YAAqB,SACzB,OAAO,eAAe,MAAM,OAAO,gCAAgB,IAAI,IAAI,CAAC;AAE9D,MAAM,YAAY,MAA6C,OAC7D,OAAO,WAAWA,MAAI,UAAU,OAAO,MAAM,EAAE,OAAO,EAAE,CAAC;AAE3D,SAAS,gBAAgB;CACvB,GAAG,OAAO,yDACR,SACE,OAAO,IAAI,aAAa;EACtB,MAAM,KAAK,MAAM,CAAC;GAAE,MAAM;GAAe,MAAM;GAAW,OAAO;EAAE,CAAC,CAAC;EACrE,OAAO,OAAO,KAA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AQ,WAAW,CAAC,CACpC,CACF;EAEA,MAAM,WAAW,OAAO,IAAI,IAAI,MAAM;EACtC,aAAO,SAAS,MAAM,CAAC,CAAC,uBAAuB,CAAC;EAChD,aAAO,SAAS,KAAK,IAAI,CAAC,CAAC,CAAC,UAAU,qBAAqB;CAC7D,CAAC,CACH,CACF;AACF,CAAC"}
|
|
@@ -1,10 +1,8 @@
|
|
|
1
|
-
import { t as AiError } from "../AiError-
|
|
1
|
+
import { t as AiError } from "../AiError-eLV9t1lU.mjs";
|
|
2
2
|
import { JobConfig } from "../job/Job.mjs";
|
|
3
3
|
import { Turn, TurnEvent } from "../domain/Turn.mjs";
|
|
4
4
|
import { ResearchJobRef, ResearchRequest, ResearchState } from "../domain/Research.mjs";
|
|
5
5
|
import { Context, Effect, Stream } from "effect";
|
|
6
|
-
|
|
7
|
-
//#region src/research/DeepResearch.d.ts
|
|
8
6
|
declare namespace DeepResearch_d_exports {
|
|
9
7
|
export { DeepResearch, DeepResearchService, DeepResearchServiceShape, ResearchJobOps, ResearchJobRef, ResearchRequest, ResearchState, cancel, collect, fromJob, research, researchStream, status, streamFrom, submit };
|
|
10
8
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DeepResearch.d.mts","names":[],"sources":["../../src/research/DeepResearch.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"DeepResearch.d.mts","names":[],"sources":["../../src/research/DeepResearch.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;KAuBY,yBAAyB;WAC1B,SAAS,SAAS,QAAQ,OAAO,OAAO,gBAAgB;WACxD,SAAS,KAAK,mBAAmB,OAAO,OAAO,eAAe;WAC9D,UAAU,KAAK,mBAAmB,OAAO,OAAO,MAAM;WACtD,aAAa,KAAK,mBAAmB,OAAO,OAAO,WAAW;WAC9D,SAAS,KAAK,mBAAmB,OAAO,aAAa;WACrD,WAAW,SAAS,QAAQ,OAAO,OAAO,MAAM;WAChD,iBAAiB,SAAS,QAAQ,OAAO,OAAO,WAAW;;KAG1D,sBAAsB,yBAAyB;;cAE9C,qBAAqB;;;KAWtB,eAAe;WAChB,SAAS,SAAS,QAAQ,OAAO,OAAO,gBAAgB;WACxD,OAAO,KAAK,mBAAmB,OAAO,OAAO,eAAe;WAC5D,SAAS,KAAK,mBAAmB,OAAO,aAAa;WACrD,cAAc,KAAK,mBAAmB,OAAO,OAAO,WAAW;;;;;;;;;;;cA2B7D,UAAW,YAAY,iBAAe,KAC5C,eAAe,MAAI,SACf,cACR,yBAAyB;;cAqBf,WAAQ,SACV,oBACR,OAAO,OAAO,MAAM,SAAiB;;cAI3B,iBAAc,SAChB,oBACR,OAAO,OAAO,WAAW,SAAiB;;cAIhC,SAAM,SACR,oBACR,OAAO,OAAO,gBAAgB,SAAiB;;cAIrC,SAAM,KACZ,mBACJ,OAAO,OAAO,eAAe,SAAiB;;cAIpC,UAAO,KAAS,mBAAiB,OAAO,OAAO,MAAM,SAAiB;;cAItE,aAAU,KAChB,mBACJ,OAAO,OAAO,WAAW,SAAiB;;cAIhC,SAAM,KAAS,mBAAiB,OAAO,aAAa,SAAiB"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as __exportAll } from "../
|
|
1
|
+
import { n as __exportAll } from "../rolldown-runtime-EAsCxrDo.mjs";
|
|
2
2
|
import { TurnEvent } from "../domain/Turn.mjs";
|
|
3
3
|
import { collect as collect$1, run } from "../job/Job.mjs";
|
|
4
4
|
import { Context, Effect, Stream } from "effect";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DeepResearch.mjs","names":["Job.collect","Job.run"],"sources":["../../src/research/DeepResearch.ts"],"sourcesContent":["import { Context, Effect, Stream } from \"effect\"\nimport * as AiError from \"../domain/AiError.js\"\nimport * as Job from \"../job/Job.js\"\nimport type { ResearchJobRef, ResearchRequest, ResearchState } from \"../domain/Research.js\"\nimport type { Turn } from \"../domain/Turn.js\"\nimport { TurnEvent } from \"../domain/Turn.js\"\n\nexport type { ResearchJobRef, ResearchRequest, ResearchState } from \"../domain/Research.js\"\n\n/**\n * Deep research: submit a question, watch a long-running background job, collect\n * one cited report. Every provider is modeled as a job (`submit` / `poll` /\n * `cancel`), so the surface is uniform. The convenience derivations\n * (`research` / `researchStream` / `collect` / `status`) are the same for every\n * provider and are built once by {@link fromJob}, so an implementor states only\n * its wire calls, never the poll loop.\n *\n * `research` is the blocking one-liner (submit then poll to the terminal `Turn`);\n * `researchStream` forwards live progress as `TurnEvent`s, terminating in\n * `TurnComplete` whose `turn` is the value `research` / `collect` return. The job\n * ref is plain serializable data, so it can be persisted and collected from a\n * later process where the provider's job is server-backed.\n */\nexport type DeepResearchServiceShape<Req> = {\n readonly submit: (request: Req) => Effect.Effect<ResearchJobRef, AiError.AiError>\n readonly status: (ref: ResearchJobRef) => Effect.Effect<ResearchState, AiError.AiError>\n readonly collect: (ref: ResearchJobRef) => Effect.Effect<Turn, AiError.AiError>\n readonly streamFrom: (ref: ResearchJobRef) => Stream.Stream<TurnEvent, AiError.AiError>\n readonly cancel: (ref: ResearchJobRef) => Effect.Effect<void, AiError.AiError>\n readonly research: (request: Req) => Effect.Effect<Turn, AiError.AiError>\n readonly researchStream: (request: Req) => Stream.Stream<TurnEvent, AiError.AiError>\n}\n\nexport type DeepResearchService = DeepResearchServiceShape<ResearchRequest>\n\nexport class DeepResearch extends Context.Service<DeepResearch, DeepResearchService>()(\n \"@betalyra/effect-uai/DeepResearch\",\n) {}\n\n// ---------------------------------------------------------------------------\n// fromJob: build the whole service from the three job ops (+ an optional real\n// live stream). The derivations are identical for every provider.\n// ---------------------------------------------------------------------------\n\n/** The wire ops a provider supplies. `streamFrom` is optional: poll-only jobs\n * get a synthesized stream ({@link synthesizedStream}) in its place. */\nexport type ResearchJobOps<Req> = {\n readonly submit: (request: Req) => Effect.Effect<ResearchJobRef, AiError.AiError>\n readonly poll: (ref: ResearchJobRef) => Effect.Effect<ResearchState, AiError.AiError>\n readonly cancel: (ref: ResearchJobRef) => Effect.Effect<void, AiError.AiError>\n readonly streamFrom?: (ref: ResearchJobRef) => Stream.Stream<TurnEvent, AiError.AiError>\n}\n\n// A poll-only job has no event stream, so synthesize one: a leading \"searching\"\n// progress event, then the terminal `TurnComplete` off the poll loop. Honest\n// low-fidelity progress, not a fabricated per-search feed.\nconst synthesizedStream = <Req>(\n ops: ResearchJobOps<Req>,\n ref: ResearchJobRef,\n config?: Job.JobConfig,\n): Stream.Stream<TurnEvent, AiError.AiError> =>\n Stream.concat(\n Stream.make(TurnEvent.WebSearchCall({ status: \"searching\" })),\n Stream.map(Stream.fromEffect(Job.collect(ops.poll, ref, config)), (turn) =>\n TurnEvent.TurnComplete({ turn }),\n ),\n )\n\n/**\n * Assemble a {@link DeepResearchServiceShape} from the job ops. `research` is\n * `submit` then poll-to-settle (best-effort cancel on interrupt, via\n * {@link Job.run}); `collect` / `status` are the detached equivalents;\n * `researchStream` submits then attaches. Generic over the request type so a\n * provider-typed tag keeps its narrowed `submit`. `config` tunes the poll\n * cadence and overall timeout of every derived poll loop (see\n * {@link Job.JobConfig} for the defaults).\n */\nexport const fromJob = <Req extends ResearchRequest>(\n ops: ResearchJobOps<Req>,\n config?: Job.JobConfig,\n): DeepResearchServiceShape<Req> => {\n const streamFrom =\n ops.streamFrom ?? ((ref: ResearchJobRef) => synthesizedStream(ops, ref, config))\n return {\n submit: ops.submit,\n status: ops.poll,\n collect: (ref) => Job.collect(ops.poll, ref, config),\n cancel: ops.cancel,\n streamFrom,\n research: (request) =>\n Job.run({ submit: ops.submit(request), poll: ops.poll, cancel: ops.cancel }, config),\n researchStream: (request) => Stream.unwrap(Effect.map(ops.submit(request), streamFrom)),\n }\n}\n\n// ---------------------------------------------------------------------------\n// Top-level accessors over the generic tag. Portable code uses these; they\n// require only `DeepResearch` in `R`.\n// ---------------------------------------------------------------------------\n\n/** Submit and poll to the terminal `Turn`. Cancels the job on interrupt. */\nexport const research = (\n request: ResearchRequest,\n): Effect.Effect<Turn, AiError.AiError, DeepResearch> =>\n Effect.flatMap(DeepResearch, (s) => s.research(request))\n\n/** Submit and forward live progress, terminating in `TurnComplete`. */\nexport const researchStream = (\n request: ResearchRequest,\n): Stream.Stream<TurnEvent, AiError.AiError, DeepResearch> =>\n Stream.unwrap(Effect.map(DeepResearch, (s) => s.researchStream(request)))\n\n/** Submit a detached job and return its ref. */\nexport const submit = (\n request: ResearchRequest,\n): Effect.Effect<ResearchJobRef, AiError.AiError, DeepResearch> =>\n Effect.flatMap(DeepResearch, (s) => s.submit(request))\n\n/** Current state of a job. */\nexport const status = (\n ref: ResearchJobRef,\n): Effect.Effect<ResearchState, AiError.AiError, DeepResearch> =>\n Effect.flatMap(DeepResearch, (s) => s.status(ref))\n\n/** Poll a detached job to completion. */\nexport const collect = (ref: ResearchJobRef): Effect.Effect<Turn, AiError.AiError, DeepResearch> =>\n Effect.flatMap(DeepResearch, (s) => s.collect(ref))\n\n/** Attach a live progress stream to a job (call again to re-attach). */\nexport const streamFrom = (\n ref: ResearchJobRef,\n): Stream.Stream<TurnEvent, AiError.AiError, DeepResearch> =>\n Stream.unwrap(Effect.map(DeepResearch, (s) => s.streamFrom(ref)))\n\n/** Cancel a running job. */\nexport const cancel = (ref: ResearchJobRef): Effect.Effect<void, AiError.AiError, DeepResearch> =>\n Effect.flatMap(DeepResearch, (s) => s.cancel(ref))\n"],"mappings":";;;;;;;;;;;;;;;;AAmCA,IAAa,eAAb,cAAkC,QAAQ,
|
|
1
|
+
{"version":3,"file":"DeepResearch.mjs","names":["Job.collect","Job.run"],"sources":["../../src/research/DeepResearch.ts"],"sourcesContent":["import { Context, Effect, Stream } from \"effect\"\nimport * as AiError from \"../domain/AiError.js\"\nimport * as Job from \"../job/Job.js\"\nimport type { ResearchJobRef, ResearchRequest, ResearchState } from \"../domain/Research.js\"\nimport type { Turn } from \"../domain/Turn.js\"\nimport { TurnEvent } from \"../domain/Turn.js\"\n\nexport type { ResearchJobRef, ResearchRequest, ResearchState } from \"../domain/Research.js\"\n\n/**\n * Deep research: submit a question, watch a long-running background job, collect\n * one cited report. Every provider is modeled as a job (`submit` / `poll` /\n * `cancel`), so the surface is uniform. The convenience derivations\n * (`research` / `researchStream` / `collect` / `status`) are the same for every\n * provider and are built once by {@link fromJob}, so an implementor states only\n * its wire calls, never the poll loop.\n *\n * `research` is the blocking one-liner (submit then poll to the terminal `Turn`);\n * `researchStream` forwards live progress as `TurnEvent`s, terminating in\n * `TurnComplete` whose `turn` is the value `research` / `collect` return. The job\n * ref is plain serializable data, so it can be persisted and collected from a\n * later process where the provider's job is server-backed.\n */\nexport type DeepResearchServiceShape<Req> = {\n readonly submit: (request: Req) => Effect.Effect<ResearchJobRef, AiError.AiError>\n readonly status: (ref: ResearchJobRef) => Effect.Effect<ResearchState, AiError.AiError>\n readonly collect: (ref: ResearchJobRef) => Effect.Effect<Turn, AiError.AiError>\n readonly streamFrom: (ref: ResearchJobRef) => Stream.Stream<TurnEvent, AiError.AiError>\n readonly cancel: (ref: ResearchJobRef) => Effect.Effect<void, AiError.AiError>\n readonly research: (request: Req) => Effect.Effect<Turn, AiError.AiError>\n readonly researchStream: (request: Req) => Stream.Stream<TurnEvent, AiError.AiError>\n}\n\nexport type DeepResearchService = DeepResearchServiceShape<ResearchRequest>\n\nexport class DeepResearch extends Context.Service<DeepResearch, DeepResearchService>()(\n \"@betalyra/effect-uai/DeepResearch\",\n) {}\n\n// ---------------------------------------------------------------------------\n// fromJob: build the whole service from the three job ops (+ an optional real\n// live stream). The derivations are identical for every provider.\n// ---------------------------------------------------------------------------\n\n/** The wire ops a provider supplies. `streamFrom` is optional: poll-only jobs\n * get a synthesized stream ({@link synthesizedStream}) in its place. */\nexport type ResearchJobOps<Req> = {\n readonly submit: (request: Req) => Effect.Effect<ResearchJobRef, AiError.AiError>\n readonly poll: (ref: ResearchJobRef) => Effect.Effect<ResearchState, AiError.AiError>\n readonly cancel: (ref: ResearchJobRef) => Effect.Effect<void, AiError.AiError>\n readonly streamFrom?: (ref: ResearchJobRef) => Stream.Stream<TurnEvent, AiError.AiError>\n}\n\n// A poll-only job has no event stream, so synthesize one: a leading \"searching\"\n// progress event, then the terminal `TurnComplete` off the poll loop. Honest\n// low-fidelity progress, not a fabricated per-search feed.\nconst synthesizedStream = <Req>(\n ops: ResearchJobOps<Req>,\n ref: ResearchJobRef,\n config?: Job.JobConfig,\n): Stream.Stream<TurnEvent, AiError.AiError> =>\n Stream.concat(\n Stream.make(TurnEvent.WebSearchCall({ status: \"searching\" })),\n Stream.map(Stream.fromEffect(Job.collect(ops.poll, ref, config)), (turn) =>\n TurnEvent.TurnComplete({ turn }),\n ),\n )\n\n/**\n * Assemble a {@link DeepResearchServiceShape} from the job ops. `research` is\n * `submit` then poll-to-settle (best-effort cancel on interrupt, via\n * {@link Job.run}); `collect` / `status` are the detached equivalents;\n * `researchStream` submits then attaches. Generic over the request type so a\n * provider-typed tag keeps its narrowed `submit`. `config` tunes the poll\n * cadence and overall timeout of every derived poll loop (see\n * {@link Job.JobConfig} for the defaults).\n */\nexport const fromJob = <Req extends ResearchRequest>(\n ops: ResearchJobOps<Req>,\n config?: Job.JobConfig,\n): DeepResearchServiceShape<Req> => {\n const streamFrom =\n ops.streamFrom ?? ((ref: ResearchJobRef) => synthesizedStream(ops, ref, config))\n return {\n submit: ops.submit,\n status: ops.poll,\n collect: (ref) => Job.collect(ops.poll, ref, config),\n cancel: ops.cancel,\n streamFrom,\n research: (request) =>\n Job.run({ submit: ops.submit(request), poll: ops.poll, cancel: ops.cancel }, config),\n researchStream: (request) => Stream.unwrap(Effect.map(ops.submit(request), streamFrom)),\n }\n}\n\n// ---------------------------------------------------------------------------\n// Top-level accessors over the generic tag. Portable code uses these; they\n// require only `DeepResearch` in `R`.\n// ---------------------------------------------------------------------------\n\n/** Submit and poll to the terminal `Turn`. Cancels the job on interrupt. */\nexport const research = (\n request: ResearchRequest,\n): Effect.Effect<Turn, AiError.AiError, DeepResearch> =>\n Effect.flatMap(DeepResearch, (s) => s.research(request))\n\n/** Submit and forward live progress, terminating in `TurnComplete`. */\nexport const researchStream = (\n request: ResearchRequest,\n): Stream.Stream<TurnEvent, AiError.AiError, DeepResearch> =>\n Stream.unwrap(Effect.map(DeepResearch, (s) => s.researchStream(request)))\n\n/** Submit a detached job and return its ref. */\nexport const submit = (\n request: ResearchRequest,\n): Effect.Effect<ResearchJobRef, AiError.AiError, DeepResearch> =>\n Effect.flatMap(DeepResearch, (s) => s.submit(request))\n\n/** Current state of a job. */\nexport const status = (\n ref: ResearchJobRef,\n): Effect.Effect<ResearchState, AiError.AiError, DeepResearch> =>\n Effect.flatMap(DeepResearch, (s) => s.status(ref))\n\n/** Poll a detached job to completion. */\nexport const collect = (ref: ResearchJobRef): Effect.Effect<Turn, AiError.AiError, DeepResearch> =>\n Effect.flatMap(DeepResearch, (s) => s.collect(ref))\n\n/** Attach a live progress stream to a job (call again to re-attach). */\nexport const streamFrom = (\n ref: ResearchJobRef,\n): Stream.Stream<TurnEvent, AiError.AiError, DeepResearch> =>\n Stream.unwrap(Effect.map(DeepResearch, (s) => s.streamFrom(ref)))\n\n/** Cancel a running job. */\nexport const cancel = (ref: ResearchJobRef): Effect.Effect<void, AiError.AiError, DeepResearch> =>\n Effect.flatMap(DeepResearch, (s) => s.cancel(ref))\n"],"mappings":";;;;;;;;;;;;;;;;AAmCA,IAAa,eAAb,cAAkC,QAAQ,QAA2C,CAAC,CACpF,mCACF,CAAC,CAAC,CAAC;AAmBH,MAAM,qBACJ,KACA,KACA,WAEA,OAAO,OACL,OAAO,KAAK,UAAU,cAAc,EAAE,QAAQ,YAAY,CAAC,CAAC,GAC5D,OAAO,IAAI,OAAO,WAAWA,UAAY,IAAI,MAAM,KAAK,MAAM,CAAC,IAAI,SACjE,UAAU,aAAa,EAAE,KAAK,CAAC,CACjC,CACF;;;;;;;;;;AAWF,MAAa,WACX,KACA,WACkC;CAClC,MAAM,aACJ,IAAI,gBAAgB,QAAwB,kBAAkB,KAAK,KAAK,MAAM;CAChF,OAAO;EACL,QAAQ,IAAI;EACZ,QAAQ,IAAI;EACZ,UAAU,QAAQA,UAAY,IAAI,MAAM,KAAK,MAAM;EACnD,QAAQ,IAAI;EACZ;EACA,WAAW,YACTC,IAAQ;GAAE,QAAQ,IAAI,OAAO,OAAO;GAAG,MAAM,IAAI;GAAM,QAAQ,IAAI;EAAO,GAAG,MAAM;EACrF,iBAAiB,YAAY,OAAO,OAAO,OAAO,IAAI,IAAI,OAAO,OAAO,GAAG,UAAU,CAAC;CACxF;AACF;;AAQA,MAAa,YACX,YAEA,OAAO,QAAQ,eAAe,MAAM,EAAE,SAAS,OAAO,CAAC;;AAGzD,MAAa,kBACX,YAEA,OAAO,OAAO,OAAO,IAAI,eAAe,MAAM,EAAE,eAAe,OAAO,CAAC,CAAC;;AAG1E,MAAa,UACX,YAEA,OAAO,QAAQ,eAAe,MAAM,EAAE,OAAO,OAAO,CAAC;;AAGvD,MAAa,UACX,QAEA,OAAO,QAAQ,eAAe,MAAM,EAAE,OAAO,GAAG,CAAC;;AAGnD,MAAa,WAAW,QACtB,OAAO,QAAQ,eAAe,MAAM,EAAE,QAAQ,GAAG,CAAC;;AAGpD,MAAa,cACX,QAEA,OAAO,OAAO,OAAO,IAAI,eAAe,MAAM,EAAE,WAAW,GAAG,CAAC,CAAC;;AAGlE,MAAa,UAAU,QACrB,OAAO,QAAQ,eAAe,MAAM,EAAE,OAAO,GAAG,CAAC"}
|
package/dist/retry/Retry.d.mts
CHANGED
|
@@ -1,13 +1,9 @@
|
|
|
1
|
-
import { d as RateLimited, m as Unavailable, p as Timeout, t as AiError } from "../AiError-
|
|
1
|
+
import { d as RateLimited, m as Unavailable, p as Timeout, t as AiError, u as InvalidRequest } from "../AiError-eLV9t1lU.mjs";
|
|
2
2
|
import { Effect, Schedule, Stream } from "effect";
|
|
3
|
-
import * as _$effect_Cause0 from "effect/Cause";
|
|
4
|
-
import * as _$effect_Types0 from "effect/Types";
|
|
5
|
-
|
|
6
|
-
//#region src/retry/Retry.d.ts
|
|
7
3
|
declare namespace Retry_d_exports {
|
|
8
4
|
export { Retryable, effect, isRetryable, stream };
|
|
9
5
|
}
|
|
10
|
-
declare const Retryable_base: new <A extends Record<string, any> = {}>(args:
|
|
6
|
+
declare const Retryable_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
11
7
|
readonly _tag: "RetryableAi";
|
|
12
8
|
} & Readonly<A>;
|
|
13
9
|
/**
|
|
@@ -37,10 +33,10 @@ declare const Retryable_base: new <A extends Record<string, any> = {}>(args: _$e
|
|
|
37
33
|
* variants if needed (e.g. a custom schedule that observes `cause`).
|
|
38
34
|
*/
|
|
39
35
|
declare class Retryable extends Retryable_base<{
|
|
40
|
-
readonly cause: RateLimited | Unavailable | Timeout;
|
|
36
|
+
readonly cause: RateLimited | Unavailable | Timeout | InvalidRequest;
|
|
41
37
|
}> {}
|
|
42
38
|
/** Type-narrowing predicate for the retryable subset. */
|
|
43
|
-
declare const isRetryable: (e: AiError) => e is RateLimited | Unavailable | Timeout;
|
|
39
|
+
declare const isRetryable: (e: AiError) => e is RateLimited | Unavailable | Timeout | InvalidRequest;
|
|
44
40
|
/**
|
|
45
41
|
* Retry a `Stream<A, AiError, R>` on the retryable subset. Other
|
|
46
42
|
* failures bypass the schedule and propagate unchanged. The whole
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Retry.d.mts","names":[],"sources":["../../src/retry/Retry.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"Retry.d.mts","names":[],"sources":["../../src/retry/Retry.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA8Ba,kBAAkB;WACpB,OACL,cACA,cACA,UACA;;;cAsCO,cAAW,GACnB,YACF,KAAK,cAAsB,cAAsB,UAAkB;;;;;;;cAmBzD,SACV,KAAG,UAAY,SAAS,SAAS,KAAK,gBACtC,GAAG,GAAC,GAAK,OAAO,OAAO,GAAG,SAAiB,OAAK,OAAO,OAAO,GAAG,SAAiB;;;;;;;;;;;cAyBxE,SACV,KAAG,UAAY,SAAS,SAAS,KAAK,cACtC,GAAG,GAAC,KAAO,OAAO,OAAO,GAAG,SAAiB,OAAK,OAAO,OAAO,GAAG,SAAiB"}
|
package/dist/retry/Retry.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as __exportAll } from "../
|
|
1
|
+
import { n as __exportAll } from "../rolldown-runtime-EAsCxrDo.mjs";
|
|
2
2
|
import { Data, Effect, Stream } from "effect";
|
|
3
3
|
//#region src/retry/Retry.ts
|
|
4
4
|
var Retry_exports = /* @__PURE__ */ __exportAll({
|
|
@@ -34,8 +34,37 @@ var Retry_exports = /* @__PURE__ */ __exportAll({
|
|
|
34
34
|
* variants if needed (e.g. a custom schedule that observes `cause`).
|
|
35
35
|
*/
|
|
36
36
|
var Retryable = class extends Data.TaggedError("RetryableAi") {};
|
|
37
|
+
/**
|
|
38
|
+
* `InvalidRequest` payloads that are a transient fault on the provider's side
|
|
39
|
+
* rather than a defect in the request.
|
|
40
|
+
*
|
|
41
|
+
* The class exists because a provider can only answer within its own error
|
|
42
|
+
* vocabulary: a constrained-decoding grammar that times out while compiling is
|
|
43
|
+
* a cold-start timeout, but it arrives as `invalid_request_error` because that
|
|
44
|
+
* is where the vendor files schema problems. Replaying it succeeds — the same
|
|
45
|
+
* schema compiles on the next call.
|
|
46
|
+
*
|
|
47
|
+
* An allow-list rather than a general softening of `InvalidRequest`, and it
|
|
48
|
+
* must stay one. The whole point of that tag being fatal is that a genuinely
|
|
49
|
+
* malformed request retried on a schedule burns quota to arrive at the same
|
|
50
|
+
* rejection, slowly. An entry earns its place by having been observed to
|
|
51
|
+
* succeed on replay.
|
|
52
|
+
*/
|
|
53
|
+
const TRANSIENT_INVALID_REQUEST = [/grammar compilation timed out/i];
|
|
54
|
+
/** The payload as text, for matching. `raw` is whatever the provider handed
|
|
55
|
+
* back — usually its response body as a string, sometimes a parsed object,
|
|
56
|
+
* and occasionally something that will not serialise. */
|
|
57
|
+
const rawText = (raw) => {
|
|
58
|
+
if (typeof raw === "string") return raw;
|
|
59
|
+
try {
|
|
60
|
+
return JSON.stringify(raw) ?? "";
|
|
61
|
+
} catch {
|
|
62
|
+
return String(raw);
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
const isTransientInvalidRequest = (e) => e._tag === "InvalidRequest" && TRANSIENT_INVALID_REQUEST.some((pattern) => pattern.test(rawText(e.raw)));
|
|
37
66
|
/** Type-narrowing predicate for the retryable subset. */
|
|
38
|
-
const isRetryable = (e) => e._tag === "RateLimited" || e._tag === "Unavailable" || e._tag === "Timeout";
|
|
67
|
+
const isRetryable = (e) => e._tag === "RateLimited" || e._tag === "Unavailable" || e._tag === "Timeout" || isTransientInvalidRequest(e);
|
|
39
68
|
/**
|
|
40
69
|
* Retry a `Stream<A, AiError, R>` on the retryable subset. Other
|
|
41
70
|
* failures bypass the schedule and propagate unchanged. The whole
|
package/dist/retry/Retry.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Retry.mjs","names":[],"sources":["../../src/retry/Retry.ts"],"sourcesContent":["import { Data, Effect, type Schedule, Stream } from \"effect\"\nimport type * as AiError from \"../domain/AiError.js\"\n\n/**\n * Subset-aware retry helpers for `AiError`.\n *\n * Effect's own `Effect.retry` / `Stream.retry` apply the schedule to\n * every failure. For AI calls that's the wrong policy — replaying a\n * `ContentFiltered` or `InvalidRequest` won't change the outcome and\n * just wastes quota. These helpers gate the schedule on the\n * {@link Retryable} subset (rate limits, transport hiccups, timeouts);\n * everything else propagates unchanged.\n *\n * Two carriers:\n * - {@link stream} — for `Stream<A, AiError, R>` (e.g. `streamTurn`,\n * `streamSynthesis`, `streamTranscriptionFrom`). Caveat: the entire\n * stream re-runs on retry, so deltas before the failure replay on\n * the next attempt.\n * - {@link effect} — for `Effect<A, AiError, R>` (e.g. `turn`, `embed`,\n * `embedMany`, `synthesize`, `transcribe`). At-most-once.\n *\n * Composes with `Stream.retry` / `Effect.retry` directly (no naming\n * collision since these live under the `Retry` namespace).\n */\n\n/**\n * Wrapper around the retryable subset of `AiError`. Internal to the\n * lift/retry/unlift dance — exported so callers can build their own\n * variants if needed (e.g. a custom schedule that observes `cause`).\n */\nexport class Retryable extends Data.TaggedError(\"RetryableAi\")<{\n readonly cause
|
|
1
|
+
{"version":3,"file":"Retry.mjs","names":[],"sources":["../../src/retry/Retry.ts"],"sourcesContent":["import { Data, Effect, type Schedule, Stream } from \"effect\"\nimport type * as AiError from \"../domain/AiError.js\"\n\n/**\n * Subset-aware retry helpers for `AiError`.\n *\n * Effect's own `Effect.retry` / `Stream.retry` apply the schedule to\n * every failure. For AI calls that's the wrong policy — replaying a\n * `ContentFiltered` or `InvalidRequest` won't change the outcome and\n * just wastes quota. These helpers gate the schedule on the\n * {@link Retryable} subset (rate limits, transport hiccups, timeouts);\n * everything else propagates unchanged.\n *\n * Two carriers:\n * - {@link stream} — for `Stream<A, AiError, R>` (e.g. `streamTurn`,\n * `streamSynthesis`, `streamTranscriptionFrom`). Caveat: the entire\n * stream re-runs on retry, so deltas before the failure replay on\n * the next attempt.\n * - {@link effect} — for `Effect<A, AiError, R>` (e.g. `turn`, `embed`,\n * `embedMany`, `synthesize`, `transcribe`). At-most-once.\n *\n * Composes with `Stream.retry` / `Effect.retry` directly (no naming\n * collision since these live under the `Retry` namespace).\n */\n\n/**\n * Wrapper around the retryable subset of `AiError`. Internal to the\n * lift/retry/unlift dance — exported so callers can build their own\n * variants if needed (e.g. a custom schedule that observes `cause`).\n */\nexport class Retryable extends Data.TaggedError(\"RetryableAi\")<{\n readonly cause:\n | AiError.RateLimited\n | AiError.Unavailable\n | AiError.Timeout\n | AiError.InvalidRequest\n}> {}\n\n/**\n * `InvalidRequest` payloads that are a transient fault on the provider's side\n * rather than a defect in the request.\n *\n * The class exists because a provider can only answer within its own error\n * vocabulary: a constrained-decoding grammar that times out while compiling is\n * a cold-start timeout, but it arrives as `invalid_request_error` because that\n * is where the vendor files schema problems. Replaying it succeeds — the same\n * schema compiles on the next call.\n *\n * An allow-list rather than a general softening of `InvalidRequest`, and it\n * must stay one. The whole point of that tag being fatal is that a genuinely\n * malformed request retried on a schedule burns quota to arrive at the same\n * rejection, slowly. An entry earns its place by having been observed to\n * succeed on replay.\n */\nconst TRANSIENT_INVALID_REQUEST: ReadonlyArray<RegExp> = [/grammar compilation timed out/i]\n\n/** The payload as text, for matching. `raw` is whatever the provider handed\n * back — usually its response body as a string, sometimes a parsed object,\n * and occasionally something that will not serialise. */\nconst rawText = (raw: unknown): string => {\n if (typeof raw === \"string\") return raw\n try {\n return JSON.stringify(raw) ?? \"\"\n } catch {\n return String(raw)\n }\n}\n\nconst isTransientInvalidRequest = (e: AiError.AiError): boolean =>\n e._tag === \"InvalidRequest\" &&\n TRANSIENT_INVALID_REQUEST.some((pattern) => pattern.test(rawText(e.raw)))\n\n/** Type-narrowing predicate for the retryable subset. */\nexport const isRetryable = (\n e: AiError.AiError,\n): e is AiError.RateLimited | AiError.Unavailable | AiError.Timeout | AiError.InvalidRequest =>\n e._tag === \"RateLimited\" ||\n e._tag === \"Unavailable\" ||\n e._tag === \"Timeout\" ||\n isTransientInvalidRequest(e)\n\n// Lift events to Items, non-retryable failures to Terminal values\n// (escape retry), retryable failures to wrapped errors (only thing\n// retry sees).\ntype Lifted<A> =\n | { readonly _tag: \"Item\"; readonly value: A }\n | { readonly _tag: \"Terminal\"; readonly cause: AiError.AiError }\n\n/**\n * Retry a `Stream<A, AiError, R>` on the retryable subset. Other\n * failures bypass the schedule and propagate unchanged. The whole\n * stream replays on each attempt — deltas emitted before the failure\n * are re-emitted on the next try.\n */\nexport const stream =\n <Out>(schedule: Schedule.Schedule<Out, Retryable>) =>\n <A, R>(s: Stream.Stream<A, AiError.AiError, R>): Stream.Stream<A, AiError.AiError, R> =>\n s.pipe(\n Stream.map((value): Lifted<A> => ({ _tag: \"Item\", value })),\n Stream.catchIf(\n isRetryable,\n (cause) => Stream.fail(new Retryable({ cause })),\n (cause) => Stream.succeed<Lifted<A>>({ _tag: \"Terminal\", cause }),\n ),\n Stream.retry(schedule),\n Stream.catchTag(\"RetryableAi\", (e) => Stream.fail<AiError.AiError>(e.cause)),\n Stream.flatMap((item) =>\n item._tag === \"Item\" ? Stream.succeed(item.value) : Stream.fail(item.cause),\n ),\n )\n\n/**\n * Retry an `Effect<A, AiError, R>` on the retryable subset. Other\n * failures bypass the schedule and propagate unchanged. At-most-once\n * — the underlying call only re-runs if the previous attempt failed\n * with a retryable tag.\n *\n * Skips the lift/unlift dance the Stream variant needs: `Effect.retry`\n * exposes a `while:` predicate so the error channel stays a plain\n * `AiError` throughout.\n */\nexport const effect =\n <Out>(schedule: Schedule.Schedule<Out, AiError.AiError>) =>\n <A, R>(eff: Effect.Effect<A, AiError.AiError, R>): Effect.Effect<A, AiError.AiError, R> =>\n Effect.retry(eff, { schedule, while: isRetryable })\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,IAAa,YAAb,cAA+B,KAAK,YAAY,aAAa,CAAC,CAM3D,CAAC;;;;;;;;;;;;;;;;;AAkBJ,MAAM,4BAAmD,CAAC,gCAAgC;;;;AAK1F,MAAM,WAAW,QAAyB;CACxC,IAAI,OAAO,QAAQ,UAAU,OAAO;CACpC,IAAI;EACF,OAAO,KAAK,UAAU,GAAG,KAAK;CAChC,QAAQ;EACN,OAAO,OAAO,GAAG;CACnB;AACF;AAEA,MAAM,6BAA6B,MACjC,EAAE,SAAS,oBACX,0BAA0B,MAAM,YAAY,QAAQ,KAAK,QAAQ,EAAE,GAAG,CAAC,CAAC;;AAG1E,MAAa,eACX,MAEA,EAAE,SAAS,iBACX,EAAE,SAAS,iBACX,EAAE,SAAS,aACX,0BAA0B,CAAC;;;;;;;AAe7B,MAAa,UACL,cACC,MACL,EAAE,KACA,OAAO,KAAK,WAAsB;CAAE,MAAM;CAAQ;AAAM,EAAE,GAC1D,OAAO,QACL,cACC,UAAU,OAAO,KAAK,IAAI,UAAU,EAAE,MAAM,CAAC,CAAC,IAC9C,UAAU,OAAO,QAAmB;CAAE,MAAM;CAAY;AAAM,CAAC,CAClE,GACA,OAAO,MAAM,QAAQ,GACrB,OAAO,SAAS,gBAAgB,MAAM,OAAO,KAAsB,EAAE,KAAK,CAAC,GAC3E,OAAO,SAAS,SACd,KAAK,SAAS,SAAS,OAAO,QAAQ,KAAK,KAAK,IAAI,OAAO,KAAK,KAAK,KAAK,CAC5E,CACF;;;;;;;;;;;AAYJ,MAAa,UACL,cACC,QACL,OAAO,MAAM,KAAK;CAAE;CAAU,OAAO;AAAY,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export {}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { ContentFiltered, RateLimited, Timeout, Unavailable } from "../domain/AiError.mjs";
|
|
2
2
|
import { effect, stream } from "./Retry.mjs";
|
|
3
|
-
import {
|
|
3
|
+
import { m as it, o as describe } from "../utils-CiH_DjFW.mjs";
|
|
4
|
+
import { n as globalExpect } from "../test.DNmyFkvJ-YPzDR0Co.mjs";
|
|
4
5
|
import { Cause, Effect, Exit, Option, Ref, Schedule, Stream } from "effect";
|
|
5
6
|
//#region src/retry/Retry.test.ts
|
|
6
7
|
const planned = (attempts, plan) => Stream.unwrap(Ref.getAndUpdate(attempts, (n) => n + 1).pipe(Effect.map((n) => plan[Math.min(n, plan.length - 1)])));
|
|
@@ -55,14 +56,16 @@ describe("Retry.stream", () => {
|
|
|
55
56
|
});
|
|
56
57
|
it("preserves items emitted before a retryable failure (and replays on retry)", async () => {
|
|
57
58
|
const program = Effect.gen(function* () {
|
|
58
|
-
const
|
|
59
|
+
const attempts = yield* Ref.make(0);
|
|
60
|
+
const s = planned(attempts, [Stream.concat(Stream.succeed("partial"), Stream.fail(new Timeout({
|
|
59
61
|
provider: "mock",
|
|
60
62
|
raw: null
|
|
61
63
|
}))), Stream.fromIterable(["partial", "done"])]).pipe(stream(Schedule.recurs(1)));
|
|
62
64
|
const out = yield* Stream.runCollect(s);
|
|
63
65
|
return Array.from(out);
|
|
64
66
|
});
|
|
65
|
-
|
|
67
|
+
const out = await Effect.runPromise(program);
|
|
68
|
+
globalExpect(out).toEqual([
|
|
66
69
|
"partial",
|
|
67
70
|
"partial",
|
|
68
71
|
"done"
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Retry.test.mjs","names":["AiError.RateLimited","Retry.stream","AiError.Unavailable","AiError.ContentFiltered","AiError.Timeout","Retry.effect"],"sources":["../../src/retry/Retry.test.ts"],"sourcesContent":["import { Cause, Effect, Exit, Option, Ref, Schedule, Stream } from \"effect\"\nimport { describe, expect, it } from \"vitest\"\nimport * as AiError from \"../domain/AiError.js\"\nimport * as Retry from \"./Retry.js\"\n\n// Each call pulls the next plan entry; the last entry repeats forever\n// (so \"succeed on attempt N\" plans naturally re-yield success after).\nconst planned = <A, E>(\n attempts: Ref.Ref<number>,\n plan: ReadonlyArray<Stream.Stream<A, E>>,\n): Stream.Stream<A, E> =>\n Stream.unwrap(\n Ref.getAndUpdate(attempts, (n) => n + 1).pipe(\n Effect.map((n) => plan[Math.min(n, plan.length - 1)]!),\n ),\n )\n\nconst plannedEffect = <A, E>(\n attempts: Ref.Ref<number>,\n plan: ReadonlyArray<Effect.Effect<A, E>>,\n): Effect.Effect<A, E> =>\n Ref.getAndUpdate(attempts, (n) => n + 1).pipe(\n Effect.flatMap((n) => plan[Math.min(n, plan.length - 1)]!),\n )\n\ndescribe(\"Retry.stream\", () => {\n it(\"retries on RateLimited and yields success on the next attempt\", async () => {\n const program = Effect.gen(function* () {\n const attempts = yield* Ref.make(0)\n const s = planned(attempts, [\n Stream.fail<AiError.AiError>(new AiError.RateLimited({ provider: \"mock\", raw: null })),\n Stream.fromIterable([\"a\", \"b\"]),\n ]).pipe(Retry.stream(Schedule.recurs(3)))\n const out = yield* Stream.runCollect(s)\n const count = yield* Ref.get(attempts)\n return { out: Array.from(out), count }\n })\n\n const { out, count } = await Effect.runPromise(program)\n expect(count).toBe(2)\n expect(out).toEqual([\"a\", \"b\"])\n })\n\n it(\"surfaces the underlying retryable failure when retries are exhausted\", async () => {\n const cause = new AiError.Unavailable({ provider: \"mock\", raw: null })\n const s = Stream.fail<AiError.AiError>(cause).pipe(Retry.stream(Schedule.recurs(2)))\n\n const exit = await Effect.runPromise(Effect.exit(Stream.runCollect(s)))\n expect(Exit.isFailure(exit)).toBe(true)\n if (Exit.isFailure(exit)) {\n expect(Cause.findErrorOption(exit.cause)).toEqual(Option.some(cause))\n }\n })\n\n it(\"bypasses retry for non-retryable AiError (ContentFiltered)\", async () => {\n const program = Effect.gen(function* () {\n const attempts = yield* Ref.make(0)\n const cause = new AiError.ContentFiltered({ provider: \"mock\", raw: null })\n const s = planned(attempts, [Stream.fail<AiError.AiError>(cause)]).pipe(\n Retry.stream(Schedule.recurs(5)),\n )\n const exit = yield* Effect.exit(Stream.runCollect(s))\n const count = yield* Ref.get(attempts)\n return { exit, count, cause }\n })\n\n const { exit, count, cause } = await Effect.runPromise(program)\n expect(count).toBe(1)\n expect(Exit.isFailure(exit)).toBe(true)\n if (Exit.isFailure(exit)) {\n expect(Cause.findErrorOption(exit.cause)).toEqual(Option.some(cause))\n }\n })\n\n it(\"preserves items emitted before a retryable failure (and replays on retry)\", async () => {\n // Documents the 'replays on retry' caveat: the entire stream re-runs.\n const program = Effect.gen(function* () {\n const attempts = yield* Ref.make(0)\n const s = planned(attempts, [\n Stream.concat(\n Stream.succeed(\"partial\"),\n Stream.fail<AiError.AiError>(new AiError.Timeout({ provider: \"mock\", raw: null })),\n ),\n Stream.fromIterable([\"partial\", \"done\"]),\n ]).pipe(Retry.stream(Schedule.recurs(1)))\n const out = yield* Stream.runCollect(s)\n return Array.from(out)\n })\n\n const out = await Effect.runPromise(program)\n expect(out).toEqual([\"partial\", \"partial\", \"done\"])\n })\n})\n\ndescribe(\"Retry.effect\", () => {\n it(\"retries on RateLimited and yields success on the next attempt\", async () => {\n const program = Effect.gen(function* () {\n const attempts = yield* Ref.make(0)\n const value = yield* plannedEffect(attempts, [\n Effect.fail<AiError.AiError>(new AiError.RateLimited({ provider: \"mock\", raw: null })),\n Effect.succeed(\"ok\"),\n ]).pipe(Retry.effect(Schedule.recurs(3)))\n const count = yield* Ref.get(attempts)\n return { value, count }\n })\n\n const { value, count } = await Effect.runPromise(program)\n expect(count).toBe(2)\n expect(value).toBe(\"ok\")\n })\n\n it(\"surfaces the underlying retryable failure when retries are exhausted\", async () => {\n const cause = new AiError.Unavailable({ provider: \"mock\", raw: null })\n const eff = Effect.fail<AiError.AiError>(cause).pipe(Retry.effect(Schedule.recurs(2)))\n\n const exit = await Effect.runPromise(Effect.exit(eff))\n expect(Exit.isFailure(exit)).toBe(true)\n if (Exit.isFailure(exit)) {\n expect(Cause.findErrorOption(exit.cause)).toEqual(Option.some(cause))\n }\n })\n\n it(\"bypasses retry for non-retryable AiError (ContentFiltered)\", async () => {\n const program = Effect.gen(function* () {\n const attempts = yield* Ref.make(0)\n const cause = new AiError.ContentFiltered({ provider: \"mock\", raw: null })\n const exit = yield* Effect.exit(\n plannedEffect(attempts, [Effect.fail<AiError.AiError>(cause)]).pipe(\n Retry.effect(Schedule.recurs(5)),\n ),\n )\n const count = yield* Ref.get(attempts)\n return { exit, count, cause }\n })\n\n const { exit, count, cause } = await Effect.runPromise(program)\n expect(count).toBe(1)\n expect(Exit.isFailure(exit)).toBe(true)\n if (Exit.isFailure(exit)) {\n expect(Cause.findErrorOption(exit.cause)).toEqual(Option.some(cause))\n }\n })\n\n it(\"does NOT replay successful prior work — at-most-once semantics\", async () => {\n // Contrast with Retry.stream: an Effect.retry only re-invokes the\n // failing computation. No replay of work done before the failure\n // (there's nothing to replay — Effects are single-shot).\n const program = Effect.gen(function* () {\n const attempts = yield* Ref.make(0)\n const value = yield* plannedEffect(attempts, [\n Effect.fail<AiError.AiError>(new AiError.Timeout({ provider: \"mock\", raw: null })),\n Effect.fail<AiError.AiError>(new AiError.Timeout({ provider: \"mock\", raw: null })),\n Effect.succeed(\"done\"),\n ]).pipe(Retry.effect(Schedule.recurs(5)))\n const count = yield* Ref.get(attempts)\n return { value, count }\n })\n\n const { value, count } = await Effect.runPromise(program)\n expect(count).toBe(3)\n expect(value).toBe(\"done\")\n })\n})\n"],"mappings":";;;;;AAOA,MAAM,WACJ,UACA,SAEA,OAAO,OACL,IAAI,aAAa,WAAW,MAAM,IAAI,EAAE,CAAC,KACvC,OAAO,KAAK,MAAM,KAAK,KAAK,IAAI,GAAG,KAAK,SAAS,EAAE,EAAG,CACvD,CACF;AAEH,MAAM,iBACJ,UACA,SAEA,IAAI,aAAa,WAAW,MAAM,IAAI,EAAE,CAAC,KACvC,OAAO,SAAS,MAAM,KAAK,KAAK,IAAI,GAAG,KAAK,SAAS,EAAE,EAAG,CAC3D;AAEH,SAAS,sBAAsB;AAC7B,IAAG,iEAAiE,YAAY;EAC9E,MAAM,UAAU,OAAO,IAAI,aAAa;GACtC,MAAM,WAAW,OAAO,IAAI,KAAK,EAAE;GACnC,MAAM,IAAI,QAAQ,UAAU,CAC1B,OAAO,KAAsB,IAAIA,YAAoB;IAAE,UAAU;IAAQ,KAAK;IAAM,CAAC,CAAC,EACtF,OAAO,aAAa,CAAC,KAAK,IAAI,CAAC,CAChC,CAAC,CAAC,KAAKC,OAAa,SAAS,OAAO,EAAE,CAAC,CAAC;GACzC,MAAM,MAAM,OAAO,OAAO,WAAW,EAAE;GACvC,MAAM,QAAQ,OAAO,IAAI,IAAI,SAAS;AACtC,UAAO;IAAE,KAAK,MAAM,KAAK,IAAI;IAAE;IAAO;IACtC;EAEF,MAAM,EAAE,KAAK,UAAU,MAAM,OAAO,WAAW,QAAQ;AACvD,eAAO,MAAM,CAAC,KAAK,EAAE;AACrB,eAAO,IAAI,CAAC,QAAQ,CAAC,KAAK,IAAI,CAAC;GAC/B;AAEF,IAAG,wEAAwE,YA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zD,eAAO,MAAM,CAAC,KAAK,EAAE;AACrB,eAAO,MAAM,CAAC,KAAK,OAAO;GAC1B;EACF"}
|
|
1
|
+
{"version":3,"file":"Retry.test.mjs","names":["AiError.RateLimited","Retry.stream","AiError.Unavailable","AiError.ContentFiltered","AiError.Timeout","Retry.effect"],"sources":["../../src/retry/Retry.test.ts"],"sourcesContent":["import { Cause, Effect, Exit, Option, Ref, Schedule, Stream } from \"effect\"\nimport { describe, expect, it } from \"vitest\"\nimport * as AiError from \"../domain/AiError.js\"\nimport * as Retry from \"./Retry.js\"\n\n// Each call pulls the next plan entry; the last entry repeats forever\n// (so \"succeed on attempt N\" plans naturally re-yield success after).\nconst planned = <A, E>(\n attempts: Ref.Ref<number>,\n plan: ReadonlyArray<Stream.Stream<A, E>>,\n): Stream.Stream<A, E> =>\n Stream.unwrap(\n Ref.getAndUpdate(attempts, (n) => n + 1).pipe(\n Effect.map((n) => plan[Math.min(n, plan.length - 1)]!),\n ),\n )\n\nconst plannedEffect = <A, E>(\n attempts: Ref.Ref<number>,\n plan: ReadonlyArray<Effect.Effect<A, E>>,\n): Effect.Effect<A, E> =>\n Ref.getAndUpdate(attempts, (n) => n + 1).pipe(\n Effect.flatMap((n) => plan[Math.min(n, plan.length - 1)]!),\n )\n\ndescribe(\"Retry.stream\", () => {\n it(\"retries on RateLimited and yields success on the next attempt\", async () => {\n const program = Effect.gen(function* () {\n const attempts = yield* Ref.make(0)\n const s = planned(attempts, [\n Stream.fail<AiError.AiError>(new AiError.RateLimited({ provider: \"mock\", raw: null })),\n Stream.fromIterable([\"a\", \"b\"]),\n ]).pipe(Retry.stream(Schedule.recurs(3)))\n const out = yield* Stream.runCollect(s)\n const count = yield* Ref.get(attempts)\n return { out: Array.from(out), count }\n })\n\n const { out, count } = await Effect.runPromise(program)\n expect(count).toBe(2)\n expect(out).toEqual([\"a\", \"b\"])\n })\n\n it(\"surfaces the underlying retryable failure when retries are exhausted\", async () => {\n const cause = new AiError.Unavailable({ provider: \"mock\", raw: null })\n const s = Stream.fail<AiError.AiError>(cause).pipe(Retry.stream(Schedule.recurs(2)))\n\n const exit = await Effect.runPromise(Effect.exit(Stream.runCollect(s)))\n expect(Exit.isFailure(exit)).toBe(true)\n if (Exit.isFailure(exit)) {\n expect(Cause.findErrorOption(exit.cause)).toEqual(Option.some(cause))\n }\n })\n\n it(\"bypasses retry for non-retryable AiError (ContentFiltered)\", async () => {\n const program = Effect.gen(function* () {\n const attempts = yield* Ref.make(0)\n const cause = new AiError.ContentFiltered({ provider: \"mock\", raw: null })\n const s = planned(attempts, [Stream.fail<AiError.AiError>(cause)]).pipe(\n Retry.stream(Schedule.recurs(5)),\n )\n const exit = yield* Effect.exit(Stream.runCollect(s))\n const count = yield* Ref.get(attempts)\n return { exit, count, cause }\n })\n\n const { exit, count, cause } = await Effect.runPromise(program)\n expect(count).toBe(1)\n expect(Exit.isFailure(exit)).toBe(true)\n if (Exit.isFailure(exit)) {\n expect(Cause.findErrorOption(exit.cause)).toEqual(Option.some(cause))\n }\n })\n\n it(\"preserves items emitted before a retryable failure (and replays on retry)\", async () => {\n // Documents the 'replays on retry' caveat: the entire stream re-runs.\n const program = Effect.gen(function* () {\n const attempts = yield* Ref.make(0)\n const s = planned(attempts, [\n Stream.concat(\n Stream.succeed(\"partial\"),\n Stream.fail<AiError.AiError>(new AiError.Timeout({ provider: \"mock\", raw: null })),\n ),\n Stream.fromIterable([\"partial\", \"done\"]),\n ]).pipe(Retry.stream(Schedule.recurs(1)))\n const out = yield* Stream.runCollect(s)\n return Array.from(out)\n })\n\n const out = await Effect.runPromise(program)\n expect(out).toEqual([\"partial\", \"partial\", \"done\"])\n })\n})\n\ndescribe(\"Retry.effect\", () => {\n it(\"retries on RateLimited and yields success on the next attempt\", async () => {\n const program = Effect.gen(function* () {\n const attempts = yield* Ref.make(0)\n const value = yield* plannedEffect(attempts, [\n Effect.fail<AiError.AiError>(new AiError.RateLimited({ provider: \"mock\", raw: null })),\n Effect.succeed(\"ok\"),\n ]).pipe(Retry.effect(Schedule.recurs(3)))\n const count = yield* Ref.get(attempts)\n return { value, count }\n })\n\n const { value, count } = await Effect.runPromise(program)\n expect(count).toBe(2)\n expect(value).toBe(\"ok\")\n })\n\n it(\"surfaces the underlying retryable failure when retries are exhausted\", async () => {\n const cause = new AiError.Unavailable({ provider: \"mock\", raw: null })\n const eff = Effect.fail<AiError.AiError>(cause).pipe(Retry.effect(Schedule.recurs(2)))\n\n const exit = await Effect.runPromise(Effect.exit(eff))\n expect(Exit.isFailure(exit)).toBe(true)\n if (Exit.isFailure(exit)) {\n expect(Cause.findErrorOption(exit.cause)).toEqual(Option.some(cause))\n }\n })\n\n it(\"bypasses retry for non-retryable AiError (ContentFiltered)\", async () => {\n const program = Effect.gen(function* () {\n const attempts = yield* Ref.make(0)\n const cause = new AiError.ContentFiltered({ provider: \"mock\", raw: null })\n const exit = yield* Effect.exit(\n plannedEffect(attempts, [Effect.fail<AiError.AiError>(cause)]).pipe(\n Retry.effect(Schedule.recurs(5)),\n ),\n )\n const count = yield* Ref.get(attempts)\n return { exit, count, cause }\n })\n\n const { exit, count, cause } = await Effect.runPromise(program)\n expect(count).toBe(1)\n expect(Exit.isFailure(exit)).toBe(true)\n if (Exit.isFailure(exit)) {\n expect(Cause.findErrorOption(exit.cause)).toEqual(Option.some(cause))\n }\n })\n\n it(\"does NOT replay successful prior work — at-most-once semantics\", async () => {\n // Contrast with Retry.stream: an Effect.retry only re-invokes the\n // failing computation. No replay of work done before the failure\n // (there's nothing to replay — Effects are single-shot).\n const program = Effect.gen(function* () {\n const attempts = yield* Ref.make(0)\n const value = yield* plannedEffect(attempts, [\n Effect.fail<AiError.AiError>(new AiError.Timeout({ provider: \"mock\", raw: null })),\n Effect.fail<AiError.AiError>(new AiError.Timeout({ provider: \"mock\", raw: null })),\n Effect.succeed(\"done\"),\n ]).pipe(Retry.effect(Schedule.recurs(5)))\n const count = yield* Ref.get(attempts)\n return { value, count }\n })\n\n const { value, count } = await Effect.runPromise(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ED,MAAM,EAAE,OAAO,UAAU,MAAM,OAAO,WAAW,OAAO;EACxD,aAAO,KAAK,CAAC,CAAC,KAAK,CAAC;EACpB,aAAO,KAAK,CAAC,CAAC,KAAK,MAAM;CAC3B,CAAC;AACH,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Memory.d.mts","names":[],"sources":["../../src/sandbox/Memory.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"Memory.d.mts","names":[],"sources":["../../src/sandbox/Memory.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;KAwBY,SAAS,MAAM;KAuBf,iBAAiB;;;;;cAqChB,kBAAe,OAAW,UAAQ;;cAelC,UAAO,GAAO,SAAS;;cAUvB,QAAK,cAAgB;;cAGrB,MAAG,cAAgB;;cAGnB,MAAG,cAAgB;;cAGnB,MAAG,cAAgB;;cAGnB,KAAE,cAAgB;;cAGlB,KAAE,cAAgB;;cAGlB,KAAE,cAAgB"}
|
package/dist/sandbox/Memory.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as __exportAll } from "../
|
|
1
|
+
import { n as __exportAll } from "../rolldown-runtime-EAsCxrDo.mjs";
|
|
2
2
|
import { Brand } from "effect";
|
|
3
3
|
//#region src/sandbox/Memory.ts
|
|
4
4
|
var Memory_exports = /* @__PURE__ */ __exportAll({
|
|
@@ -20,9 +20,9 @@ const UNIT_BYTES = {
|
|
|
20
20
|
gb: 1e9,
|
|
21
21
|
tb: 0xe8d4a51000,
|
|
22
22
|
kib: 1024,
|
|
23
|
-
mib:
|
|
24
|
-
gib:
|
|
25
|
-
tib:
|
|
23
|
+
mib: 1048576,
|
|
24
|
+
gib: 1073741824,
|
|
25
|
+
tib: 1099511627776
|
|
26
26
|
};
|
|
27
27
|
const PARSE_RE = /^\s*(\d+(?:\.\d+)?)\s*([a-zA-Z]*)\s*$/;
|
|
28
28
|
const parseString = (s) => {
|