@skaile/forge-voice 0.0.0-stage → 0.1.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/CHANGELOG.md +20 -0
- package/LICENSE +21 -0
- package/README.md +329 -2
- package/dist/browser/index.d.mts +2102 -0
- package/dist/browser/index.mjs +5808 -0
- package/dist/browser/index.mjs.map +1 -0
- package/dist/h3/index.d.mts +26 -0
- package/dist/h3/index.mjs +234 -0
- package/dist/h3/index.mjs.map +1 -0
- package/dist/index.d.mts +138 -0
- package/dist/index.mjs +1 -0
- package/dist/relay.d.mts +345 -0
- package/dist/relay.mjs +1194 -0
- package/dist/relay.mjs.map +1 -0
- package/dist/server/index.d.mts +57 -0
- package/dist/server/index.mjs +1 -0
- package/dist/speech-terms.d.mts +237 -0
- package/dist/wire.mjs +792 -0
- package/dist/wire.mjs.map +1 -0
- package/package.json +90 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# @skaile/forge-voice
|
|
2
|
+
|
|
3
|
+
## 0.1.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- c981694: Steer: push a message into the agent's running turn instead of waiting for it to end.
|
|
8
|
+
|
|
9
|
+
- `@skaile/forge-agent-runtime`: the app runner host's `POST /runs/:id/commands` accepts `steer` (`promptId`, `text`, `urgency` `fold`/`now`, optional `author`, `turnId`; `meta` and anything else are dropped). The run answers with a `steer_result` event.
|
|
10
|
+
- `@skaile/forge-chat`: `ChatSession.steer(text, urgency = 'fold')` sends into the running turn and shows the text as a user message at once (while idle it is `send`); `ChatSession.canSteer` says whether the transport can. New optional `ChatTransport.steer` and `SkaileLink.steer`; `mapSkaileEvent` maps `steer_result` to the new `steer-result` stream event (the reducer ignores it); `createWorkspacesClientLink` steers and resends an `unsupported` steer as a prompt (after a `cancel` for `now`). `useChat()` exposes `steer`. New types `ChatSteerUrgency`, `ChatSteerOutcome`.
|
|
11
|
+
- `@skaile/forge-layer-workspace-agent`: new action `workspaceAgent.steer { threadId, text, urgency }` (people only, scope `agents:write`), used by the `skaile` engine's link. A run whose `protocol_info` lists `steer.v1` gets a real `steer`; otherwise (the `omp` harness today) `fold` goes out as a queued prompt and `now` cancels the turn and goes out as a prompt the runner runs right after it. `steer_result` and `prompt_ack` reach the tabs and are not stored.
|
|
12
|
+
- `@skaile/forge-voice`: the README shows a `ConversationPort` over a forge-chat session that steers in `skaile` mode and falls back to `withSteerFallback` in `byok`.
|
|
13
|
+
|
|
14
|
+
## 0.1.0
|
|
15
|
+
|
|
16
|
+
### Minor Changes
|
|
17
|
+
|
|
18
|
+
- b7e7fab: New entry `@skaile/forge-voice/browser`: the headless browser engine of the platform's Talk, moved without behaviour change. `PipelineVoiceLayer` (behind the `VoiceLayer` seam) captures the microphone as 16 kHz PCM (an AudioWorklet node, `createWorkletCaptureNode`, or a ScriptProcessor), decides when an utterance is finished and sends it eagerly before that, detects barge-in by voice and by words, filters its own voice out of the transcript, re-transcribes an utterance whose language it doubts, and speaks a reply as it streams (over the relay's TTS socket, else clip by clip), with time-stretch for faster or slower speech. It reaches the relay only through the `SpeechTransport` port; `createRelayTransport({ baseUrl, paths?, scope?, getToken?, fetch?, WebSocket? })` implements it for wire protocol v1. Also exported: level calibration and envelope for visuals, audio route and headphone detection, turn latency records and their report, and the diagnostic sink (`createTalkDiagSink`, lengths, ids and reasons only).
|
|
19
|
+
- d535c8f: First release of `@skaile/forge-voice`, the headless voice package. The root entry has the shared speech types and pure text logic: wire protocol v1 (the frames of the speech-to-text and text-to-speech sockets and the re-transcription and clip routes), spoken languages, speech terms with the Deepgram keyterm budget (`buildKeyterms`), audio tags, stop phrases, utterance-end holds and spoken sentences. `@skaile/forge-voice/server` is a framework-free relay (`createVoiceRelay`) between the browser and Deepgram (live speech to text, re-transcription) and ElevenLabs (streamed speech, clips): the host's `authorize` hook decides who may use voice and with which keys, per-principal stream caps, and privacy it enforces itself (`mip_opt_out=true` and `enable_logging=false` set last on every provider URL, keys redacted from every frame and log line, no content logged, the WebSocket Origin check fails closed). `@skaile/forge-voice/h3` serves all four routes from one h3 / Nitro handler (`defineVoiceRelayRoutes`).
|
|
20
|
+
- 3c95734: `createTalk` in `@skaile/forge-voice/browser`: the turn-taking Talk session on top of the browser engine, moved from the platform without behaviour change. It decides what to send for each utterance (eagerly, folded into the running turn, restarting it with the whole request, or cutting the reply), speaks the reply as it streams, marks what the user heard of a reply they cut off, plays fillers while a slow answer is on its way, and applies spoken speed and language commands. The host connects its agent through a `ConversationPort` and may plug in a `TalkInterceptor` that speaks its own questions and claims the answers. `talkPhase` folds the session's state into one phase for a UI; `withSteerFallback` wraps a port whose agent cannot take messages into a running turn. Also exported: the filler scheduler and clip cache, the speed and speak-language helpers, and optional setters on the `VoiceLayer` seam (`setVoice`, `setPlaybackRate`, `switchToLanguage`, …).
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Matthias Ortegro
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,330 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @skaile/forge-voice
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Headless voice for skaile apps: speech in (Deepgram) and speech out (ElevenLabs) through a relay
|
|
4
|
+
that holds the provider keys on the server. The package ships state, types and protocol, never UI:
|
|
5
|
+
each app draws its own controls.
|
|
6
|
+
|
|
7
|
+
It has the shared text logic, the wire protocol, the server relay, the browser engine (capture,
|
|
8
|
+
voice activity and barge-in, echo filter, streamed playback) and, on top of the engine, the
|
|
9
|
+
turn-taking Talk session (`createTalk`): a full-duplex voice conversation with the host's agent.
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
bun add @skaile/forge-voice
|
|
13
|
+
bun add ws # the relay's default upstream dialer (optional peer)
|
|
14
|
+
bun add h3 # only for @skaile/forge-voice/h3 (optional peer)
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Entry points
|
|
18
|
+
|
|
19
|
+
| Import | Runs on | Contents |
|
|
20
|
+
| --- | --- | --- |
|
|
21
|
+
| `@skaile/forge-voice` | browser and server | Wire protocol v1 frame types and constants; spoken languages (`STT_LANGUAGES`, `parseSttLanguage`, `ttsLanguageCode`); speech terms and the keyterm budget (`buildKeyterms`, `estimateKeytermTokens`); audio tags (`stripAudioTags`, `toElevenLabsTags`, …); stop phrases, utterance-end holds, spoken sentences, spoken-language defaults |
|
|
22
|
+
| `@skaile/forge-voice/browser` | browser (every DOM dependency injected or read at call time) | `createTalk` → `TalkSession`, `talkPhase`, `withSteerFallback`, the ports (`ConversationPort`, `TalkInterceptor`); fillers (`AckScheduler`, `AckClipCache`, `ToolDurations`, phrases), speed and language helpers (`talkSpeedAfter`, `TALK_SPEEDS`, `parseTalkSpeakLanguages`, …); `PipelineVoiceLayer` and the `VoiceLayer` seam; `createRelayTransport` and the `SpeechTransport` port; `RealtimeTtsStream`; the capture worklet (`createWorkletCaptureNode`); PCM, VAD and barge-in, echo filter, noise gate, level calibration and envelope, time-stretch, sticky language, eager send, speakable chunker, speech aliases, audio route, turn latency (record and report), the diag sink (`createTalkDiagSink`) |
|
|
23
|
+
| `@skaile/forge-voice/server` | Node ≥ 22, no framework | `createVoiceRelay(config, host)`, `relayRequest(...)`, the URL builders `buildDeepgramUrl` / `buildElevenLabsUrl`, `withoutKey`, `formatAuditLine`, socket shims (`wsRelaySocket`, `wsDialer`) |
|
|
24
|
+
| `@skaile/forge-voice/h3` | h3 1.x / Nitro | `defineVoiceRelayRoutes(relay)`: one event handler for all four routes |
|
|
25
|
+
|
|
26
|
+
ESM only. A CommonJS host (NestJS compiled to CommonJS) loads `dist/server/index.mjs` through Node's
|
|
27
|
+
`require(esm)`; the package has no top-level await. For linking a checkout, each export has a
|
|
28
|
+
`forge-voice-source` condition pointing at the TypeScript source.
|
|
29
|
+
|
|
30
|
+
## Ports: what the host provides
|
|
31
|
+
|
|
32
|
+
The relay decides nothing about who may speak. Everything that is policy comes in through the host:
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
import { createVoiceRelay } from '@skaile/forge-voice/server'
|
|
36
|
+
|
|
37
|
+
const relay = createVoiceRelay(
|
|
38
|
+
{ allowedOrigins: ['https://app.example'] },
|
|
39
|
+
{
|
|
40
|
+
// Once per request, before any provider is contacted. Return a grant or a refusal.
|
|
41
|
+
async authorize(req) {
|
|
42
|
+
const user = await userFromToken(req.token) // or cookies in req.headers / req.context
|
|
43
|
+
if (!user) return { refuse: 401 }
|
|
44
|
+
if (!(await voiceAllowed(user, req.scope))) return { refuse: 403, code: 'ADD_ON_DISABLED' }
|
|
45
|
+
return {
|
|
46
|
+
principalId: user.id, // caps count per principal
|
|
47
|
+
deepgram: { apiKey: () => keys.deepgram(user), host: 'api.eu.deepgram.com', model: 'nova-3', defaultLanguage: 'auto' },
|
|
48
|
+
elevenlabs: {
|
|
49
|
+
apiKey: process.env.ELEVENLABS_API_KEY!,
|
|
50
|
+
voiceId: 'JBFqnCBsd6RMkjVDRZzb',
|
|
51
|
+
models: { stream: 'eleven_v4_turbo', clip: 'eleven_multilingual_v2', clipFast: 'eleven_flash_v2_5' },
|
|
52
|
+
},
|
|
53
|
+
keyterms: async language => termsFor(user, language), // already filtered by your opt-in rules
|
|
54
|
+
}
|
|
55
|
+
},
|
|
56
|
+
limits: { stt: { maxConcurrent: 5 } }, // optional overrides
|
|
57
|
+
audit: line => log.warn(line), // optional; default logger.warn(formatAuditLine(line))
|
|
58
|
+
},
|
|
59
|
+
)
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
| Port | Shape | Notes |
|
|
63
|
+
| --- | --- | --- |
|
|
64
|
+
| `authorize(req)` | `RelayRequest → VoiceGrant \| RelayRefusal` | `req` has `kind`, `origin`, `token` (`?token=` or a bearer header), `headers`, `scope` (every query parameter, or `speak` body field, the relay does not read itself: `sessionId`, `spaceId`, …), the raw `language`, and the adapter's `context` |
|
|
65
|
+
| `VoiceGrant.*.apiKey` | `string` or `() => Promise<string \| null>` | A function is read only after the concurrency cap passed; `null` answers 501 |
|
|
66
|
+
| `VoiceGrant.deepgram.host` | bare host | No default: pass your region (`api.eu.deepgram.com`). Must match `allowedHosts.deepgram` (default `*.deepgram.com`) |
|
|
67
|
+
| `VoiceGrant.keyterms` | `(language) => Promise<string[]>` | Gets the stream language (`multi` = every language) or `null` for a detecting re-transcription; a rejection streams without keyterms. Build the list with `buildKeyterms` to stay inside Deepgram's token budget |
|
|
68
|
+
| `config.dial` | `(url, headers) => UpstreamSocket` | Default: `ws`. `wsDialer(WebSocket)` makes one from an imported `ws` (bundlers that do not trace `require`) |
|
|
69
|
+
| `config.fetch` | `typeof fetch` | Default: the global `fetch` |
|
|
70
|
+
| `RelaySocket` | `send`, `close`, `onMessage`, `onClose` | The browser socket; `wsRelaySocket(ws)` wraps a `ws` socket, the h3 entry wraps crossws peers |
|
|
71
|
+
|
|
72
|
+
### Serving the routes
|
|
73
|
+
|
|
74
|
+
**h3 / Nitro** (`experimental: { websocket: true }` in the Nitro config):
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
// server/routes/voice/[...].ts
|
|
78
|
+
import { defineVoiceRelayRoutes } from '@skaile/forge-voice/h3'
|
|
79
|
+
import { relay } from '../../utils/voice-relay'
|
|
80
|
+
|
|
81
|
+
export default defineVoiceRelayRoutes(relay)
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
`authorize` then gets `req.context = { request, event? }`: the web `Request` (cookies, headers), and on
|
|
85
|
+
the HTTP routes the `H3Event`.
|
|
86
|
+
|
|
87
|
+
**Any other server** calls the relay itself. For the WebSocket routes, admit before the upgrade so a
|
|
88
|
+
refusal is an HTTP status, then hand the socket over:
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
import { createVoiceRelay, isRelayRefusal, relayRequest, wsRelaySocket } from '@skaile/forge-voice/server'
|
|
92
|
+
|
|
93
|
+
server.on('upgrade', async (req, socket, head) => {
|
|
94
|
+
const url = new URL(req.url ?? '', 'http://localhost')
|
|
95
|
+
if (url.pathname !== '/voice/transcribe-stream') return
|
|
96
|
+
const admitted = await relay.admit(relayRequest({ kind: 'stt', url, headers: req.headers, context: req }))
|
|
97
|
+
if (isRelayRefusal(admitted)) return void socket.end(`HTTP/1.1 ${admitted.refuse} Refused\r\n\r\n`)
|
|
98
|
+
wss.handleUpgrade(req, socket, head, ws => relay.stt(wsRelaySocket(ws), admitted))
|
|
99
|
+
})
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Give the TTS socket server `maxPayload: TTS_MAX_CLIENT_FRAME_BYTES` (64 KiB), so an oversized
|
|
103
|
+
client frame is refused before it is buffered; the h3 entry closes such a frame with 1009, but only
|
|
104
|
+
after crossws has received it (crossws has no per-route limit). Read HTTP bodies with a size cap
|
|
105
|
+
(`limits.retranscribe.maxBytes`) before calling the relay, as the h3 entry does.
|
|
106
|
+
|
|
107
|
+
An admission holds a slot under the principal's cap; it is freed when the stream closes, by
|
|
108
|
+
`admitted.release()` if the upgrade fails, or after 10 s if it is never handed over.
|
|
109
|
+
`relay.retranscribe(req, pcm)` and `relay.speak(req, body)` answer the HTTP routes with
|
|
110
|
+
`{ ok: true, value }` or `{ ok: false, status, message, code?, retryAfterS? }`.
|
|
111
|
+
|
|
112
|
+
## Browser engine
|
|
113
|
+
|
|
114
|
+
`PipelineVoiceLayer` runs one side of a voice conversation: one 16 kHz PCM capture feeds the speech-to-text
|
|
115
|
+
socket, a pre-open buffer and a re-transcription ring; replies play through WebAudio, so playback end,
|
|
116
|
+
output latency and the output level share the clock of the user's speech. It decides when an utterance
|
|
117
|
+
is finished (and sends it eagerly before that), detects barge-in by voice and by words, filters its own
|
|
118
|
+
voice out of the transcript, and speaks a reply as it streams. It knows no URLs, scopes or credentials:
|
|
119
|
+
it reaches the relay through a `SpeechTransport`.
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
import { createRelayTransport, createWorkletCaptureNode, PipelineVoiceLayer } from '@skaile/forge-voice/browser'
|
|
123
|
+
|
|
124
|
+
const transport = createRelayTransport({
|
|
125
|
+
baseUrl: 'https://api.example.com', // HTTP routes are appended; sockets go to this host
|
|
126
|
+
scope: () => ({ spaceId }), // opaque, on every request
|
|
127
|
+
getToken: async () => auth.token(), // bearer in ?token= on the sockets; omit for a cookie
|
|
128
|
+
fetch: (url, init) => authedFetch(url, init), // optional, default: global fetch
|
|
129
|
+
})
|
|
130
|
+
|
|
131
|
+
const layer = new PipelineVoiceLayer(
|
|
132
|
+
{
|
|
133
|
+
transport,
|
|
134
|
+
getUserMedia: c => navigator.mediaDevices.getUserMedia(c),
|
|
135
|
+
createAudioContext: () => new AudioContext(),
|
|
136
|
+
createCaptureNode: createWorkletCaptureNode, // falls back to a ScriptProcessor without it
|
|
137
|
+
storage: localStorage, // the device's home language; optional
|
|
138
|
+
diag: (event, fields) => sink.log(event, fields), // lengths, ids and reasons only
|
|
139
|
+
},
|
|
140
|
+
{ voiceId, speakLanguages: ['de', 'en'], deviceLocale: navigator.language },
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
layer.on('utterance', u => u.final && !u.hush && agent.send(u.text))
|
|
144
|
+
layer.on('bargeIn', b => agent.noteHeard(b.turnId, b.heardChars))
|
|
145
|
+
await layer.start()
|
|
146
|
+
layer.speak(turnId, replyDeltas) // AsyncIterable<string> or a whole string
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
| Port | Shape | Notes |
|
|
150
|
+
| --- | --- | --- |
|
|
151
|
+
| `SpeechTransport` | `socketCredential()`, `openStt(query, credential)`, `openTtsStream(query, credential)`, `retranscribe(pcm, query, signal)`, `speakClip(body, signal?)` | Sockets open synchronously after the credential is fetched; the HTTP calls return the raw `Response`. `createRelayTransport` speaks wire protocol v1; `paths` moves the routes |
|
|
152
|
+
| `PipelineVoiceDeps` | `getUserMedia`, `createAudioContext`, `transport`, `createCaptureNode?`, `timers?`, `createId?`, `storage?`, `storageKeys?`, `diag?`, `nowMs?` | Fakes for all of them drive the tests |
|
|
153
|
+
| `PipelineVoiceOptions` | `voiceId`, `pinnedLanguage`, `speakLanguages`, `audioMode`, `headphones`, `pushToTalk`, `speakerHush`, `realtimeTts`, `playbackRate`, `speechTerms`, … | Changed later through the layer's setters (`setVoice`, `setPlaybackRate`, `setSpeakLanguages`, …) |
|
|
154
|
+
| Storage keys | `LanguageHome` (`skaile.talk.language-*.v1`), level peaks (`skaile.talk.level-peaks.v1`), tool durations (`skaile.talk.toolDurations`, through `createTalk`'s `storage`); the host's own helpers: default speed (`skaile:talk:default-speed`), speak languages (`skaile:talk:speak-languages`), headphones toggle (host key) | The defaults keep what devices stored before the move |
|
|
155
|
+
|
|
156
|
+
The engine emits `utterance`, `partial`, `bargeIn`, `dropped`, `state`, `language` and `replyStage`.
|
|
157
|
+
Levels for a visual: `layer.levels.mic()` / `.output()` (raw RMS) and `TalkLevelCalibration` (0..1 per
|
|
158
|
+
device and voice).
|
|
159
|
+
|
|
160
|
+
## Talk session
|
|
161
|
+
|
|
162
|
+
`createTalk` runs a voice conversation with the host's agent on top of the engine. It decides what
|
|
163
|
+
to send for each utterance: an eager send before the user finished, words folded into the running
|
|
164
|
+
turn, the whole request again when the user went on before any of the answer was heard, or a new
|
|
165
|
+
message that cuts the reply. It speaks the reply as it streams (holding back what looks like a note
|
|
166
|
+
the agent wrote to itself between tool calls), marks what the user heard of a reply they cut off,
|
|
167
|
+
plays a short filler while a slow answer is on its way, and applies spoken speed and language
|
|
168
|
+
commands ("faster", "sprich Englisch"). It ships state and events; the host draws the orb, captions
|
|
169
|
+
and buttons.
|
|
170
|
+
|
|
171
|
+
```ts
|
|
172
|
+
import { createRelayTransport, createTalk, talkPhase, withSteerFallback } from '@skaile/forge-voice/browser'
|
|
173
|
+
|
|
174
|
+
const talk = createTalk({
|
|
175
|
+
conversation: withSteerFallback(myConversationPort), // drop the wrapper if your agent can steer (see below)
|
|
176
|
+
speech: createRelayTransport({ baseUrl: '/api', scope: () => ({ spaceId }) }),
|
|
177
|
+
storage: localStorage, // home language, tool durations; optional
|
|
178
|
+
voice: { voiceId, speakLanguages: ['de', 'en'], deviceLocale: navigator.language },
|
|
179
|
+
audio: { pauseInBackground: isIphone },
|
|
180
|
+
diag: (event, fields) => sink.log(event, fields), // lengths, ids and reasons only
|
|
181
|
+
})
|
|
182
|
+
|
|
183
|
+
const off = talk.subscribe(() => render(talkPhase(talk.state), talk.state.layer.speakingText))
|
|
184
|
+
talk.on('speed', (_command, rate) => saveSpeed(rate))
|
|
185
|
+
await talk.start() // rejects when the mic cannot open
|
|
186
|
+
// later: talk.tapInterrupt(), talk.muteMic(), talk.resume(), talk.set({ voiceId }), talk.stop(), talk.dispose()
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
### The conversation port
|
|
190
|
+
|
|
191
|
+
The session reaches the agent only through a `ConversationPort` the host implements:
|
|
192
|
+
|
|
193
|
+
| Member | Shape | Notes |
|
|
194
|
+
| --- | --- | --- |
|
|
195
|
+
| `send(message)` | `TalkOutgoing → Promise<string \| undefined>` | `{ text, utteranceId, final, language?, continuation?, steer? }`. Resolves with the host's prompt id, if it has one. `final: false` is an eager send; a later send with the same `utteranceId` supersedes it. `steer` is set while a turn runs: `now` replaces the turn, `fold` is read at its next step. `continuation: 'restart'` says the message repeats and replaces a cut-off start, `fold` that it goes on with the previous one. A rejection is retried once unless `describeSendError` calls it refused |
|
|
196
|
+
| `cancelTurn()` | `void` | Ends the running turn, keeping what streamed (a hush, a tap that is not followed by words) |
|
|
197
|
+
| `markInterrupted(mark)` | `TalkMarkInterrupted → Promise<{ marked }>` | What the user heard of a cut reply (`lastHeardSentence`, `heardChars`, or `replyStart` when nothing was heard), so the agent's next turn knows. `marked: false` is sent again as `phase: 'settle'` once the turn ended. A host that stores nothing resolves `{ marked: true }` |
|
|
198
|
+
| `describeSendError?(error)` | `→ { code, refused }` | The code goes to the diagnostic log; a refused send is not retried |
|
|
199
|
+
| `subscribe(listener)` | `ConversationEvent` | `turn{running}`, then the reply as `text{text}` (the text so far) or `delta{delta, segmentStart?}`, `toolStarted{name?, subagent?}`, `toolEnded{name?, subagent?}`, `turnEnded{outcome?}`. Emit synchronously, in order |
|
|
200
|
+
|
|
201
|
+
Name each tool in `toolStarted` / `toolEnded`: the fillers learn per name which tools return fast,
|
|
202
|
+
and an end without a name is ignored.
|
|
203
|
+
|
|
204
|
+
An agent that cannot take a message into a running turn: wrap the port in `withSteerFallback(port)`.
|
|
205
|
+
A `now` send then cancels the turn, waits for it to end (5 s at most) and goes out as a new message;
|
|
206
|
+
a `fold` send is held until the turn ends. Held words are sent once: a `now` message carries those it
|
|
207
|
+
does not already repeat, and `cancelTurn` (a hush, a tap) drops them with the turn.
|
|
208
|
+
|
|
209
|
+
#### A forge app: real steer in `skaile` mode, the fallback in `byok`
|
|
210
|
+
|
|
211
|
+
A `@skaile/forge-chat` session steers when its transport does (`session.canSteer`): the `skaile`
|
|
212
|
+
engine of `@skaile/forge-layer-workspace-agent` sends `workspaceAgent.steer`, and the server picks
|
|
213
|
+
the way (a real `steer` where the run's harness takes one; otherwise a queued prompt for `fold`, and
|
|
214
|
+
a cancel and resend for `now`). The AI SDK transport of `byok` has no `steer`, so that port goes through
|
|
215
|
+
`withSteerFallback`. The send side of such a port:
|
|
216
|
+
|
|
217
|
+
```ts
|
|
218
|
+
import type { ChatSession } from '@skaile/forge-chat'
|
|
219
|
+
import type { ConversationPort } from '@skaile/forge-voice/browser'
|
|
220
|
+
import { withSteerFallback } from '@skaile/forge-voice/browser'
|
|
221
|
+
|
|
222
|
+
function chatConversation(session: ChatSession, subscribe: ConversationPort['subscribe']): ConversationPort {
|
|
223
|
+
// `send` is false for a turn the barge-in cancelled too (AI SDK): only a real error may be retried.
|
|
224
|
+
const failed = () => {
|
|
225
|
+
const error = session.state.get().error
|
|
226
|
+
if (error) throw new Error(error)
|
|
227
|
+
return undefined
|
|
228
|
+
}
|
|
229
|
+
const port: ConversationPort = {
|
|
230
|
+
async send({ text, steer }) {
|
|
231
|
+
if (steer && session.canSteer) {
|
|
232
|
+
const sent = await session.steer(text, steer) // shown in the transcript at once
|
|
233
|
+
return sent ? sent.promptId : failed()
|
|
234
|
+
}
|
|
235
|
+
return (await session.send(text)) ? undefined : failed()
|
|
236
|
+
},
|
|
237
|
+
cancelTurn: () => void session.abort(),
|
|
238
|
+
markInterrupted: async () => ({ marked: true }), // or add "the user heard up to: …" to the next prompt
|
|
239
|
+
subscribe, // turn / text / toolStarted / toolEnded / turnEnded from the session's events
|
|
240
|
+
}
|
|
241
|
+
// Without steer a send while the turn runs would be refused: hold or cancel-and-resend it instead.
|
|
242
|
+
return session.canSteer ? port : withSteerFallback(port)
|
|
243
|
+
}
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
`session.steer` while no turn runs is a plain `send`. The skaile server answers a real steer with a
|
|
247
|
+
`steer-result` event (`steered`, `started_turn`, or `unsupported`, which it has already resent as a
|
|
248
|
+
prompt), which the session hands to `onEvent`.
|
|
249
|
+
|
|
250
|
+
### Options and controls
|
|
251
|
+
|
|
252
|
+
| Option | Notes |
|
|
253
|
+
| --- | --- |
|
|
254
|
+
| `speech` | A `SpeechTransport` (the session builds a `PipelineVoiceLayer` on the browser's mic and WebAudio), or `{ layer, transport? }` for a ready `VoiceLayer` (native, tests); `transport` then only serves the filler clips |
|
|
255
|
+
| `interceptor` | A host extension (below) |
|
|
256
|
+
| `voice` | `voiceId`, `speed`, `speakLanguages`, `pinnedLanguage`, `conversationLocale`, `lastUtteranceLanguage`, `deviceLocale`, `speechTerms` |
|
|
257
|
+
| `audio` | `mode`, `headphones`, `pushToTalk`, `speakerHush`, `realtimeTts`, `pauseInBackground` |
|
|
258
|
+
| `fillers` | `{ enabled?, phrases?, clips?, durations? }`, `false`, or your own `TalkFillers`. Clips are spoken once through `transport.speakClip` and cached (`clips` shares a cache across sessions); built-in phrases in eight languages |
|
|
259
|
+
| `commands` | `{ speed?, language? }`, both on by default; a command is never sent |
|
|
260
|
+
| `storage`, `storageKeys` | The device's home language and tool durations; nothing is stored without `storage` |
|
|
261
|
+
| `browser` | `getUserMedia`, `createAudioContext`, `createCaptureNode`, `timers`, `createId`, `now`, `nowMs`, `random` |
|
|
262
|
+
|
|
263
|
+
`TalkSession`: `state` (`TalkSnapshot`: `active`, `layer` with `listening` / `speaking` / `speakingText`
|
|
264
|
+
/ `error` / `micMuted` / …, `partial`, `unsupportedLanguage`, `turnRunning`, `promptIds`, `paused`),
|
|
265
|
+
`subscribe`, `on(event)` for `utterance`, `bargeIn`, `dropped`, `language`, `replyStage`, `speed`,
|
|
266
|
+
`languageCommand`, `turnLatency`; `start`, `stop`, `dispose`, `muteMic`, `resume`, `pageHidden`,
|
|
267
|
+
`pageVisible`, `tapInterrupt`, `pressTalk`, `releaseTalk`, `expectReplyToTypedSend(promptIdPromise)`
|
|
268
|
+
(a message typed while Talk runs: its reply is spoken), `set({ voiceId, speed, speakLanguages, language,
|
|
269
|
+
languageContext, audioMode, headphones, pushToTalk, speechTerms })`, `speed`, `levels`, `layer`.
|
|
270
|
+
`talkPhase(state)` folds the snapshot into `idle`, `listening`, `userSpeaking`, `thinking`, `speaking`,
|
|
271
|
+
`paused` or `error`.
|
|
272
|
+
|
|
273
|
+
### Host extensions
|
|
274
|
+
|
|
275
|
+
A `TalkInterceptor` lets the host speak its own questions in the conversation and take the answers
|
|
276
|
+
before they reach the agent (an approval flow, an offer). It gets a `TalkInterceptorApi` on
|
|
277
|
+
`attach`: `ask(turnId, text)` speaks a question in one of Talk's turns (no filler follows it, and an
|
|
278
|
+
answer never continues the request), `say(id, text)` speaks a sentence under its own id, `turns`
|
|
279
|
+
(a frozen array of read-only views, read afresh each time; each view is live and stays the same
|
|
280
|
+
object for its turn), `state`, `spokenLanguage`, `lastSpokenAtMs`,
|
|
281
|
+
`interruptedTurnId`, `suspended`, `now()` and `changed()` (host state next to the snapshot changed).
|
|
282
|
+
As each utterance ends, `utteranceEnded(u)` may return a `TalkHostQuestion`: while one is open eager
|
|
283
|
+
sends wait, and its `claim(text)` takes the final words or lets them go to the agent. `ownsTurn(id)`
|
|
284
|
+
marks speak ids that are the host's own, so cutting them marks nothing.
|
|
285
|
+
|
|
286
|
+
## Wire protocol v1
|
|
287
|
+
|
|
288
|
+
Frozen: a change to a frame is a `### Breaking` changeset and a new `VOICE_WIRE_PROTOCOL_VERSION`.
|
|
289
|
+
Optional fields are additive. The types live in the root entry, so a browser transport and the relay
|
|
290
|
+
share them. Default paths: `VOICE_RELAY_DEFAULT_PATHS`.
|
|
291
|
+
|
|
292
|
+
| Route | Client → relay | Relay → client |
|
|
293
|
+
| --- | --- | --- |
|
|
294
|
+
| `WS /voice/transcribe-stream` `?language&encoding=linear16&<scope>&token?` | binary audio (16 kHz PCM with `linear16`, else a container such as webm/opus); `{type:'stop'}` | `ready`, `speech_started{timestamp?}`, `transcript{transcript,is_final,speech_final,start?,duration?,wordsStart?,wordsEnd?,confidence?,language?}`, `expiring{inMs}`, `error{error}`, `closed`; close 1000 `max-duration` / `idle-timeout`, 1011 `upstream-error` |
|
|
295
|
+
| `WS /voice/speak-stream` `?voiceId&languageCode&<scope>&token?` | `{type:'text',text,flush?}`, `{type:'end'}` (each ≤ 64 KiB) | `ready{sampleRate}`, then per audio piece an optional `alignment{text}` followed by ONE binary PCM s16le frame, `done`, `error{error}`; close 1000 `done`, 1011, 1008 `text-limit` |
|
|
296
|
+
| `POST /voice/retranscribe` `?language&<scope>`, body `audio/l16; rate=16000` ≤ 960,000 B | | `{transcript, language, languageConfidence, confidence}`; 400 / 401 / 403 / 413 / 415 / 429 / 501 / 502 / 504 |
|
|
297
|
+
| `POST /voice/speak` JSON `{text, voiceId?, languageCode?, expressive?, lowLatency?, <scope>}` | | `audio/mpeg` |
|
|
298
|
+
|
|
299
|
+
Defaults of the caps (`DEFAULT_RELAY_LIMITS`, each overridable through `host.limits`): STT 5 streams
|
|
300
|
+
per principal, 10 min with an `expiring` warning 30 s before, 90 s idle; TTS 3 streams, 5 min, 2 min
|
|
301
|
+
idle, a provider keep-alive every 10 s, 10,000 characters; re-transcription 960,000 bytes and 15 s;
|
|
302
|
+
clips 10,000 characters, `expressive` up to 200. The caps are in memory, per process.
|
|
303
|
+
|
|
304
|
+
## Privacy contract
|
|
305
|
+
|
|
306
|
+
What the package enforces itself, pinned by its tests, and no option turns off:
|
|
307
|
+
|
|
308
|
+
- **Provider retention off.** Every Deepgram URL carries `mip_opt_out=true` and every ElevenLabs URL
|
|
309
|
+
`enable_logging=false`, set last by the only URL builders, so a caller-supplied value never wins.
|
|
310
|
+
(ElevenLabs ignores the flag below its enterprise plans; purging its history is the host's job.)
|
|
311
|
+
- **Keys stay server-side.** Keys travel in request headers only, never in a URL; a key is redacted
|
|
312
|
+
(`[redacted]`) from every frame relayed and every line logged, and a dial that fails with the key in
|
|
313
|
+
its error answers fixed text.
|
|
314
|
+
- **No content in logs.** No audio, transcript, reply text or keyterm is logged; the audit lines carry
|
|
315
|
+
ids, sizes, counts and the privacy values read back from the URL actually sent
|
|
316
|
+
(`VOICE_PROVIDER_PRIVACY: Deepgram stream opened: user=… host=… model=… language=… mip_opt_out=true keyterms=3`).
|
|
317
|
+
Provider error bodies that may echo the request are relayed redacted (Deepgram) or not at all (ElevenLabs).
|
|
318
|
+
- **Closed lists for anything in a URL.** Languages come from `STT_LANGUAGES`, the encoding from
|
|
319
|
+
`parseSttEncoding`, voice ids match `^[A-Za-z0-9]+$`; the Deepgram host must be a bare host on the
|
|
320
|
+
allowlist.
|
|
321
|
+
- **Fail closed.** The WebSocket routes refuse a missing or unlisted `Origin`; `authorize` runs before
|
|
322
|
+
any provider contact and gets nothing from the relay. The relay sets no cookies.
|
|
323
|
+
|
|
324
|
+
- **HTTP routes have no Origin check** (they are meant for a bearer token). A host whose `authorize`
|
|
325
|
+
trusts cookies relies on the h3 entry taking `speak` as `application/json` only and `retranscribe`
|
|
326
|
+
as `audio/l16` only, which a cross-site form cannot send without a CORS preflight; keep that
|
|
327
|
+
in any other adapter.
|
|
328
|
+
|
|
329
|
+
What it leaves to the host: who may use voice (add-ons, opt-ins, data zones), which keys pay, rate
|
|
330
|
+
limits beyond the stream caps, and storing nothing it receives.
|