Repository navigation
Voice Call: enforce spoken-output contract and fix stream TTS silence regression - #51500
Conversation
🔒 Aisle Security AnalysisWe found 1 potential security issue(s) in this PR:
1. 🟠 Unbounded CPU consumption in windowed-sinc resampler (telephony-audio) enabling call-triggered DoS
DescriptionThe new
Impact: A caller who can trigger long TTS outputs (e.g., via inbound transcripts influencing auto-responses) can cause high CPU usage and event-loop stalls, degrading or denying service. Vulnerable code (hot loop + bandlimited sampling): const outputSamples = Math.floor(inputSamples / ratio);
const output = Buffer.alloc(outputSamples * 2);
for (let i = 0; i < outputSamples; i++) {
const srcPos = i * ratio;
const sample = Math.round(
sampleBandlimited(input, inputSamples, srcPos, cutoffCyclesPerSample),
);
output.writeInt16LE(clamp16(sample), i * 2);
}RecommendationAdd hard limits to prevent unbounded resampling work, and fail fast when exceeded.
const MAX_SPOKEN_CHARS = 800; // tune for your use-case
const spoken = result.text?.slice(0, MAX_SPOKEN_CHARS) ?? null;
const MAX_TTS_SECONDS = 30;
if (!Number.isFinite(inputSampleRate) || inputSampleRate <= 0) {
throw new Error(`Invalid inputSampleRate: ${inputSampleRate}`);
}
const inputSamples = Math.floor(input.length / 2);
const maxSamples = Math.floor(inputSampleRate * MAX_TTS_SECONDS);
if (inputSamples > maxSamples) {
throw new Error(`PCM too long (${inputSamples} samples)`);
}
These controls prevent an attacker from turning long TTS outputs into CPU/memory exhaustion. Analyzed PR: #51500 at commit Last updated on: 2026-03-21T09:43:55Z |
Greptile SummaryThis PR hardens voice-call reply generation and fixes a silence regression in Twilio streaming calls. The changes span five areas: (1) a JSON spoken-output contract injected into the system prompt with multi-strategy extraction and reasoning/meta-text filtering; (2) state-aware barge-in suppression (tied to Key findings:
Confidence Score: 3/5
Prompt To Fix All With AIThis is a comment left during a code review.
Path: extensions/voice-call/src/response-generator.ts
Line: 77-84
Comment:
**Empty `{"spoken":""}` contract response falls through to plain-text, speaking the raw JSON**
When the model correctly follows the contract and returns `{"spoken":""}` (which the contract explicitly instructs for "nothing to say"), `tryParseSpokenJson` parses the JSON successfully and calls `normalizeSpokenText("")`, which returns `null`. Since `null` is returned, `extractSpokenTextFromPayloads` at line 155–161 treats this as "couldn't parse the JSON contract" and falls through to `sanitizePlainSpokenText(rawText)`.
`sanitizePlainSpokenText` then processes the raw string `{"spoken":""}` as plain conversational text, which passes all filters (it's a single paragraph, not meta-reasoning), and ultimately returns `"{"spoken":""}"` — causing that literal JSON string to be spoken to the caller.
The problem is that `tryParseSpokenJson` conflates two distinct outcomes with a single `null` return:
- **"Successfully parsed the contract but `spoken` is empty"** → caller should hear nothing.
- **"Could not find/parse any JSON contract at all"** → should fall back to plain-text extraction.
Only the second case should trigger the plain-text fallback. A targeted fix is to use a sentinel for "successfully parsed but empty":
```typescript
// In tryParseSpokenJson, before returning normalizeSpokenText(parsed.spoken):
const normalized = normalizeSpokenText(parsed.spoken);
return normalized ?? ""; // "" = "parsed OK, nothing to say"; null = "not a contract"
```
Then in `extractSpokenTextFromPayloads`:
```typescript
const structured = tryParseSpokenJson(rawText);
if (structured !== null) { // null means "not a contract"
if (structured.length > 0) { // "" means "contract says nothing"
spokenSegments.push(structured);
}
continue; // Either way, don't fall through to plain-text
}
// ... plain-text path unchanged
```
The same fix should be applied to the inline-fallback path (line 83–93): `!inlineSpokenMatch?.[1]` currently returns `null` for both "no match" and "matched but group is empty string". For an empty-string match the function should also return `""` rather than `null` so the plain-text fallback is not triggered.
How can I resolve this? If you propose a fix, please make it concise.Last reviewed commit: "voice-call: fix sile..." |
| return normalizeSpokenText(parsed.spoken); | ||
| } catch { | ||
| // Continue trying other candidates. | ||
| } | ||
| } | ||
|
|
||
| const inlineSpokenMatch = trimmed.match(/"spoken"\s*:\s*"((?:[^"\\]|\\.)*)"/i); | ||
| if (!inlineSpokenMatch?.[1]) { |
There was a problem hiding this comment.
Empty
{"spoken":""} contract response falls through to plain-text, speaking the raw JSON
When the model correctly follows the contract and returns {"spoken":""} (which the contract explicitly instructs for "nothing to say"), tryParseSpokenJson parses the JSON successfully and calls normalizeSpokenText(""), which returns null. Since null is returned, extractSpokenTextFromPayloads at line 155–161 treats this as "couldn't parse the JSON contract" and falls through to sanitizePlainSpokenText(rawText).
sanitizePlainSpokenText then processes the raw string {"spoken":""} as plain conversational text, which passes all filters (it's a single paragraph, not meta-reasoning), and ultimately returns "{"spoken":""}" — causing that literal JSON string to be spoken to the caller.
The problem is that tryParseSpokenJson conflates two distinct outcomes with a single null return:
- "Successfully parsed the contract but
spokenis empty" → caller should hear nothing. - "Could not find/parse any JSON contract at all" → should fall back to plain-text extraction.
Only the second case should trigger the plain-text fallback. A targeted fix is to use a sentinel for "successfully parsed but empty":
// In tryParseSpokenJson, before returning normalizeSpokenText(parsed.spoken):
const normalized = normalizeSpokenText(parsed.spoken);
return normalized ?? ""; // "" = "parsed OK, nothing to say"; null = "not a contract"Then in extractSpokenTextFromPayloads:
const structured = tryParseSpokenJson(rawText);
if (structured !== null) { // null means "not a contract"
if (structured.length > 0) { // "" means "contract says nothing"
spokenSegments.push(structured);
}
continue; // Either way, don't fall through to plain-text
}
// ... plain-text path unchangedThe same fix should be applied to the inline-fallback path (line 83–93): !inlineSpokenMatch?.[1] currently returns null for both "no match" and "matched but group is empty string". For an empty-string match the function should also return "" rather than null so the plain-text fallback is not triggered.
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/voice-call/src/response-generator.ts
Line: 77-84
Comment:
**Empty `{"spoken":""}` contract response falls through to plain-text, speaking the raw JSON**
When the model correctly follows the contract and returns `{"spoken":""}` (which the contract explicitly instructs for "nothing to say"), `tryParseSpokenJson` parses the JSON successfully and calls `normalizeSpokenText("")`, which returns `null`. Since `null` is returned, `extractSpokenTextFromPayloads` at line 155–161 treats this as "couldn't parse the JSON contract" and falls through to `sanitizePlainSpokenText(rawText)`.
`sanitizePlainSpokenText` then processes the raw string `{"spoken":""}` as plain conversational text, which passes all filters (it's a single paragraph, not meta-reasoning), and ultimately returns `"{"spoken":""}"` — causing that literal JSON string to be spoken to the caller.
The problem is that `tryParseSpokenJson` conflates two distinct outcomes with a single `null` return:
- **"Successfully parsed the contract but `spoken` is empty"** → caller should hear nothing.
- **"Could not find/parse any JSON contract at all"** → should fall back to plain-text extraction.
Only the second case should trigger the plain-text fallback. A targeted fix is to use a sentinel for "successfully parsed but empty":
```typescript
// In tryParseSpokenJson, before returning normalizeSpokenText(parsed.spoken):
const normalized = normalizeSpokenText(parsed.spoken);
return normalized ?? ""; // "" = "parsed OK, nothing to say"; null = "not a contract"
```
Then in `extractSpokenTextFromPayloads`:
```typescript
const structured = tryParseSpokenJson(rawText);
if (structured !== null) { // null means "not a contract"
if (structured.length > 0) { // "" means "contract says nothing"
spokenSegments.push(structured);
}
continue; // Either way, don't fall through to plain-text
}
// ... plain-text path unchanged
```
The same fix should be applied to the inline-fallback path (line 83–93): `!inlineSpokenMatch?.[1]` currently returns `null` for both "no match" and "matched but group is empty string". For an empty-string match the function should also return `""` rather than `null` so the plain-text fallback is not triggered.
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ded14c6f26
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| throw new Error( | ||
| "Cannot use TwiML fallback while media stream is active; telephony TTS is unavailable", |
There was a problem hiding this comment.
Restore audio fallback for streaming calls without telephony TTS
extensions/voice-call/src/runtime.ts:216-236 still treats “Twilio streaming enabled, but no textToSpeechTelephony runtime” as a supported configuration and only logs that streaming TTS is disabled. After this change, once a stream is registered, playTts() throws here instead of using the existing TwiML <Say> fallback, so every response on those deployments becomes silent whenever telephony TTS is unavailable or fails to initialize.
Useful? React with 👍 / 👎.
| // Clear only after successful playback so transient provider failures can retry. | ||
| if (call.metadata) { | ||
| delete call.metadata.initialMessage; |
There was a problem hiding this comment.
Guard initial greeting against overlapping replay triggers
Clearing metadata.initialMessage only after await speak(...) makes speakInitialMessage() re-entrant. extensions/voice-call/src/webhook.ts calls this on every Twilio stream connect, so if the stream reconnects or a duplicate answered/connect event arrives while the first greeting is still playing, the second invocation still sees initialMessage and queues the same greeting again. Before this change the field was cleared up front, so the duplicate trigger was a no-op.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d5a77fe0af
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if (mode === "conversation") { | ||
| const shouldWaitForStreamConnect = | ||
| this.provider?.name === "twilio" && this.config.streaming.enabled; | ||
| if (shouldWaitForStreamConnect) { | ||
| return; |
There was a problem hiding this comment.
Fall back to answered-time greeting when streaming is unavailable
This now suppresses the outbound conversation greeting whenever provider.name === "twilio" && config.streaming.enabled, but that flag does not guarantee a stream will ever connect. In this same codepath initializeMediaStreaming() can bail out when no OpenAI key is present, and TwilioProvider only emits <Connect><Stream> when it has a public URL; in either case onConnect never fires. Those deployments used to speak the initial message on call.answered, but after this change the callee just gets silence because we wait for a stream that cannot exist.
Useful? React with 👍 / 👎.
| if (suppressBargeIn) { | ||
| console.log( | ||
| `[voice-call] Skipping auto-response while initial message is still playing (${providerCallId})`, | ||
| ); | ||
| return; |
There was a problem hiding this comment.
Drop suppressed transcripts before they reach the call manager
When suppressBargeIn is true, this early return happens only after manager.processEvent(event) has already run above. processManagerEvent() treats that final call.speech as real user input: it appends the transcript and flips the call to listening. The result is that an outbound caller who speaks once during the greeting gets no reply at all—their utterance is consumed and recorded, but handleInboundResponse() is skipped here, so nothing ever answers it.
Useful? React with 👍 / 👎.
| if (this.provider.name === "twilio") { | ||
| (this.provider as TwilioProvider).unregisterCallStream(callId); | ||
| } |
There was a problem hiding this comment.
Keep reconnect grace keyed to the disconnected stream
This unregisters the call's stream by callId before starting the grace timer, but TwilioProvider stores only one callId -> streamSid mapping. If Twilio reconnects by opening a replacement stream before the old socket's disconnect callback arrives, that stale disconnect will delete the new mapping here; two seconds later hasRegisteredStream(callId) is false and we auto-end a call whose replacement stream is already active. The grace logic needs to distinguish the old streamSid from the current one.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b6b93e03ec
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| markSent = sendPlaybackMark(`tts-${Date.now()}`).sent; | ||
| } | ||
|
|
||
| if (!signal.aborted && chunkAttempts > 0 && (chunkDelivered === 0 || !markSent)) { |
There was a problem hiding this comment.
Don't fail the turn when only the completion mark drops
If Twilio drops the terminal mark frame after the media chunks were already accepted, playTtsViaStream() still throws here because !markSent is treated the same as chunkDelivered === 0. In that case the caller may already have heard the full prompt, but speak() reports failure, so extensions/voice-call/src/manager/outbound.ts skips the bot transcript and leaves metadata.initialMessage intact. A duplicate answered/stream-connect callback will then replay audio that was already played.
Useful? React with 👍 / 👎.
| while (paragraphs.length > 1 && isLikelyMetaReasoningParagraph(paragraphs[0])) { | ||
| paragraphs.shift(); |
There was a problem hiding this comment.
Strip one-paragraph reasoning lead-ins before speaking
The new reasoning scrubber only removes meta text when it is in a separate paragraph. If the model returns something like Reasoning: ... Sure, what time works for you? or The user ... I should ... as a single paragraph, the paragraphs.length > 1 guard leaves the whole string intact, so callers still hear the planning text this change is meant to suppress.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 47a9f8f671
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| transitionState(call, "speaking"); | ||
| persistCallRecord(ctx.storePath, call); | ||
|
|
||
| addTranscriptEntry(call, "bot", text); | ||
|
|
||
| const voice = provider.name === "twilio" ? ctx.config.tts?.openai?.voice : undefined; | ||
| await provider.playTts({ |
There was a problem hiding this comment.
Delay greeting suppression until playback really starts
On Twilio streaming calls, speak() flips the call to speaking before provider.playTts() has synthesized or queued any real greeting audio. VoiceCallWebhookServer.shouldSuppressBargeInForInitialMessage() then drops transcripts for any outbound conversation call that is speaking and still has metadata.initialMessage, and this patch now keeps that metadata until playback succeeds. In practice, if telephony TTS is slow or cold-starting, a callee who says something immediately after answering can be ignored for several seconds even though the greeting has not actually started yet.
Useful? React with 👍 / 👎.
| const synthPromise = ttsProvider.synthesizeForTelephony(text); | ||
| const timeoutPromise = new Promise<Buffer>((_, reject) => { | ||
| synthTimeout = setTimeout(() => { | ||
| reject( | ||
| new Error( |
There was a problem hiding this comment.
Cancel timed-out telephony synthesis requests
This 8-second guard only races synthesizeForTelephony() against a timer; it never aborts the underlying synthesis request. The shared TTS runtime still uses its own longer network timeout (30s by default), so every stream reply that hits this path leaves an orphaned OpenAI/ElevenLabs request running in the background even though the call path has already failed. Under a slow or wedged TTS backend, repeated calls can pile up these stray requests and waste capacity/cost for tens of seconds after each timeout.
Useful? React with 👍 / 👎.
Signed-off-by: joshavant <[email protected]>
… regression (openclaw#51500) * voice-call: harden streaming startup and fallback behavior * voice-call: suppress barge-in during intro * voice-call: skip first-turn auto-response while greeting plays * Voice-call: improve telephony audio fidelity and pacing * voice-call: enforce spoken JSON and first-message barge skip * voice-call: fix silent stream TTS regression * voice-call: remove TTS timing diagnostics and document stream behavior * voice-call: fail stream playback when stream sends are dropped * voice-call: harden spoken contract and initial stream replay * voice-call: suppress barge transcripts during initial greeting * voice-call: harden stream fallback and media safety
… regression (openclaw#51500) * voice-call: harden streaming startup and fallback behavior * voice-call: suppress barge-in during intro * voice-call: skip first-turn auto-response while greeting plays * Voice-call: improve telephony audio fidelity and pacing * voice-call: enforce spoken JSON and first-message barge skip * voice-call: fix silent stream TTS regression * voice-call: remove TTS timing diagnostics and document stream behavior * voice-call: fail stream playback when stream sends are dropped * voice-call: harden spoken contract and initial stream replay * voice-call: suppress barge transcripts during initial greeting * voice-call: harden stream fallback and media safety
… regression (openclaw#51500) * voice-call: harden streaming startup and fallback behavior * voice-call: suppress barge-in during intro * voice-call: skip first-turn auto-response while greeting plays * Voice-call: improve telephony audio fidelity and pacing * voice-call: enforce spoken JSON and first-message barge skip * voice-call: fix silent stream TTS regression * voice-call: remove TTS timing diagnostics and document stream behavior * voice-call: fail stream playback when stream sends are dropped * voice-call: harden spoken contract and initial stream replay * voice-call: suppress barge transcripts during initial greeting * voice-call: harden stream fallback and media safety
… regression (openclaw#51500) * voice-call: harden streaming startup and fallback behavior * voice-call: suppress barge-in during intro * voice-call: skip first-turn auto-response while greeting plays * Voice-call: improve telephony audio fidelity and pacing * voice-call: enforce spoken JSON and first-message barge skip * voice-call: fix silent stream TTS regression * voice-call: remove TTS timing diagnostics and document stream behavior * voice-call: fail stream playback when stream sends are dropped * voice-call: harden spoken contract and initial stream replay * voice-call: suppress barge transcripts during initial greeting * voice-call: harden stream fallback and media safety
… regression (openclaw#51500) * voice-call: harden streaming startup and fallback behavior * voice-call: suppress barge-in during intro * voice-call: skip first-turn auto-response while greeting plays * Voice-call: improve telephony audio fidelity and pacing * voice-call: enforce spoken JSON and first-message barge skip * voice-call: fix silent stream TTS regression * voice-call: remove TTS timing diagnostics and document stream behavior * voice-call: fail stream playback when stream sends are dropped * voice-call: harden spoken contract and initial stream replay * voice-call: suppress barge transcripts during initial greeting * voice-call: harden stream fallback and media safety
… regression (openclaw#51500) * voice-call: harden streaming startup and fallback behavior * voice-call: suppress barge-in during intro * voice-call: skip first-turn auto-response while greeting plays * Voice-call: improve telephony audio fidelity and pacing * voice-call: enforce spoken JSON and first-message barge skip * voice-call: fix silent stream TTS regression * voice-call: remove TTS timing diagnostics and document stream behavior * voice-call: fail stream playback when stream sends are dropped * voice-call: harden spoken contract and initial stream replay * voice-call: suppress barge transcripts during initial greeting * voice-call: harden stream fallback and media safety
… regression (openclaw#51500) * voice-call: harden streaming startup and fallback behavior * voice-call: suppress barge-in during intro * voice-call: skip first-turn auto-response while greeting plays * Voice-call: improve telephony audio fidelity and pacing * voice-call: enforce spoken JSON and first-message barge skip * voice-call: fix silent stream TTS regression * voice-call: remove TTS timing diagnostics and document stream behavior * voice-call: fail stream playback when stream sends are dropped * voice-call: harden spoken contract and initial stream replay * voice-call: suppress barge transcripts during initial greeting * voice-call: harden stream fallback and media safety
… regression (openclaw#51500) * voice-call: harden streaming startup and fallback behavior * voice-call: suppress barge-in during intro * voice-call: skip first-turn auto-response while greeting plays * Voice-call: improve telephony audio fidelity and pacing * voice-call: enforce spoken JSON and first-message barge skip * voice-call: fix silent stream TTS regression * voice-call: remove TTS timing diagnostics and document stream behavior * voice-call: fail stream playback when stream sends are dropped * voice-call: harden spoken contract and initial stream replay * voice-call: suppress barge transcripts during initial greeting * voice-call: harden stream fallback and media safety
… regression (openclaw#51500) * voice-call: harden streaming startup and fallback behavior * voice-call: suppress barge-in during intro * voice-call: skip first-turn auto-response while greeting plays * Voice-call: improve telephony audio fidelity and pacing * voice-call: enforce spoken JSON and first-message barge skip * voice-call: fix silent stream TTS regression * voice-call: remove TTS timing diagnostics and document stream behavior * voice-call: fail stream playback when stream sends are dropped * voice-call: harden spoken contract and initial stream replay * voice-call: suppress barge transcripts during initial greeting * voice-call: harden stream fallback and media safety
Summary
This PR hardens voice-call response generation and Twilio streaming behavior to remove reasoning leakage, prevent silent playback failures, and close stream lifecycle edge cases.
Problem
Two issues were reproduced in voice-call flows:
What Changed
1) Deterministic spoken output extraction
In
extensions/voice-call/src/response-generator.ts:{"spoken":"..."}).2) Initial-message and barge handling hardening
In
extensions/voice-call/src/manager.ts,extensions/voice-call/src/manager/outbound.ts, andextensions/voice-call/src/webhook.ts:listening.answered.3) Twilio stream playback contract + reliability
In
extensions/voice-call/src/providers/twilio.ts:<Say>fallback remains only for calls without an active stream.4) Stream reconnect/disconnect correctness
In
extensions/voice-call/src/providers/twilio.tsandextensions/voice-call/src/webhook.ts:unregisterCallStreamnow supports stream-SID-aware unregisters.5) Media stream security hardening
In
extensions/voice-call/src/media-stream.ts:bufferedAmount.Testing
Automated:
pnpm test -- extensions/voice-call/src/response-generator.test.tspnpm test -- extensions/voice-call/src/manager.notify.test.tspnpm test -- extensions/voice-call/src/providers/twilio.test.tspnpm test -- extensions/voice-call/src/media-stream.test.tspnpm test -- extensions/voice-call/src/webhook.test.tspnpm test -- extensions/voice-call/src/manager.notify.test.ts extensions/voice-call/src/providers/twilio.test.ts extensions/voice-call/src/media-stream.test.ts extensions/voice-call/src/webhook.test.tsRepository checks were also run via
scripts/committerfor committed changes.Notes
getTtsDiagnostics(); final implementation uses explicit send-result semantics + delivery checks and does not expose that method.extensions/voice-callbehavior and tests.