@effect-uai/core 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +1 -1
  2. package/dist/{Audio-BfCTGnH3.d.mts → Audio-DPlTsNdz.d.mts} +3 -2
  3. package/dist/Audio-DPlTsNdz.d.mts.map +1 -0
  4. package/dist/{Items-pXR5BAgW.d.mts → Items-D8UaXQx_.d.mts} +4 -4
  5. package/dist/{Items-pXR5BAgW.d.mts.map → Items-D8UaXQx_.d.mts.map} +1 -1
  6. package/dist/{Tool-DP-AwKOf.d.mts → Tool-CiFXYjmR.d.mts} +2 -2
  7. package/dist/{Tool-DP-AwKOf.d.mts.map → Tool-CiFXYjmR.d.mts.map} +1 -1
  8. package/dist/capabilities/Capabilities.d.mts +78 -0
  9. package/dist/capabilities/Capabilities.d.mts.map +1 -0
  10. package/dist/capabilities/Capabilities.mjs +65 -0
  11. package/dist/capabilities/Capabilities.mjs.map +1 -0
  12. package/dist/domain/Audio.d.mts +1 -1
  13. package/dist/domain/Audio.mjs.map +1 -1
  14. package/dist/domain/Items.d.mts +1 -1
  15. package/dist/domain/Music.d.mts +131 -72
  16. package/dist/domain/Music.d.mts.map +1 -1
  17. package/dist/domain/Music.mjs +36 -9
  18. package/dist/domain/Music.mjs.map +1 -1
  19. package/dist/domain/Transcript.d.mts +8 -2
  20. package/dist/domain/Transcript.d.mts.map +1 -1
  21. package/dist/domain/Transcript.mjs.map +1 -1
  22. package/dist/domain/Turn.d.mts +1 -1
  23. package/dist/embedding-model/Embedding.d.mts +12 -2
  24. package/dist/embedding-model/Embedding.d.mts.map +1 -1
  25. package/dist/embedding-model/Embedding.mjs.map +1 -1
  26. package/dist/embedding-model/EmbeddingModel.d.mts +36 -23
  27. package/dist/embedding-model/EmbeddingModel.d.mts.map +1 -1
  28. package/dist/embedding-model/EmbeddingModel.mjs +20 -1
  29. package/dist/embedding-model/EmbeddingModel.mjs.map +1 -1
  30. package/dist/embedding-model/EmbeddingModel.test.mjs +15 -3
  31. package/dist/embedding-model/EmbeddingModel.test.mjs.map +1 -1
  32. package/dist/index.d.mts +5 -4
  33. package/dist/index.mjs +2 -1
  34. package/dist/language-model/LanguageModel.d.mts +2 -2
  35. package/dist/music-generator/MusicGenerator.d.mts +48 -25
  36. package/dist/music-generator/MusicGenerator.d.mts.map +1 -1
  37. package/dist/music-generator/MusicGenerator.mjs +17 -9
  38. package/dist/music-generator/MusicGenerator.mjs.map +1 -1
  39. package/dist/music-generator/MusicGenerator.test.mjs +81 -56
  40. package/dist/music-generator/MusicGenerator.test.mjs.map +1 -1
  41. package/dist/speech-synthesizer/SpeechSynthesizer.d.mts +21 -36
  42. package/dist/speech-synthesizer/SpeechSynthesizer.d.mts.map +1 -1
  43. package/dist/speech-synthesizer/SpeechSynthesizer.mjs.map +1 -1
  44. package/dist/speech-synthesizer/SpeechSynthesizer.test.mjs +3 -3
  45. package/dist/speech-synthesizer/SpeechSynthesizer.test.mjs.map +1 -1
  46. package/dist/testing/MockMusicGenerator.d.mts +12 -7
  47. package/dist/testing/MockMusicGenerator.d.mts.map +1 -1
  48. package/dist/testing/MockMusicGenerator.mjs +4 -3
  49. package/dist/testing/MockMusicGenerator.mjs.map +1 -1
  50. package/dist/testing/MockProvider.d.mts +1 -1
  51. package/dist/testing/MockSpeechSynthesizer.d.mts +1 -1
  52. package/dist/tool/Approval.d.mts +1 -1
  53. package/dist/tool/HistoryCheck.d.mts +1 -1
  54. package/dist/tool/Tool.d.mts +1 -1
  55. package/dist/tool/ToolResult.d.mts +1 -1
  56. package/dist/tool/Toolkit.d.mts +2 -2
  57. package/dist/transcriber/Transcriber.d.mts +11 -10
  58. package/dist/transcriber/Transcriber.d.mts.map +1 -1
  59. package/dist/transcriber/Transcriber.mjs.map +1 -1
  60. package/dist/transcriber/Transcriber.test.mjs +3 -3
  61. package/dist/transcriber/Transcriber.test.mjs.map +1 -1
  62. package/package.json +5 -1
  63. package/src/capabilities/Capabilities.ts +81 -0
  64. package/src/domain/Audio.ts +2 -1
  65. package/src/domain/Music.ts +142 -68
  66. package/src/domain/Transcript.ts +7 -1
  67. package/src/embedding-model/Embedding.ts +11 -0
  68. package/src/embedding-model/EmbeddingModel.test.ts +15 -4
  69. package/src/embedding-model/EmbeddingModel.ts +48 -21
  70. package/src/index.ts +1 -0
  71. package/src/music-generator/MusicGenerator.test.ts +78 -53
  72. package/src/music-generator/MusicGenerator.ts +65 -24
  73. package/src/speech-synthesizer/SpeechSynthesizer.test.ts +3 -3
  74. package/src/speech-synthesizer/SpeechSynthesizer.ts +18 -33
  75. package/src/testing/MockMusicGenerator.ts +28 -18
  76. package/src/transcriber/Transcriber.test.ts +3 -3
  77. package/src/transcriber/Transcriber.ts +10 -7
  78. package/dist/Audio-BfCTGnH3.d.mts.map +0 -1
@@ -1,8 +1,16 @@
1
- import { Effect, Stream } from "effect"
1
+ import { Duration, Effect, Stream } from "effect"
2
2
  import { describe, expect, expectTypeOf, it } from "vitest"
3
3
  import type * as AiError from "../domain/AiError.js"
4
4
  import type { AudioChunk, AudioFormat } from "../domain/Audio.js"
5
- import { configInput, promptsInput, type MusicResult } from "../domain/Music.js"
5
+ import {
6
+ audioEvent,
7
+ controlInput,
8
+ type GenerateResult,
9
+ type MusicResult,
10
+ type MusicStreamEvent,
11
+ promptsInput,
12
+ singleVariant,
13
+ } from "../domain/Music.js"
6
14
  import * as MockMusicGenerator from "../testing/MockMusicGenerator.js"
7
15
  import * as MusicGenerator from "./MusicGenerator.js"
8
16
 
@@ -13,50 +21,69 @@ const mp3Format: AudioFormat = {
13
21
  channels: 2,
14
22
  }
15
23
 
16
- const result: MusicResult = {
17
- format: mp3Format,
18
- bytes: new Uint8Array([0xff, 0xfb, 0x90, 0x00]),
19
- durationSeconds: 30,
24
+ const oneResult: MusicResult = {
25
+ audio: {
26
+ format: mp3Format,
27
+ bytes: new Uint8Array([0xff, 0xfb, 0x90, 0x00]),
28
+ duration: Duration.seconds(30),
29
+ },
30
+ provider: "mock-music",
20
31
  lyrics: "[Verse]\nhello\n",
21
- watermark: { kind: "synthid" },
32
+ watermark: "synthid",
22
33
  }
23
34
 
35
+ const oneVariant: GenerateResult = singleVariant(oneResult)
36
+
24
37
  const chunk = (n: number): AudioChunk => ({ bytes: new Uint8Array([n]) })
25
38
 
26
39
  describe("MusicGenerator.generate", () => {
27
- it("returns the scripted MusicResult", async () => {
28
- const mock = MockMusicGenerator.layer({ results: [result] })
40
+ it("returns the scripted GenerateResult", async () => {
41
+ const mock = MockMusicGenerator.layer({ results: [oneVariant] })
29
42
  const program = MusicGenerator.generate({
30
43
  model: "mock-music",
31
- prompts: "upbeat indie pop",
44
+ prompt: "upbeat indie pop",
32
45
  })
33
46
  const out = await Effect.runPromise(program.pipe(Effect.provide(mock.layer)))
34
- expect(out.bytes).toEqual(result.bytes)
35
- expect(out.durationSeconds).toBe(30)
36
- expect(out.watermark?.kind).toBe("synthid")
37
- expect(out.lyrics).toContain("[Verse]")
47
+ expect(out.primary.audio.bytes).toEqual(oneResult.audio.bytes)
48
+ expect(out.primary.audio.duration).toEqual(Duration.seconds(30))
49
+ expect(out.primary.watermark).toBe("synthid")
50
+ expect(out.primary.lyrics).toContain("[Verse]")
51
+ expect(out.variants).toHaveLength(1)
52
+ expect(out.variants[0]).toBe(out.primary)
53
+ })
54
+
55
+ it("exposes multiple variants when the provider returned more than one", async () => {
56
+ const secondTrack: MusicResult = {
57
+ ...oneResult,
58
+ audio: { ...oneResult.audio, bytes: new Uint8Array([0xff, 0xfb, 0xa0, 0x00]) },
59
+ }
60
+ const twoVariants: GenerateResult = {
61
+ primary: oneResult,
62
+ variants: [oneResult, secondTrack],
63
+ }
64
+ const mock = MockMusicGenerator.layer({ results: [twoVariants] })
65
+ const program = MusicGenerator.generate({ model: "m", prompt: "house" })
66
+ const out = await Effect.runPromise(program.pipe(Effect.provide(mock.layer)))
67
+ expect(out.variants).toHaveLength(2)
68
+ expect(out.variants[1]!.audio.bytes).toEqual(secondTrack.audio.bytes)
38
69
  })
39
70
 
40
71
  it("records the request shape on the recorder", async () => {
41
- const mock = MockMusicGenerator.layer({ results: [result, result] })
72
+ const mock = MockMusicGenerator.layer({ results: [oneVariant, oneVariant] })
42
73
  const program = Effect.gen(function* () {
43
- yield* MusicGenerator.generate({ model: "m", prompts: "techno" })
74
+ yield* MusicGenerator.generate({ model: "m", prompt: "techno" })
44
75
  yield* MusicGenerator.generate({
45
76
  model: "m",
46
- prompts: [
47
- { text: "synthwave", weight: 1.0 },
48
- { text: "80s movie OST", weight: 0.4 },
49
- ],
50
- bpm: 120,
51
- instrumental: true,
77
+ prompt: "synthwave",
78
+ duration: Duration.seconds(45),
79
+ seed: 42,
52
80
  })
53
81
  return yield* mock.recorder
54
82
  })
55
83
  const rec = await Effect.runPromise(program.pipe(Effect.provide(mock.layer)))
56
84
  expect(rec.generateCalls.length).toBe(2)
57
- expect(rec.generateCalls[1]!.bpm).toBe(120)
58
- expect(rec.generateCalls[1]!.instrumental).toBe(true)
59
- expect(Array.isArray(rec.generateCalls[1]!.prompts)).toBe(true)
85
+ expect(rec.generateCalls[1]!.duration).toEqual(Duration.seconds(45))
86
+ expect(rec.generateCalls[1]!.seed).toBe(42)
60
87
  })
61
88
  })
62
89
 
@@ -66,7 +93,7 @@ describe("MusicGenerator.streamGeneration", () => {
66
93
  streamGenerationChunks: [[chunk(1), chunk(2), chunk(3)]],
67
94
  })
68
95
  const program = Stream.runCollect(
69
- MusicGenerator.streamGeneration({ model: "m", prompts: "ambient" }),
96
+ MusicGenerator.streamGeneration({ model: "m", prompt: "ambient" }),
70
97
  )
71
98
  const out = await Effect.runPromise(program.pipe(Effect.provide(mock.layer)))
72
99
  expect(out.map((c) => Array.from(c.bytes))).toEqual([[1], [2], [3]])
@@ -76,15 +103,15 @@ describe("MusicGenerator.streamGeneration", () => {
76
103
  describe("MusicGenerator capability marker (compile-time)", () => {
77
104
  const sgfReq: MusicGenerator.CommonStreamGenerateMusicRequest = {
78
105
  model: "m",
79
- prompts: "",
106
+ prompt: "",
80
107
  }
81
108
 
82
109
  it("requires `MusicInteractiveSession` on the R channel of streamGenerationFrom", () => {
83
110
  const inputs = Stream.fromIterable([promptsInput([{ text: "techno" }])])
84
- const audio = inputs.pipe(MusicGenerator.streamGenerationFrom(sgfReq))
85
- expectTypeOf(audio).toEqualTypeOf<
111
+ const events = inputs.pipe(MusicGenerator.streamGenerationFrom(sgfReq))
112
+ expectTypeOf(events).toEqualTypeOf<
86
113
  Stream.Stream<
87
- AudioChunk,
114
+ MusicStreamEvent,
88
115
  AiError.AiError,
89
116
  MusicGenerator.MusicGenerator | MusicGenerator.MusicInteractiveSession
90
117
  >
@@ -92,14 +119,14 @@ describe("MusicGenerator capability marker (compile-time)", () => {
92
119
  })
93
120
 
94
121
  it("does NOT require `MusicInteractiveSession` for sync `generate`", () => {
95
- const eff = MusicGenerator.generate({ model: "m", prompts: "ambient" })
122
+ const eff = MusicGenerator.generate({ model: "m", prompt: "ambient" })
96
123
  expectTypeOf(eff).toEqualTypeOf<
97
- Effect.Effect<MusicResult, AiError.AiError, MusicGenerator.MusicGenerator>
124
+ Effect.Effect<GenerateResult, AiError.AiError, MusicGenerator.MusicGenerator>
98
125
  >()
99
126
  })
100
127
 
101
128
  it("does NOT require `MusicInteractiveSession` for `streamGeneration`", () => {
102
- const audio = MusicGenerator.streamGeneration({ model: "m", prompts: "ambient" })
129
+ const audio = MusicGenerator.streamGeneration({ model: "m", prompt: "ambient" })
103
130
  expectTypeOf(audio).toEqualTypeOf<
104
131
  Stream.Stream<AudioChunk, AiError.AiError, MusicGenerator.MusicGenerator>
105
132
  >()
@@ -108,8 +135,8 @@ describe("MusicGenerator capability marker (compile-time)", () => {
108
135
  it("a layer without the marker leaves `MusicInteractiveSession` unsatisfied in R", () => {
109
136
  const noMarker = MockMusicGenerator.layerWithoutInteractive({})
110
137
  const inputs = Stream.fromIterable([promptsInput([{ text: "techno" }])])
111
- const audio = inputs.pipe(MusicGenerator.streamGenerationFrom(sgfReq))
112
- const program = Stream.runDrain(audio).pipe(Effect.provide(noMarker.layer))
138
+ const events = inputs.pipe(MusicGenerator.streamGenerationFrom(sgfReq))
139
+ const program = Stream.runDrain(events).pipe(Effect.provide(noMarker.layer))
113
140
  expectTypeOf(program).toEqualTypeOf<
114
141
  Effect.Effect<void, AiError.AiError, MusicGenerator.MusicInteractiveSession>
115
142
  >()
@@ -117,53 +144,51 @@ describe("MusicGenerator capability marker (compile-time)", () => {
117
144
 
118
145
  it("a full layer (with marker) clears R to never", () => {
119
146
  const fullMock = MockMusicGenerator.layer({
120
- streamGenerationFromChunks: [[]],
147
+ streamGenerationFromEvents: [[]],
121
148
  })
122
149
  const inputs = Stream.fromIterable([promptsInput([{ text: "techno" }])])
123
- const audio = inputs.pipe(MusicGenerator.streamGenerationFrom(sgfReq))
124
- const program = Stream.runDrain(audio).pipe(Effect.provide(fullMock.layer))
150
+ const events = inputs.pipe(MusicGenerator.streamGenerationFrom(sgfReq))
151
+ const program = Stream.runDrain(events).pipe(Effect.provide(fullMock.layer))
125
152
  expectTypeOf(program).toEqualTypeOf<Effect.Effect<void, AiError.AiError, never>>()
126
153
  })
127
154
  })
128
155
 
129
156
  describe("MusicGenerator.streamGenerationFrom", () => {
130
157
  const sgfReq: MusicGenerator.CommonStreamGenerateMusicRequest = {
131
- model: "lyria-realtime-001",
132
- prompts: "",
158
+ model: "lyria-realtime-exp",
159
+ prompt: "",
133
160
  }
134
161
 
135
- it("drains a session-input stream and emits scripted audio", async () => {
162
+ it("drains a session-input stream and emits scripted events", async () => {
136
163
  const mock = MockMusicGenerator.layer({
137
- streamGenerationFromChunks: [[chunk(10), chunk(20)]],
164
+ streamGenerationFromEvents: [[audioEvent(chunk(10)), audioEvent(chunk(20))]],
138
165
  })
139
166
  const inputs = Stream.fromIterable([
140
167
  promptsInput([{ text: "minimal techno", weight: 1.0 }]),
141
- configInput({ bpm: 124 }),
168
+ controlInput("play"),
142
169
  promptsInput([
143
170
  { text: "minimal techno", weight: 1.0 },
144
171
  { text: "1980s synthwave", weight: 0.3 },
145
172
  ]),
146
173
  ])
147
- const audio = inputs.pipe(MusicGenerator.streamGenerationFrom(sgfReq))
148
- const out = await Effect.runPromise(Stream.runCollect(audio).pipe(Effect.provide(mock.layer)))
149
- expect(out.map((c) => Array.from(c.bytes))).toEqual([[10], [20]])
174
+ const events = inputs.pipe(MusicGenerator.streamGenerationFrom(sgfReq))
175
+ const out = await Effect.runPromise(Stream.runCollect(events).pipe(Effect.provide(mock.layer)))
176
+ const audioChunks = out.flatMap((e) => (e._tag === "audio" ? [e.chunk] : []))
177
+ expect(audioChunks.map((c) => Array.from(c.bytes))).toEqual([[10], [20]])
150
178
  })
151
179
 
152
180
  it("records the request on the streamGenerationFrom call channel", async () => {
153
181
  const mock = MockMusicGenerator.layer({
154
- streamGenerationFromChunks: [[chunk(42)]],
182
+ streamGenerationFromEvents: [[audioEvent(chunk(42))]],
155
183
  })
156
184
  const program = Effect.gen(function* () {
157
- yield* Stream.runDrain(
158
- Stream.fromIterable([promptsInput([{ text: "x" }])]).pipe(
159
- MusicGenerator.streamGenerationFrom(sgfReq),
160
- ),
161
- )
185
+ const inputs = Stream.fromIterable([promptsInput([{ text: "x" }])])
186
+ yield* Stream.runDrain(inputs.pipe(MusicGenerator.streamGenerationFrom(sgfReq)))
162
187
  return yield* mock.recorder
163
188
  })
164
189
  const rec = await Effect.runPromise(program.pipe(Effect.provide(mock.layer)))
165
190
  expect(rec.streamGenerationFromCalls.length).toBe(1)
166
- expect(rec.streamGenerationFromCalls[0]!.model).toBe("lyria-realtime-001")
191
+ expect(rec.streamGenerationFromCalls[0]!.model).toBe("lyria-realtime-exp")
167
192
  expect(rec.generateCalls.length).toBe(0)
168
193
  expect(rec.streamGenerationCalls.length).toBe(0)
169
194
  })
@@ -1,18 +1,24 @@
1
1
  import { Context, Effect, Function, Stream } from "effect"
2
2
  import * as AiError from "../domain/AiError.js"
3
- import type { AudioChunk } from "../domain/Audio.js"
4
3
  import type {
5
4
  CommonGenerateMusicRequest,
6
5
  CommonStreamGenerateMusicRequest,
7
- MusicResult,
6
+ GenerateResult,
8
7
  MusicSessionInput,
8
+ MusicStreamEvent,
9
9
  } from "../domain/Music.js"
10
+ import type { AudioChunk } from "../domain/Audio.js"
10
11
 
11
12
  export type {
12
13
  CommonGenerateMusicRequest,
13
14
  CommonStreamGenerateMusicRequest,
15
+ GenerateResult,
14
16
  MusicResult,
17
+ MusicSection,
18
+ MusicSessionControl,
15
19
  MusicSessionInput,
20
+ MusicStreamEvent,
21
+ Watermark,
16
22
  WeightedPrompt,
17
23
  } from "../domain/Music.js"
18
24
 
@@ -20,35 +26,50 @@ export type MusicGeneratorService = {
20
26
  /**
21
27
  * One-shot. Prompt in, full audio bytes out. Universally supported.
22
28
  * Async/poll-based providers (Suno, Mureka) hide their poll loop
23
- * inside the adapter — caller still sees a single `Effect`.
29
+ * inside the adapter, caller still sees a single `Effect`.
30
+ *
31
+ * Returns `GenerateResult` with `primary` plus a `variants` array.
32
+ * Suno and Mureka always return 2 tracks; every other provider
33
+ * returns 1 (and `primary === variants[0]`).
24
34
  */
25
35
  readonly generate: (
26
36
  request: CommonGenerateMusicRequest,
27
- ) => Effect.Effect<MusicResult, AiError.AiError>
37
+ ) => Effect.Effect<GenerateResult, AiError.AiError>
28
38
  /**
29
39
  * Prompt in, audio chunks streamed out. Providers without a native
30
40
  * chunked-output endpoint (Lyria 3 sync, Mureka, MiniMax, Stable
31
41
  * Audio) emulate this by calling `generate` and emitting a single
32
- * `AudioChunk` — first-class, no `Unsupported`.
42
+ * `AudioChunk`, first-class, no `Unsupported`.
33
43
  */
34
44
  readonly streamGeneration: (
35
45
  request: CommonStreamGenerateMusicRequest,
36
46
  ) => Stream.Stream<AudioChunk, AiError.AiError>
37
47
  /**
38
- * Bidirectional session: a `Stream` of prompt-or-config updates flows
39
- * in, a `Stream` of audio chunks flows out. The session WS / RPC is
40
- * acquired on first pull and released when the output stream is
41
- * finalized via `Stream.scoped`.
48
+ * Bidirectional session: a `Stream` of `MusicSessionInput` (prompts
49
+ * + playback control) flows in, a `Stream` of `MusicStreamEvent`
50
+ * flows out. The session WS / RPC is acquired on first pull and
51
+ * released when the output stream is finalized via `Stream.scoped`.
52
+ *
53
+ * Cross-provider callers send `prompts` (steer the active
54
+ * generation) and `control` (play / pause / stop / reset) — the two
55
+ * actions that converge across interactive-media protocols.
56
+ * Provider-specific model knobs (Lyria RealTime's density /
57
+ * brightness / mute-stems / BPM / scale, etc.) live on the
58
+ * provider-typed service (`LyriaRealtimeGenerator.streamGenerationFrom`),
59
+ * which extends this union with its own `config` variant.
60
+ *
61
+ * Output is `MusicStreamEvent`: `audio` chunks alongside in-band
62
+ * `warning` and `filteredPrompt` events the model emits server-side.
42
63
  *
43
64
  * Gated by the `MusicInteractiveSession` capability marker on the
44
- * top-level helper — providers without bidirectional support don't
65
+ * top-level helper. Providers without bidirectional support don't
45
66
  * ship the marker, so calls fail at `Effect.provide` with a type
46
67
  * error.
47
68
  */
48
69
  readonly streamGenerationFrom: <E, R>(
49
70
  input: Stream.Stream<MusicSessionInput, E, R>,
50
71
  request: CommonStreamGenerateMusicRequest,
51
- ) => Stream.Stream<AudioChunk, AiError.AiError | E, R>
72
+ ) => Stream.Stream<MusicStreamEvent, AiError.AiError | E, R>
52
73
  }
53
74
 
54
75
  export class MusicGenerator extends Context.Service<MusicGenerator, MusicGeneratorService>()(
@@ -56,23 +77,23 @@ export class MusicGenerator extends Context.Service<MusicGenerator, MusicGenerat
56
77
  ) {}
57
78
 
58
79
  /**
59
- * Capability marker — provided by provider layers whose
80
+ * Capability marker, provided by provider layers whose
60
81
  * `streamGenerationFrom` is wired up at the wire level. Currently only
61
82
  * Lyria RealTime (via the BidiGenerateMusic WebSocket) ships it.
62
83
  * Calling `streamGenerationFrom` while only a non-interactive Layer is
63
84
  * in scope fails at `Effect.provide` with a type error.
64
85
  *
65
- * Phantom — the value is `void`; providers register with
86
+ * Phantom: the value is `void`; providers register with
66
87
  * `Layer.succeed(MusicInteractiveSession, undefined)`.
67
88
  */
68
89
  export class MusicInteractiveSession extends Context.Service<MusicInteractiveSession, void>()(
69
90
  "@betalyra/effect-uai/capability/MusicInteractiveSession",
70
91
  ) {}
71
92
 
72
- /** One-shot generation. */
93
+ /** One-shot generation. Returns the full `GenerateResult`. */
73
94
  export const generate = (
74
95
  request: CommonGenerateMusicRequest,
75
- ): Effect.Effect<MusicResult, AiError.AiError, MusicGenerator> =>
96
+ ): Effect.Effect<GenerateResult, AiError.AiError, MusicGenerator> =>
76
97
  Effect.flatMap(MusicGenerator.asEffect(), (s) => s.generate(request))
77
98
 
78
99
  /** Prompt in, audio chunks out. */
@@ -83,17 +104,25 @@ export const streamGeneration = (
83
104
 
84
105
  /**
85
106
  * Bidirectional generation. Dual-arity: pipeable (data-last) and
86
- * direct (data-first). Requires `MusicInteractiveSession` in R —
107
+ * direct (data-first). Requires `MusicInteractiveSession` in R,
87
108
  * providers without bidirectional support are a type error at provide
88
109
  * time.
89
110
  *
111
+ * On the cross-provider surface, `input` is `Stream<unknown>` and
112
+ * output is `Stream<MusicStreamEvent>`. Use the provider-typed
113
+ * service (`LyriaRealtimeGenerator`) when you want to construct
114
+ * typed session messages.
115
+ *
90
116
  * @example
91
117
  * ```ts
92
- * const audio = Stream.fromIterable([
93
- * Music.promptsInput([{ text: "minimal techno", weight: 1.0 }]),
94
- * Music.configInput({ bpm: 124 }),
95
- * ]).pipe(
96
- * MusicGenerator.streamGenerationFrom({ model: "lyria-realtime-001", prompts: "" }),
118
+ * // Generic surface (opaque input):
119
+ * const audio = inputs.pipe(
120
+ * MusicGenerator.streamGenerationFrom({ model: "lyria-realtime-exp", prompt: "" }),
121
+ * )
122
+ *
123
+ * // Lyria-typed surface (full config knobs):
124
+ * const audio = inputs.pipe(
125
+ * LyriaRealtimeGenerator.streamGenerationFrom({ model: "lyria-realtime-exp", prompt: "" }),
97
126
  * )
98
127
  * ```
99
128
  */
@@ -102,17 +131,29 @@ export const streamGenerationFrom: {
102
131
  request: CommonStreamGenerateMusicRequest,
103
132
  ): <E, R>(
104
133
  input: Stream.Stream<MusicSessionInput, E, R>,
105
- ) => Stream.Stream<AudioChunk, AiError.AiError | E, R | MusicGenerator | MusicInteractiveSession>
134
+ ) => Stream.Stream<
135
+ MusicStreamEvent,
136
+ AiError.AiError | E,
137
+ R | MusicGenerator | MusicInteractiveSession
138
+ >
106
139
  <E, R>(
107
140
  input: Stream.Stream<MusicSessionInput, E, R>,
108
141
  request: CommonStreamGenerateMusicRequest,
109
- ): Stream.Stream<AudioChunk, AiError.AiError | E, R | MusicGenerator | MusicInteractiveSession>
142
+ ): Stream.Stream<
143
+ MusicStreamEvent,
144
+ AiError.AiError | E,
145
+ R | MusicGenerator | MusicInteractiveSession
146
+ >
110
147
  } = Function.dual(
111
148
  2,
112
149
  <E, R>(
113
150
  input: Stream.Stream<MusicSessionInput, E, R>,
114
151
  request: CommonStreamGenerateMusicRequest,
115
- ) =>
152
+ ): Stream.Stream<
153
+ MusicStreamEvent,
154
+ AiError.AiError | E,
155
+ R | MusicGenerator | MusicInteractiveSession
156
+ > =>
116
157
  Stream.unwrap(
117
158
  Effect.gen(function* () {
118
159
  const s = yield* MusicGenerator.asEffect()
@@ -1,4 +1,4 @@
1
- import { Effect, Stream } from "effect"
1
+ import { Duration, Effect, Stream } from "effect"
2
2
  import { describe, expect, expectTypeOf, it } from "vitest"
3
3
  import type * as AiError from "../domain/AiError.js"
4
4
  import type { AudioBlob, AudioChunk, AudioFormat } from "../domain/Audio.js"
@@ -14,7 +14,7 @@ const pcmFormat: AudioFormat = {
14
14
  const blob: AudioBlob = {
15
15
  format: pcmFormat,
16
16
  bytes: new Uint8Array([0xde, 0xad, 0xbe, 0xef]),
17
- durationSeconds: 0.5,
17
+ duration: Duration.millis(500),
18
18
  }
19
19
 
20
20
  const chunk = (n: number): AudioChunk => ({ bytes: new Uint8Array([n]) })
@@ -29,7 +29,7 @@ describe("SpeechSynthesizer.synthesize", () => {
29
29
  })
30
30
  const result = await Effect.runPromise(program.pipe(Effect.provide(mock.layer)))
31
31
  expect(result.bytes).toEqual(blob.bytes)
32
- expect(result.durationSeconds).toBe(0.5)
32
+ expect(result.duration).toEqual(Duration.millis(500))
33
33
  })
34
34
  })
35
35
 
@@ -3,31 +3,20 @@ import * as AiError from "../domain/AiError.js"
3
3
  import type { AudioBlob, AudioChunk, AudioFormat } from "../domain/Audio.js"
4
4
 
5
5
  /**
6
- * Phonetic alphabets accepted by `CustomPronunciation`. Not every
7
- * provider supports every alphabet — adapters translate or warn+drop
8
- * unsupported entries.
6
+ * Per-phrase pronunciation override. `pronunciation` is always IPA, the
7
+ * universal phonetic interchange format. Adapters translate to the
8
+ * provider's wire form (inline `/ipa/` token, SSML `<phoneme>`, or a
9
+ * structured field), converting IPA to X-SAMPA internally where the wire
10
+ * requires it (Google, Azure).
9
11
  *
10
- * - `ipa` — universal lowest common denominator (Google, ElevenLabs,
11
- * Inworld, Deepgram, Cartesia, MiniMax).
12
- * - `x-sampa` — Google Cloud TTS.
13
- * - `cmu-arpabet` — ElevenLabs `eleven_flash_v2` / `eleven_english_v1`.
14
- */
15
- export type PhoneticEncoding = "ipa" | "x-sampa" | "cmu-arpabet"
16
-
17
- /**
18
- * Per-phrase pronunciation override. The same shape unifies the
19
- * structured-field providers (Google) and the inline-markup providers
20
- * (ElevenLabs SSML, Inworld `/ipa/`, Deepgram, Cartesia, MiniMax) — the
21
- * adapter does the wire translation.
22
- *
23
- * Unsupported alphabets are dropped at the adapter with a structured
24
- * `logWarning` (one per call). The audio still renders, just without
25
- * the override.
12
+ * Pronunciations are load-bearing (the configured word is mispronounced
13
+ * if dropped), so a provider with no stateless IPA path fails the call
14
+ * with `AiError.Unsupported` rather than silently degrading.
26
15
  */
27
16
  export type CustomPronunciation = {
28
17
  readonly phrase: string
18
+ /** IPA notation, e.g. `"ænˈθrɒpɪk"`. */
29
19
  readonly pronunciation: string
30
- readonly encoding: PhoneticEncoding
31
20
  }
32
21
 
33
22
  /**
@@ -52,11 +41,10 @@ export type CommonSynthesizeRequest = {
52
41
  readonly speed?: number
53
42
  readonly languageCode?: string
54
43
  /**
55
- * Phoneme overrides for specific phrases. 7 of 9 TTS providers
56
- * support some form of this; adapters either translate to a
57
- * structured field, rewrite `text` inline, or `warn+drop` per-entry
58
- * for alphabets they don't accept. OpenAI rejects non-empty arrays
59
- * with `Unsupported`.
44
+ * IPA phoneme overrides for specific phrases. Adapters render them to
45
+ * the provider's wire form (inline token, SSML `<phoneme>`, structured
46
+ * field). Load-bearing: a provider with no stateless IPA path fails
47
+ * the call with `AiError.Unsupported` rather than mispronouncing.
60
48
  */
61
49
  readonly pronunciations?: ReadonlyArray<CustomPronunciation>
62
50
  }
@@ -73,18 +61,15 @@ export type CommonSynthesizeRequest = {
73
61
  export type CommonStreamSynthesizeRequest = Omit<CommonSynthesizeRequest, "text">
74
62
 
75
63
  /**
76
- * One turn in a multi-speaker dialogue.
77
- *
78
- * `styleDescription` and `speed` are honored by providers that expose
79
- * per-turn knobs (Hume Octave-2) and silently ignored by others
80
- * (ElevenLabs `/v1/text-to-dialogue` accepts `{voice_id, text}` only;
81
- * Google Gemini TTS multi-speaker has no per-turn styling).
64
+ * One turn in a multi-speaker dialogue. Just a voice and its line; the
65
+ * only in-tree dialogue endpoint (ElevenLabs `/v1/text-to-dialogue`)
66
+ * accepts `{ voice_id, text }` per turn. Per-turn styling knobs
67
+ * (Hume Octave-2 `styleDescription` / `speed`) are provider-specific
68
+ * and belong on a provider-typed turn extension, not here.
82
69
  */
83
70
  export type DialogueTurn = {
84
71
  readonly voiceId: string
85
72
  readonly text: string
86
- readonly styleDescription?: string
87
- readonly speed?: number
88
73
  }
89
74
 
90
75
  /**
@@ -1,11 +1,13 @@
1
1
  import { Effect, Layer, Ref, Stream } from "effect"
2
2
  import * as AiError from "../domain/AiError.js"
3
3
  import type { AudioChunk } from "../domain/Audio.js"
4
- import type {
5
- CommonGenerateMusicRequest,
6
- CommonStreamGenerateMusicRequest,
7
- MusicResult,
8
- MusicSessionInput,
4
+ import {
5
+ audioEvent,
6
+ type CommonGenerateMusicRequest,
7
+ type CommonStreamGenerateMusicRequest,
8
+ type GenerateResult,
9
+ type MusicSessionInput,
10
+ type MusicStreamEvent,
9
11
  } from "../domain/Music.js"
10
12
  import {
11
13
  MusicGenerator,
@@ -21,11 +23,15 @@ export type MockMusicGeneratorRecorder = {
21
23
 
22
24
  export type MockMusicGeneratorScript = {
23
25
  /** One result per `generate` call, consumed in order. */
24
- readonly results?: ReadonlyArray<MusicResult>
26
+ readonly results?: ReadonlyArray<GenerateResult>
25
27
  /** One chunk-list per `streamGeneration` call, consumed in order. */
26
28
  readonly streamGenerationChunks?: ReadonlyArray<ReadonlyArray<AudioChunk>>
27
- /** One chunk-list per `streamGenerationFrom` call, consumed in order. */
28
- readonly streamGenerationFromChunks?: ReadonlyArray<ReadonlyArray<AudioChunk>>
29
+ /**
30
+ * One event-list per `streamGenerationFrom` call, consumed in order.
31
+ * If a list contains only `AudioChunk`s for ergonomics, wrap them in
32
+ * `audioEvent(chunk)` first.
33
+ */
34
+ readonly streamGenerationFromEvents?: ReadonlyArray<ReadonlyArray<MusicStreamEvent>>
29
35
  }
30
36
 
31
37
  const makeService = (
@@ -74,22 +80,23 @@ const makeService = (
74
80
  streamGenerationFrom: <E, R>(
75
81
  input: Stream.Stream<MusicSessionInput, E, R>,
76
82
  request: CommonStreamGenerateMusicRequest,
77
- ): Stream.Stream<AudioChunk, AiError.AiError | E, R> =>
83
+ ): Stream.Stream<MusicStreamEvent, AiError.AiError | E, R> =>
78
84
  Stream.unwrap(
79
85
  Effect.gen(function* () {
80
86
  yield* record.streamGenerationFrom(request)
81
87
  const i = yield* Ref.getAndUpdate(sgfCursor, (n) => n + 1)
82
- const scripted = script.streamGenerationFromChunks ?? []
88
+ const scripted = script.streamGenerationFromEvents ?? []
83
89
  if (i >= scripted.length) {
84
- const exhausted: Stream.Stream<AudioChunk, AiError.AiError | E, R> = Stream.fail(
85
- new AiError.InvalidRequest({
86
- provider: "mock",
87
- raw: `MockMusicGenerator exhausted: ${scripted.length} streamGenerationFrom lists scripted, but call ${i + 1} was made`,
88
- }),
89
- )
90
+ const exhausted: Stream.Stream<MusicStreamEvent, AiError.AiError | E, R> =
91
+ Stream.fail(
92
+ new AiError.InvalidRequest({
93
+ provider: "mock",
94
+ raw: `MockMusicGenerator exhausted: ${scripted.length} streamGenerationFrom lists scripted, but call ${i + 1} was made`,
95
+ }),
96
+ )
90
97
  return exhausted
91
98
  }
92
- // Drain the input fully before emitting scripted audio chunks,
99
+ // Drain the input fully before emitting scripted events,
93
100
  // so consumers can assert on what session messages were pushed.
94
101
  return Stream.drain(input).pipe(Stream.concat(Stream.fromIterable(scripted[i]!)))
95
102
  }),
@@ -133,7 +140,7 @@ export const layer = (
133
140
  }
134
141
 
135
142
  /**
136
- * Variant that omits the `MusicInteractiveSession` marker — simulates a
143
+ * Variant that omits the `MusicInteractiveSession` marker, simulates a
137
144
  * provider without bidirectional support (Lyria 3 sync, ElevenLabs,
138
145
  * Mureka, MiniMax, Stable Audio, Suno). Calls to
139
146
  * `streamGenerationFrom` in code under test should be a compile-time
@@ -166,3 +173,6 @@ export const layerWithoutInteractive = (
166
173
  }),
167
174
  }
168
175
  }
176
+
177
+ // Re-export the event constructor for test-script ergonomics.
178
+ export { audioEvent }
@@ -1,4 +1,4 @@
1
- import { Effect, Stream } from "effect"
1
+ import { Duration, Effect, Stream } from "effect"
2
2
  import { describe, expect, expectTypeOf, it } from "vitest"
3
3
  import type * as AiError from "../domain/AiError.js"
4
4
  import type { TranscriptEvent, TranscriptResult } from "../domain/Transcript.js"
@@ -8,7 +8,7 @@ import * as Transcriber from "./Transcriber.js"
8
8
  describe("Transcriber.transcribe", () => {
9
9
  it("returns the scripted TranscriptResult", async () => {
10
10
  const mock = MockTranscriber.layer({
11
- transcripts: [{ text: "hello world", durationSeconds: 1.23 }],
11
+ transcripts: [{ text: "hello world", duration: Duration.seconds(1.23) }],
12
12
  })
13
13
  const program = Transcriber.transcribe({
14
14
  audio: { _tag: "bytes", bytes: new Uint8Array([0]), mimeType: "audio/wav" },
@@ -16,7 +16,7 @@ describe("Transcriber.transcribe", () => {
16
16
  })
17
17
  const result = await Effect.runPromise(program.pipe(Effect.provide(mock.layer)))
18
18
  expect(result.text).toBe("hello world")
19
- expect(result.durationSeconds).toBe(1.23)
19
+ expect(result.duration).toStrictEqual(Duration.seconds(1.23))
20
20
  })
21
21
 
22
22
  it("records each transcribe call", async () => {