@sentry/junior-tts 0.234.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,71 @@
1
+ # @sentry/junior-tts
2
+
3
+ Generate WAV narration through Vercel AI Gateway with `google/gemini-3.8-flash-tts`. Includes a reusable `junior-v1` voice preset and a short sample script. No OpenRouter account, Google key, SDK install, or voice cloning is needed.
4
+
5
+ ## Setup
6
+
7
+ ```sh
8
+ pnpm add @sentry/junior @sentry/junior-tts
9
+ ```
10
+
11
+ Register the package in the app's shared plugin set:
12
+
13
+ ```ts
14
+ import { defineJuniorPlugins } from "@sentry/junior";
15
+ export const plugins = defineJuniorPlugins(["@sentry/junior-tts"]);
16
+ ```
17
+
18
+ Use the same plugin set for the app and `juniorNitro`. See [plugin setup](https://junior.sentry.dev/extend/).
19
+
20
+ Set **`AI_GATEWAY_API_KEY` on the host deployment**. In Vercel, use the Junior app project's Settings → Environment Variables, select the intended environment, and mark the variable sensitive. Then redeploy with the plugin installed and registered. Do not paste the key into Slack, Git, `jr-rpc config`, or the Sandbox.
21
+
22
+ An existing deployment API key can be reused if the team has speech access and credits. **This manifest does not reuse core's Vercel OIDC credential flow.** If the app uses only OIDC, an operator must provision a Gateway API key for this plugin. No new secret is needed when a suitable `AI_GATEWAY_API_KEY` already exists. Speech is in beta; availability can differ by team.
23
+
24
+ The host proxy inserts the bearer key only for `ai-gateway.vercel.sh`. The script neither reads nor accepts the key. This is a shared deployment account, not per-user authorization. Enable it only where users may spend that account's credits. Use a dedicated key with a spending limit when isolation is needed. Rotate the key in Vercel, replace the deployment value, and redeploy.
25
+
26
+ The domain permission covers the Gateway host, not only the speech route. The bundled script uses one fixed speech endpoint and refuses redirects; it does not create an endpoint-level credential restriction.
27
+
28
+ ## Junior Voice
29
+
30
+ `skills/tts/assets/junior-v1.json` pairs the prebuilt `Puck` voice with sustained delivery instructions: bright, warm, quietly confident, lightly raspy, mischievous, and gently snarky. It is an original adult helper voice, not an imitation of a character or performer.
31
+
32
+ The preset translates the supplied Junior persona into performance cues. It does not transmit the full persona or unrelated user-specific instructions. Model and voice selection are pinned in the preset; style is sent separately as `instructions`, never prepended to the spoken text. Reusing a preset does not guarantee identical audio across provider updates.
33
+
34
+ Use `--delivery plain` for serious or sensitive material. It keeps the same voice but removes teasing and dramatic delivery. Version a changed voice identity as a new preset rather than silently changing `junior-v1` after it is accepted.
35
+
36
+ ## Generate the Sample
37
+
38
+ From the skill directory, with the plugin active:
39
+
40
+ ```sh
41
+ node scripts/speech.mjs --profile
42
+ node scripts/speech.mjs --sample --output /tmp/junior-sample.wav
43
+ node scripts/speech.mjs --text-file /tmp/narration.txt --output /tmp/narration.wav
44
+ node scripts/speech.mjs --text-file /tmp/incident.txt --output /tmp/incident.wav --delivery plain
45
+ ```
46
+
47
+ Sample text:
48
+
49
+ > Hey, I'm Junior. I check the evidence, do the work, and keep the recap short. Fewer mystery errors. Fewer meetings about mystery errors. That's the dream, anyway. Show me what you're building. Let's make it work.
50
+
51
+ The sample is a generation recipe, **not a recorded or listening-approved sample**. A real clip requires an active plugin, a funded key, and team model access. Share generated audio with `sendFiles`; for PR evidence, link the delivered sample or an approved artifact location. Do not label synthetic narration as a recording by a person.
52
+
53
+ ## Request Contract
54
+
55
+ - Fixed REST endpoint: `https://ai-gateway.vercel.sh/v4/ai/speech-model`.
56
+ - Headers: Gateway protocol `0.0.1`, speech model specification `4`, selected model ID. Authorization is host-managed.
57
+ - Request: `text`, `voice`, `instructions`, and `outputFormat: wav`.
58
+ - Response: JSON with base64 `audio`; decode before saving. This is **not** OpenRouter's raw-audio endpoint.
59
+ - Maximum: 5,000 characters per clip, a local limit. Split longer scripts into scenes.
60
+ - Exclusive output creation avoids overwrites. Failures remove incomplete local files; an abrupt process exit can leave a reserved file that needs inspection.
61
+ - No automatic retry. A timeout or local validation failure after the request can still spend credits. Check Gateway usage before an authorized retry.
62
+ - Provider warnings fail generation rather than silently dropping voice instructions.
63
+ - The requested text and voice directions go to Vercel and its model provider. This plugin does not promise zero retention.
64
+
65
+ No deployment changes or keys are included. Unit/component checks use a mocked HTTP edge and do not spend credits:
66
+
67
+ ```sh
68
+ pnpm --filter @sentry/junior-tts test
69
+ ```
70
+
71
+ References: [Vercel TTS](https://vercel.com/docs/ai-gateway/modalities/text-to-speech), [Gemini TTS launch](https://vercel.com/changelog/gemini-3-8-text-to-speech-models-now-available-on-ai-gateway).
package/package.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "@sentry/junior-tts",
3
+ "version": "0.234.0",
4
+ "private": false,
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "type": "module",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/getsentry/junior.git",
12
+ "directory": "packages/junior-tts"
13
+ },
14
+ "files": [
15
+ "plugin.yaml",
16
+ "skills"
17
+ ],
18
+ "scripts": {
19
+ "test": "node --test tests/*.test.mjs"
20
+ }
21
+ }
package/plugin.yaml ADDED
@@ -0,0 +1,12 @@
1
+ name: tts
2
+ display-name: Text to Speech
3
+ description: Generate narrated audio with Gemini through Vercel AI Gateway
4
+
5
+ env-vars:
6
+ AI_GATEWAY_API_KEY:
7
+
8
+ domains:
9
+ - ai-gateway.vercel.sh
10
+
11
+ api-headers:
12
+ Authorization: Bearer ${AI_GATEWAY_API_KEY}
@@ -0,0 +1,45 @@
1
+ ---
2
+ name: tts
3
+ description: Generates spoken narration with Gemini TTS through Vercel AI Gateway. Use for text-to-speech, audio samples, voiceovers, or speaking as Junior with the reusable Junior voice. Do not use for transcription, voice cloning, music generation, or rendering a video without a narration request.
4
+ ---
5
+
6
+ # Text to Speech
7
+
8
+ Use the bundled `scripts/speech.mjs` from this directory. Node.js and the installed plugin's host-managed Gateway key are required. Do not install an SDK or ask for secrets in chat.
9
+
10
+ ## Workflow
11
+
12
+ 1. Resolve the requested spoken text. For a sample of Junior's voice, use the bundled sample. Do not send unrelated private context or the full persona to the provider.
13
+ 2. Use the default `junior-v1` preset: a bright, warm, mischievous adult helper with dry humor. Use `--delivery plain` for serious or sensitive text. Do not present it as an imitation or recording of a real performer.
14
+ 3. Write narration to a UTF-8 file. Keep each clip at 1–5000 characters. Generation spends Gateway credits. Do not generate extra variants without a request.
15
+ 4. Generate to a fresh `.wav` path. Inspect an existing file before trying again. Do not automatically retry timeouts or failures: generation may already have spent credits.
16
+ 5. Use `sendFiles` to deliver the returned path as `audio/wav`. Say it is synthetic narration. For a video, measure the new audio and pass it to the rendering workflow; speech generation alone does not update the video.
17
+
18
+ ## Commands and Assets
19
+
20
+ ```sh
21
+ # Local, no API call: show the reusable voice preset.
22
+ node scripts/speech.mjs --profile
23
+
24
+ # Paid: generate the bundled Junior sample.
25
+ node scripts/speech.mjs --sample --output /tmp/junior-sample.wav
26
+
27
+ # Paid: generate requested narration.
28
+ node scripts/speech.mjs --text-file /tmp/narration.txt --output /tmp/narration.wav
29
+
30
+ # Paid: use the same voice without snark.
31
+ node scripts/speech.mjs --text-file /tmp/incident.txt --output /tmp/incident.wav --delivery plain
32
+ ```
33
+
34
+ Read `assets/junior-v1.json` when the user asks how the voice is defined. Read `assets/sample.txt` when previewing the sample script. The script sends delivery instructions separately from text. Do not prepend those directions to narration.
35
+
36
+ Results are JSON with path, bytes, MIME type, model, voice, profile, delivery, and synthetic status. Use `--help` for the command surface. No key argument is accepted.
37
+
38
+ ## Failures
39
+
40
+ - Missing host key or HTTP 401/403: ask the operator to check `AI_GATEWAY_API_KEY`, plugin registration, and team speech access, then redeploy. A missing key in the Sandbox is expected. Core's OIDC authentication is not reused by this manifest-only plugin.
41
+ - HTTP 402: ask the operator to check credits and spending limits.
42
+ - HTTP 404: report that the requested Gemini model is unavailable for the team. Do not silently choose a different model or provider.
43
+ - Timeout, provider warning, or bad audio: stop and check Gateway usage before a user-authorized retry. Do not claim that an audio file was created or approved by listening.
44
+ - Missing script or Node.js: report plugin setup failure. Do not improvise a token-bearing command.
45
+ - Missing credentials: share the preset and script as a recipe, clearly labeled as not generated audio.
@@ -0,0 +1,17 @@
1
+ # TTS Sources and Decisions
2
+
3
+ Reviewed 2026-09-28.
4
+
5
+ - [Vercel text-to-speech](https://vercel.com/docs/ai-gateway/modalities/text-to-speech): authoritative REST endpoint, protocol headers, base64 response, separate instructions, WAV output, and beta access limits.
6
+ - [Gemini 3.8 launch](https://vercel.com/changelog/gemini-3-8-text-to-speech-models-now-available-on-ai-gateway): model availability and expressive character delivery.
7
+ - User-supplied Junior personality: practical, concise, evidence-first, warm, mildly playful, with dry humor; plain delivery for serious topics. Transformed into original performance cues. No raw persona file or user-specific identity rules are sent to TTS.
8
+ - `packages/junior-datadog/plugin.yaml`: existing host-managed API-header pattern.
9
+ - `packages/junior/src/chat/plugins/auth/api-headers-broker.ts`: host-only secret resolution and missing-key behavior.
10
+ - `packages/junior/src/chat/pi/gateway-auth.ts`: core prefers OIDC. This plugin does not import core internals or claim that it shares that path.
11
+ - Repo skill validator and skill-writer guidance: registration and artifact layout.
12
+
13
+ Class: integration-documentation. Shape: script-backed workflow. Plain instructions alone were rejected because paid requests and base64 audio need consistent validation. No SDK or new core runtime contract is needed. The script requires Junior's host proxy; it is not a standalone credential client.
14
+
15
+ Coverage: API, key setup, narration workflow, failure handling, protocol version, and delivery are documented and tested. Added one preset to keep voice identity reusable and one sample script for listening review. No provider selection layer, key-entry UI, or unrelated persona rules were added.
16
+
17
+ Gaps: no live Gateway speech credential or listening test at authoring time. The user-provided AI Studio guide returned an empty page through text fetch; the current Vercel provider documentation is the protocol source. Further source collection cannot verify team-specific access. A real sample remains a deployment smoke test.
@@ -0,0 +1,23 @@
1
+ # TTS Skill Specification
2
+
3
+ ## Intent
4
+
5
+ Create requested synthetic narration with a reusable original Junior voice. Use Gemini 3.8 Flash TTS through Vercel AI Gateway, not OpenRouter. Keep the key on the host.
6
+
7
+ ## Scope and Contract
8
+
9
+ The manifest owns credentials and the approved domain. `scripts/speech.mjs` owns request validation, the REST protocol, audio decoding, and output files. `assets/junior-v1.json` owns the playful voice identity. `assets/sample.txt` is a non-sensitive sample script. `SKILL.md` owns narration scope, delivery mode, retries, and sharing.
10
+
11
+ Out of scope: voice cloning, per-user key storage, OIDC support, transcription, video rendering, automatic retries, deployment changes, and alternate providers.
12
+
13
+ ## Triggers and Validation
14
+
15
+ Should trigger: “Read this aloud”; “Give me a Junior voice sample”; “Make a Gemini voiceover for this demo.”
16
+
17
+ Should not trigger: “Transcribe this clip”; “Clone this performer's voice”; “Make a silent animation.”
18
+
19
+ Run package tests, core credential-broker tests, skills validation, and package/release checks. Local tests mock only the HTTP edge and use generated WAV fixture bytes. Live validation needs an installed plugin, a funded key, and team speech access. Do not claim a listening-approved voice from mock tests.
20
+
21
+ ## Maintenance
22
+
23
+ Keep provenance in `SOURCES.md`. Confirm the Gateway endpoint and headers when its speech protocol changes. Preserve the distinction between base64 JSON from Gateway and raw audio from other APIs. Version accepted voice changes. Do not store credentials, customer scripts, or private account details in fixtures.
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "junior-v1",
3
+ "model": "google/gemini-3.8-flash-tts",
4
+ "voice": "Puck",
5
+ "instructions": "An original adult animated helper with a bright, lightly raspy mid-range voice. Warm, clear, and quietly confident. Speak at a brisk conversational pace with crisp consonants, short pauses, and natural contractions. Add a small mischievous grin and dry, gently snarky timing to playful lines; aim jokes at broken software and awkward situations, never the listener. Sound like a capable teammate, not a corporate presenter or trailer announcer. Keep the energy light, not shrill, aggressive, or childish. On serious or sensitive lines, drop the teasing and speak plainly. Read only the supplied text; do not add jokes, catchphrases, introductions, or sound effects. Do not imitate a named character or real performer."
6
+ }
@@ -0,0 +1 @@
1
+ Hey, I'm Junior. I check the evidence, do the work, and keep the recap short. Fewer mystery errors. Fewer meetings about mystery errors. That's the dream, anyway. Show me what you're building. Let's make it work.
@@ -0,0 +1,176 @@
1
+ import { open, readFile, unlink } from "node:fs/promises";
2
+ import { resolve } from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { parseArgs } from "node:util";
5
+
6
+ const PROFILE = new URL("../assets/junior-v1.json", import.meta.url);
7
+ const ENDPOINT = "https://ai-gateway.vercel.sh/v4/ai/speech-model";
8
+ const HELP = `Generate Gemini speech through Junior's host-managed AI Gateway key.
9
+ node scripts/speech.mjs --text-file FILE --output FILE.wav [--delivery playful|plain]
10
+ node scripts/speech.mjs --sample --output FILE.wav
11
+ node scripts/speech.mjs --profile
12
+
13
+ Paid requests are not retried. Existing output files are never overwritten.
14
+ No API key argument is accepted.`;
15
+
16
+ /** Decode and check Gateway WAV audio before making it available for delivery. */
17
+ export function decodeAudio(result) {
18
+ if (
19
+ typeof result.audio !== "string" ||
20
+ !result.audio.length ||
21
+ !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(
22
+ result.audio,
23
+ )
24
+ ) {
25
+ throw new Error("Gateway did not return valid base64 audio.");
26
+ }
27
+ const audio = Buffer.from(result.audio, "base64");
28
+ if (
29
+ audio.length <= 44 ||
30
+ audio.toString("ascii", 0, 4) !== "RIFF" ||
31
+ audio.toString("ascii", 8, 12) !== "WAVE"
32
+ ) {
33
+ throw new Error("Gateway did not return a WAV file.");
34
+ }
35
+ if (audio.readUInt32LE(4) + 8 !== audio.length) {
36
+ throw new Error("Gateway returned an incomplete WAV file.");
37
+ }
38
+ return audio;
39
+ }
40
+
41
+ /** Generate a single clip; style stays separate from the spoken text. */
42
+ export async function generateSpeech(text, output, delivery = "playful") {
43
+ if (!text.trim() || [...text].length > 5000) {
44
+ throw new Error(
45
+ "Use 1–5000 characters per clip. Split longer narration into scenes.",
46
+ );
47
+ }
48
+ if (!["playful", "plain"].includes(delivery))
49
+ throw new Error("Choose playful or plain delivery.");
50
+ if (!output.endsWith(".wav"))
51
+ throw new Error("Output must have a .wav extension.");
52
+ const profile = JSON.parse(await readFile(PROFILE, "utf8"));
53
+ const instructions =
54
+ delivery === "plain"
55
+ ? "Speak warmly, clearly, and calmly, like a capable adult teammate. Use natural conversational pacing. No snark, jokes, teasing, or dramatic performance. Read only the supplied text."
56
+ : profile.instructions;
57
+ const path = resolve(output);
58
+ const file = await open(path, "wx", 0o600);
59
+ let completed = false;
60
+ try {
61
+ // The plugin's host proxy supplies Authorization. Never read a key here.
62
+ const response = await fetch(ENDPOINT, {
63
+ method: "POST",
64
+ redirect: "error",
65
+ signal: AbortSignal.timeout(120_000),
66
+ headers: {
67
+ "Content-Type": "application/json",
68
+ "ai-gateway-protocol-version": "0.0.1",
69
+ "ai-speech-model-specification-version": "4",
70
+ "ai-model-id": profile.model,
71
+ },
72
+ body: JSON.stringify({
73
+ text,
74
+ voice: profile.voice,
75
+ instructions,
76
+ outputFormat: "wav",
77
+ }),
78
+ });
79
+ if (!response.ok) {
80
+ await response.body?.cancel();
81
+ const hint =
82
+ response.status === 401 || response.status === 403
83
+ ? "Check the host-side AI_GATEWAY_API_KEY and team speech access."
84
+ : response.status === 402
85
+ ? "Check Gateway credits and spending limits."
86
+ : response.status === 404
87
+ ? "Check Gemini TTS availability for the Gateway team."
88
+ : "Check Gateway usage and provider status.";
89
+ throw new Error(`Gateway HTTP ${response.status}. ${hint}`);
90
+ }
91
+ let result;
92
+ try {
93
+ result = await response.json();
94
+ } catch {
95
+ // JSON parse errors can quote provider response data. Keep it out of logs.
96
+ throw new Error("Gateway did not return a valid speech response.");
97
+ }
98
+ // Unsupported delivery options must not silently produce the wrong voice.
99
+ if (Array.isArray(result.warnings) && result.warnings.length) {
100
+ throw new Error(
101
+ "Gateway returned speech warnings. Review model support before generating again.",
102
+ );
103
+ }
104
+ const audio = decodeAudio(result);
105
+ await file.writeFile(audio);
106
+ completed = true;
107
+ return {
108
+ path,
109
+ bytes: audio.length,
110
+ mimeType: "audio/wav",
111
+ model: profile.model,
112
+ voice: profile.voice,
113
+ profile: profile.name,
114
+ delivery,
115
+ synthetic: true,
116
+ };
117
+ } catch (error) {
118
+ throw new Error(
119
+ "Speech did not finish locally. Credits may have been used. Check Gateway usage before retrying; no automatic retry was made.",
120
+ { cause: error },
121
+ );
122
+ } finally {
123
+ await file.close();
124
+ if (!completed) await unlink(path);
125
+ }
126
+ }
127
+
128
+ /** Parse the bounded speech CLI, including the bundled sample and profile. */
129
+ export async function run(args) {
130
+ const { values } = parseArgs({
131
+ args,
132
+ options: {
133
+ "text-file": { type: "string" },
134
+ output: { type: "string" },
135
+ delivery: { type: "string" },
136
+ sample: { type: "boolean" },
137
+ profile: { type: "boolean" },
138
+ help: { type: "boolean" },
139
+ },
140
+ });
141
+ if (values.help) return { help: HELP };
142
+ if (values.profile) {
143
+ if (Object.keys(values).length !== 1)
144
+ throw new Error("Use --profile alone.");
145
+ return JSON.parse(await readFile(PROFILE, "utf8"));
146
+ }
147
+ if (
148
+ !values.output ||
149
+ Boolean(values.sample) === Boolean(values["text-file"])
150
+ ) {
151
+ throw new Error(
152
+ "Provide --output and exactly one of --sample or --text-file.",
153
+ );
154
+ }
155
+ const source = values.sample
156
+ ? new URL("../assets/sample.txt", import.meta.url)
157
+ : values["text-file"];
158
+ return generateSpeech(
159
+ await readFile(source, "utf8"),
160
+ values.output,
161
+ values.delivery,
162
+ );
163
+ }
164
+
165
+ if (
166
+ process.argv[1] &&
167
+ import.meta.url === pathToFileURL(resolve(process.argv[1])).href
168
+ ) {
169
+ try {
170
+ console.log(JSON.stringify(await run(process.argv.slice(2)), null, 2));
171
+ } catch (error) {
172
+ console.error(error.message);
173
+ if (error.cause instanceof Error) console.error(error.cause.message);
174
+ process.exitCode = 1;
175
+ }
176
+ }