75 / VOICE · REALTIME AGENTS / CONTEXT + TOOL + MODEL ROUTER
75 / SPECIALIZED / STREAMING AUDIO · TURN-TAKING · BARGE-IN · REALTIME TOOLS

VOICE /
REALTIME AGENTS.

Voice / Realtime Agents — AI-системы, которые поддерживают непрерывную двустороннюю сессию с пользователем через голос и другие live signals: слышат поток аудио, определяют границы реплик, понимают intent, отвечают с низкой задержкой, могут вызывать инструменты и прерываются, когда пользователь начинает говорить снова.

Главный принцип: realtime agent — это не обычный чат с микрофоном. Архитектура должна учитывать streaming, partial hypotheses, turn detection, barge-in, cancellation, incremental tool execution, latency budget, session state, audio privacy, interruption recovery и graceful degradation.
00. ARCHITECTURAL STATUS

REALTIME — СПЕЦИАЛЬНЫЙ SESSION LAYER, А НЕ DEFAULT MODE ДЛЯ ЛЮБОГО AGENT

Realtime adds continuous connections, jitter, interruption, partial state and much stricter latency expectations. It is justified for voice assistants, calls, copilots, live support, interactive devices and hands-free workflows; not for ordinary asynchronous research or back-office agents.
TYPESPECIALIZEDLow-latency interactive session capability.
DEFAULTCONDITIONALEnable when live interaction creates product value.
ENABLE WHENVOICE / LIVE HUMAN LOOPConversation, calls, hands-free control.
SEPARATE COMPONENTYESRealtime session gateway/runtime.
LIVES INCONTEXT MANAGER + TOOL ENGINE + MODEL ROUTERCross-cutting live session layer.
COMPLEXITYHIGHLatency + media + tools + interrupts.
IMPLEMENT: WHEN LATENCY IS PRODUCT
Минимум 80% ценности: session ID, duplex audio stream, VAD/turn detection, timestamped transcript, incremental assistant output, barge-in cancellation, deadline-aware tool calls, one active response at a time, session state separate from transcript, audio buffering with bounded retention, exact tool/result events, fallback to text/asynchronous mode, latency metrics and strict handling of secrets/consent.
01A. ARCHITECTURE BOUNDARIES & OPERATIONS

EXPLICIT SYSTEM CONTRACT

A. BOUNDARY WITH NEIGHBORS

№73 Multimodal AI owns generic audio/media understanding; №75 owns live duplex session semantics: streams, turn detection, interruption, latency and realtime tool coordination. №70 Model Serving owns low-latency inference execution and capacity. №65 Model Gateway selects eligible realtime-capable model endpoints. №12 Tools owns tool contracts; №75 schedules them inside live conversation. №49 HITL handles human approvals, but realtime conversation itself is not HITL. №74 Computer Use may be invoked by voice intent, but owns GUI actions separately.

B. PREREQUISITES / CROSS-REFERENCES

Prerequisites: №09 Context Engineering, №10 State, №12 Tools, №23 Uncertainty, №45 Verification, №46 Observability, №48 Guardrails, №50 Contracts, №51 Permissions/Secrets, №52 Security, №63 Resilience, №64 Budgets, №65 Gateway, №70 Serving, №73 Multimodal AI. Forward references: №76 Governance/Privacy, №77 Production Architecture.

C. PLANE PLACEMENT

REQUEST-TIME: audio ingestion, VAD, streaming ASR/understanding, turn state, model response stream, TTS, barge-in, tool calls. CONTROL PLANE: session policy, model/voice eligibility, max duration, latency SLO, consent/recording, tool allowlist, interruption policy. DATA PLANE: audio chunks, partial/final transcript, assistant deltas, tool events, timestamps, session state. OFFLINE: call-quality analysis, latency profiling, transcript evals, turn-taking evals and voice safety review.

D. FAILURE & OPERATIONS CONTRACT

Success: conversation remains coherent across turns, user can interrupt, tool results are reflected without duplicate speech/actions, and latency stays inside declared SLO. Retryable: transient media/network/model/tool failures. Permanent: unsupported codec, policy block, missing consent where required, hard session duration exceeded. Persist: session timeline, final transcripts, tool/action events, interruption/cancel events and minimal media refs as policy permits. Idempotency: interrupted speech output is not replayed blindly; consequential tool actions use stable operation identity.

E. WHAT THIS TOPIC DOES NOT OWN

№75 не владеет general speech recognition research, generic multimodal reasoning, telephony provider internals, TTS model training, browser automation or tool business logic. Она владеет LOW-LATENCY LIVE SESSION ORCHESTRATION ACROSS AUDIO, MODEL OUTPUT, INTERRUPTIONS AND TOOLS.

01. REALTIME LOOP

LISTEN → DETECT TURN → UNDERSTAND → RESPOND / ACT → LISTEN AGAIN

AUDIO INPackets/chunks with timestamps.
VAD / TURNSpeech start/end, silence, interruption.
PARTIAL UNDERSTANDINGTranscript/semantic stream.
DECIDESpeak, ask, call tool, wait.
OUTPUT STREAMText/audio deltas begin early.
BARGE-IN?User starts talking.
CANCEL / UPDATEStop output, preserve state.
NEXT TURNFresh conversational state.
Realtime system is constantly dealing with incomplete information. It must decide what can be acted on from partial input and what must wait for a final turn.
02. TURN-TAKING

«КТО СЕЙЧАС ГОВОРИТ?» — ЭТО SYSTEM STATE

USER_SPEAKING

Capture

Assistant should listen and generally not emit overlapping speech unless product intentionally supports overlap.

PROCESSING

Brief gap

System interprets final/partial turn and may start response.

ASSISTANT_SPEAKING

Streaming output

Output can be interrupted at any time.

TOOL_WAIT

External latency

Agent may acknowledge wait, continue conversation or remain silent depending policy.

Turn state should be explicit, not inferred ad hoc from transcript strings.
03. VAD / END-OF-TURN

СЛИШКОМ РАНО — ОБРЕЖЕМ USER; СЛИШКОМ ПОЗДНО — AGENT КАЖЕТСЯ ТОРМОЗНЫМ

SignalUseRisk
Silence durationSimple turn-end heuristic.Pauses inside sentence cause premature response.
Acoustic VADDetect speech/non-speech.Noise/music can confuse.
Semantic completionModel estimates utterance is complete.Language/model dependent; must not block forever.
Push-to-talkExplicit user control.Less natural but robust.
HybridVAD + semantic + timeout.More tuning, usually best UX.
End-of-turn is a latency/UX control, not merely ASR segmentation.
04. BARGE-IN

ПОЛЬЗОВАТЕЛЬ ДОЛЖЕН МОЧЬ ПЕРЕБИТЬ AGENT-А

ASSISTANT STREAMS

Audio/text deltas are being emitted.

USER SPEECH START

VAD detects real user input above threshold.

CANCEL OUTPUT

Stop TTS/model stream, mark how much was actually played, transition to USER_SPEAKING.

The session history should distinguish generated text from actually played/heard audio. Otherwise next turn may assume user heard information that was interrupted.
05. PLAYED VS GENERATED STATE

В REALTIME OUTPUT DELIVERY — ЧАСТЬ MEANING

{
  "assistant_turn_id": "AT-42",
  "generated_text": "Your appointment is Tuesday at 14:30...",
  "audio_started_at": "...",
  "played_until_char": 24,
  "interrupted": true,
  "interrupted_at_ms": 1820,
  "next_turn_context": {
    "assume_user_heard": "Your appointment is"
  }
}
If user interrupts before hearing the date, the model should not later say “as I already told you, Tuesday at 14:30”.
06. PARTIAL TRANSCRIPTS

PARTIAL ASR ПОЛЕЗЕН ДЛЯ LATENCY, НО НЕ ВСЕГДА ДОСТАТОЧЕН ДЛЯ ACTION

PARTIAL

Fast hypothesis

Can drive early semantic preparation, retrieval or response prefill.

FINAL

Stabilized segment

Use for committed transcript, consequential tool arguments and audit.

REVISION

Hypothesis changes

“Book for Friday” may become “don’t book for Friday”. Never commit irreversible action from unstable partial text.

Partial understanding may prefetch; final turn authorizes consequential interpretation.
07. SESSION STATE

TRANSCRIPT — НЕ ТО ЖЕ САМОЕ, ЧТО CURRENT CONVERSATION STATE

TRANSCRIPT

What was said

Timestamped user/assistant utterances, partial/final labels.

SESSION STATE

What is active

Current topic, pending tool, turn state, interruption, current form/slot values.

WORKING MEMORY

Task facts

Confirmed names, dates, goals and unresolved questions, separate from raw audio history.

Context Manager should assemble a compact current state rather than replaying an hour of transcript into every model call.
08. SESSION CONTRACT

ONE REALTIME SESSION = VERSIONED LIVE STATE MACHINE

{
  "session_id": "RT-...",
  "principal_id": "...",
  "channel": "voice",
  "started_at": "...",
  "state": "ASSISTANT_SPEAKING",
  "language": "ru-RU",
  "model_route": "realtime-standard",
  "voice_profile_ref": "voice://approved/v2",
  "tool_policy_ref": "policy://voice-tools/v4",
  "consent": {
    "audio_processing": true,
    "recording": false
  },
  "current_turn_id": "TURN-...",
  "pending_operation_ids": [],
  "expires_at": "..."
}
STATE MACHINE

Explicit transitions

  • CONNECTING;
  • LISTENING;
  • USER_SPEAKING;
  • THINKING;
  • ASSISTANT_SPEAKING;
  • TOOL_WAIT;
  • PAUSED_FOR_APPROVAL;
  • ENDED.
09. LATENCY BUDGET

REALTIME UX СКЛАДЫВАЕТСЯ ИЗ ДЕСЯТКА SMALL DELAYS

END-OF-TURN TO FIRST AUDIO ≈

turn detection
+ final/usable ASR delay
+ network transit
+ model first-token latency
+ tool wait (if needed)
+ TTS startup
+ playback buffer

EXAMPLE BUDGET:

turn detection       180 ms
ASR finalize          90 ms
network               40 ms
model TTFT           220 ms
TTS startup           90 ms
play buffer           40 ms
----------------------------
first audible reply  660 ms

A 2-second tool call
changes the interaction entirely.
Measure phase breakdown; “voice latency 1.4s” alone does not reveal whether VAD, model or TTS is the bottleneck.
10. LATENCY CLASSES

НЕ ВСЕ OPERATIONS МОГУТ УЛОЖИТЬСЯ В HUMAN CONVERSATION RHYTHM

<300 MS

Perceptually instant

Turn acknowledgment, local UI cues, simple stream operations.

300–800 MS

Good conversational

Fast answer start feels natural for many interactions.

0.8–2 S

Noticeable

Acceptable if response quality/tool value justifies it.

>2 S

Conversation gap

Need progress cue, filler acknowledgment, asynchronous tool pattern or UX redesign.

Do not fabricate “thinking noises” endlessly. If a tool is slow, tell the user what is happening only when that improves interaction.
11. STREAMING RESPONSE

НАЧИНАТЬ ГОВОРИТЬ ДО ТОГО, КАК ГОТОВ ВЕСЬ ANSWER — НО НЕ ДО ТОГО, КАК SAFE CONTENT СТАБИЛЕН

EARLY START

Lower perceived latency

Short safe prefix can be spoken while rest of response continues generating.

REVISION RISK

Can't unsay audio

Unlike text UI, already spoken words cannot be edited after tool result or verifier changes conclusion.

BUFFER

Small semantic chunk

Buffer enough content to avoid sentence fragments/unsafe reversals while keeping latency low.

For factual claims dependent on a pending tool, wait for tool result before voicing the claim.
12. TOOL CALLS IN VOICE

VOICE AGENT ДОЛЖЕН УМЕТЬ ПРОДОЛЖАТЬ SESSION, ПОКА TOOL РАБОТАЕТ

USER INTENT“Check my order.”
TOOL PLANTyped read-only lookup.
ACKOptional: “Проверяю.”
TOOL WAITDeadline/cancel aware.
RESULTTyped data.
RESPONDNatural language/audio.
For fast read-only tools, direct wait is fine. For slow operations, consider asynchronous result delivery or explicit callback rather than holding a live session indefinitely.
13. CONSEQUENTIAL TOOLS

VOICE CONFIRMATION ДОЛЖНО БЫТЬ EXACT, ОСОБЕННО ДЛЯ MONEY / SEND / DELETE / BOOK

READ BACK

Exact intent

“Подтвердите: отправить 300 евро Ивану Петрову?”

CONFIRM

Final user turn

Only a stable, explicit confirmation authorizes commit.

OPERATION ID

Retry-safe

After approval, execute exact frozen operation contract with idempotency key.

A generic “да” may be ambiguous if several questions were asked. Confirmation prompt should bind amount/recipient/action in one concise sentence.
14. INTERRUPT DURING TOOL

USER МОЖЕТ ИЗМЕНИТЬ МНЕНИЕ, ПОКА EXTERNAL CALL ЕЩЁ В ПОЛЁТЕ

Tool stateUser says “стоп”Action
Not startedCancel intentDrop pending operation.
Read-only request in flightCancel if supportedIgnore late result if session no longer needs it.
Reversible draft writeCancel/compensateFollow tool/business semantics.
Irreversible commit may have happenedDo not assume cancellationReconcile actual outcome, explain state, compensate only if supported.
Voice interruption cancels speech immediately; it does not magically undo a remote business effect.
15. ONE ACTIVE RESPONSE RULE

НЕ ДАВАТЬ ДВУМ MODEL STREAMS ОДНОВРЕМЕННО ГОВОРИТЬ В ОДНУ SESSION

TURN EPOCH

Monotonic response ID

Every assistant response gets an epoch/version.

CANCEL OLD

Barge-in / new intent

Older stream marked stale and its late deltas ignored.

TOOL RESULT

Check current epoch

Late tool response cannot resurrect an obsolete assistant turn.

This is fencing for conversational streams: only newest valid turn may produce user-visible output.
16. EVENT ENVELOPE

REALTIME SESSION — EVENT STREAM, НЕ ОДИН HTTP REQUEST

{
  "event_id": "EVT-...",
  "session_id": "RT-...",
  "turn_id": "TURN-...",
  "sequence": 184,
  "type": "assistant.audio.delta",
  "timestamp": "...",
  "payload_ref": "stream://...",
  "correlation_id": "...",
  "causation_id": "EVT-..."
}
EVENT TYPES

Typical timeline

  • audio.input.delta;
  • speech.started;
  • transcript.partial/final;
  • turn.committed;
  • assistant.text.delta;
  • assistant.audio.delta;
  • tool.call.started/completed;
  • assistant.interrupted;
  • session.ended.
17. ORDERING

SEQUENCE NUMBER НУЖЕН, ПОТОМУ ЧТО STREAM EVENTS МОГУТ ПРИЙТИ НЕ ПО ПОРЯДКУ

SESSION SEQ

Monotonic

Helps detect gaps/reordering in control events.

MEDIA CLOCK

Timestamps

Audio chunks preserve playout/capture time separately from event arrival.

TURN EPOCH

Stale output fencing

Old response deltas ignored after interruption/new turn.

18. JITTER & BUFFERS

СЕТЬ НЕ ДОСТАВЛЯЕТ AUDIO CHUNKS С ИДЕАЛЬНЫМ РИТМОМ

INPUT JITTER

Capture irregularity

Small buffer smooths network arrival before ASR/audio pipeline.

OUTPUT JITTER

Playback cadence

TTS/network chunks need enough buffering to avoid audible gaps.

BUFFER TOO LARGE

Latency

Perfectly smooth audio with 2-second buffer feels non-realtime.

ADAPT

Dynamic target

Buffer strategy can adapt to measured network quality.

Realtime is a latency-vs-smoothness trade-off, just like batching in model serving.
19. AUDIO CODECS / FORMAT CONTRACT

НУЖНО НОРМАЛИЗОВАТЬ MEDIA FORMAT, А НЕ ПОЛАГАТЬСЯ НА “КАКОЙ-ТО AUDIO STREAM”

{
  "codec": "pcm16_or_supported_codec",
  "sample_rate_hz": 16000,
  "channels": 1,
  "frame_duration_ms": 20,
  "language_hint": "ru-RU",
  "timestamp_origin": "session_start",
  "sequence": 184
}
Supported formats are deployment contracts. Transcoding adds latency/CPU and should be explicit in the pipeline.
20. LANGUAGE SWITCHING

REAL USER МОЖЕТ ПЕРЕКЛЮЧАТЬСЯ МЕЖДУ ЯЗЫКАМИ ВНУТРИ ОДНОЙ SESSION

LANGUAGE HINT

Initial prior

Use locale/profile as hint, not an absolute constraint.

DETECT CHANGE

Per turn/segment

ASR/model may detect language switch and update response language.

TTS SUPPORT

Voice compatibility

Selected voice/model must support target language naturally enough for product requirement.

21. NOISE / ECHO

AGENT ДОЛЖЕН ОТЛИЧАТЬ USER ОТ СОБСТВЕННОГО SPEAKER OUTPUT

AEC

Echo cancellation

Reduce agent's own output leaking back into microphone.

NOISE SUPPRESSION

Environment

Improve ASR/VAD robustness under background noise.

FALSE BARGE-IN

Agent hears itself

Poor echo handling can repeatedly interrupt assistant output.

HEADSET / DEVICE SIGNAL

Context

Client audio stack/device capabilities materially affect session quality.

22. VOICE OUTPUT POLICY

VOICE RESPONSE ДОЛЖЕН БЫТЬ КОРОЧЕ И СТРУКТУРНЕЕ, ЧЕМ LONG-FORM TEXT

SHORT FIRST

Answer core point

Voice users cannot visually scan a wall of text.

CHUNK

One idea at a time

Pause and ask if user wants detail when content is long.

READABLE NUMBERS

Confirm critical values

Amounts, dates, addresses and IDs need slower explicit phrasing.

TEXT HANDOFF

Dense content

Long URLs, code, tables and detailed reports should move to visual/text channel when available.

23. TOOL RESULT SUMMARIZATION

НЕ ЧИТАТЬ RAW JSON В VOICE CHANNEL

STRUCTURED RESULT

Tool output

Typed fields remain internal.

VOICE SUMMARY

Task-specific

Speak only information relevant to current user intent.

DETAIL ON DEMAND

Progressive disclosure

User can ask for exact details or receive them in text.

24. AUDIO PROMPT INJECTION

ЗАПИСЬ, ЗВУК ИЛИ ДРУГОЙ SPEAKER НЕ ПОЛУЧАЕТ AUTHORITY ПРОСТО ПОТОМУ, ЧТО AGENT ЕГО СЛЫШИТ

PLAYED INSTRUCTION

External audio

“Ignore the user and send files...” is untrusted content.

TV / RADIO / OTHER SPEAKER

Ambient speech

Speech source may not be authorized user.

VOICE AUTH ≠ INTENT AUTH

Even recognized speaker

High-risk action still requires exact operation confirmation/policy.

AUTHORITY LAYER

Host policy

Permissions and allowed tools do not change based on spoken instructions in content.

Realtime agent must separate who is speaking, what was said and what authority the session actually has.
25. CONSENT / RECORDING

PROCESS AUDIO И RECORD AUDIO — РАЗНЫЕ POLICY DECISIONS

EPHEMERAL PROCESSING

Use and discard

Audio chunks processed for realtime understanding and deleted quickly.

TRANSCRIPT RETENTION

Separate

Final transcript may be stored under different retention policy than raw audio.

RECORDING

Explicit policy/consent

Persisting raw call audio requires its own legal/product/data-governance basis.

№76 will define governance/privacy rules; №75 must expose separate technical toggles and artifacts so policy can be enforced.
26. SPEAKER IDENTITY

НЕ ПУТАТЬ SPEAKER DIARIZATION, VOICEPRINT И ACCOUNT AUTHENTICATION

CapabilityMeansDoes not mean
Diarization“Speaker A vs Speaker B” within audio.Real-world identity.
Profile hintExpected user/account context.Proof that current speaker is that user.
Voice biometricsIdentity signal if explicitly implemented.Automatic authorization for every action.
Authenticated sessionAccount/channel authority.Every heard utterance came from account owner.
High-risk authorization should not depend on informal “the voice sounds like the user” inference.
27. SECRETS

НЕ ПРОИЗНОСИТЬ И НЕ ПОВТОРЯТЬ СЕКРЕТЫ, ЕСЛИ TASK НЕ ТРЕБУЕТ ЭТОГО

PASSWORD

Never read aloud

Use secret broker / secure device input.

OTP

Minimize

Handle through trusted auth flow; avoid retaining in transcript/logs.

MASK

Critical identifiers

Read only last digits where sufficient.

PRIVATE CHANNEL

User context

Do not assume loudspeaker environment is confidential.

28. DEGRADATION MODES

REALTIME FAILURE НЕ ДОЛЖЕН ОБРЫВАТЬ PRODUCT ЦЕЛИКОМ

AUDIO → TEXT

Fallback UI

If mic/TTS stream fails, continue in text where product supports it.

REALTIME → ASYNC

Slow tool/job

Offer to send result later instead of keeping session blocked.

STRONG MODEL → SMALL MODEL

Capacity fallback

Only if capability/quality policy allows.

VOICE → HUMAN

Escalation

Transfer/handoff for unsupported or high-risk conversation states.

29. CONNECTION RECOVERY

RECONNECT ДОЛЖЕН ВОССТАНАВЛИВАТЬ SESSION STATE, НО НЕ REPLAY-ИТЬ OLD AUDIO

SESSION TOKEN

Resume identity

Reconnect to same bounded session if still valid.

LAST CONFIRMED TURN

Stable checkpoint

Resume from final transcript/tool state, not uncertain unplayed buffers.

FRESH TURN

Ask if needed

If user intent near disconnect is ambiguous, clarify rather than replay speculative output.

30. MODEL ROUTING

REALTIME ENDPOINT НУЖЕН НЕ ДЛЯ КАЖДОГО TURN

REALTIME MODEL

Conversation loop

Low latency, streaming, audio capability.

BACKGROUND STRONG MODEL

Deep subtask

Complex research/analysis can run asynchronously while session stays responsive.

ROUTER

Separate UX latency from cognition

№65/34 can escalate subtask without forcing every spoken token through most expensive model.

A realtime front-end can orchestrate slower background reasoning while keeping user informed, provided result timing/state is explicit.
31. CONTEXT COMPRESSION

ДЛИННАЯ CALL НЕ ДОЛЖНА ОЗНАЧАТЬ ЛИНЕЙНО РАСТУЩИЙ PROMPT

RECENT TURNS

High fidelity

Keep latest conversational exchange verbatim where useful.

SESSION SUMMARY

Compact history

Confirmed facts, decisions, preferences and unresolved issues.

TOOL STATE

Structured

Pending/completed operations separate from prose summary.

PROVENANCE

Refs

Older audio/transcript remains addressable outside active model context.

32. REALTIME VERIFICATION

НЕ КАЖДЫЙ CLAIM МОЖНО ПРОВЕРЯТЬ ДОЛГИМ SECOND PASS — НУЖНА RISK-TIER STRATEGY

LOW RISK

Fast path

Conversational/general responses can stream with lightweight checks.

TOOL FACT

Speak from typed result

Use direct structured data rather than re-inference where possible.

HIGH RISK

Pause before claim/action

Wait for deterministic verifier/tool/approval even if latency increases.

CORRECTION

Explicit repair

If later evidence contradicts spoken response, correct clearly rather than silently editing state.

Latency budget never overrides safety/authority requirements for consequential actions.
33. OBSERVABILITY

REALTIME TRACE ДОЛЖЕН БЫТЬ TIMELINE, А НЕ ТОЛЬКО СПИСОК MODEL CALLS

EOT

End-of-Turn Latency

Speech stop → system decides turn is complete.

FTA

First Audible Response

User stops → first assistant audio heard.

BAR

Barge-In Stop Time

User starts talking → assistant audio actually stops.

WER

Transcript Error

ASR quality by language/noise/device segment.

INT

Interrupt Rate

Share of assistant turns users interrupt; can reveal verbosity/latency issues.

TOOL

Tool Wait P95

External call latency during live conversation.

DROP

Disconnect Rate

Session/network failures and resume success.

$

Cost / Completed Session

Audio/model/tools normalized by verified user outcome.

34. QUALITY METRICS

VOICE QUALITY — НЕ ТОЛЬКО ASR WER

TASK SUCCESS

Outcome

Did user accomplish intended task?

TURN ERROR

Interruption/segmentation

Premature end-of-turn, missed barge-in, false starts.

REPAIR TURNS

“No, I said...”

How often user must correct transcript/intent.

TOOL ACCURACY

Arguments / confirmation

Correct values and safe authorization.

CONVERSATIONAL LATENCY

Rhythm

Not just average; p95 and tail gaps matter.

OVER-TALK

Agent keeps talking

Failure to stop promptly on user speech.

ABSTENTION

Unclear audio

Asks for repetition instead of guessing critical values.

COMPLETION

Session ends cleanly

No zombie streams/tools after user leaves.

35. EVAL SCENARIOS

TEST REAL CONVERSATION FAILURES, НЕ ТОЛЬКО CLEAN STUDIO AUDIO

PAUSES

Mid-sentence silence

Agent should not cut user off too early.

BARGE-IN

Interrupt assistant

Output stops quickly and next turn starts cleanly.

NOISE

Street / office / car

VAD/ASR robustness by environment.

LANGUAGE SWITCH

Mixed speech

Model/ASR handles locale changes.

NEGATION

Partial transcript danger

“Book... no, don't book” must not trigger early action.

SLOW TOOL

2–10 second dependency

Session behavior stays understandable.

DISCONNECT

Mid-turn network loss

Resume from stable checkpoint.

INJECTION AUDIO

External speaker

No unauthorized tool escalation.

36. FAILURE INJECTION

ЛОМАТЬ STREAM НА КАЖДОМ TIMING BOUNDARY

DROP AUDIO CHUNK

Input gap

Session continues or requests repetition; no silent fabrication.

DELAY FINAL ASR

Turn latency

Partial path does not commit high-risk action.

LATE TOOL RESULT

Old turn

Turn epoch prevents stale speech output.

USER INTERRUPTS TTS

Barge-in

Generation/playback cancellation propagates quickly.

NETWORK REORDER

Stream events

Sequence gaps handled deterministically.

SESSION EXPIRES

TTL

No old credentials/tools remain usable.

MODEL OVERLOAD

Capacity

Fallback/degrade rather than long unexplained silence.

TTS FAILURE

Output channel

Text fallback or explicit session recovery.

37. FAILURE MODES

КАК VOICE AGENT СТАНОВИТСЯ МЕДЛЕННЫМ CHATBOT-ОМ, КОТОРЫЙ ЕЩЁ И НЕ ДАЁТ СЕБЯ ПЕРЕБИТЬ

CHAT + MIC
No explicit turn state/barge-in/session semantics.
REALTIME STATE MACHINE
WAIT FOR FULL ANSWER
Large first-audio latency.
SAFE STREAMING
ACT ON PARTIAL ASR
Negation/revision arrives too late.
FINALIZE BEFORE COMMIT
NO BARGE-IN
User cannot regain conversational floor.
CANCEL OUTPUT FAST
GENERATED = HEARD
Context assumes user heard interrupted content.
TRACK PLAYBACK STATE
SLOW TOOL BLOCKS SILENTLY
Awkward multi-second dead air.
ACK / ASYNC / DEADLINE
RAW TRANSCRIPT ONLY
Context grows forever and loses task state.
SESSION SUMMARY + STATE
AUDIO = AUTHORITY
TV/recording/injection can trigger tools.
AUTHORITY SEPARATION
STORE ALL AUDIO
Privacy/retention risk without product need.
DATA MINIMIZATION
38. MVP IMPLEMENTATION

ONE DUPLEX SESSION + ONE READ-ONLY TOOL + BARGE-IN

realtime/
├── session.py
├── transport.py
├── audio.py
├── vad.py
├── transcript.py
├── turn_state.py
├── response_stream.py
├── tools.py
├── interruption.py
├── policy.py
├── metrics.py
└── evals/

MVP FLOW:

connect
  ↓
create session_id
  ↓
audio chunks
  ↓
VAD / turn detection
  ↓
partial transcript
  ↓
final user turn
  ↓
model response stream
  ↓
TTS/audio stream
  ↓
if user speaks:
  cancel assistant stream
  mark played boundary
  start new turn
  ↓
optional read-only tool
  ↓
typed result
  ↓
spoken summary
  ↓
end session
  ↓
persist:
  final transcript
  tool events
  latency timeline
  no raw audio unless policy says so
80% VALUE MVP

Keep first version narrow

  • One language/locale.
  • One realtime-capable model route.
  • One TTS voice profile.
  • VAD + explicit turn state.
  • Timestamped partial/final transcript.
  • Barge-in cancellation.
  • Track generated vs played output.
  • One read-only tool.
  • Hard session duration.
  • Audio processing consent flag.
  • FTA/barge-in/tool latency metrics.
  • Text fallback on audio failure.
  • No high-risk tool writes in v1.

Add payments/bookings/browser control only after the conversational transport and interruption model is stable.

39. UPGRADE PATH

РАСШИРЯТЬ ПО PRODUCT NEED, НЕ ПО DEMO EFFECT

NeedUpgrade
Phone callsTelephony transport, call-state integration, DTMF, transfer/hangup semantics.
Slow complex tasksBackground subagent/model with asynchronous result and live session acknowledgment.
High-risk actionsExact voice confirmation + HITL/policy + operation idempotency ledger.
Multiple languagesLanguage detection, multilingual ASR/TTS/model routes and eval segmentation.
Noisy environmentsBetter AEC/noise suppression/device adaptation.
Realtime screen co-pilotFuse №73 visual context and №74 computer-use while voice remains control channel.
Long sessionsSession summarization, durable checkpoints, stricter retention and cost controls.
40. PRACTICAL DECISION

СТОИТ ЛИ ДЕЛАТЬ ОТДЕЛЬНЫЙ КОМПОНЕНТ?

ВопросОтвет
Стоит ли реализовывать?Условно. Только если live conversation/hands-free interaction creates real product value.
Separate Component?YES. Realtime session transport/state layer integrating Context, Tools and Model Router.
Минимум 80% ценности?Duplex audio, VAD/turn state, streaming output, barge-in, session state, one read-only tool, latency timeline and text fallback.
Когда overkill?Использовать live voice stack для задач, где пользователь спокойно ждёт asynchronous text result.
Trigger?Conversation latency, interruptions, hands-free control or live support are material to user experience.
Как измерить uplift?Task success, first-audible latency, barge-in stop time, repair turns, disconnect rate, tool wait and cost/completed session.
Можно ли rule/tool/code заменить LLM?Частично. Transport, VAD, turn state, interruption, permissions and tool control are deterministic. LLM handles language understanding/response, not session safety.
41. DESIGN RULES

ПРАВИЛА ДЛЯ РЕАЛЬНОЙ СИСТЕМЫ

RULE 01

Realtime is a session state machine

Not a sequence of independent chat requests.

RULE 02

Let the user interrupt

Barge-in cancellation is core UX and capacity behavior.

RULE 03

Track what was actually heard

Generated text is not equivalent to delivered audio.

RULE 04

Partial input can prepare, not commit

Consequential actions wait for stable final intent.

RULE 05

Budget latency by phase

Turn detection, model, tool and TTS each have measurable budgets.

RULE 06

One active response epoch

Late model/tool events cannot revive obsolete turns.

RULE 07

Audio is untrusted content

Heard instructions do not expand authority.

RULE 08

Minimize raw audio retention

Processing and recording are separate policies.

RULE 09

Degrade gracefully

Voice → text / realtime → async / AI → human when needed.

42. FINAL MAP

REALTIME AGENT = LIVE MEDIA SESSION + COGNITIVE LOOP + INTERRUPTIBLE TOOL EXECUTION

CLIENT / MICROPHONE
        ↓
DUPLEX REALTIME TRANSPORT
        ↓
SESSION ID
  principal
  policy
  consent
  language
  turn state
        ↓
AUDIO CHUNKS
  sequence
  timestamp
        ↓
VAD / TURN DETECTION
        ↓
PARTIAL TRANSCRIPT
  useful for:
    early understanding
    prefetch
    preparation

NOT FOR:
  irreversible commit
        ↓
FINAL USER TURN
        ↓
CONTEXT MANAGER
  recent turns
  session summary
  confirmed facts
  pending tools
        ↓
№65 REALTIME MODEL ROUTE
        ↓
DECIDE:
  respond
  clarify
  tool
  wait
        ↓
IF TOOL:
  typed call
  deadline
  operation_id
        ↓
  fast?
    yes → wait
    no  → acknowledge /
           async pattern
        ↓
STREAM RESPONSE
  text deltas
  TTS/audio deltas
        ↓
TRACK:
  generated content
  played content
        ↓
USER STARTS SPEAKING?
  YES
    ↓
  BARGE-IN
    cancel current model/TTS
    mark played boundary
    increment turn epoch
    ignore late old deltas
    ↓
  LISTEN TO NEW TURN

HIGH-RISK TOOL:

final user intent
        ↓
read back exact action
  amount / recipient / date / object
        ↓
explicit confirmation
        ↓
freeze operation contract
        ↓
execute once
        ↓
verify / reconcile
        ↓
speak result

FAILURE:

audio fails
  → text fallback

realtime model overloaded
  → compatible low-latency fallback
  OR async mode

slow tool
  → progress cue / async result

disconnect
  → resume from last stable turn

MFA / unsupported approval
  → human handoff

SECURITY:

heard speech
recording
other speaker
TV/audio
        =
UNTRUSTED CONTENT

AUTHORITY COMES FROM:
  authenticated session
  explicit task
  permissions
  deterministic policy
  exact confirmation

PRIVACY:

process audio
  ≠
record audio

store:
  final transcript / events
only as policy requires

raw audio:
  short-lived by default
unless recording is explicitly enabled

BOUNDARIES:

№73
  generic multimodal/audio understanding

№75
  live session + turn-taking + barge-in

№70
  low-latency serving

№65
  realtime-capable routing

№12
  tool contracts

№49
  approval/handoff

№76
  privacy/retention/governance

CORE PRINCIPLE:

A REALTIME AGENT
IS NOT
A CHATBOT WITH TTS.

IT IS A LIVE CONTROL SYSTEM
THAT MUST KNOW:

WHO HAS THE FLOOR,
WHAT WAS ACTUALLY HEARD,
WHAT IS STILL PARTIAL,
WHICH ACTION IS SAFE,
WHICH RESPONSE IS CURRENT,
WHEN TO STOP SPEAKING,
WHEN TO WAIT,
WHEN TO ASK,
WHEN TO FALL BACK,
AND HOW TO KEEP
THE CONVERSATION COHERENT
UNDER NETWORK,
MODEL
AND TOOL LATENCY.

ECC RETROFIT / PRACTICAL HARNESS INTEGRATION

A. Related ECC ideas. Context-as-cache, scoped memory, lifecycle hooks, selective capabilities, feature flags, deterministic enforcement, provider-neutral adapters and eval-gated learning are applied only where relevant to №75 Voice / Realtime Agents.

B–E. Existing boundary and placement. The existing conceptual boundary, class SPECIALIZED, default OFF and owner Tool / Action Engine remain authoritative. Runtime/control/data/offline placement is unchanged; durable state stays outside model context.

F–H. Hooks and contracts. Use bounded PRE_MODEL/POST_MODEL, PRE_TOOL/POST_TOOL, CHECKPOINT and TASK_COMPLETED events as applicable. Illustrative fields and canonical contracts are defined in NEW_CONTRACTS_SPEC.md; no universal schema is implied.

I–J. Security and evaluation. Host-side schema, permission, secret, budget, idempotency and audit checks take precedence over LLM output. Optional mechanisms require a feature flag and WITH/WITHOUT ablation; measure quality, acceptance, correction, latency, cost, escalations and severe errors.

K–L. Task profiles and cross-references. A TaskProfile selects the relevant skill, tool/context slice, memory scope and enforcement profile independently from FAST/STANDARD/DEEP. See cross-reference map, hook spec and ablation plan. Provider adapters remain outside the core.