From 6b8c27fd7611f6b736502dcdd88e03ac58980b3e Mon Sep 17 00:00:00 2001 From: Alvaro Parker Date: Mon, 5 Oct 2026 10:11:35 -0300 Subject: [PATCH] docs: consolidate English documentation under root docs --- .dockerignore | 19 + README.md | 50 + docs/README.md | 35 + .../0001-docker-space-with-search-proxy.md | 8 +- docs/client/architecture.md | 98 ++ docs/client/context-injection.md | 132 ++ docs/client/design.md | 90 ++ docs/client/glossary.md | 40 + docs/client/reasoning.md | 106 ++ docs/client/tool-calling.md | 137 +++ docs/client/troubleshooting.md | 115 ++ docs/client/usage.md | 153 +++ docs/examples/README.md | 16 + .../examples/agent-profile.json | 6 +- .../examples/reference-audio.wav | Bin docs/proposals/vocero-architecture.html | 272 +++++ docs/speech/llm.md | 162 +++ docs/speech/realtime-api.md | 230 ++++ docs/speech/stt.md | 166 +++ docs/speech/tts.md | 151 +++ reasoning.md | 608 --------- s2s-client/ARCHITECTURE.md | 188 --- s2s-client/CHANGELOG.es.md | 859 ------------- s2s-client/CHANGELOG.md | 1087 ++++------------- s2s-client/CONTEXT.md | 108 -- s2s-client/DESIGN.md | 205 ---- s2s-client/Dockerfile | 10 +- s2s-client/HOWITWORKS.md | 584 --------- s2s-client/INJECTIONS.md | 498 -------- s2s-client/README.md | 253 +--- s2s-client/index_video.html | 356 ------ s2s-client/project/index.html | 139 --- s2s-client/public/docs.html | 272 ----- s2s-client/server.py | 15 +- speech_to_speech/LLM/README.md | 143 +-- speech_to_speech/STT/README.md | 166 +-- speech_to_speech/TTS/README.md | 158 +-- .../api/openai_realtime/README.md | 220 +--- 38 files changed, 2261 insertions(+), 5594 deletions(-) create mode 100644 .dockerignore create mode 100644 README.md create mode 100644 docs/README.md rename {s2s-client/docs => docs}/adr/0001-docker-space-with-search-proxy.md (77%) create mode 100644 docs/client/architecture.md create mode 100644 docs/client/context-injection.md create mode 100644 docs/client/design.md create mode 100644 docs/client/glossary.md create mode 100644 docs/client/reasoning.md create mode 100644 docs/client/tool-calling.md create mode 100644 docs/client/troubleshooting.md create mode 100644 docs/client/usage.md create mode 100644 docs/examples/README.md rename sample.json => docs/examples/agent-profile.json (93%) rename speech_to_speech/TTS/ref_audio.wav => docs/examples/reference-audio.wav (100%) create mode 100644 docs/proposals/vocero-architecture.html create mode 100644 docs/speech/llm.md create mode 100644 docs/speech/realtime-api.md create mode 100644 docs/speech/stt.md create mode 100644 docs/speech/tts.md delete mode 100644 reasoning.md delete mode 100644 s2s-client/ARCHITECTURE.md delete mode 100644 s2s-client/CHANGELOG.es.md delete mode 100644 s2s-client/CONTEXT.md delete mode 100644 s2s-client/DESIGN.md delete mode 100644 s2s-client/HOWITWORKS.md delete mode 100644 s2s-client/INJECTIONS.md delete mode 100644 s2s-client/index_video.html delete mode 100644 s2s-client/project/index.html delete mode 100644 s2s-client/public/docs.html diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..33e4966 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,19 @@ +.git/ +.agents/ +.codex/ +.aws/ +**/.env +**/.env.* +!**/.env.example +**/secrets/ +**/__pycache__/ +**/*.pyc +**/.venv/ +**/venv/ +**/node_modules/ +**/.node-red/ +**/.cache/ +**/*.log +**/uploads/ +**/sessions/ +debug_files/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..1105d3a --- /dev/null +++ b/README.md @@ -0,0 +1,50 @@ +# Vocero speech-to-speech + +Vocero provides a browser voice interface, a Python speech pipeline, and an +optional Node-RED reasoning service. The interface defaults to Spanish; +documentation, source identifiers, comments, and internal instructions use English. + +| Component | Purpose | +|---|---| +| [s2s-client](s2s-client) | Browser UI, FastAPI server, realtime WebSocket proxy, search and ApiPilot bridges | +| [speech_to_speech](speech_to_speech) | Queue-driven VAD, speech recognition, language model, and speech synthesis pipeline | +| [s2s-reasoning-engine](s2s-reasoning-engine) | Optional Node-RED HTTP reasoning and conversation logging flows | + +Start with [client setup and usage](docs/client/usage.md), then read the +[architecture](docs/client/architecture.md) and [documentation index](docs/README.md). +The speech backend needs its own installed model and runtime dependencies; +`s2s-client/requirements.txt` installs only the UI server dependencies. + +## Run the browser client + +From the repository root, point the client at an existing realtime backend: + +```bash +SPEECH_TO_SPEECH_URL=ws://localhost:8765/v1/realtime ./start_ui.sh +``` + +Open and allow microphone access. The launcher creates +`.venv`, installs missing UI requirements, loads the root `.env` if present, and +starts the server. For the local WebSocket proxy instead of a direct browser +connection, configure `S2S_PROXY_TARGET` and leave `SPEECH_TO_SPEECH_URL` unset. + +To build the UI container, use the repository root as the Docker build context so +the root documentation is included: + +```bash +docker build -f s2s-client/Dockerfile -t s2s-client . +docker run --rm -p 7860:7860 \ + -e SPEECH_TO_SPEECH_URL=ws://localhost:8765/v1/realtime s2s-client +``` + +The direct WebSocket URL is resolved by the user's browser. For a server-side +proxy deployment, supply a backend address reachable from the container instead. + +## Project references + +- [Change history](s2s-client/CHANGELOG.md) +- [Realtime protocol and pipeline](docs/speech/realtime-api.md) +- [Context injection](docs/client/context-injection.md) +- [Tool calling](docs/client/tool-calling.md) +- [Troubleshooting](docs/client/troubleshooting.md) +- [Historical architecture proposal](docs/proposals/vocero-architecture.html) diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..2a6cbdb --- /dev/null +++ b/docs/README.md @@ -0,0 +1,35 @@ +# Documentation + +All maintained documentation is in English. Spanish examples represent actual +user input or spoken output. Historical proposals are identified explicitly and +do not define the current implementation. + +## Browser client + +- [Usage and configuration](client/usage.md) +- [Architecture and source map](client/architecture.md) +- [Reasoning modes](client/reasoning.md) +- [Context injection](client/context-injection.md) +- [Tool calling](client/tool-calling.md) +- [Design language](client/design.md) +- [Glossary](client/glossary.md) +- [Troubleshooting](client/troubleshooting.md) +- [Change history](../s2s-client/CHANGELOG.md) + +## Speech backend + +- [Language model backends](speech/llm.md) +- [Speech-to-text backends](speech/stt.md) +- [Text-to-speech backends](speech/tts.md) +- [Realtime API, tools, and interruption handling](speech/realtime-api.md) + +## Decisions, proposals, and examples + +- [Example files and usage](examples/README.md) +- [ADR 0001: Docker hosting and search proxy](adr/0001-docker-space-with-search-proxy.md) +- [Historical Vocero architecture proposal](proposals/vocero-architecture.html) +- [Agent-profile example](examples/agent-profile.json): an illustrative profile + with agent instructions and tool definitions; this is not the current + `/api/config` response or an automatically loaded runtime configuration. +- [Reference audio](examples/reference-audio.wav): an optional voice-cloning + example described in the [TTS guide](speech/tts.md). diff --git a/s2s-client/docs/adr/0001-docker-space-with-search-proxy.md b/docs/adr/0001-docker-space-with-search-proxy.md similarity index 77% rename from s2s-client/docs/adr/0001-docker-space-with-search-proxy.md rename to docs/adr/0001-docker-space-with-search-proxy.md index 740a506..624fe56 100644 --- a/s2s-client/docs/adr/0001-docker-space-with-search-proxy.md +++ b/docs/adr/0001-docker-space-with-search-proxy.md @@ -1,11 +1,15 @@ # Convert the static Space into a Docker app with a search proxy +Status: accepted. This records the original hosting decision; the current route +is `/api/search`, and the current container also includes the root documentation. +See [client usage](../client/usage.md) for the root-context Docker build. + To give the model a web search tool, the executor (which runs in the browser of a public Space) needs a search key. A `sdk: static` Space serves files as-is with no runtime process, so it cannot hold a secret the browser uses without exposing it. We convert the Space from `sdk: static` to `sdk: docker`: a single container runs a small server (FastAPI + uvicorn) that both serves the existing front-end *unchanged* -and exposes a same-origin `/search` proxy holding `SERPER_API_KEY` server-side. The +and exposes a same-origin `/api/search` proxy holding `SERPER_API_KEY` server-side. The whole app lives in that one container; the s2s speech-to-speech backend stays the separate load-balanced service it already is. @@ -23,7 +27,7 @@ separate load-balanced service it already is. - Deployment is no longer static: there is a Dockerfile and a server process; the README front-matter changes from `sdk: static` to `sdk: docker`. -- The client calls `/search` same-origin; the server reads the key from env. A user +- The client calls `/api/search` same-origin; the server reads the key from env. A user may still supply their own key as a fallback, sent per-request to the proxy. - The front-end, audio pipeline, and s2s handshake are untouched — only the hosting shape and the new route are added. diff --git a/docs/client/architecture.md b/docs/client/architecture.md new file mode 100644 index 0000000..76dd251 --- /dev/null +++ b/docs/client/architecture.md @@ -0,0 +1,98 @@ +# Client architecture + +The [browser client](../../s2s-client) combines a voice UI with a FastAPI server. +The speech pipeline and optional Node-RED reasoning service run separately. +Runtime configuration comes from environment variables and the root `.env`. + +```mermaid +flowchart LR + Browser[Browser UI] + Server[Client FastAPI server] + Speech[Realtime speech backend] + Reasoning[Node-RED or HTTP reasoning provider] + Tools[ApiPilot backend] + Browser -->|HTTP configuration and proxies| Server + Browser <-->|WebSocket via local proxy| Server + Server <-->|Realtime events and audio| Speech + Browser <-->|Optional direct connection| Speech + Server -->|Optional transcript reasoning| Reasoning + Server -->|Tool discovery and execution| Tools +``` + +## Connection modes + +`SPEECH_TO_SPEECH_URL` pins a direct browser connection. Otherwise, +`S2S_PROXY_TARGET` exposes the same-origin `/v1/realtime` proxy. Either setting +disables load-balancer mode. With neither set, `LOAD_BALANCER_URL` enables the +session/queue proxy, or the user can enter a direct URL in settings. See +[usage](usage.md) for the configuration matrix. + +The local realtime proxy relays audio and events in both directions. It also +patches selected `session.update` instructions, handles ApiPilot marker-based +tool execution, filters internal text, and can suppress speculative/tool-marker +audio. It is not an unconditional byte-for-byte tunnel. + +## Source map + +| Source | Responsibility | +|---|---| +| [server.py](../../s2s-client/server.py) | Configuration, static serving, WebSocket relay, context loading, ApiPilot, reasoning, search, queue and usage routes | +| [main.js](../../s2s-client/main.js) | UI state, settings, transcripts, caller/report displays, custom RAG context, and external reasoning | +| [index.html](../../s2s-client/index.html) | Orb and light-theme voice controls, inline chat, dialogs, profile and reports sidebar | +| [style.css](../../s2s-client/style.css) | Dark aurora/glass theme, light theme, responsive layout and motion | +| [ui/chat.js](../../s2s-client/ui/chat.js) | Transcript history, tool results, export and autoscroll | +| [ui/account.js](../../s2s-client/ui/account.js) | Account controls, queue and usage dialogs | +| [ui/dom.js](../../s2s-client/ui/dom.js) | DOM, escaping and error-display helpers | +| [ws/s2s-ws-client.js](../../s2s-client/ws/s2s-ws-client.js) | Realtime events, microphone/playback, session updates, tool-call events and ApiPilot prompt catalog | +| [ws/codec.js](../../s2s-client/ws/codec.js) | PCM/base64 conversion and transcript extraction | +| [ws/orb-visualizer.js](../../s2s-client/ws/orb-visualizer.js) | Audio-reactive orb state | +| [auth.py](../../s2s-client/auth.py) | Hugging Face OAuth and caller identity/tier | +| [limiter.py](../../s2s-client/limiter.py) | SQLite daily talk-time reservations and reconciliation | +| [flows.json](../../s2s-reasoning-engine/flows.json) | Node-RED reasoning and assistant-response logging | + +## Server routes + +| Route | Purpose | +|---|---| +| `GET /api/config` | Connection settings, primary prompt, reasoning/theme/start modes, and feature flags | +| `WS /v1/realtime` | Local realtime proxy to `S2S_PROXY_TARGET` | +| `POST /api/reasoning` | Node-RED or OpenAI-compatible HTTP reasoning; disabled in `PROXY` mode | +| `GET /api/user/phone` | Configured caller profile lookup | +| `GET /api/user/reports` | Configured scheduled report lookup, subject to report-injection controls | +| `GET /api/apipilot/tools` | Tool discovery with optional authorization and cache refresh | +| `POST /api/apipilot/execute` | Validated tool execution returning a `success/data/error` envelope | +| `POST /api/search` | Serper web search proxy | +| `/api/session`, `/api/queue/*` | Load-balancer session and waiting-queue proxies | +| `/api/me`, `/api/session/heartbeat`, `/api/session/end` | Identity, reservation extension and usage reconciliation | + +The root serves the UI. `/docs` remains the FastAPI API explorer, while project +documentation files are served in the `/docs/` subdirectories. Markdown remains +source text, and directories without `index.html` are not browsable pages. +Static HTML, JS and CSS +responses receive `Cache-Control: no-store` during development. + +## Audio path + +1. The browser captures microphone audio with echo cancellation, noise + suppression and automatic gain-control settings. +2. [mic-capture.js](../../s2s-client/worklets/mic-capture.js) resamples to 16 kHz + mono PCM16. The browser sends base64 `input_audio_buffer.append` frames. +3. The backend processes VAD → STT → LLM → TTS and emits realtime events. +4. Assistant PCM16 audio at 24 kHz is decoded and sent to + [audio-playback.js](../../s2s-client/worklets/audio-playback.js), which buffers, + resamples and fades playback edges. Input speech can clear playback for barge-in. + +Audio worklets are loaded through `AudioWorklet.addModule`; keep their processor +registration structure intact when editing them. The speech backend's thread +and cancellation model is documented in [realtime API](../speech/realtime-api.md). + +## Reasoning and context + +The browser triggers external reasoning on completed user transcripts only in +`OPENAI` or `NODE_RED` mode. Node-RED `log_only=true` responses leave native speech +output running; an answer-producing response uses the external-answer path. +The server can independently forward assistant text to Node-RED for paired +conversation logs. These HTTP operations supplement the realtime audio path. + +Read [reasoning](reasoning.md), [context injection](context-injection.md), and +[tool calling](tool-calling.md) for the conditions and limitations of each path. diff --git a/docs/client/context-injection.md b/docs/client/context-injection.md new file mode 100644 index 0000000..d429c8f --- /dev/null +++ b/docs/client/context-injection.md @@ -0,0 +1,132 @@ +# Context injection + +Context reaches the assistant through browser-built instructions, server-patched +realtime session instructions, and HTTP reasoning context. The implementation is +in [server.py](../../s2s-client/server.py), +[main.js](../../s2s-client/main.js), and the +[WebSocket client](../../s2s-client/ws/s2s-ws-client.js). + +## Independent controls + +`S2S_INJECT_PROFILE` defaults to false and gates server loading of caller, +episode, report and prior-conversation context. It also controls whether the +browser appends caller profile text to its realtime instructions. + +It is not a master switch for every context source. Operator-supplied RAG text +and configured ApiPilot discovery work independently. `S2S_INJECT_TODAY` +defaults to true; date and voice-output guards are built on paths that invoke +instruction augmentation or HTTP context assembly. A WebSocket session with no +profile/episode/report/summary or ApiPilot block skips proxy augmentation. +Direct browser connections bypass server-side WebSocket injection entirely. + +| Setting | Default | Effect | +|---|---|---| +| `S2S_INJECT_PROFILE` | false | Enable server-resolved caller, episode and history context | +| `S2S_INJECT_REPORTS` | false | Allow scheduled-report fetch/injection; also requires the profile gate | +| `S2S_REPORTS_INJECT_MODE` | `minimal` | `minimal`: labels/dates; `full`: scripts; `off`/`none`: no report prompt block | +| `S2S_REPORTS_QUICK_HINT_MAX` | 5 | Keep at most this many newest reports, clamped to 1–50 | +| `S2S_INJECT_TODAY` | true | Add the current server-local date guard when its context builder runs | +| `S2S_DEBUG_PROMPT` | false | Log complete prompt/context text instead of only summaries | + +## Context sources + +| Block | Trigger and source | Size/behavior | +|---|---|---| +| Podcast episode | `episode_id` page/query/body value and profile gate | Up to 24,000 characters of serialized episode content | +| Caller profile | `phoneNumber` and `VOCERO_USER_PHONE_AUTH_URL` | Up to 1,600 serialized characters | +| Scheduled reports | `S2S_REPORT_LIST`, profile gate and report gate | Newest N labels/dates by default; full mode includes scripts with a 12,000-character block limit | +| Latest conversation | `S2S_LATEST_SUMMARY_TEXT`, or `S2S_LATEST_SUMMARY` with a phone number | Up to 1,600 characters; static text overrides HTTP fetch | +| Custom RAG | Operator applies text through the RAG dialog | Up to 12,000 characters; appended in browser instructions and HTTP `user_context` | +| ApiPilot discovery | Configured `S2S_APIPILOT_TOOLS_URL` | Tool names/descriptions/auth requirements and call-marker rules, independent of the profile gate | + +### Episode + +The current episode fetch uses the deployment-specific URL: + +```text +https://aquachile.azurianlab.com/api/v1/podcast/episodes/{episode_id} +``` + +It follows redirects with a 15-second timeout, accepts JSON or plain text, +unwraps a `result` field, and includes arbitrary episode fields. The prompt +labels it as the primary reference for the user's current episode. The endpoint +is hardcoded in the fetch helper rather than selected through an environment +variable. + +### Caller profile and login + +For caller-specific context, the proxy can first post +`{"phoneNumber":"+56912345678"}` to `S2S_LOGIN_BY_PHONE`, extract a bearer token, +and forward it to subsequent profile/history requests. Profile retrieval uses +`GET VOCERO_USER_PHONE_AUTH_URL?phoneNumber=...` with a 10-second timeout and +accepts an object, optionally wrapped in `result`. + +Encode the leading plus sign in page links, for example +`?phoneNumber=%2B56912345678`. Caller information is also fetched through +`/api/user/phone` for the UI. An available profile can update live browser +instructions when profile injection is enabled. + +### Scheduled reports + +`S2S_INJECT_REPORTS=false` skips report fetching and prompt content, including +the table of contents. When enabled, the report endpoint may be called with or +without a phone number. The resolver keeps dictionary entries, reads +`sourceScheduleLabel` or `sourceSchedule.label`, reads `date` or +`sourceSchedule.date`, and optionally keeps `podcastScript` in full mode. + +Entries are sorted newest first using ISO/date/timestamp handling and an +ISO-like string fallback. Empty/unparseable dates sort last. The newest-item +limit applies before constructing the prompt block. `minimal` exposes only the +labels and dates; `full` explicitly opts into script content. + +### Latest conversation summary + +`S2S_LATEST_SUMMARY_TEXT` takes priority over `S2S_LATEST_SUMMARY` and needs no +phone number or network request. Literal `\n` sequences in the environment value +become newlines. Otherwise the proxy fetches +`S2S_LATEST_SUMMARY?phoneNumber=...` and accepts text or JSON with an optional +`result` wrapper. Both sources pass through the same cap and history wrapper. + +### Custom RAG + +The operator can paste reference material and explicitly apply it to the +session. The browser appends it to instructions even with profile injection +disabled, includes it in HTTP `user_context`, and updates an open realtime +session. This context does not require an external retrieval endpoint. + +## Application timing and order + +At local WebSocket connect, the server resolves enabled context and stores it in +`session_ctx`. Each client `session.update` then passes through +`_patch_client_session_update_with_profile()`. Other client frame types are not +modified by this helper. The broader relay still performs ApiPilot handling and +text/audio filtering. + +The current augmentation function **keeps base instructions first**, then +appends surviving voice-output guards, date context, episode, profile, reports, +and summary blocks. ApiPilot discovery is appended separately. If a block type +is already present in the base, deduplication may omit its server candidate. +This describes string assembly, not a guarantee of model attention or priority. + +Every HTTP reasoning request rebuilds enabled context. Its `user_context` +assembly orders voice guard, date, episode, profile, reports, summary, ApiPilot +and browser-provided context, then deduplicates recognized types and strips +internal markers. Server instruction augmentation remains separate, so avoid +assuming the WebSocket and HTTP prompts have identical ordering. + +Context markers support internal deduplication and diagnostics; ordinary +profile/report/episode/history sentinels are stripped before final augmentation. +ApiPilot call/catalog markers have their own handling. Treat the source helpers +as the reference for the exact final payload. + +## Failure behavior and inspection + +Optional context-fetch errors are logged and the affected context is skipped. +The speech conversation normally continues without that reference material. +This does not mean all API calls ignore errors: missing reasoning configuration, +invalid tool arguments and tool authorization can return explicit errors. + +Inspect `/api/config` for active gates, the actual outbound `session.update` in +browser DevTools, and `[INJECT-*]`/`[DEBUG-PROMPT]` server logs. Full prompt +logging includes caller data and conversation text. See +[troubleshooting](troubleshooting.md) for a step-by-step diagnostic flow. diff --git a/docs/client/design.md b/docs/client/design.md new file mode 100644 index 0000000..f85fcb5 --- /dev/null +++ b/docs/client/design.md @@ -0,0 +1,90 @@ +# Design language + +This guide describes the current browser UI. Use +[style.css](../../s2s-client/style.css) as the token/selector reference and +[index.html](../../s2s-client/index.html) for the theme-specific structure. +Earlier documentation described a monochrome-only dark UI; the current design +also uses aurora gradients, glass surfaces, and a separate light theme. + +## Themes and tokens + +`S2S_THEME=white` selects the white/blue interface. Empty or `dark` selects the +dark aurora interface. The browser sets `html[data-theme]` after configuration +loads; an initial visibility guard prevents the wrong theme flashing on first +paint. Extend the existing theme selectors when adding components. + +| Token group | Dark theme values/purpose | +|---|---| +| Canvas | `--bg: #07080d`; translucent `--bg-elev` and `--bg-elev-2` surfaces | +| Glass | `--glass` and `--glass-strong` for translucent floating elements | +| Text | `--text`, `--text-dim`, `--text-faint` | +| Borders | `--border` and `--border-strong` hairlines | +| Brand | `--brand: #8b5cf6`, `--brand-2: #ec4899`, `--brand-3: #22d3ee` | +| Radius | `--radius-sm: 10px`, `--radius-md: 16px`, `--radius-lg: 26px`, `--radius-xl: 34px` | +| Shadows | `--shadow-soft`, `--shadow-glow-brand`, `--shadow-glass` | + +Prefer existing variables and `color-mix` over new unrelated colors. The dark +theme's orb is the strongest visual focus, while gradients and restrained role +tints also appear in the surrounding interface. The white theme changes +surfaces, typography contrast, controls and chat presentation through its own +selector overrides rather than a second stylesheet. + +## Voice state + +| State | Dark-theme color | +|---|---| +| Listening/user speaking | Cyan (`--listening`) | +| Assistant speaking | Violet (`--speaking`) | +| Processing | Amber (`--processing`) | +| Ready/authenticated | Green (`--success`) | +| Error | Red (`--error`) | + +`--voice-user`, `--voice-assistant` and `--voice-tool` connect transcript roles +to the same state vocabulary. When adding a state, define its existing control, +caption and transcript behavior together. Light-theme controls can use their +blue palette while retaining recognizable state feedback. + +## Typography and copy + +Use Inter (`--font-sans`) for human prose, buttons, settings and transcript +bodies. Geist Mono (`--font-mono`) is reserved for machine status, role labels, +tool identifiers and diagnostic JSON. Font stacks have system fallbacks. + +Visible labels, accessibility text, permission instructions and recovery +messages default to Spanish. Source identifiers, comments, diagnostic logs and +internal model instructions use English. Exact model/voice/protocol identifiers +and proper names are preserved. Spanish wake phrases are user-input literals. + +Use sentence case and concrete verbs. Empty states should explain the next +action; errors should say what failed and how to recover. Keep internal system +details out of ordinary user flows. + +## Layout and components + +The page uses a column layout: header, voice stage, always-visible inline +conversation, and sticky footer. The conversation is no longer the old +toggleable right overlay. Preserve space below the latest message so the sticky +footer does not obscure it; chat autoscroll retries after layout/reflow changes. + +In the dark theme, the reports sidebar is fixed on the left at desktop widths +of at least 1024px. On smaller screens it becomes an off-canvas panel with a +toggle and backdrop. The white theme hides the sidebar, its toggle, and hint. +The user avatar opens a profile dialog; profile fields collapse from two +columns on narrow screens. Some controls are intentionally gated by `?debug=true`. + +Use the existing button, icon-button, modal, switch and chat-message classes. +The dark theme uses glass bubbles with role tints, borders and restrained glow; +the light theme uses its white/blue message and avatar treatment. Keep required +chat DOM elements intact; optional historical overlay controls may be absent. + +## Motion and accessibility + +Microphone RMS and assistant audio levels drive the voice visualization. +Breathing, glow and decorative gradients should remain subordinate to speech +feedback. `body.booting` suppresses initial transitions; new animation should +respect that state and `prefers-reduced-motion`. + +For changes, verify both themes, narrow mobile layouts down to 360px, keyboard +focus, dialog dismissal, and readable contrast. Prefer touch targets of at least +44px and respect safe-area padding. A CSS guideline is not proof that every +existing control already meets the target. diff --git a/docs/client/glossary.md b/docs/client/glossary.md new file mode 100644 index 0000000..6697e05 --- /dev/null +++ b/docs/client/glossary.md @@ -0,0 +1,40 @@ +# Context glossary + +These terms explain the product and its conversation flow. Implementation +details belong in [architecture](architecture.md) and the source. Model/provider +names shown in a deployment are configuration examples, not definitions. + +| Term | Meaning | +|---|---| +| Speech-to-speech client | The browser interface used to start a voice conversation, display transcripts, and play the assistant's reply | +| Pipeline | The ordered backend path: VAD → STT → LLM → TTS | +| VAD | Voice activity detection; determines when a user speech segment starts and stops | +| STT | Speech to text; transcribes an audio utterance | +| LLM | Language model; generates response text and optional tool calls | +| VLM | Vision-language model; a language model with image support when that capability is configured | +| TTS | Text to speech; synthesizes response audio with the configured voice/model | +| Realtime backend | The service that processes audio and exposes the `/v1/realtime` WebSocket protocol | +| Client server/proxy | The local FastAPI service serving the page and optional HTTP/WebSocket bridges | +| Builder | A person/team credited with creating the interface or deployment, distinct from a model's authors | +| Powered by | Hosting or inference infrastructure credited by the deployment | +| Tool | A callable operation used on demand; distinct from the pipeline stages that process ordinary turns | +| Native tool declaration | A function name, description and JSON Schema sent in `session.tools` | +| Tool executor | Code that receives a tool call, executes it and returns the result to the model | +| Web search | The browser-supported native tool whose request goes through the server's `/api/search` proxy | +| Search proxy | Same-origin server route holding a deployment search key and calling the external provider | +| ApiPilot | The dynamic-tool discovery/execution bridge, with both HTTP endpoints and model-text call markers | +| Call marker | Internal structured text such as `<<>>` used by the ApiPilot bridge; separate from native function-call events | +| Tools panel | Controls for available browser tools and search-key configuration | +| Settings | Connection, voice, audio and instruction controls persisted in browser storage | +| Identity block | The header's product/user identity, separate from configuration dialogs | +| About panel | Introduction and project/pipeline credits | +| Caller profile | Information looked up using the page's `phoneNumber`, used for identity display and optionally model context | +| RAG context | Reference material explicitly applied by the operator for the current session | +| Episode context | Content loaded for the page's `episode_id`, treated as the current episode reference | +| Queue | Users waiting for an available compute slot; waiting is not yet an active conversation | +| Ticket | A held queue position returned by the load balancer | +| Position | The displayed place in the queue; distinct from a time estimate | +| Claim | The transition from a waiting ticket to an allocated realtime session and usage reservation | +| At capacity | A full waiting queue that cannot accept another ticket | +| Barge-in | User speech interrupts an active assistant response, coordinating playback clearing and backend cancellation | +| Log-only reasoning | External transcript processing that observes/logs the turn without replacing native speech output | diff --git a/docs/client/reasoning.md b/docs/client/reasoning.md new file mode 100644 index 0000000..ab093dd --- /dev/null +++ b/docs/client/reasoning.md @@ -0,0 +1,106 @@ +# Reasoning modes + +Reasoning determines the assistant's response text. The realtime backend always +provides the speech channel; optional HTTP reasoning can observe a transcript or +produce a separate answer. Set `S2S_REASONING_TYPE` to select the mode. + +| Mode | Response owner | HTTP hook | +|---|---|---| +| `PROXY` (default) | Realtime backend | Browser does not call `/api/reasoning`; that endpoint returns 409 | +| `NODE_RED` | Realtime backend for `log_only=true`; external answer otherwise | Server forwards to `S2S_REASONING_NODE_RED_URL/api/reasoning` | +| `OPENAI` | OpenAI-compatible Chat Completions response | Server calls `OPENAI_BASE_URL/chat/completions` | + +The mode is normalized case-insensitively. `NODERED` and `NODE-RED` resolve to +`NODE_RED`; unknown values resolve to `PROXY`. + +## Shared instruction assembly + +In [main.js](../../s2s-client/main.js), `effectiveReasoningInstructions()` starts +with `pinnedPrompt || settings.instructions`. `/api/config` pins +`S2S_PRIMARY_PROMPT` when non-empty; otherwise the settings prompt or +`DEFAULT_INSTRUCTIONS` is used. The current server does not fetch a remote agent +profile to choose this base prompt. + +The browser adds caller context when `injectProfile` is enabled, custom RAG text +when the operator has applied it, and an available ApiPilot catalog block. +`effectiveInstructions()` adds `OPENAI_RENDER_HINT` only in `OPENAI` mode. +The WebSocket client packages these instructions in `session.update.session`; +the local proxy may then add server-resolved context. Details belong in +[context injection](context-injection.md). + +## Native realtime reasoning (`PROXY`) + +The realtime backend receives session instructions and enabled native tools, +then processes each voice turn through STT, model generation and TTS. +Native function-call events are executed by the browser. ApiPilot also has a +separate marker-based path handled by the local proxy. These are distinct +protocols, described in [tool calling](tool-calling.md). + +Using a direct browser URL bypasses local WebSocket proxy processing. Browser +instructions still apply, but server-side session context and marker execution +require the local `/v1/realtime` route. + +## Node-RED reasoning + +Configure a Node-RED base URL reachable by the UI server: + +```env +S2S_REASONING_TYPE=NODE_RED +S2S_REASONING_NODE_RED_URL=http://localhost:1881 +``` + +`maybeRunOpenAiReasoning()` handles both external modes despite its historical +function name. It runs after a complete user transcript and posts a body with +`transcript`, `instructions`, `language`, `user_context`, `phoneNumber`, and +`episode_id`. The server builds context and forwards the reasoning fields to +Node-RED with a 30-second timeout. + +The checked-in Node-RED flow exposes `POST /api/reasoning` and +`POST /api/log/system-response`. Its reasoning response uses `log_only=true` and +an empty answer. The browser returns early in that case, preserving the native +backend's response. Assistant-text logging is forwarded separately by the relay +and is not an audio transport. + +An answer-producing flow must return a non-empty `answer` and omit `log_only` or +set it to `false`. That activates the external-answer behavior below. + +## OpenAI-compatible HTTP reasoning + +```env +S2S_REASONING_TYPE=OPENAI +OPENAI_API_KEY=YOUR_API_KEY +OPENAI_BASE_URL=https://api.openai.com/v1 +OPENAI_REASONING_MODEL=gpt-4.1-mini +``` + +`OPENAI_ORGANIZATION` and `OPENAI_PROJECT` are optional headers. The model value +is a runtime default, not a recommendation about provider availability. + +The server combines instructions and context into model messages, requests a +final answer, and returns `answer` with available usage metadata. ApiPilot can +append discovery instructions, execute a detected call marker, and request a +second response based on the tool result. The endpoint does not forward the +browser's native `session.tools` catalog as OpenAI Chat Completions `tools`. + +For a non-log-only answer, the browser cancels/suppresses the active native +response and appends the external assistant text. It uses browser +`SpeechSynthesis` when available. Its compatibility fallback sends +`[VOCERO_RENDER_REPLY]` plus the answer to the realtime backend and requests a +response. The render hint asks the model to read only the answer after that +marker. This instruction is model behavior, not a guarantee of exact playback. + +External reasoning adds an HTTP operation to each completed transcript and has +separate provider token usage. It is not the speech pipeline's `responses-api` +or `chat-completions` LLM backend setting; those configure the model inside the +realtime backend instead. + +## Where to change behavior + +| Goal | Source | +|---|---| +| Change the base agent prompt | `S2S_PRIMARY_PROMPT` or browser settings when unpinned | +| Change browser context assembly | `effectiveReasoningInstructions()` in `main.js` | +| Change HTTP provider messages | `reasoning()` in `server.py` | +| Change external-answer rendering | `maybeRunOpenAiReasoning()` in `main.js` | +| Change Node-RED processing | `s2s-reasoning-engine/flows.json` | +| Change native model/tool generation | `speech_to_speech/LLM` and realtime handlers | diff --git a/docs/client/tool-calling.md b/docs/client/tool-calling.md new file mode 100644 index 0000000..d9b27f4 --- /dev/null +++ b/docs/client/tool-calling.md @@ -0,0 +1,137 @@ +# Tool calling + +The application has two tool mechanisms: native realtime function calling and +ApiPilot calls detected from model text. A spoken promise to fetch something is +not evidence that either mechanism executed a tool. + +## Native realtime function calls + +The browser sends tool declarations inside the `session` object: + +```json +{ + "type": "session.update", + "session": { + "type": "realtime", + "tools": [ + { + "type": "function", + "name": "web_search", + "description": "Search the web for information.", + "parameters": { + "type": "object", + "properties": {"query": {"type": "string"}}, + "required": ["query"] + } + } + ], + "tool_choice": "auto" + } +} +``` + +Keep configuration inside `session`, not at the event root. The backend has a +legacy flat-payload compatibility path, but new clients should use the nested +shape. The current browser's `activeToolDefs()` declares `web_search` when +enabled and a deploy/user search key is available. It does not load the old +remote agent-profile MCP catalog into native session tools. + +For a native call, the backend emits: + +```json +{ + "type": "response.function_call_arguments.done", + "call_id": "call_example", + "name": "web_search", + "arguments": "{\"query\":\"example query\"}" +} +``` + +`arguments` is a JSON-encoded string. The +[WebSocket client](../../s2s-client/ws/s2s-ws-client.js) parses it and dispatches +`toolcall`; [main.js](../../s2s-client/main.js) runs the supported executor. +Web search uses `POST /api/search`, keeping the deployment's Serper key on the +server. Tool output returns to the model as: + +```json +{ + "type": "conversation.item.create", + "item": { + "type": "function_call_output", + "call_id": "call_example", + "output": "Tool result text" + } +} +``` + +The client requests follow-up generation with `response.create` when the +result should be spoken. A `function_call_output` item alone does not start +generation. See the [realtime API guide](../speech/realtime-api.md) for local +model `` extraction and native remote-provider tool calls. + +## ApiPilot discovery and execution + +`S2S_APIPILOT_TOOLS_URL` enables the current dynamic-tool bridge. The backend +discovers tools through its `/tools` route and executes through `/execute`. +`S2S_APIPILOT_TOOLS_EXECUTE_URL` can override the execution target. The same-origin UI +server exposes: + +- `GET /api/apipilot/tools?include_unauthorized=true`: discovery envelope with + `data.tools`, `data.count`, and `data.include_unauthorized`. +- `POST /api/apipilot/execute`: body `{"name":"tool_name","arguments":{}}` and + a `success/data/error` envelope. + +Tool definitions contain `name`, `description`, JSON Schema `parameters`, and +`requires_auth`. Execution looks up the current discovery cache, refreshes once +if the tool is missing, and applies an authorization gate and argument +validation before forwarding. Caller `Authorization` and +`x-demo-session` can be forwarded; configured service credentials and +login-by-phone provide additional server paths. Display `error.message` to the +user; keep `error.code`, `error.status_code`, and `error.raw` for diagnostics. + +The discovery cache defaults to 300 seconds server-side +(`S2S_APIPILOT_TTL_SEC`) and can be refreshed with `refresh=true`. The browser +also keeps a per-user catalog cache. ApiPilot configuration is independent of +`S2S_INJECT_PROFILE`. + +## Marker-based two-pass reasoning + +The browser and proxy add an ApiPilot catalog as **instruction text**, including +tool names, descriptions, authentication requirements and required parameters. +The model is instructed to emit a call marker when it chooses a matching tool: + +```text +<<>> +``` + +Tool names are exact identifiers and must not be translated. The local realtime +proxy accumulates assistant text, detects the marker, validates and executes +the ApiPilot call, then injects the result as context and requests a new +response. The HTTP reasoning route has analogous discovery/execution and +second-answer handling. Internal marker text and its speculative audio are +filtered from user output where those handlers run. + +This marker is not `response.function_call_arguments.done`, and ApiPilot prompt +discovery is not the same as declaring a native `session.tools` array. Direct +browser connections bypass the local relay's marker executor even if the +browser includes catalog instructions. + +## Retired documentation assumptions + +The former `HOWITWORKS.md` described `/api/mcp/tool`, remote +`S2S_AGENT_PROFILE` loading, and Spanish/Italian-to-English client ranking. +Those APIs/rankers are absent from the current client/server path. The retained +agent-profile JSON is an illustrative historical/example shape. Add or modify +current ApiPilot tool definitions in the provider; do not restore obsolete +endpoints solely to match older documentation. + +## Verify a tool turn + +1. Confirm `/api/config` reports the intended feature and connection mode. +2. Inspect `session.update`: native `tools` and ApiPilot instruction text are + separate evidence. +3. For native calls, find `response.function_call_arguments.done`, then the + browser `toolcall` and executor request. +4. For ApiPilot, find the discovery, call-marker detection and execution logs. +5. Confirm the tool result reaches the model and follow-up text/audio reaches + the browser. A spoken acknowledgement alone does not complete the flow. diff --git a/docs/client/troubleshooting.md b/docs/client/troubleshooting.md new file mode 100644 index 0000000..c68c6b1 --- /dev/null +++ b/docs/client/troubleshooting.md @@ -0,0 +1,115 @@ +# Troubleshooting + +Diagnose configuration, protocol events, execution and playback separately. +Use [architecture](architecture.md), [tool calling](tool-calling.md) and +[context injection](context-injection.md) to identify which path is active. + +## Check configuration and connection first + +Inspect the server configuration without printing secret environment files: + +```bash +curl -fsS http://localhost:8420/api/config | jq +``` + +Confirm `s2sUrl`, `lb`, `reasoningType`, `injectProfile`, `apipilot`, `theme` +and `startSessionMode`. A direct WebSocket URL bypasses the local relay's +server-side context injection and marker execution. For a local proxy, confirm +the server can resolve and reach `S2S_PROXY_TARGET`. + +In browser DevTools, inspect the WebSocket handshake and `session.created`, +`session.update` and error events. Check that instructions and native tools are +inside `session`. A cached browser module can disagree with current server +code; inspect served asset versions and reload with cache disabled when needed. + +## The assistant promises a tool but nothing happens + +Follow the actual execution mechanism: + +1. For a native tool, confirm it appears in the outbound `session.tools` array. +2. Find `response.function_call_arguments.done` with a tool name, `call_id`, and + JSON-string arguments. +3. Confirm the browser dispatched `toolcall` and the executor sent its request. +4. Confirm `function_call_output` and any required `response.create` were sent. +5. For ApiPilot, inspect discovery, marker detection, authorization/schema + validation, execution, and second-pass result injection instead. + +A spoken sentence such as “Voy a buscar el reporte” does not satisfy step 2. +If the function-call event is absent, inspect model/backend tool generation +before debugging a browser executor that has not been invoked. + +Earlier local debug notes recorded a reproduction where tools and required +tool policy were sent but the model produced only spoken text. Those notes +refer to the retired MCP ranking path; they do not establish a current ApiPilot +failure. Both local investigation notes remain marked `OPEN`. Their useful +lesson is to collect evidence at each boundary and reproduce against current +code before claiming a root cause is resolved. + +## The assistant misses caller or report context + +- Verify the page has an encoded `phoneNumber` or the intended `episode_id`. +- Inspect `/api/user/phone` and context-fetch logs for HTTP/JSON failures. +- Confirm profile injection is enabled; a visible profile alone does not prove + realtime instructions contain it. +- Reports need `S2S_INJECT_REPORTS=true`; `minimal` sends only labels and dates. + A historical script will not be in the prompt in that mode. +- Static summary text overrides the HTTP summary endpoint. +- Inspect the final `session.update` rather than only its browser base prompt. + The proxy can append and deduplicate context after the browser sends it. + +`S2S_DEBUG_PROMPT=true` enables complete prompt logs, including caller information +and conversation text. Use summaries when full payloads are unnecessary. The +browser's application functions are module-scoped; do not assume names such as +`effectiveInstructions()` are available directly on `window` in DevTools. + +## Short gaps or clipped words around tool results + +The retained audio investigation found very low local serialization/render +times for one large tool result, while still observing audio interruptions. +That evidence ruled out a UI-render bottleneck for that reproduction; it does +not rule out rendering costs for all future payloads. + +Useful checks are: + +- Measure tool-result size, prompt length, serialization time and UI render time. +- Inspect whether result injection overlaps an active or pending response. +- Check whether a speculative response starts before its `response.created` + reaches the browser. Cancellation based only on an existing response ID can + miss that window. +- Inspect deferred text/response queues and whether they flush after + `response.done` rather than interrupting the active turn. +- Inspect playback prebuffering and queue underflow, especially when the first + words of every sentence are affected. +- Confirm oversized tool results are summarized or capped on the relevant + path rather than assuming every tool payload gets the same treatment. + +The historical investigation introduced a 90ms playback prebuffer and reduced +MCP prompt reinjection. The old 150ms MCP fallback timer is historical, not a +current ApiPilot configuration knob. Verify the live worklet and current relay +before changing audio timing based on those observations. + +## External reasoning and startup + +`/api/reasoning` returning 409 is expected in `PROXY` mode. In `NODE_RED`, check +that `S2S_REASONING_NODE_RED_URL` is reachable from the server and whether the +response is `log_only=true`. An empty answer is valid only in log-only mode. +In `OPENAI`, check the configured endpoint/model/key and provider logs; HTTP +reasoning does not use the native session's tool array. + +For `TALK`/`TALKFIRST`, the two-second warmup does not override browser +microphone/audio permissions. If automatic startup fails, use the unlocker +gesture and inspect the permission error rather than increasing the timer +without evidence. + +## Read-only source checks + +From the repository root, useful syntax checks are: + +```bash +node --check s2s-client/main.js +node --check s2s-client/ws/s2s-ws-client.js +python -m py_compile s2s-client/server.py +``` + +Syntax checks do not validate microphone access, network services, model output, +or audio quality. Collect a fresh browser/backend reproduction for those paths. diff --git a/docs/client/usage.md b/docs/client/usage.md new file mode 100644 index 0000000..2c9caf4 --- /dev/null +++ b/docs/client/usage.md @@ -0,0 +1,153 @@ +# Client usage and configuration + +The browser voice client connects to an existing OpenAI Realtime-compatible +speech backend. The UI server can also proxy WebSocket traffic, search, +reasoning, caller context, ApiPilot tools and load-balancer requests. + +## Local startup + +From the repository root: + +```bash +SPEECH_TO_SPEECH_URL=ws://localhost:8765/v1/realtime ./start_ui.sh +``` + +The launcher loads the root `.env`, creates `.venv` if needed, installs the +client requirements when the dependency check fails, and runs uvicorn on port +8420. `UI_PORT` overrides the UI port. Because `.env` is sourced by the script, +values in that file can replace variables supplied on the command line. + +To install and start the UI manually: + +```bash +python3 -m venv .venv +.venv/bin/python -m pip install -r s2s-client/requirements.txt +SPEECH_TO_SPEECH_URL=ws://localhost:8765/v1/realtime \ + .venv/bin/python -m uvicorn --app-dir s2s-client server:app --port 8420 +``` + +Open , tap the orb/microphone control, grant microphone +access, and speak. Microphone access requires HTTPS or a local browser origin; +use HTTPS when accessing the UI from another machine. + +The speech pipeline has separate model/runtime dependencies and no complete +dependency manifest in this checkout. In an already prepared speech +environment, a local realtime server can be started with: + +```bash +python -m speech_to_speech.s2s_pipeline \ + --mode realtime \ + --stt parakeet-tdt \ + --llm_backend transformers \ + --tts kokoro \ + --model_name Qwen/Qwen3-4B-Instruct-2507 \ + --llm_device cuda \ + --llm_torch_dtype float16 \ + --enable_live_transcription +``` + +Select backends and devices supported by the host; the example model is not a +fixed deployment requirement. The default realtime endpoint is +`ws://localhost:8765/v1/realtime`, configured through `--ws_host` and `--ws_port`. +`--num_pipelines` controls the number of isolated concurrent realtime sessions. +See [LLM](../speech/llm.md), [STT](../speech/stt.md), and [TTS](../speech/tts.md). + +## Connection modes + +| Configuration | Browser connection | Settings URL | Load-balancer features | +|---|---|---|---| +| `SPEECH_TO_SPEECH_URL` set | Direct to pinned URL | Locked | Disabled | +| `S2S_PROXY_TARGET` set, no direct URL | Same-origin `/v1/realtime` proxy | Locked | Disabled | +| `LOAD_BALANCER_URL` set, neither above set | Per-session compute URL from `/api/session` | Hidden | Queue enabled; metering requires `SPACE_ID` too | +| None set | User-provided realtime URL | Editable | Disabled | + +Direct URLs may be full `ws(s)://.../v1/realtime` addresses or host values that +the browser normalizes. A direct URL must be reachable **from the browser**. +`S2S_PROXY_TARGET` must be reachable **from the UI server**. HTTPS deployments +need a secure browser WebSocket URL. + +The launcher supplies `ws://ai-server:12345/v1/realtime` as a proxy-target +default when no value is configured. That hostname must resolve from the UI +server; it is not a universally available local service. + +## Docker + +Use the project root as the build context: + +```bash +docker build -f s2s-client/Dockerfile -t s2s-client . +docker run --rm -p 7860:7860 \ + -e SPEECH_TO_SPEECH_URL=ws://localhost:8765/v1/realtime s2s-client +``` + +For the proxy path, replace the direct setting with a server-reachable +`S2S_PROXY_TARGET`. If the upstream is another container, attach the UI to the +appropriate existing network and use that service's hostname. An upstream +bound only to host loopback is not reachable via an arbitrary container name. + +The image includes `s2s-client` and root `docs`. `/docs` is still the FastAPI API +explorer; documentation lives under `/docs/client/`, `/docs/speech/`, +`/docs/adr/`, `/docs/examples/`, and `/docs/proposals/`. Legacy `/project/` and +`/public/docs.html` redirect to the historical proposal. Markdown is served as a +source file rather than rendered through a separate documentation site. Request +file paths such as `/docs/README.md`; directories without `index.html` are not +browsable pages. + +## Settings and tools + +Voice, editable system instructions and connection settings are kept in browser +`localStorage` under `s2s.ws.*` keys. A non-empty `S2S_PRIMARY_PROMPT` pins the +instruction field. Restart applies connection/voice changes to a new session. +Model voice names are runtime identifiers and stay unchanged across UI +translations. + +Web search needs `SERPER_API_KEY` on the server or a user-supplied key in the +tools panel. The server proxies requests through `/api/search`; its own key is +not returned to the browser. Dynamic ApiPilot tools are configured through +`S2S_APIPILOT_TOOLS_URL`; see [tool calling](tool-calling.md). + +Operator RAG text is applied through the RAG dialog and updates live +instructions. Caller links may include `phoneNumber=%2B...`; episode links may +include `episode_id=...`. See [context injection](context-injection.md) for +enabled data sources and limits. + +## Theme and session startup + +`S2S_THEME=white` selects the light interface. `dark` or an empty value selects +the dark aurora theme. Theme-specific sections remain hidden until configuration +resolves, with a fallback to avoid an invisible page after config failure. + +`S2S_START_SESSION_MODE` controls initial microphone/session startup: + +| Value | Behavior | +|---|---| +| Empty/default | User taps to start | +| `TALK` | After a 2-second warmup, show an audio unlocker; a user gesture starts the session and greeting | +| `TALKFIRST` | After a 2-second warmup, attempt automatic start and inject the Spanish wake phrase; microphone failure falls back to the unlocker | + +The warmup is a timer, not proof that all upstream context requests have +finished. Browser permission and audio policies can still require a gesture. +The greeting uses the same `hola vocero` input as wake-word handling. + +## Queue and daily usage + +Load-balancer mode proxies session acquisition and queue polling. Waiting does +not reserve conversation time; a daily budget is reserved when a compute slot +is granted. The server enables metering only with both `LOAD_BALANCER_URL` and +`SPACE_ID` and with neither pinned direct/proxy mode active. + +| Environment setting | Default | Purpose | +|---|---|---| +| `LIMIT_ANON_SEC` | 300 | Anonymous seconds per UTC day | +| `LIMIT_FREE_SEC` | 600 | Signed-in non-PRO seconds per UTC day | +| `UNLIMITED_ORGS` | Adds to built-in organizations | Additional unlimited organization members | +| `USAGE_HASH_SECRET` | Random if unset | Identity-key hashing and anonymous cookie signing | + +PRO members are unlimited. Built-in unlimited organizations are `cerebras`, +`HuggingFaceM4`, `smolagents`, and `pollen-robotics`; organization matching is +case-insensitive. See [auth.py](../../s2s-client/auth.py) and +[limiter.py](../../s2s-client/limiter.py) for the current enforcement behavior. + +For external transcript processing, configure the selected +[reasoning mode](reasoning.md). For connection, context and audio diagnostics, +use [troubleshooting](troubleshooting.md). diff --git a/docs/examples/README.md b/docs/examples/README.md new file mode 100644 index 0000000..9f2f151 --- /dev/null +++ b/docs/examples/README.md @@ -0,0 +1,16 @@ +# Examples + +- [agent-profile.json](agent-profile.json) is an illustrative agent-profile + response with a dynamic tool catalog. Its model instructions are written in + English and request Spanish speech through both instructions and `language`. + Tool names and schemas illustrate the original API response; this file is not + loaded by the application and is not a live API contract. +- [reference-audio.wav](reference-audio.wav) is the existing optional + voice-cloning sample, moved out of the implementation directory. CustomVoice + models do not require it. When testing a compatible Base/voice-cloning model, + supply its path explicitly with `--qwen3_tts_ref_audio + docs/examples/reference-audio.wav` from the project root and use the matching + transcription required by that model. See [the TTS guide](../speech/tts.md). + +These examples contain no deployment credentials and are not default runtime +configuration. Use an authorized reference voice for your own deployment. diff --git a/sample.json b/docs/examples/agent-profile.json similarity index 93% rename from sample.json rename to docs/examples/agent-profile.json index 6254278..57e9d88 100644 --- a/sample.json +++ b/docs/examples/agent-profile.json @@ -1,7 +1,7 @@ { "agent": { "name": "Aquachile Voice Agent", - "description": "Asistente de voz de Aquachile para soporte, informacion operativa y guia conversacional en tiempo real.", + "description": "Aquachile voice assistant for support, operational information, and real-time conversational guidance.", "model": "gpt-realtime", "voice": "alloy", "language": "es", @@ -564,9 +564,9 @@ "operations", "voice" ], - "instructions": "Eres el asistente de voz oficial de Aquachile. Debes hablar siempre en espanol, con tono profesional, claro, cordial y seguro. Responde de forma breve pero util. Haz una sola pregunta por turno cuando necesites aclaraciones. No inventes datos, precios, fechas, disponibilidad ni politicas. Si necesitas informacion verificable, usa primero las herramientas disponibles. Si una accion requiere confirmacion del usuario, pidela antes de continuar. Resume siempre la accion o conclusion al final de cada respuesta. Si el usuario cambia de tema, adapta el contexto sin perder claridad. Si no tienes datos suficientes, dilo explicitamente y propone el siguiente paso mas util. Nunca respondas en italiano o ingles salvo que el usuario lo pida de forma explicita.", + "instructions": "You are Aquachile's official voice assistant. Always speak Spanish in a professional, clear, friendly, and confident tone. Keep replies brief and useful. Ask one question per turn when clarification is needed. Do not invent data, prices, dates, availability, or policies. Use the available tools first when you need verifiable information. If an action requires user confirmation, ask before proceeding. Summarize the action or conclusion at the end of each reply. If the user changes the subject, adapt the context while staying clear. If you lack sufficient information, say so explicitly and suggest the most useful next step. Never reply in Italian or English unless the user explicitly asks.", "turnDetection": { "type": "server_vad" } } -} \ No newline at end of file +} diff --git a/speech_to_speech/TTS/ref_audio.wav b/docs/examples/reference-audio.wav similarity index 100% rename from speech_to_speech/TTS/ref_audio.wav rename to docs/examples/reference-audio.wav diff --git a/docs/proposals/vocero-architecture.html b/docs/proposals/vocero-architecture.html new file mode 100644 index 0000000..6795aa1 --- /dev/null +++ b/docs/proposals/vocero-architecture.html @@ -0,0 +1,272 @@ + + + +Vocero S2S — Target technical architecture and implementation plan + + + +
+
+

Technical architecture document

+

Vocero S2S

+

Target technical architecture and implementation plan

+

Status: proposal for technical review
Source cutoff date: July 20, 2026
Scope: a decoupled, local Speech-to-Speech conversational platform extensible through MCP
Audience: architecture, platform, security, MLOps, development, QA and operations

+
+
+ +

Vocero S2S

+

Target technical architecture and implementation plan

+

Document status: proposal for technical review
+Source cutoff date: July 20, 2026
+Scope: a decoupled, local Speech-to-Speech conversational platform extensible through MCP
+Audience: architecture, platform, security, MLOps, development, QA and operations

+
+

Traceability convention

+
    +
  • [REQ] Supplied requirement: comes directly from the Vocero S2S description provided by the requester.
  • +
  • [REC] Recommended decision: a design proposal that must be approved through an ADR.
  • +
  • [BENCH] Pending assumption: a hypothesis requiring measurement, load testing, legal assessment or validation in the target environment.
  • +
+
+

1. Executive summary

+

Vocero S2S is proposed as a real-time conversational platform separating four responsibilities: web experience, session control, speech and language inference, and enterprise integration through Model Context Protocol (MCP). [REQ] The initial implementation must use Parakeet TDT 0.6B for STT/VAD, LLaMA 3.1 8B Instruct for reasoning and tool calls, Qwen3-TTS 12Hz 1.7B Base in FP16 for synthesis and zero-shot cloning, and an NVIDIA GB10 node initially accessible through port 12345.

+

The target architecture retains this decoupled pipeline while avoiding placing all logic in the WebSocket connection. [REC] The proposal includes a Control Plane on the UI & Relay server for authentication, authorization, agent profiles, voice policy, MCP orchestration and auditing; a Realtime Data Plane for audio and events with ephemeral session state and priority cancellation; and a local Inference Plane that exposes versioned adapters for STT, LLM and TTS. This separation allows models, transport or infrastructure to be replaced without changing business contracts.

+

For web clients, WebRTC offers operational advantages for media on variable networks, while WebSocket remains appropriate for server-to-server links and the proposed first version. Realtime platform documentation recommends WebRTC for browser/media and WebSocket for server pipelines 1. [REC] The plan therefore adopts WebSocket as the initial compatible transport and defines WebRTC as a controlled evolution rather than an MVP prerequisite.

+

Interruption management is a first-class capability: when user speech is detected during a response, the system must cancel still-reversible generation, stop audio, flush unplayed buffers and truncate history to what was actually heard. Realtime systems document this pattern through cancellation and truncation of conversation items 2, as do agent frameworks that adjust history to the audio actually played 3.

+

MCP is integrated through an enterprise gateway with policy, schema validation, delegated identity, limits, auditing and version adapters. Critical timing decision: as of July 20, 2026, the announcement for 2026-07-28 explicitly describes a Release Candidate whose final standard is expected on July 28, 2026 and includes breaking changes 4. Therefore:

+
    +
  1. [REC] the initial stable compatibility version will be 2025-11-25, verified in the official transport documentation 5; this decision follows the requested source cutoff and does not contradict the stateless technical direction proposed by the RC;
  2. +
  3. [REC] 2026-07-28 will be implemented only behind an experimental adapter and feature flag;
  4. +
  5. [REC] the domain design will remain ready for the RC's stateless model: self-contained requests, application state through explicit handles, and routing independent of affinity;
  6. +
  7. [REC] promotion will require official ratification, conformance tests and an approved migration;
  8. +
  9. this document will not assume it is a final standard.
  10. +
+

Finally, running STT, LLM and TTS concurrently on a single GB10 has not been demonstrated through a benchmark of the complete pipeline. [BENCH] The first engineering deliverable must be a reproducible harness measuring end-to-end latency, memory, bandwidth, degradation under concurrency, interruption accuracy and cloning quality before committing to capacity or a contractual SLO.

+

2. Scope

+

2.1 Objectives

+
    +
  • [REQ] Deliver bidirectional, low-latency voice conversation from a browser.
  • [REQ] Identify users through the customer API and personalize sessions by identity or role.
  • [REQ] Dynamically load the agent profile, instructions, rules and tools.
  • [REQ] Preserve a corporate cloned voice against defaults sent by the client.
  • [REQ] Run STT, reasoning, tool calls and TTS in a decoupled pipeline.
  • [REQ] Integrate enterprise systems through an MCP gateway without changing the core.
  • [REC] Include barge-in, cancellation, backpressure, timeouts, isolation, traceability and failure recovery as core capabilities.
  • [REC] Maintain versioned contracts that allow transports, models, runtimes and MCP servers to be replaced.
  • [REC] Provide operational evidence for sizing, SLOs and auditing.
  • +
+

2.2 Non-goals

+
  • Train STT, LLM or TTS models from scratch.
  • Replace ERP, CRM, catalogs or other systems of record.
  • Allow the LLM to execute directly against databases or APIs without a gateway and policy.
  • Make the browser a repository for enterprise credentials or master voice material.
  • Guarantee capacity, latency or concurrency before benchmarking on GB10.
  • Declare MCP version 2026-07-28 a final standard before ratification.
  • Design a complete contact center, universal regulatory recording or SIP telephony at this stage; these may be added as later domains.
+

3. Architecture principles

+
  1. Separate control and media. Audio has real-time requirements; identity, policy and auditing require consistency and traceability.
  2. Contracts before implementations. Each boundary publishes versioned events and schemas; models remain behind adapters.
  3. Priority interruption. Cancellation and audio stopping take precedence over generating more content.
  4. Explicit state with ownership. Vocero owns conversational sessions; the protocol adapter or explicit handles own MCP state.
  5. Zero trust between planes. Each hop authenticates the service, authorizes the action, limits scope and propagates audited identity.
  6. Least privilege for tools. A tool receives only the strictly necessary arguments, identity and scopes.
  7. Privacy by default. Audio, transcripts, prompts, responses and voices are sensitive data; retention is explicit and minimized.
  8. Conversational failure handling. Technical failures become deterministic events and safe responses without leaking internal details.
  9. Measure before promising. Stage latency and percentiles govern the experience, rather than isolated averages.
  10. Versioned MCP compatibility. The gateway negotiates a stable version and encapsulates future candidates.
+

4. Context and container view

+
+Vocero S2S — C4 container view +VOCERO S2S +UserSpeaks from a browserIdentity / customer APIUser, roles and attributesProfile serviceInstructions, rules, toolsand voice policyEnterprise systemsERP, CRM, catalogs,reports and workflowsObservabilityMetrics, logs, tracesand alertsWeb clientWeb Audio + WS/WebRTCEdge / terminationTLS, connection, rate limitRealtime RelayAudio/events, sanitizationSession OrchestratorStates, turns, profileand policyMCP GatewayMCP client + policyenforcementSession StoreKV with TTLAudit StoreImmutable storeInference GatewayInternal realtime APISTT, LLM and TTSParakeet TDT 0.6BNeMo / GPULLaMA 3.1 8BLocal runtimeQwen3-TTS 1.7BFP16 / GPUVoice VaultAuthorized referencesAudio, controls and confirmationsMedia and events · TLSAuthenticated streamSession eventsResolve identity · HTTPSLoad profiles and policies · HTTPSRead/write ephemeral stateTool intent + delegated context · mTLSInference commands and events · mTLSAudio chunksContext and tokensText and voice_profile_refRead authorized referenceVersioned MCP/HTTPSExecutions and decisionsAudit eventsTelemetryTelemetryGPU/model telemetry
Static vector representation of the C4 view included in version v2.
+

4.1 Logical view by plane

+

Experience Plane

  • Web client, microphone capture, echo cancellation, playback and consent controls.
  • Retains only required visual state and cursors; does not retain secrets or master voice material.
+

Realtime Data Plane

  • WebSocket or WebRTC termination, media relay and event multiplexing.
  • Enforces buffer, sequence and size limits; discards stale data when generation changes.
  • Separates a high-priority control queue —cancel, barge_in, close— from the audio/data queue.
+

Conversation Control Plane

  • Resolves identity, profile, permissions and effective configuration.
  • Maintains the session and turn state machine.
  • Builds context, coordinates inference and decides whether a tool can be executed, confirmed or rejected.
+

Inference Plane

  • Hides runtime details and exposes uniform capabilities: transcribe, generate, synthesize, cancel, health, capacity.
  • Correlates each output with session_id, turn_id and generation_id to discard late responses.
+

Enterprise Integration Plane

  • MCP gateway with version adapters, allowlists, validation, authorization, service secrets, idempotency and auditing.
  • No tool response enters the context without size, classification and sanitization checks.
+

5. Component responsibilities

+
ComponentResponsibilitiesMust not
Web clientCapture/play audio; AEC/NS/AGC where appropriate; show state; send confirmations; report playout progressAuthorize tools; store secrets; decide the effective voice
Realtime edgeTLS; connection authentication; limits; routing; DoS protection; WS upgrade or WebRTC terminationInterpret prompts or MCP arguments
Realtime RelayMultiplex audio/events; order sequences; backpressure; sanitize session.update; prioritize interruptionsRetain business logic or downstream credentials
Session OrchestratorState machine; identity; profile; context; turns; cancellation; degradation; correlationExecute SQL, ERP or APIs directly
Policy EngineEvaluate identity, role, tool, risk, scope, consent and data policySilently rewrite business arguments without a record
MCP GatewayNegotiate versions; discover tools; validate JSON Schema; delegate identity; apply timeouts/retries; auditExpose credentials to the LLM or browser
Inference GatewayAdmit/cancel jobs; adapt protocols; measure stages; health/capacityDecide enterprise permissions
STT/VADEmit partial/final transcripts and speech signals with timestampsPersist audio indefinitely
LLMGenerate structured text or tool intent within allowed schemasTreat itself as the authority to execute actions
TTSSynthesize a stream tied to a generation and authorized voice profileAccept arbitrary ref_audio from the client
Voice VaultVersion, encrypt and govern voice references and consentServe files without service and tenant authorization
StoresEphemeral state with TTL, immutable auditing and versioned configurationMix operational PII with unrestricted telemetry
ObservabilityMetrics, structured logs, traces, alerts and dashboardsLog audio, tokens or sensitive arguments by default
+

6. Deployment view

+
Vocero S2S — Deployment view +PUBLIC ZONE +DMZ / EDGE +APPLICATION NETWORK +RESTRICTED INFERENCE SEGMENT +ENTERPRISE NETWORK +OPERATIONSBrowserWAF + Reverse ProxyOptional TURN/SFUWebRTC evolutionRealtime Relay ARealtime Relay BSession Orchestrator ASession Orchestrator BPolicy EngineMCP GatewaySession StoreTTLAudit StoreInference GatewayInternal port 12345Parakeet STT/VADLLaMA 3.1 8BQwen3-TTS 1.7BFP16Voice Vaultencrypted cacheNVIDIA GB10Auth + Agent Profile APIsMCP Servers / AdaptersERP / CRM / Data / WorkflowsOTel CollectorMetrics / Logs / Traces / AlertsSecrets + KMSInitial TLS WSFuture WebRTCFuture WebRTCmTLS realtimemTLS realtime
Static vector representation of the deployment view included in version v2.
+

[REC] Port 12345 must be internal, protected by a firewall, mTLS and service authentication; it must not be exposed directly to the Internet. [REC] Relay and Orchestrator are deployed with at least two logical instances in production. This does not require physical high availability from the first day of the MVP, but contracts must not depend exclusively on local memory.

+

[BENCH] The GB10 is initially a single failure and capacity domain. Before production, define the spare-node strategy, admission queue, session limit, shedding policy and model recovery procedure.

+

7. State machine and session management

+

7.1 Proposed states

+
Vocero S2S — Session state machineStartCONNECTINGAUTHENTICATINGCONFIGURINGLISTENINGTRANSCRIBINGTHINKINGTOOL_PENDINGAWAITING_CONFIRMATIONTOOL_RUNNINGSPEAKINGINTERRUPTINGDEGRADEDCLOSINGFAILEDtransport readyvalid identityrejection or timeoutprofile + voice + tools loadednoncritical dependency failsspeech_startedturn_committedtool_intentsensitive actionconfirmedallowedtool_resultaudio_first_chunkbarge_inoutput stoppedresponse_completedalternative availablecloseclosecloseclose
Static vector representation of the state machine included in version v2.
+

7.2 Identifiers

+
  • connection_id: transport connection; may change on reconnection.
  • session_id: stable, opaque conversational session.
  • turn_id: committed user input.
  • generation_id: agent response; changes after cancellation or regeneration.
  • tool_call_id: unique invocation; must be idempotent when supported by the tool.
  • voice_profile_id + voice_version: immutable reference to the authorized voice.
  • trace_id: distributed correlation; does not replace functional identifiers.
+

7.3 Effective session state

+

[REC] Calculated in this order, without allowing the client to escalate privileges:

  1. secure platform defaults;
  2. tenant policy;
  3. versioned agent profile;
  4. authorized user attributes;
  5. allowed session preferences;
  6. explicitly allowlisted per-response overrides.
+

The sanitizer for session.update removes or rejects fields that could replace voice_profile_id, tools, system instructions, limits or scopes. Any difference between requested and effective configuration is recorded in a session.configuration_applied event with coded reasons.

[REC] Ephemeral state is stored with TTL and optimistic version control. Resumption requires a short-lived opaque token, the same identity and a profile-version check. Uncommitted audio and generation jobs are not resumed: they are canceled and the client returns to LISTENING.

+

8. Execution flows

8.1 Normal conversational and MCP flow

8.2 Tool call with confirmation

+
  1. The LLM emits intent, never direct execution.
  2. Orchestrator validates the name against the allowlist and current schema.
  3. Policy Engine classifies the action: read, reversible write, irreversible action or prohibited.
  4. If consent is required, emit tool.confirmation_required with a readable summary and nonsensitive fields.
  5. The user confirms; create a confirmation_id bound to a hash of tool + arguments + identity + expiration.
  6. MCP Gateway executes with a delegated token of minimum scope.
  7. Validate, limit and classify the result before returning it to the LLM.
  8. Record the decision, not secrets or complete sensitive payloads.
+

For stable compatibility 2025-11-25, the adapter maintains the protocol lifecycle and session according to the official transport 5. RC 2026-07-28 proposes eliminating the handshake and protocol session, using self-contained requests, routing headers and InputRequiredResult; these capabilities remain only in the experimental adapter until ratification 4.

+

8.3 Barge-in

Rules:

  • An interruption event bypasses token and audio queues.
  • Each subsequent chunk from G1 is discarded because of a stale generation_id .
  • The client cursor is the source of truth for played audio; when missing, use the last conservative ACK.
  • A read-only tool can be canceled; an already confirmed, irreversible action is not undone by barge-in. Report its status and avoid repeating it.
  • Apply AEC and adaptive thresholds to reduce self-interruptions; test brief interjections as a specific case.
+

8.4 Errors and degradation

+
ConditionAutomatic actionUser experienceAuditing/operations
Authentication deniedClose with a stable codeUnauthorized access messageReason, tenant, subject hash
Profile unavailableBounded retry; fallback only if approved“I cannot start the assistant right now”Dependency alert
Unhealthy STTPause admission or enable text mode if availableReport degradationMetric and circuit breaker
LLM timeoutCancel generation; retry once only if no tool side effect occurredBrief, safe responseSpan with timeout
TTS failsKeep text; do not replace the voice without a policyShow text or request a retryVoice/model status
MCP timeoutCancel or mark status unknown“I could not confirm the operation”Do not retry writes without idempotency
Invalid MCP responseReject the payload; do not send it to the LLMControlled errorSchema violation
Saturated bufferSlow the producer; discard stale partials; never lose cancellationPossible network indicatorDrop/backpressure counters
Client disconnectedShort lease; cancel media; retain minimal resumable stateControlled retryClose reason
GPU at capacityEarly rejection or bounded queue“Service busy, please try again”Saturation, queue and shedding
+

9. Illustrative contracts and events

[REC] The following schemas are illustrative. They must become versioned JSON Schema with compatibility tests and size limits. They do not represent a final contract.

9.1 Common envelope

{
+  "specversion": "1.0",
+  "type": "vocero.audio.input.delta.v1",
+  "source": "web-client",
+  "id": "evt_opaque",
+  "time": "RFC3339 timestamp",
+  "subject": "session/{session_id}",
+  "traceparent": "00-...",
+  "data": {
+    "session_id": "ses_opaque",
+    "turn_id": "turn_opaque",
+    "sequence": 42,
+    "payload": {}
+  }
+}
+

9.2 Minimum event catalog

Client → platform

  • session.connect.v1
  • session.update_requested.v1
  • audio.input.delta.v1
  • audio.input.commit.v1
  • input.speech_started.v1
  • output.playout_progress.v1
  • generation.cancel_requested.v1
  • tool.confirmation_submitted.v1
  • session.close.v1

Platform → client

  • session.configuration_applied.v1
  • transcript.partial.v1
  • transcript.final.v1
  • response.text_delta.v1
  • response.audio_delta.v1
  • response.completed.v1
  • output.stop_and_flush.v1
  • tool.confirmation_required.v1
  • tool.status.v1
  • error.v1
+

9.3 Example of session.update_requested

{
+  "type": "vocero.session.update_requested.v1",
+  "data": {
+    "session_id": "ses_opaque",
+    "client_capabilities": {
+      "audio_codecs": ["opus", "pcm16"],
+      "supports_playout_ack": true
+    },
+    "preferences": {
+      "locale": "es-CL",
+      "turn_mode": "server_vad"
+    }
+  }
+}

Fields such as system_prompt, tools, mcp_credentials, ref_audio, ref_text or voice_profile_id are not accepted through this public contract. If received, the relay rejects or removes them according to policy and records the reason.

+

9.4 Example of internal tool intent

{
+  "tool_call_id": "tc_opaque",
+  "session_id": "ses_opaque",
+  "turn_id": "turn_opaque",
+  "tool": {
+    "name": "production.report.get",
+    "schema_version": "1.2.0"
+  },
+  "arguments": {
+    "site_id": "site_authorized",
+    "period": "value_from_user_or_context"
+  },
+  "execution": {
+    "mode": "read",
+    "idempotency_key": "idem_opaque",
+    "deadline_ms": "configured_value"
+  },
+  "principal": {
+    "subject_ref": "opaque_subject",
+    "tenant_id": "tenant_opaque",
+    "scopes": ["report:read"]
+  }
+}
+

9.5 Errors

{
+  "type": "vocero.error.v1",
+  "data": {
+    "code": "MCP_TOOL_TIMEOUT",
+    "category": "dependency",
+    "retryable": false,
+    "user_message_key": "tool.temporarily_unavailable",
+    "correlation_id": "corr_opaque",
+    "details_ref": "internal_log_reference"
+  }
+}

Public messages do not contain stack traces, internal endpoints, prompts, tokens, sensitive arguments or secret names.

+

9.6 MCP compatibility

McpAdapter
+├── StableAdapter_2025_11_25   # default
+├── CandidateAdapter_2026_07_28 # feature flag, not enabled in production by default
+└── ConformanceHarness
+    ├── discovery
+    ├── tools/list
+    ├── tools/call
+    ├── cancellation
+    ├── schema validation
+    ├── auth propagation
+    └── error mapping

The official MCP architecture separates a JSON-RPC data layer from a transport layer and includes lifecycle, primitives and notifications 6. [REC] Vocero will preserve this separation inside the adapter so transport details do not contaminate conversational logic.

Candidate capabilities being prepared but not activated as a final standard: the RC 2026-07-28 introduces server/discover, metadata ttlMs and cacheScope in list/read results, and headers Mcp-Method/Mcp-Name for routing 4. [REC] The gateway will model discovery and caching through neutral interfaces: the stable adapter will resolve its mechanism according to 2025-11-25, while the candidate adapter can map the new capabilities. The cache will never share results beyond the allowed identity/tenant scope and will always respect revocation and policy changes.

+

10. Voice cloning and governance

10.1 Operating model

[REQ] Qwen3-TTS must use ref_audio and ref_text for zero-shot cloning and preserve a corporate voice. The Qwen3-TTS 1.7B Base model card confirms streaming, Spanish support and fast cloning from short audio 7. Repository documentation describes streaming generation and voice cloning 8.

Modes to evaluate:

  • Full ICL — recommended for maximum fidelity: uses ref_audio and an exact, aligned transcript ref_text . [REC] This will be the default candidate mode for approved corporate voices.
  • x-vector (x_vector_only_mode=True): allows operation without ref_text, but research reports lower timbre and prosody fidelity. [BENCH] It can be promoted for a profile only after meeting the defined quality and risk thresholds.

[REC] The client never sends master references during a session. The agent profile contains only voice_profile_id and voice_version; TTS resolves the reference from Voice Vault using service identity. The relay removes standard voices proposed by the client, and Orchestrator applies the authorized effective voice.

+

10.2 Lifecycle

  1. Request: voice owner, purpose, tenant, languages and usage period.
  2. Verifiable consent: document or authorization evidence; legal review for the applicable jurisdiction.
  3. Controlled ingestion: antivirus, normalization, noise assessment and aligned transcription.
  4. Evaluation: fidelity, intelligibility, pronunciation, stability and impersonation risk.
  5. Four-eyes approval: business owner plus security/legal or equivalent roles.
  6. Versioning: hash of ref_audio, hash of ref_text, model, parameters and effective date.
  7. Publication: only approved profiles can be used in production.
  8. Monitoring: usage by tenant/agent, anomalies and complaints.
  9. Revocation: immediately block new sessions; rotate cache; provide deletion evidence.
+

10.3 Controls

  • Encryption in transit and at rest using managed keys.
  • Isolation by tenant and environment; do not copy real voices into development.
  • Short-lived signed URLs or direct reading through workload identity.
  • Access logging without including audio in logs.
  • Provenance markers or disclosure when required by corporate policy or regulation.
  • Abuse tests: offensive text, fraud, social engineering, reference extraction and cross-tenant use.
  • [BENCH] Compare Full ICL with ref_audio + ref_text against text-free mode; do not assume equivalent quality.
  • [BENCH] Legal review of code and weight licenses before commercial use; collected evidence must not replace legal advice.
+

11. Security

11.1 Zones and trust view

11.2 Main threats and mitigations

+
ThreatRecommended mitigations
User impersonationOIDC/OAuth, ephemeral tokens, issuer/audience validation, reauthentication for sensitive actions
Prompt injection from users or tool resultsInstruction separation, tool allowlist, output validation, untrusted-content labeling, authorization outside the LLM
Tool poisoning or malicious schemaApproved-server registry, version/hash pinning, schema review, depth/size limits, cache with secure invalidation
Confused deputyPropagate subject and tenant; token exchange; per-tool scopes; backend resource checks
Exfiltration through toolsEgress allowlist, DLP/classification, response minimization, limits and redaction before context insertion
Repeated writesIdempotency key, hash-bound confirmation, execution ledger, no retries for unknown status
Voice theftVault, encryption, isolation, consent, revocation, no browser download
Session hijacking/replayShort-lived connection tokens, nonce, expiration, identity binding, reconnection limits
Audio/GPU DoSQuotas, bitrate/chunk limits, admission control, bounded queues, circuit breakers, shedding
Leaks through logs/tracesRedaction, attribute classification, sampling, limited retention, RBAC access
Lateral movementSegmentation, mTLS, workload identities, deny-by-default and controlled egress
+

11.3 Tool authorization

The decision evaluates:

permit = policy(
+  tenant,
+  principal,
+  agent_profile_version,
+  tool_name,
+  tool_schema_version,
+  action_class,
+  resource_scope,
+  argument_classification,
+  confirmation,
+  session_risk
+)

The LLM can propose tool_name and arguments, but not principal, scopes, credentials, action classification or policy outcomes. [REC] Irreversible actions require specific human confirmation or a documented corporate exception.

+

11.4 Data and retention

Define a matrix by data class:

  • raw audio;
  • voice references;
  • transcripts;
  • prompt/context;
  • model responses;
  • tool arguments and results;
  • telemetry and auditing.

For each class, approve purpose, legal basis, location, encryption, retention, deletion, export, access, training use and redaction. Pending: the requester did not supply corporate policies or jurisdictions; this document therefore sets no retention periods.

+

12. Observability and initial SLOs

12.1 Telemetry model

Traces: one trace per turn with spans for capture, relay, STT, endpointing, LLM, policy, MCP, TTS, network and playout. The future RC proposes standardized names for propagating W3C Trace Context in _meta, but this form remains a candidate until ratification 4. In the stable adapter, Vocero will propagate traceparent through compatible internal metadata without requiring future domain changes.

Experience metrics

  • turn_endpointing_ms: acoustic endpoint to turn commit.
  • stt_partial_ms and stt_final_ms.
  • llm_ttft_ms: commit to first token.
  • tts_ttfa_ms: available text to first audio.
  • ttfs_ms: end of speech to first playable sound.
  • barge_in_stop_ms: interruption detection to effective silence.
  • tool_latency_ms by tool and outcome.
  • turn_e2e_ms by direct or tool-assisted path.
  • reconnection, cancellation, false barge-in and abandonment rates.

TTFT and end-to-end latency are recognized as distinct, relevant dimensions for voice/realtime workloads 9.

Quality metrics

  • WER/CER by language, accent, noise and domain.
  • early/late endpointing rate.
  • intelligibility and human assessment of naturalness.
  • speaker similarity and voice stability.
  • accuracy of tool selection, arguments, policy and task completion.

Resource metrics

  • GPU utilization and memory; KV cache; per-model queues; tokens/s; audio seconds/s.
  • buffer depth and age; drops; retransmissions; jitter; playout underruns.
  • active connections, admitted/rejected sessions and dependency errors.
+

12.2 Initial targets — not observed performance

[REC/BENCH] These values are provisional engineering targets, not measured figures, guarantees or a contractual SLO. They must be ratified after benchmarking with real audio, networks, tools and concurrency.

+
IndicatorProposed initial targetWindow/percentileRatification condition
Conversational service availability≥ 99,5 %MonthlyExclude agreed windows and define the GPU dependency
Response audio start ttfs_ms≤ 1,200 msp95, direct turnTarget corporate network and warm session
Barge-in stopping≤ 300 msp95Measured through playout silence, not only ACK
Turns without platform errors≥ 99,0 %MonthlySeparate dependency errors from invalid input
MCP read executions accepted by the gateway≥ 99,0 %MonthlyExclude policy rejections and downstream timeouts
Loss of accepted control events0Every windowVerified by sequence and ACK
Unauthorized voice use0Every windowMandatory alert and audit

Provisional budget for ttfs_ms for analysis, not a commitment:

endpointing + STT final + scheduling + LLM TTFT + TTS primer audio + transporte/playout

No fixed milliseconds are allocated per stage before benchmarking; the dashboard must show contributions and percentiles separately.

+

12.3 Initial alerts

  • Availability and successful-turn burn rates.
  • Sustained queue growth or buffer age.
  • GPU OOM, model restart or degraded health.
  • Divergence between generation.cancel and the last emitted chunk.
  • MCP error/latency by tool, tenant and dependency.
  • Denied access or voice anomalies.
  • Missing traces or uncontrolled cardinality.
+

13. Scalability, backpressure and resilience

13.1 Scaling

  • Edge/Relay: horizontal scaling by connections; minimal state; drain before deployment.
  • Orchestrator: horizontal scaling by session with a store lease; optional affinity as an optimization rather than a correctness requirement.
  • MCP Gateway: horizontal scaling; per-downstream pools; per-tenant/tool bulkheads.
  • Inference: admission control based on actual capacity, not only CPU; separate STT, LLM and TTS queues; prioritize cancellation and active audio.
  • Voice cache: encrypted cache bounded by approved voices; invalidate on version changes/revocation.
+

13.2 Backpressure

[REC] Each link publishes high_watermark, low_watermark and an overflow policy. The LLM can produce text faster than TTS or the network can consume it; the system must throttle tokens, group pronounceable units and limit buffered audio. Realtime pipelines document the general problem of fast producers and slow consumers 10.

Policies:

  1. Control events never share a blocking queue with audio.
  2. Stale partial STT transcripts may be coalesced; final transcripts and commits may not.
  3. Discard unsynthesized tokens from a canceled generation.
  4. Discard generated but unplayed audio on interruption.
  5. A slow connection cannot consume unbounded memory.
  6. The client reports buffered_ms and playout; the server adjusts chunking or pauses.
  7. Queues have deadlines; expired work is not processed merely for completeness.
+

13.3 Resilience

  • Per-stage timeouts and a propagated total deadline.
  • Circuit breakers by dependency and model.
  • Retries with jitter only for idempotent operations.
  • Bulkheads by tenant and tool to avoid cascading failures.
  • Separate process health, model readiness and capacity signals.
  • Verified warmup before accepting sessions.
  • Deploy with connection draining and safe cancellation.
  • Configuration snapshots and profile/model rollback.
  • Runbooks for GPU OOM, STT/TTS degradation, slow MCP, unavailable stores and voice compromise.

[BENCH] The ability to host the entire pipeline simultaneously on one GB10, and the number of sustainable sessions, must be measured. Parakeet TDT 0.6B v3 has documented streaming support and timestamps 11; this validates functional capability rather than the complete system's concurrent capacity.

+

14. Phased implementation plan

Phases include no dates or durations because team availability, environments, procurement and change windows were not supplied. Each phase ends with an explicit decision to proceed, correct or stop.

+

Phase 0 — Discovery, contracts and risks

Deliverables

  • Inventory of functional requirements, data, tenants, roles, tools and sensitive actions.
  • Initial ADRs and threat model.
  • Event catalog v1 and audio/control schemas.
  • License matrix and voice governance.
  • Benchmark corpus definition and measurement plan.

Dependencies

  • Access to auth/profile APIs and the customer's MCP definition.
  • Security, legal, business and operations owners.
  • GB10 hardware and versioned model artifacts.

Acceptance criteria

  • Labeled and approved requirements; outstanding items have owners.
  • No secrets or real voices required for early development.
  • ADR-001 through ADR-006 have status Proposed or Accepted.
  • Critical threats have an associated control and test.

Risks

  • Ambiguous identity/roles.
  • Unresolved licensing or voice consent.
  • MCP tools without idempotency or risk classification.
+

Phase 1 — Local vertical slice without write tools

Deliverables

  • Web client + WebSocket, Relay, Orchestrator and Inference Gateway.
  • Streaming STT → LLM → TTS with an authorized test voice.
  • State machine, IDs, cancellation and structured logs.
  • Deterministic STT/LLM/TTS simulators for CI.

Dependencies

  • Loadable models and compatible runtime.
  • Service certificates and an isolated environment.

Acceptance criteria

  • Reproducible normal conversation.
  • Reconnection does not duplicate turns.
  • Canceling a generation prevents late chunks from reaching playout.
  • The client-requested voice does not replace the effective voice.
  • First latency and resource baseline recorded.

Risks

  • GPU contention.
  • Endpointing latency.
  • Runtime instability or FP16 incompatibility.
+

Phase 2 — Barge-in, backpressure and robust sessions

Deliverables

  • Priority control queue and output.stop_and_flush.
  • Playout ACK/cursor; history truncation.
  • Buffer limits, shedding, deadlines and circuit breakers.
  • Tests with noise, echo, interjections and degraded networks.

Dependencies

  • Per-stage instrumentation.
  • Dataset of representative conversations and acoustic conditions.

Acceptance criteria

  • No stale-generation audio after the approved interruption limit.
  • No unbounded memory growth with a slow client.
  • No duplicate response after reconnection/cancellation.
  • False barge-in measured and within the threshold defined by the business.

Risks

  • Echo triggers VAD.
  • Inaccurate playout cursor.
  • Races between cancellation, TTS and network delivery.
+

Phase 3 — Read-only MCP gateway

Deliverables

  • StableAdapter_2025_11_25.
  • Allowlisted discovery, schema validation and read-only tools/call .
  • Policy Engine, delegated identity, limits, auditing and idempotency.
  • Simulated MCP server and contract tests.

Dependencies

  • Customer MCP server and authorization schema.
  • Tool and data classification.

Acceptance criteria

  • A tool outside the allowlist is rejected before reaching downstream.
  • Invalid arguments and results do not reach the LLM/systems.
  • Every tool call correlates with user, session, turn and policy.
  • Timeouts do not cause unsafe retries.

Risks

  • Prompt injection in results.
  • Overprivileged credentials.
  • Unstable downstream contracts.
+

Phase 4 — Writes, confirmation and voice governance

Deliverables

  • Confirmation flows bound to hashes and idempotency keys.
  • Action ledger and unknown status.
  • Voice Vault, approval workflow, revocation and secure cache.
  • Abuse tests and incident runbooks.

Dependencies

  • Legal approval of voices/licenses.
  • Idempotency semantics in enterprise systems.

Acceptance criteria

  • No sensitive action executes without the required policy/confirmation.
  • Repeated events do not repeat side effects.
  • Revoking a voice blocks new synthesis and clears caches.
  • Cross-tenant access fails and is audited.

Risks

  • Non-idempotent actions.
  • Incomplete consent.
  • Voice exfiltration or misuse.
+

Phase 5 — Preproduction, SLOs and resilience

Deliverables

  • Load, soak, chaos and recovery tests.
  • Dashboards, alerts, ratified SLOs and runbooks.
  • Capacity model and admission limits.
  • DR/backup for configuration, auditing and Voice Vault.
  • Security review and go-live checklist.

Dependencies

  • Representative traffic/profiles.
  • Production-equivalent environment.
  • Defined on-call model and ownership.

Acceptance criteria

  • Experience targets ratified or renegotiated with evidence.
  • Demonstrated recovery from critical failures.
  • No open critical vulnerabilities.
  • Operations can detect, diagnose and mitigate runbook scenarios.

Risks

  • Single GB10 as a SPOF.
  • Insufficient capacity under a real traffic mix.
  • Differences between test and field networks.
+

Phase 6 — Progressive rollout and evolution

Deliverables

  • Canary by user/tenant and automatic rollback.
  • Post-pilot review of quality, latency, security and task completion.
  • WebRTC roadmap if WebSocket does not meet targets.
  • CandidateAdapter_2026_07_28 only if the specification has been ratified.

Acceptance criteria

  • Canary without SLO/security regression.
  • Validated support and operational escalation.
  • MCP migration passes the conformance suite and promotion ADR.
+

15. Testing strategy

15.1 Pyramid

Unit tests

  • state machine, sanitization, policy, error mapping, deduplication, expiration and redaction.

Contract tests

  • Event JSON Schema, backward compatibility, MCP adapters, profile and identity APIs.

Integration tests

  • Real STT/LLM/TTS; simulated and real MCP; Voice Vault; KMS; stores.

End-to-end

  • audio to audio with measured playout, direct paths, tools, confirmation, cancellation and reconnection.

Load and soak

  • concurrent sessions, mixed turns, long audio, slow clients, slow tools, connection churn and warm/cold models.

Chaos

  • dead process, GPU OOM, slow store, network loss, late response, expired certificate, partial dependency failure and restart during a tool call.

Security

  • authn/authz, tenant isolation, replay, prompt injection, schema bombs, SSRF, egress, secrets, DLP, voice abuse and supply chain.
+

15.2 Minimum scenario matrix

DimensionCases
Audiosilence, noise, echo, clipping, variable bitrate, distant microphone
Speechtarget accents, speed, numbers, proper names, domain terms
Turnslong pause, overlap, backchannel, interruption, push-to-talk
Networklatency, jitter, loss, reconnection, slow client
Toolssuccess, empty, invalid, timeout, 4xx/5xx, confirmed side effect, unknown status
Modelscold start, OOM, late response, excessive tokens/audio, cancellation
Securityprohibited tool, insufficient scope, injection, cross-tenant access, revoked voice
+

15.3 Test oracles and reproducibility

  • Versioned test audio with consent and labels.
  • Deterministic fakes for races and errors.
  • Recorded generation seeds/parameters where applicable.
  • Golden transcripts and schemas with defined acoustic tolerances.
  • Capture monotonic timestamps at every boundary.
  • Report percentiles and conditions, not only averages.
  • A/B comparison of VAD, chunking and voice configurations.
+

16. Decision matrix and ADRs

ADRDecisionInitial statusAlternativesEvidence for acceptance
ADR-001Decoupled STT → LLM → TTS pipelineAccepted by requirementNative S2S modelBenchmark and per-component control
ADR-002Initial WebSocket; WebRTC as an evolutionProposedWebRTC from MVP; bothNetwork testing and operational complexity
ADR-003Separate Relay and Session OrchestratorProposedMonolithic serviceLoad profile, isolation and maintainability
ADR-004Stable MCP 2025-11-25 + versioned adaptersProposedAdopt a future RCRatification, conformance and compatibility
ADR-005Voice Vault and server-side referencesProposedSend ref_audio per sessionThreat model, cache latency and governance
ADR-006External ephemeral state with TTL and leasesProposedLocal memory/sticky sessionsRecovery and load
ADR-007Priority control queue for barge-inProposedSingle FIFO queueRace tests and interruption target
ADR-008Policy Engine outside the LLMProposedPrompt-only controlsBypass tests and auditing
ADR-009Confirmation + idempotency for writesProposedImmediate executionDownstream semantics and UX
ADR-010One GB10 in the MVP with admission controlProposedCluster from the startCapacity/cost/risk benchmark
ADR-011OpenTelemetry end-to-endProposedUncorrelated logsTrace coverage and cost/cardinality
ADR-012Versioned event contracts v1ProposedAd hoc provider payloadsCompatibility tests

Each ADR must include context, decision, alternatives, consequences, risks, status and review condition. Reversible decisions may start as Proposed; decisions affecting security, data, licenses or external compatibility require explicit approval.

+

17. Outstanding items and open questions

Product and experience

  • Which channels are included: browser only, mobile, telephony or all?
  • Which languages, accents, vocabulary and acoustic conditions take priority?
  • What behavior is expected when voice fails: text, an alternative voice or closure?
  • Which actions require verbal confirmation, visual confirmation or stronger authentication?

Identity and authorization

  • Actual contract for /api/v1/auth/user-by-phone and authentication mechanism.
  • Roles, tenants, scopes and data-isolation model.
  • Token exchange/delegation to MCP and downstream systems.

MCP

  • Inventory of servers, tools, schemas, side effects, idempotency and downstream SLOs.
  • Stable version actually supported by the customer's server.
  • Discovery cache/refresh strategy.
  • Future ratification of 2026-07-28 and SDK/conformance-suite availability.

Inference and capacity

  • Exact runtime for LLaMA, memory allocation and KV cache policy.
  • Sustainable STT + LLM + TTS concurrency on GB10.
  • Effects of context length, agent prompts and tool results on TTFT.
  • Cold start, model loading, fragmentation and OOM recovery.
  • Parakeet quality on real audio and domain content.
  • Owner and consent evidence for every voice.
  • Applicable licensing for weights, code, redistribution and commercial use.
  • Disclosure, retention, localization and revocation-right rules.
  • Fidelity/security metric and acceptance threshold.

Operations

  • Environments, topology, certificates, secrets, KMS, stores and backups.
  • RTO/RPO and on-call model.
  • Logging, sampling, redaction and retention policy.
  • Spare-node capacity or alternative service.
+

18. Consolidated risks

RiskInitial likelihoodImpactTreatment
Complete pipeline exceeds GB10 capacityUnknownHighEarly benchmark; admission control; separation options
Late or false barge-inUnknownHighPriority queue, AEC, playout ACK, noise corpus
MCP permits an improper actionMedium until testedCriticalExternal policy, scopes, confirmation, auditing, idempotency
Voice compromise or unauthorized useMedium until governedCriticalVoice Vault, consent, isolation, revocation
Dependency on a candidate MCP versionAvoidableHighStable adapter by default and feature flag
Tool result injects instructionsMediumHighTreat content as untrusted; sanitize, limit and evaluate
Inconsistent state after reconnectionMediumHighIDs, versioning, leases, deduplication and cancellation
Observability leaks PIIMediumHighRedaction, attribute allowlist, access and retention
Single inference node failsHigh in the initial topologyHighRunbook, spare/failover, degradation and communication
Incomplete licensing/consentUnknownCriticalLegal gate before production

Nonnumeric likelihoods reflect missing data; update them after testing and organizational review.

+

19. Pilot readiness criteria

The solution is ready for a pilot only when:

  1. requirements and critical ADRs are approved;
  2. the stable MCP path is tested and the future candidate remains isolated;
  3. the end-to-end benchmark demonstrates capacity for the pilot load;
  4. barge-in and backpressure pass acoustic and network tests;
  5. sensitive tools have policy, confirmation and idempotency;
  6. the voice is authorized, versioned and revocable;
  7. security has no open critical findings;
  8. dashboards, alerts and runbooks enable service operation;
  9. provisional SLOs were ratified or replaced with evidence;
  10. tested application, profile, model and configuration rollback exists.
+

20. Sources

  1. [1] OpenAI — Realtime and audio — https://developers.openai.com/api/docs/guides/realtime
  2. [2] Microsoft Azure — Realtime audio — https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/realtime-audio
  3. [3] LiveKit — Turns overview — https://docs.livekit.io/agents/logic/turns/
  4. [4] Model Context Protocol — 2026-07-28 Release Candidate — https://blog.modelcontextprotocol.io/posts/2026-07-28-release-candidate/
  5. [5] Model Context Protocol — Transport specification 2025-11-25 — https://modelcontextprotocol.io/specification/2025-11-25/basic/transports
  6. [6] Model Context Protocol — Architecture overview — https://modelcontextprotocol.io/docs/learn/architecture
  7. [7] Qwen — Qwen3-TTS 12Hz 1.7B Base model card — https://huggingface.co/Qwen/Qwen3-TTS-12Hz-1.7B-Base
  8. [8] QwenLM — Qwen3-TTS repository — https://github.com/QwenLM/Qwen3-TTS
  9. [9] Telnyx — Inference Benchmark: TTFT vs E2E Latency — https://telnyx.com/resources/inference-benchmark-ttft-vs-e2e
  10. [10] Arun Baby — Real-Time Agent Pipelines — https://www.arunbaby.com/ai-agents/0016-real-time-agent-pipelines/
  11. [11] NVIDIA — Parakeet TDT 0.6B v3 model card — https://huggingface.co/nvidia/parakeet-tdt-0.6b-v3
+

Appendix A — Implementation checklist

  • [ ] Requirements [REQ], recommendations [REC] and assumptions [BENCH] reviewed.
  • [ ] Critical ADRs approved.
  • [ ] Models and hashes pinned; SBOM and licenses reviewed.
  • [ ] Identity, roles, scopes and tenants defined.
  • [ ] Event schemas v1 published and contract-tested.
  • [ ] Stable MCP adapter tested against 2025-11-25.
  • [ ] Candidate MCP adapter disabled by default.
  • [ ] Voice Vault, consent, rotation and revocation operational.
  • [ ] Admission control and buffer limits configured.
  • [ ] Barge-in measured through actual playout.
  • [ ] Tool confirmation and idempotency verified.
  • [ ] Telemetry redacted and correlated.
  • [ ] SLOs ratified through benchmarking.
  • [ ] Runbooks and rollback rehearsed.
  • [ ] Security review and go-live completed.
+
+ + + \ No newline at end of file diff --git a/docs/speech/llm.md b/docs/speech/llm.md new file mode 100644 index 0000000..c9c3072 --- /dev/null +++ b/docs/speech/llm.md @@ -0,0 +1,162 @@ +# Language model backends + +## Available LLM backends (`--llm_backend`) + +Runtime-supported values in [s2s_pipeline.py](../../speech_to_speech/s2s_pipeline.py): + +- `transformers` → `language_model.py` (Transformers backend) +- `mlx-lm` → `language_model.py` (MLX backend) +- `responses-api` → `responses_api_language_model.py` +- `chat-completions` → `chat_completions_language_model.py` + +Run the commands below from the repository root in an environment with the speech +pipeline dependencies installed. This checkout has no package manifest or complete +speech dependency installer; the UI requirements alone do not install the pipeline. + +## Usage + +### 1) Transformers (`--llm_backend transformers`) + +- Handler: `LanguageModelHandler` +- Typical use: local GPU/CPU inference using Hugging Face Transformers +- Backend-specific args prefix: `--llm_*` +- Shared args (from base): `--model_name`, `--chat_size`, `--init_chat_prompt`, `--enable_lang_prompt` + +```bash +python -m speech_to_speech.s2s_pipeline \ + --llm_backend transformers \ + --model_name Qwen/Qwen3-4B-Instruct-2507 \ + --llm_device cuda \ + --llm_torch_dtype float16 \ + --llm_gen_max_new_tokens 128 +``` + +Common options: +- `--llm_gen_min_new_tokens` +- `--llm_gen_temperature` +- `--llm_gen_do_sample` +- `--chat_size` +- `--init_chat_prompt` + +### 2) MLX-LM (`--llm_backend mlx-lm`) + +- Handler: `LanguageModelHandler` +- Typical use: Apple Silicon local inference +- Backend-specific args prefix: same as Transformers (`--llm_*`) + +```bash +python -m speech_to_speech.s2s_pipeline \ + --llm_backend mlx-lm \ + --model_name mlx-community/Qwen3-4B-Instruct-2507-bf16 \ + --llm_device mps \ + --llm_gen_max_new_tokens 128 +``` + +Common options: +- `--llm_gen_temperature` +- `--llm_gen_do_sample` +- `--chat_size` +- `--init_chat_prompt` + +### 3) OpenAI-compatible API (`--llm_backend responses-api`) + +- Handler: `ResponsesApiModelHandler` +- Typical use: remote model serving via OpenAI-compatible endpoints +- Backend-specific args prefix: `--responses_api_*` +- Shared args (from base): `--model_name`, `--chat_size`, `--init_chat_prompt`, `--enable_lang_prompt` + +```bash +python -m speech_to_speech.s2s_pipeline \ + --llm_backend responses-api \ + --model_name gpt-5.4-mini \ + --responses_api_api_key YOUR_API_KEY \ + --responses_api_base_url https://api.example.com/v1 \ + --responses_api_stream true +``` + +Common options: +- `--chat_size` +- `--init_chat_prompt` +- `--user_role` + +### 4) Chat Completions (`--llm_backend chat-completions`) + +- Handler: `ChatCompletionsLanguageModelHandler` +- Uses the provider's `/chat/completions` API rather than `/responses` +- Inherits the same `--responses_api_base_url`, `--responses_api_api_key`, + `--responses_api_stream`, and `--responses_api_disable_thinking` flags +- Adds `--responses_api_reasoning_effort` for providers that support that setting + +The current handler removes `tools` and `tool_choice` from outgoing provider +requests as a compatibility workaround. Native tool calling therefore differs +from the `responses-api` backend; see the [realtime guide](realtime-api.md). + +```bash +python -m speech_to_speech.s2s_pipeline \ + --llm_backend chat-completions \ + --model_name YOUR_MODEL \ + --responses_api_base_url https://api.example.com/v1 \ + --responses_api_api_key YOUR_API_KEY +``` + +The default LLM backend is `responses-api`. Model names in this guide are examples; +select a model available in your environment or from your provider. + +## LLM Behavior + +When STT is set to language auto-detection (`--language auto`), LLM handlers can receive `(text, language_code)` and prepend a language control instruction like: + +- `Please reply to my message in .` + +This helps the assistant respond in the detected language. The behavior is opt-in via `--enable_lang_prompt` (shared across all backends); it defaults to `False`. + +## Setup + +### CUDA setup + +```bash +python -m speech_to_speech.s2s_pipeline \ + --llm_backend transformers \ + --model_name microsoft/Phi-3-mini-4k-instruct +``` + +### Local Mac setup + +```bash +python -m speech_to_speech.s2s_pipeline \ + --local_mac_optimal_settings \ + --model_name mlx-community/Qwen3-4B-Instruct-2507-bf16 +``` + +`--local_mac_optimal_settings` already sets `--llm_backend mlx-lm` and will default the model to `mlx-community/Qwen3-4B-Instruct-2507-bf16` if not overridden. + +### Realtime (OpenAI-compatible) setup + +Run the server in realtime mode, then connect with the [browser client](../client/usage.md): + +```bash +# 1. Start the pipeline in realtime mode +python -m speech_to_speech.s2s_pipeline \ + --mode realtime \ + --llm_backend mlx-lm \ + --model_name mlx-community/Qwen3-4B-Instruct-2507-bf16 \ + --ws_host 0.0.0.0 \ + --ws_port 8765 + +# 2. Point the browser client at ws://localhost:8765/v1/realtime. +# See the browser-client usage guide for startup commands. +``` + +For realtime mode on Apple Silicon, set the desired MLX/STT/TTS/device options +explicitly. The current `--local_mac_optimal_settings` helper forces +`mode="local"`, so combining it with `--mode realtime` does not preserve realtime +mode. + +### Remote API setup + +```bash +python -m speech_to_speech.s2s_pipeline \ + --llm_backend responses-api \ + --model_name gpt-5.4-mini \ + --responses_api_api_key YOUR_API_KEY +``` diff --git a/docs/speech/realtime-api.md b/docs/speech/realtime-api.md new file mode 100644 index 0000000..fdaee81 --- /dev/null +++ b/docs/speech/realtime-api.md @@ -0,0 +1,230 @@ +# Realtime API + +## High-level architecture + +The server runs as a handler thread inside the existing pipeline. A FastAPI/uvicorn instance serves the WebSocket endpoint at `/v1/realtime`, while the same queue-driven handler chain (VAD, STT, LLM, TTS) processes audio in parallel threads. + +```mermaid +flowchart LR + subgraph client [Client] + WS["WebSocket /v1/realtime"] + end + + subgraph server [Realtime Server] + Router["WebSocket Router"] + Service["RealtimeService"] + Config["RuntimeConfig"] + end + + subgraph pipeline [Pipeline Threads] + VAD["VAD"] + STT["STT"] + TN["TranscriptionNotifier"] + LLM["LLM"] + Proc["LMOutputProcessor"] + TTS["TTS"] + end + + WS -- "client events (JSON)" --> Router + Router -- "parse / dispatch" --> Service + Service -- "PCM chunks" --> VAD + Service -- "session config" --> Config + Config -. "read by" .-> VAD & LLM & TTS + VAD -- "speech segments" --> STT + STT -- "transcript" --> TN + TN -- "transcript + notify" --> LLM + LLM -- "text + tools" --> Proc + Proc -- "clean text" --> TTS + TTS -- "PCM audio" --> Router + Proc -- "assistant_text / tools" --> Router + VAD -- "speech_started/stopped" --> Router + TN -- "transcription events" --> Router + Router -- "server events (JSON)" --> WS +``` + +**Key flow:** + +1. **Inbound audio**: Client sends `input_audio_buffer.append` with base64 PCM. `RealtimeService` decodes, resamples to 16 kHz, splits into 512-sample chunks, and puts them on the `recv_audio_chunks_queue` for VAD. +2. **Speech detection**: VAD detects speech boundaries and emits `speech_started` / `speech_stopped` events on the `text_output_queue`. Full utterance audio goes to STT. +3. **Transcription**: STT output passes through `TranscriptionNotifier`, which taps the transcript for `transcription.delta` / `transcription.completed` events before forwarding to the LLM. +4. **Generation**: The LLM generates text (and optional tool calls). `LMOutputProcessor` splits the output: clean text goes to TTS, and `assistant_text` + tool call dicts go to the `text_output_queue`. +5. **Outbound audio**: TTS writes PCM chunks to `send_audio_chunks_queue`. The router's async `_send_loop` drains both queues, encoding PCM as `response.output_audio.delta` events and translating internal messages into protocol events. +6. **Session config**: `session.update` events deep-merge into `RuntimeConfig`, which is a shared Pydantic model read by VAD (turn detection thresholds), LLM (instructions, tools), and TTS (voice) at processing time. + +--- + +## Supported OpenAI Realtime Events + +### Client -> Server + +| Event | Description | +|---|---| +| `input_audio_buffer.append` | Stream base64 PCM audio. Decoded, resampled to 16 kHz, and chunked for the VAD. | +| `session.update` | Deep-merge session config (instructions, tools, voice, turn detection, audio format). | +| `conversation.item.create` | Inject `input_text` or `function_call_output` into the LLM context without triggering generation. | +| `response.create` | Trigger LLM generation. Supports per-response `instructions` and `tool_choice` overrides. | +| `response.cancel` | Cancel the in-progress response and re-enable listening. | + +### Server -> Client + +| Event | Description | +|---|---| +| `session.created` | Sent on connection with current session config. | +| `error` | Protocol errors (`session_limit_reached`, `unknown_or_invalid_event`, `invalid_session_type`, `conversation_already_has_active_response`, etc.) | +| `input_audio_buffer.speech_started` | VAD detected user speech. | +| `input_audio_buffer.speech_stopped` | End of user speech segment. | +| `conversation.item.created` | Acknowledges injected `input_text` from `conversation.item.create`. | +| `conversation.item.input_audio_transcription.delta` | Streaming partial transcript (when live transcription is enabled). | +| `conversation.item.input_audio_transcription.completed` | Final transcript for the user turn (with duration usage). | +| `response.created` | Emitted on the first outbound audio chunk (response is `in_progress`). | +| `response.output_audio.delta` | Base64 PCM audio chunk from TTS. | +| `response.output_audio.done` | Audio stream complete for the current output item. | +| `response.output_audio_transcript.done` | Full assistant text transcript for the turn. | +| `response.function_call_arguments.done` | Tool call with `call_id`, `name`, and JSON `arguments`. | +| `response.done` | Response finished (`completed`, `cancelled` with reason `turn_detected` or `client_cancelled`). | + +--- + +## Tool Calling Design + +Tool calling works through two distinct paths depending on the LLM backend, but both converge to the same wire protocol for the client. + +### Local LLM path (`LanguageModelHandler` -- transformers / mlx-lm) + +Tools defined in `session.update` are converted to `FunctionTool` objects. Each tool's JSON Schema `parameters` are turned into a Python `inspect.Signature` (via `signature_from_schema`), and `to_code_prompt()` renders a human-readable `def name(...): """docstring"""` block. + +These tool signatures are injected into the system prompt using a Jinja2 template (`tool_prompt.py`) that instructs the model to wrap tool calls in `...` delimiters: + +``` + +function_name(arg_name_1=value1, arg_name_2='string_value') + +``` + +After generation, `_extract_tools` uses a regex to find `` blocks, then `extract_function_calls_from_text` parses each `name(kwargs)` call and validates it against registered tools. Valid calls become `ResponseFunctionToolCall` dicts with generated `call_id`s. + +### Remote API paths + +`ResponsesApiModelHandler` passes tools natively to `client.responses.create`. +The API returns structured `function_call` items. Per-response `tool_choice` +overrides are read from `response.create`. + +`ChatCompletionsLanguageModelHandler` also contains conversion for Chat +Completions tool-call results, but its current `_request()` removes `tools` and +`tool_choice` before the HTTP call to avoid a provider rejection. That backend +does not currently declare native tools to its provider. Do not assume its +result parsing implies working native tool selection. + +### Common output path + +Both handlers yield `(text, language_code, tools)` tuples. `LMOutputProcessor` forwards clean text to TTS and puts `{"type": "assistant_text", "text": ..., "tools": [...]}` on the `text_output_queue`. The router's `_send_loop` translates these into: +- `response.output_audio_transcript.done` for the text +- `response.function_call_arguments.done` for each tool call + +### Tool result flow + +1. Client executes the tool and sends `conversation.item.create` with `type: "function_call_output"` and `output: ""` +2. `RealtimeService` appends the tool output to the chat context and emits `conversation.item.created`; this does not trigger generation. +3. If the tool result needs to be spoken to the user, such as camera/search/data results, the client sends `response.create` to trigger follow-up generation. +4. For fire-and-forget robot actions such as dance, emotion, head movement, stop, or idle tools, the client can stop after `conversation.item.created`; the assistant should already have spoken the natural lead-in before the tool call. + +--- + +## Interruption Handling + +Barge-in (user speaks while the assistant is playing audio) is handled cooperatively between the VAD, the `_send_loop`, and the LLM/TTS handlers via a shared `CancelScope` object (`cancel_scope.py`). + +### CancelScope design + +`CancelScope` replaces the old two-signal pattern (`cancel_response` Event + `discard_stale_output` boolean) with a single object that manages: + +- **Generation counter** (`cancel_scope.generation`): pipeline threads (LLM, TTS) capture the current generation at the start of each response and check `cancel_scope.is_stale(gen)` on every streaming token. When `cancel()` is called, the generation increments and all prior generations become stale -- no timing games required. +- **Discard flag** (`cancel_scope.discarding`): set by `cancel()`, checked by the async `_send_loop` to drop output from superseded generations that arrives between `cancel()` and `response_done()`. Cleared by `response_done(generation)` (only when the sentinel's generation matches the discarded or current one -- sentinels from unrelated older generations are ignored), by `new_response()` on an explicit `response.create`, or by `reset()` on session claim/release. + +Pipeline output is **generation-tagged**: `AudioOutput` chunks and `AssistantTextEvent`s carry a `cancel_generation` field stamped by the handler that produced them. The send loop's `_generation_is_discardable` drops an item if its generation is stale, or if `discarding` is set and the item is not from the current generation. Output from the *current* generation always passes through, so a fresh response is never swallowed by a lingering discard window (e.g. a superseded speculative turn whose TTS never emitted a `__RESPONSE_DONE__` sentinel). + +```mermaid +sequenceDiagram + participant User + participant VAD + participant SendLoop as _send_loop + participant LLM + participant TTS + participant Client + + Note over TTS,Client: Response active or pending (in_response / response_pending) + User->>VAD: speaks + VAD->>SendLoop: speech_started on text_output_queue + SendLoop->>Client: input_audio_buffer.speech_started + SendLoop->>Client: response.done (status=cancelled, reason=turn_detected) + SendLoop->>SendLoop: cancel_scope.cancel() (gen++ & discarding=True) + SendLoop->>SendLoop: flush output_queue + text_output_queue + SendLoop->>SendLoop: response_playing.clear() + LLM->>LLM: is_stale(gen) → True, aborts generation + TTS->>TTS: is_stale(gen) → True, aborts generation + TTS->>SendLoop: __RESPONSE_DONE__ (tagged with gen) + SendLoop->>SendLoop: cancel_scope.response_done(gen) (discarding=False) + Note over VAD,Client: Pipeline is now processing the new user utterance +``` + +**Step by step:** + +1. **VAD detects speech**: puts a `SpeechStartedEvent` on `text_output_queue`. +2. **`_send_loop` processes text events first** (priority over audio): translates `speech_started` into protocol events. If an active response was in progress, `RealtimeService.dispatch_pipeline_event` emits `response.output_audio.done` + `response.done` with `status="cancelled"` and `reason="turn_detected"`. +3. **Cancel + queue flush**: if a response is active (`in_response`) *or* pending (`response_pending` -- accepted `response.create`, no audio yet), and interrupts are enabled (see step 4), the send loop calls `cancel_scope.cancel()` (increments generation, enables discard), clears `response_pending`, drains `output_queue` (preserving `__RESPONSE_DONE__` sentinels) and `text_output_queue` (preserving user-side events: `speech_stopped`, partial/completed transcriptions, token usage), then clears `response_playing`. +4. **Interrupt gating**: the cancel only fires if the `SpeechStartedEvent.interrupt_response` flag is set *and* the session config allows it (`turn_detection.interrupt_response`, read via `RuntimeConfig.interrupt_response_enabled`, default true). When disabled, user speech during a response is transcribed but the response keeps playing. +5. **LLM/TTS cancellation**: handlers capture `gen = cancel_scope.generation` at the start of each response and check `cancel_scope.is_stale(gen)` on every streaming token, aborting early when stale. +6. **Discard guard**: while `cancel_scope.discarding` is True, the send loop drops audio chunks and assistant text whose `cancel_generation` is not current (see `_generation_is_discardable` above). The guard clears when a `__RESPONSE_DONE__` with a matching generation arrives (via `cancel_scope.response_done(gen)`), or when an explicit `response.create` starts a new response (`cancel_scope.new_response()`). +7. **Client-initiated cancel**: `response.cancel` calls `cancel_scope.cancel()` (only if a response was active), flushes both queues with the same preservation rules, triggers `finish_response(status="cancelled", reason="client_cancelled")`, re-enables `should_listen`, and clears `response_playing`. +8. **Spurious cancel safety**: if no response is active, `cancel_scope.cancel()` is not called, preventing the discard guard from being set without a `__RESPONSE_DONE__` to clear it. + +--- + +## Testing + +Run these examples from the repository root in an environment with the speech +dependencies installed. See [LLM](llm.md), [STT](stt.md), and [TTS](tts.md) for +backend-specific options; this checkout does not include a package manifest. + +### Local LLM with Transformers + +```bash +python -m speech_to_speech.s2s_pipeline \ + --mode realtime \ + --stt parakeet-tdt \ + --llm_backend transformers \ + --tts kokoro \ + --model_name "Qwen/Qwen3-4B-Instruct-2507" \ + --llm_device mps \ + --llm_torch_dtype float16 \ + --enable_live_transcription +``` + +### Local LLM with MLX-LM + +```bash +python -m speech_to_speech.s2s_pipeline \ + --mode realtime \ + --stt parakeet-tdt \ + --llm_backend mlx-lm \ + --tts kokoro \ + --model_name "mlx-community/Qwen3-4B-Instruct-2507-bf16" \ + --llm_device mps \ + --llm_torch_dtype float16 \ + --enable_live_transcription +``` + +### Remote LLM with OpenAI-compatible API + +```bash +python -m speech_to_speech.s2s_pipeline \ + --mode realtime \ + --stt parakeet-tdt \ + --llm_backend responses-api \ + --tts kokoro \ + --model_name "openai/gpt-oss-20b:groq" \ + --responses_api_base_url "https://router.huggingface.co/v1" \ + --responses_api_api_key "$HF_TOKEN" \ + --responses_api_stream \ + --enable_live_transcription +``` diff --git a/docs/speech/stt.md b/docs/speech/stt.md new file mode 100644 index 0000000..efae81b --- /dev/null +++ b/docs/speech/stt.md @@ -0,0 +1,166 @@ +# Speech-to-text backends + +This document summarizes the speech-to-text implementations in +[speech_to_speech/STT](../../speech_to_speech/STT), including language support, +language abbreviations, and pipeline options. Run examples from the repository +root in an environment with the speech dependencies installed. + +## Available STT Modes (`--stt`) + +- `whisper` → `STT/whisper_stt_handler.py` +- `whisper-mlx` → `STT/lightning_whisper_mlx_handler.py` +- `mlx-audio-whisper` → `STT/mlx_audio_whisper_handler.py` +- `faster-whisper` → `STT/faster_whisper_handler.py` +- `parakeet-tdt` → `STT/parakeet_tdt_handler.py` +- `paraformer` → `STT/paraformer_handler.py` + +## Language Support by Handler + +### 1) Whisper (`--stt whisper`) + +- Handler: `WhisperSTTHandler` +- Language input flag: `--language` (from shared Whisper args) +- Supports fixed language (e.g. `en`) or `auto` +- Internal supported language list: + - `en`, `fr`, `es`, `zh`, `ja`, `ko`, `hi`, `de`, `pt`, `pl`, `it`, `nl` +- Behavior: + - Detects language from token output + - If detected language is outside the supported list, it falls back to the previous language + +### 2) Lightning Whisper MLX (`--stt whisper-mlx`) + +- Handler: `LightningWhisperSTTHandler` +- Uses same shared `--language` argument as Whisper +- Internal supported language list: + - `en`, `fr`, `es`, `zh`, `ja`, `ko`, `hi`, `de`, `pt`, `pl`, `it`, `nl` +- Behavior: + - If `--language auto`, model auto-detects each utterance + - If detected language is unsupported, falls back to last supported language + +### 3) MLX Audio Whisper (`--stt mlx-audio-whisper`) + +- Handler: `MLXAudioWhisperSTTHandler` +- Model flag: `--mlx_audio_whisper_model_name` +- Language still comes from shared `--language` flag (wired in pipeline) +- Internal supported language list: + - `en`, `fr`, `es`, `zh`, `ja`, `ko`, `hi`, `de`, `pt`, `pl`, `it`, `nl` +- Behavior: + - Uses fixed language unless `--language auto` + - Falls back to last known supported language when needed + +### 4) Faster-Whisper (`--stt faster-whisper`) + +- Handler: `FasterWhisperSTTHandler` +- Language flag: `--faster_whisper_stt_gen_language` +- Default language: `en` +- Note: + - This handler passes generation kwargs directly to `faster_whisper.WhisperModel.transcribe(...)` + - Effective language coverage depends on selected Faster-Whisper/OpenAI Whisper model + +### 5) Parakeet TDT (`--stt parakeet-tdt`) + +- Handler: `ParakeetTDTSTTHandler` +- Language flag: `--parakeet_tdt_language` (optional) +- Supports auto language detection when language not specified +- Declared supported language list (25 European languages): + - `en`, `de`, `fr`, `es`, `it`, `pt`, `nl`, `pl`, `ru`, `uk`, `cs`, `sk`, `hu`, `ro`, `bg`, `hr`, `sl`, `sr`, `da`, `no`, `sv`, `fi`, `et`, `lv`, `lt` +- Backend behavior: + - On macOS/MPS: MLX (`mlx-community/parakeet-tdt-0.6b-v3`) + - On CUDA/CPU: nano-parakeet (`nvidia/parakeet-tdt-0.6b-v3`) + +### 6) Paraformer (`--stt paraformer`) + +- Handler: `ParaformerSTTHandler` +- Model flag: `--paraformer_stt_model_name` +- Default model: `paraformer-zh` +- No dedicated language flag in current args class +- Practical support: + - Depends on selected FunASR model checkpoint + - Default setup is Chinese-oriented (`zh`) + +## Language Abbreviations (ISO-style codes seen in STT handlers) + +| Code | Language | +|---|---| +| `en` | English | +| `fr` | French | +| `es` | Spanish | +| `zh` | Chinese | +| `ja` | Japanese | +| `ko` | Korean | +| `hi` | Hindi | +| `de` | German | +| `pt` | Portuguese | +| `pl` | Polish | +| `it` | Italian | +| `nl` | Dutch | +| `ru` | Russian | +| `uk` | Ukrainian | +| `cs` | Czech | +| `sk` | Slovak | +| `hu` | Hungarian | +| `ro` | Romanian | +| `bg` | Bulgarian | +| `hr` | Croatian | +| `sl` | Slovenian | +| `sr` | Serbian | +| `da` | Danish | +| `no` | Norwegian | +| `sv` | Swedish | +| `fi` | Finnish | +| `et` | Estonian | +| `lv` | Latvian | +| `lt` | Lithuanian | +| `auto` | Per-utterance automatic language detection | + +## Usage Examples + +### Whisper (Transformers) + +```bash +python -m speech_to_speech.s2s_pipeline --stt whisper --language es +python -m speech_to_speech.s2s_pipeline --stt whisper --language auto +``` + +### Whisper MLX (LightningWhisperMLX) + +```bash +python -m speech_to_speech.s2s_pipeline --stt whisper-mlx --language auto --device mps +``` + +### MLX Audio Whisper + +```bash +python -m speech_to_speech.s2s_pipeline --stt mlx-audio-whisper \ + --mlx_audio_whisper_model_name mlx-community/whisper-large-v3-turbo \ + --language auto +``` + +### Faster-Whisper + +```bash +python -m speech_to_speech.s2s_pipeline --stt faster-whisper \ + --faster_whisper_stt_model_name large-v3 \ + --faster_whisper_stt_gen_language en +``` + +### Parakeet TDT + +```bash +python -m speech_to_speech.s2s_pipeline --stt parakeet-tdt --parakeet_tdt_device auto +python -m speech_to_speech.s2s_pipeline --stt parakeet-tdt --parakeet_tdt_language es +``` + +With live transcription (MLX or CUDA/nano-parakeet backend): + +```bash +python -m speech_to_speech.s2s_pipeline --stt parakeet-tdt \ + --enable_live_transcription \ + --live_transcription_update_interval 0.25 +``` + +### Paraformer + +```bash +python -m speech_to_speech.s2s_pipeline --stt paraformer --paraformer_stt_model_name paraformer-zh +``` diff --git a/docs/speech/tts.md b/docs/speech/tts.md new file mode 100644 index 0000000..49ad382 --- /dev/null +++ b/docs/speech/tts.md @@ -0,0 +1,151 @@ +# Text-to-speech backends + +## Available TTS modes (`--tts`) + +Runtime-supported values in [s2s_pipeline.py](../../speech_to_speech/s2s_pipeline.py): + +- `chatTTS` → `chatTTS_handler.py` +- `facebookMMS` → `facebookmms_handler.py` +- `pocket` → `pocket_tts_handler.py` +- `kokoro` → `kokoro_handler.py` +- `qwen3` → `qwen3_tts_handler.py` + +Run examples from the repository root in an environment with the speech +dependencies installed. The UI requirements do not install TTS dependencies. + +## Usage + +### 1) ChatTTS (`--tts chatTTS`) + +Primary args prefix: `--chat_tts_*` + +```bash +python -m speech_to_speech.s2s_pipeline \ + --tts chatTTS \ + --chat_tts_device cuda \ + --chat_tts_stream true \ + --chat_tts_chunk_size 512 +``` + +### 2) Facebook MMS (`--tts facebookMMS`) + +Primary args prefix: `--facebook_mms_*` plus `--tts_language` + +```bash +python -m speech_to_speech.s2s_pipeline \ + --tts facebookMMS \ + --facebook_mms_device cuda \ + --tts_language en +``` + +This handler maps STT language codes (e.g. `en`, `fr`, `es`) to MMS model suffixes (e.g. `eng`, `fra`, `spa`) and reloads the model on language changes. + +### 3) Pocket TTS (`--tts pocket`) + +Primary args prefix: `--pocket_tts_*` + +```bash +python -m speech_to_speech.s2s_pipeline \ + --tts pocket \ + --pocket_tts_voice jean \ + --pocket_tts_device cpu \ + --pocket_tts_sample_rate 16000 +``` + +Available preset voices include: +`alba`, `marius`, `javert`, `jean`, `fantine`, `cosette`, `eponine`, `azelma`. + +### 4) Kokoro (`--tts kokoro`) + +Primary args prefix: `--kokoro_*` + +```bash +python -m speech_to_speech.s2s_pipeline \ + --tts kokoro \ + --kokoro_device auto \ + --kokoro_voice bm_fable \ + --kokoro_lang_code b +``` + +Behavior: +- Uses MLX backend on Apple Silicon (`mlx-community/Kokoro-82M-bf16`) +- Uses native kokoro pipeline otherwise (`hexgrad/Kokoro-82M`) +- Can auto-switch voice/language based on STT language code mapping + +### 5) Qwen3-TTS (`--tts qwen3`) + +Primary args prefix: `--qwen3_tts_*` + +```bash +python -m speech_to_speech.s2s_pipeline \ + --tts qwen3 \ + --qwen3_tts_model_name Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice \ + --qwen3_tts_device cuda \ + --qwen3_tts_backend ggml \ + --qwen3_tts_speaker Aiden \ + --qwen3_tts_language auto \ + --qwen3_tts_non_streaming_mode True +``` + +Behavior: +- Uses `faster-qwen3-tts` on non-macOS platforms, defaulting to the GGML backend. Pass `--qwen3_tts_backend torch` to use the CUDA-graphs backend instead. +- Uses `mlx-audio` on Apple Silicon and auto-maps `Qwen/...` model IDs to `mlx-community/...`, defaulting to the `6bit` MLX variant unless the model name already pins a suffix. +- Supports MLX quantization overrides on Apple Silicon via `--qwen3_tts_mlx_quantization bf16|4bit|6bit|8bit`. +- Keeps the existing voice-clone/custom-voice/voice-design handler flow intact. +- Defaults to the CustomVoice model with speaker `Aiden`, so no reference audio is required. Voice-clone/base models can still use `--qwen3_tts_ref_audio`. + +Install notes for Linux GGML: +- The default PyPI `qwentts-cpp-python` wheel targets CUDA 12.8. +- If that wheel does not match your CUDA runtime, install one of the Hugging Face wheelhouse builds before installing `speech-to-speech`. + +```bash +pip install "qwentts-cpp-python==0.3.1+cu130" \ + -f https://huggingface.co/datasets/andito/qwentts-cpp-python-wheels/tree/main/whl/cu130 +pip install speech-to-speech +``` + +Available wheelhouse directories include `cu124`, `cu128`, `cu130`, and `cpu`. + +Example for Apple Silicon using the default 6-bit MLX variant: + +```bash +python -m speech_to_speech.s2s_pipeline \ + --tts qwen3 \ + --qwen3_tts_model_name Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice \ + --qwen3_tts_speaker Aiden +``` + +You can override the default and select `bf16`, `4bit`, or `8bit` explicitly: + +```bash +python -m speech_to_speech.s2s_pipeline \ + --tts qwen3 \ + --qwen3_tts_model_name Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice \ + --qwen3_tts_mlx_quantization 4bit \ + --qwen3_tts_speaker Aiden +``` + +For voice-cloning examples, an optional reference clip is retained at +[docs/examples/reference-audio.wav](../examples/reference-audio.wav). Supply an +appropriate base/voice-cloning model and `--qwen3_tts_ref_audio` explicitly; +CustomVoice mode does not need this clip. The repository does not include a TTS +benchmark script. + +## Setup + +### Low-latency GPU setup + +```bash +python -m speech_to_speech.s2s_pipeline \ + --stt whisper \ + --tts pocket +``` + +### Apple Silicon setup + +```bash +python -m speech_to_speech.s2s_pipeline \ + --local_mac_optimal_settings +``` + +`--tts pocket` and `--tts kokoro` are also valid options on macOS. diff --git a/reasoning.md b/reasoning.md deleted file mode 100644 index e0b8b82..0000000 --- a/reasoning.md +++ /dev/null @@ -1,608 +0,0 @@ -# Reasoning & Context Injection — Architettura Completa - -Questo documento descrive **come funziona il "reasoning"** (il layer di intelligenza che decide cosa rispondere) nell'app Vocero/S2S e **in quali punti puoi iniettare contesto** (identità dell'agente, istruzioni, strumenti MCP, profilo chiamante, dati extra, ecc.). - -Esistono **due modalità di reasoning** distinte: - -| Modalità | Variabile env | Chi fa il "pensiero" | Flusso | -|---|---|---|---| -| **PROXY** *(default)* | `S2S_REASONING_TYPE=PROXY` | Il server realtime upstream (`ai-server`, Vocero, o qualunque backend dietro `S2S_PROXY_TARGET`) | Browser → WebSocket `/v1/realtime` → upstream (prompt + tools inviati in `session.update`) | -| **OPENAI** *(reasoning esterno)* | `S2S_REASONING_TYPE=OPENAI` | Una chiamata HTTP separata a OpenAI Chat Completions (es. `gpt-4.1-mini`) | Browser → `POST /api/reasoning` → OpenAI → risposta reiniettata nel realtime come messaggio utente forzato | - -In **entrambe** le modalità le informazioni di contesto vengono assemblate lato client in un'unica stringa "istruzioni" (`effectiveReasoningInstructions`) e passate poi in modo diverso. - ---- - -## 1. Panoramica del flusso completo (uno sguardo dall'alto) - -``` - ┌─────────────────────────────────────────────────────────────────────────┐ - │ /home/duxiter/s2s/.env │ - │ S2S_PRIMARY_PROMPT S2S_AGENT_PROFILE S2S_REASONING_TYPE │ - │ S2S_TOOL_EXECUTION_MCP_URL S2S_USER_PHONE_AUTH_URL │ - │ OPENAI_API_KEY / BASE_URL / REASONING_MODEL / ORG / PROJECT │ - │ S2S_PROXY_TARGET S2S_SEARCH_MCP etc. │ - └───────────────────────────┬─────────────────────────────────────────────┘ - │ caricato da start_ui.sh - ▼ - ┌─────────────────────────────────────────────────────────────────────────┐ - │ demo/server.py (backend Python FastAPI) │ - │ │ - │ fetchConfig() GET /api/config ←─────── GET /api/user/phone │ - │ │ │ (se URL param phone) │ - │ ├─ primaryPrompt (priorità 1: Aquachile /agents/profile │ - │ │ priorità 2: S2S_PRIMARY_PROMPT env) │ - │ ├─ agentProfile (URL di dove abbiamo preso il prompt) │ - │ ├─ agentTools[] (catalogo MCP Aquachile, enabled=True) │ - │ ├─ reasoningType = "PROXY" oppure "OPENAI" │ - │ └─ searchMcp, s2sUrl, lb, auth, search, ecc. │ - │ │ - │ POST /api/reasoning (solo se reasoningType=OPENAI) │ - │ body → httpx POST {OPENAI_BASE_URL}/chat/completions │ - │ │ - │ POST /api/mcp/tool │ - │ body → httpx POST {S2S_TOOL_EXECUTION_MCP_URL} + chiavi API │ - │ │ - │ WS /v1/realtime (proxy a S2S_PROXY_TARGET) │ - │ client ↔ proxy ↔ upstream: logga [INPUT UTENTE]/[OUTPUT AGENTE] │ - └───────────────────────────┬─────────────────────────────────────────────┘ - │ fetch su caricamento pagina - ▼ - ┌─────────────────────────────────────────────────────────────────────────┐ - │ demo/main.js (frontend browser) │ - │ │ - │ pinnedPrompt = primaryPrompt (da /api/config) — read-only se valoriz.│ - │ agentToolDefs[] = agentTools (da /api/config) │ - │ reasoningType = "PROXY" | "OPENAI" │ - │ voceroUserPhoneNumber = new URL(location).searchParams.phoneNumber │ - │ │ │ - │ └─► async fetchVoceroUserProfile() │ - │ GET api/user/phone?phoneNumber=… → voceroUserProfile{} │ - │ │ - │ Quando l'utente clicca l'orb → doStart(): │ - │ startInstructions = effectiveInstructions() │ - │ startTools = activeToolDefs() │ - │ │ │ - │ └─► new S2sWsRealtimeClient({instructions, tools, …}) │ - │ │ │ - │ ├─► session.update al realtime upstream │ - │ │ (se reasoningType=PROXY → qui pensa) │ - │ │ │ - │ └─► event "transcript" (user, partial=false) │ - │ │ │ - │ └─► maybeRunOpenAiReasoning() │ - │ (solo reasoningType=OPENAI) │ - │ → POST /api/reasoning → answer │ - │ → sendUserText(renderPrompt) │ - │ → requestResponse() │ - └─────────────────────────────────────────────────────────────────────────┘ -``` - ---- - -## 2. Assemblaggio del prompt: `effectiveReasoningInstructions()` - -La funzione **centrale** che costruisce il blocco di testo che verrà dato al modello è in [main.js:516-533](file:///home/duxiter/s2s/demo/main.js#L516-L533): - -```js -function effectiveReasoningInstructions() { - const base = pinnedPrompt || settings.instructions; - let instructions = base; - if (activeToolDefs().length) instructions += TOOL_USE_HINT; - if (searchMcpEnabled && agentToolDefs.length) { - instructions += MCP_SEARCH_HINT; - instructions += ` Available MCP tools: ${buildMcpToolCatalogSummary(agentToolDefs)}`; - } - const suggested = topSuggestedAgentTools(3); - if (searchMcpEnabled && suggested.length) { - instructions += ` Current user request: "${lastUserQuery}". Client-side ranking hint only: …`; - } - const userContext = voceroUserContextText(); - if (userContext) instructions += userContext; - return instructions; -} -``` - -Ordine di concatenazione (dalla priorità più alta alla più bassa): - -| # | Fonte | Dove viene da | Note | -|---|---|---|---| -| 1 | **`pinnedPrompt`** | `S2S_AGENT_PROFILE` (`instructions` campo Aquachile) → fallback `S2S_PRIMARY_PROMPT` env → fallback `settings.instructions` (localStorage) → fallback `DEFAULT_INSTRUCTIONS` | **Identità e personalità principale dell'agente**. Quando `pinnedPrompt` è presente, il campo `instructions` di Settings è disabilitato in UI (read-only). | -| 2 | **`TOOL_USE_HINT`** | Costante in linea [main.js:32-36](file:///home/duxiter/s2s/demo/main.js#L32-L36) | Aggiunto se c'è **almeno 1 tool attivo**: "*When the user's request calls for one of your tools, do not describe your capabilities or say you can do it and wait for another turn. Instead, say a brief acknowledgement… and call the tool right away in the same response.*" | -| 3 | **`MCP_SEARCH_HINT`** + catalogo completo tools | Condizionato a `S2S_SEARCH_MCP=true` in env | Istruisce il modello a leggere l'intero catalogo MCP e scegliere lo strumento migliore. Poi **appende come testo TUTTI i tool MCP** (`buildMcpToolCatalogSummary`) con nome, descrizione e parametri obbligatori. | -| 4 | **Suggerimento tool client-side (top 3)** | `topSuggestedAgentTools(3)` basato su `lastUserQuery` | Messaggio "Client-side ranking hint only: 1. get_day_report: … 2. … 3. …". Usato **solo come hint secondario**, il modello deve sempre controllare il catalogo completo prima. | -| 5 | **`voceroUserContextText()`** | Profile restituito da `/api/user/phone?phoneNumber=…` | Stringa: `" Caller profile resolved from the page phoneNumber: {JSON profilo}. Use this as trusted caller context when relevant."` (troncato a 1600 char) | - -Poi la funzione **`effectiveInstructions()`** ([main.js:537-539](file:///home/duxiter/s2s/demo/main.js#L537-L539)) prende il risultato e: -- Se `reasoningType=OPENAI` → **appende `OPENAI_RENDER_HINT`**: istruisce il realtime a **rispondere solo ai messaggi che iniziano con il marker `[VOCERO_RENDER_REPLY]`**, in modalità "leggi e basta" (niente tool, niente ragionamento). Questo è il segreto che permette di scrivere la frase pensata da OpenAI e farla ripetere fedelmente in TTS. -- Se `reasoningType=PROXY` → ritorna le istruzioni tal quali. - -### Quando viene ricalcolato e reinviato al modello - -- **Alla connessione** in `doStart()`: `startInstructions = effectiveInstructions()` → `new S2sWsRealtimeClient({instructions: startInstructions, …})`. -- **Durante la chiamata**, in risposta a: - - ogni **trascrizione utente** parziale o finale (linee [1122-1128](file:///home/duxiter/s2s/demo/main.js#L1122-L1128)): `pushLiveToolPolicy()` + `pushLiveInstructions(effectiveInstructions())` → `client.updateSession({ instructions })` - - quando arriva il **profilo chiamante da phone auth** ([2388-2390](file:///home/duxiter/s2s/demo/main.js#L2388-L2390)): stesso `pushLiveInstructions` - - quando l'utente **modifica le impostazioni** nel form e salva. - ---- - -## 3. I due motori di reasoning, nel dettaglio - -### 3.1 Modalità **PROXY** (default — consigliata con Aquachile) - -``` -S2S_REASONING_TYPE=PROXY (o qualsiasi valore diverso da "OPENAI") -S2S_PROXY_TARGET=ws://ai-server:12345/v1/realtime # o qualunque endpoint WS realtime -``` - -In questa modalità, **l'upstream realtime è l'unico a "pensare"**. Tutta l'intelligenza risiede nel backend puntato da `S2S_PROXY_TARGET` (es. Vocero, un wrapper realtime custom, un server che parla OpenAI Realtime API). - -Flusso **testuale** di quello che succede a ogni avvio: - -1. `doStart()` calcola `startInstructions = effectiveInstructions()` (tutto il blocco §2). -2. Costruisce `startTools = activeToolDefs()` = tool browser (web_search, camera_snapshot) **+** `agentToolDefs` (catalogo MCP Aquachile). -3. Passa `instructions` e `tools` al costruttore di `S2sWsRealtimeClient`. -4. Quando il WS si connette e arriva `session.created`, il client manda `session.update` con: - ```json - { - "type": "realtime", - "instructions": "", - "tools": [ { "type":"function", "name":"…", "description":"…", "parameters":{…} }, … ], - "tool_choice": "auto", - "audio": { "output": { "voice": "Aiden" } } - } - ``` -5. **TUTTO IL RESTO è SULL'UPSTREAM**: L'upstream decide quando fare tool call, quando parlare, quando ascoltare. Il browser è solo uno "schermo+microfono+telecomando". -6. Quando l'upstream fa `conversation.item.input_audio_transcription.completed` il log server stampa `[INPUT UTENTE] …`. -7. Quando l'upstream fa `response.*_transcript.done` / `response.content_part.done` ecc. il log server stampa `[OUTPUT AGENTE] …`. - -**Vantaggi:** -- Un solo round trip per tutto (latenza più bassa per voce→voce). -- L'upstream può usare qualsiasi modello/rete interna (non per forza OpenAI). -- Le MCP tool call sono orchestrate dallo stesso server che fa STT/TTS → meno desincronizzazioni. - -**Svantaggi:** -- Tutto il "pensiero" è black-box sull'upstream; non puoi vedere i token del thinking né usare un modello diverso senza cambiare upstream. - ---- - -### 3.2 Modalità **OPENAI** (reasoning HTTP separato) - -``` -S2S_REASONING_TYPE=OPENAI -OPENAI_API_KEY=sk-… # obbligatorio -OPENAI_BASE_URL=https://api.openai.com/v1 # default -OPENAI_REASONING_MODEL=gpt-4.1-mini # default -OPENAI_ORGANIZATION=… # opzionale -OPENAI_PROJECT=… # opzionale -``` - -In questa modalità il **ragionamento vero e proprio** non viene fatto dall'upstream realtime. Invece: - -1. L'upstream fa solo **STT** (converte voce in testo) e **TTS** (converte testo in voce). Agisce come un "dumb" audio I/O. -2. **Non appena arriva una trascrizione utente COMPLETA** (evento `transcript`, `role=="user"`, `partial==false`), `maybeRunOpenAiReasoning(transcript, itemId)` viene triggerato. -3. Questo chiama `fetchOpenAiReasoningAnswer(transcript)` ([main.js:563-586](file:///home/duxiter/s2s/demo/main.js#L563-L586)) che fa: - ``` - POST /api/reasoning - body = { - transcript: "quanto è il report giornaliero?", - instructions: effectiveReasoningInstructions(), // stesse di PROXY - language: "es-CL" o vuoto, - user_context: voceroUserContextText(), // duplicato per sicurezza - } - ``` -4. Il server (endpoint in [server.py:635-710](file:///home/duxiter/s2s/demo/server.py#L635-L710)) a sua volta fa: - ``` - POST {OPENAI_BASE_URL}/chat/completions - body = { - model: OPENAI_REASONING_MODEL, - messages: [ - { role:"system", - content: "{instructions}\n\n{user_context}\nReply only with final answer. Language=…" }, - { role:"user", content: transcript } - ] - } - ``` -5. Riceve `answer` (stringa semplice, pensata per essere "parlata"), logga `[Vocero REASONING] transcript=… answer=…` e la restituisce al client. -6. Il client costruisce `renderPrompt = "[VOCERO_RENDER_REPLY]\n" + answer` e lo **manda come se fosse un testo scritto dall'utente** al realtime: - ``` - client.sendUserText(renderPrompt); - client.requestResponse(); - ``` -7. L'upstream realtime, a causa di `OPENAI_RENDER_HINT` nel prompt, **vede il marker `[VOCERO_RENDER_REPLY]`** e quindi: - - NON usa tool, NON fa ragionamento proprio, NON modifica la frase. - - Si limita a leggere la parte dopo il marker in TTS. -8. Risultato: l'utente sente "la voce dell'agente" (TTS dell'upstream) ma il testo **è stato scritto da OpenAI** in `/chat/completions`. - -Log server corrispondenti: -``` -[EXT][OPENAI] reasoning POST https://api.openai.com/v1/chat/completions model=gpt-4.1-mini systemLen=… transcriptLen=… -[EXT][OPENAI] reasoning RESP status=200 len=… -[EXT][OPENAI] reasoning USAGE prompt=1234 completion=89 total=1323 -INFO [s2s] [Vocero REASONING] transcript=… answer=… -``` - -**Vantaggi:** -- Scegli tu **qualsiasi modello compatibile Chat Completions** (anche Azure, Together, self-hosted se l'endpoint parla lo stesso protocollo). -- Hai **usage e log del reasoning separati** da quelli dell'audio. -- Puoi aggiungere facilmente post-processing, cache o fallback. - -**Svantaggi:** -- Due round trip invece di uno → un po' più di latenza totale (~200-800 ms). -- Più costoso in token: `instructions` + contesto utente vengono mandati **due volte** (una a OpenAI, una al realtime). -- Le tool call che il modello OpenAI vorrebbe fare non possono essere usate direttamente — in OPENAI mode `chat/completions` NON ha accesso a `tools` (al momento l'endpoint `POST /api/reasoning` non inoltra il catalogo MCP a OpenAI). **Quindi in OPENAI mode, le MCP Aquachile vengono ancora passate al realtime (che in questa modalità non "pensa" ma solo reinderizza il testo), quindi non sono usabili.** - -> ⚠️ Importante: se usi Aquachile con il suo ecosistema MCP, **la modalità PROXY è quella corretta da usare**. OPENAI mode è pensata per scenari "solo testo + voce" senza tool complessi. - ---- - -## 4. TUTTI i modi per iniettare contesto all'agente, dal più semplice al più avanzato - -I punti di injection sono ordinati per **priorità di applicazione** (chi "vince" in caso di conflitto) e per **facilità di modifica**. - ---- - -### 🅿️ Punto 1 — `.env` (variabili di ambiente, configurazione statica) - -File: [.env](file:///home/duxiter/s2s/.env) -Caricato in memoria da [start_ui.sh](file:///home/duxiter/s2s/start_ui.sh#L8-L12) (`source "$ROOT_DIR/.env"`) prima di avviare uvicorn. - -| Variabile | Tipo | Cosa fa all'agente | -|---|---|---| -| **`S2S_PRIMARY_PROMPT`** | testo lungo | **Prompt backup quando Aquachile è irraggiungibile o `S2S_AGENT_PROFILE` non è impostato.** Sarà il valore di `primaryPrompt` in `/api/config` se `_extract_agent_prompt()` torna stringa vuota. Supporta `\n` → convertiti in newline. | -| **`S2S_AGENT_PROFILE`** | URL | Endpoint `GET` (es. Aquachile: `https://aquachile.azurianlab.com/api/v1/agents/profile`). Deve ritornare JSON `{ agent: { instructions: "...", tools: [ {name, description, parameters, enabled}, ... ] } }`. **Ha priorità su `S2S_PRIMARY_PROMPT`** — vedi `primary_prompt = agent_prompt or S2S_PRIMARY_PROMPT` in [server.py:517](file:///home/duxiter/s2s/demo/server.py#L517). | -| **`S2S_TOOL_EXECUTION_MCP_URL`** | URL | Endpoint `POST` per **eseguire** le tool call MCP (stesso backend Aquachile). Riceve `{server, name, arguments}` e viene chiamata ogni volta che il modello invoca uno strumento. | -| `S2S_TOOL_EXECUTION_MCP_API_KEY` / `S2S_TOOL_EXECUTION_MCP_API_SECRET` | stringhe segrete | Intestazioni `X-API-KEY` e `X-API-SECRET` aggiunte a ogni chiamata MCP. | -| **`S2S_USER_PHONE_AUTH_URL`** | URL | Endpoint `GET` (con `?phoneNumber=…`) che restituisce il profilo del chiamante. Se l'URL della UI contiene `?phoneNumber=+56…`, questo endpoint viene chiamato e il JSON risultante viene appeso al prompt di sistema (vedi Punto 4). | -| **`S2S_SEARCH_MCP=true\|false`** | bool | Quando `true`, appende `MCP_SEARCH_HINT` + il catalogo COMPLETO dei tool MCP dentro le `instructions`. Fondamentale se vuoi che il modello sappia che esistono 17 strumenti e possa scegliere tra quelli. | -| **`S2S_REASONING_TYPE`** | `PROXY` \| `OPENAI` | Motore di reasoning (§3). Normalizzato con `_normalize_reasoning_type()` (case-insensitive). | -| **`OPENAI_API_KEY` / `BASE_URL` / `REASONING_MODEL`** | stringhe | Solo per mode OPENAI. `BASE_URL` serve anche per compatibilità Azure/Together (basta che parli /chat/completions). | -| **`S2S_PROXY_TARGET`** | URL WS | Upstream realtime che fa STT/TTS + (in mode PROXY) il reasoning vero e proprio. Di solito `ws://ai-server:12345/v1/realtime`. | -| `S2S_PRELOAD_DATA_ENDPOINT`, `SERPER_API_KEY`, `LOAD_BALANCER_URL`, `SPEECH_TO_SPEECH_URL` | varie | Non iniettano testo nel prompt direttamente, ma abilitano altre funzionalità (PowerBI preload, web search Serper, queue & limiter, direct URL fissa). | - ---- - -### 🅿️ Punto 2 — **Aquachile `/api/v1/agents/profile`** (contesto Aziendale + Tools) - -URL impostato da `S2S_AGENT_PROFILE`. Fetchato lato server in [_agent_profile_data()](file:///home/duxiter/s2s/demo/server.py#L357-L397) con: -- cache 60 secondi globale (`_agent_profile_cached`), lock asincrona -- timeout 10 s -- chiamata GET senza header speciali (aggiungibili se serve a mano nel codice) - -**Formato JSON atteso** (si adatta in modo tollerante): - -```jsonc -{ - "agent": { - // ↓ usato come prompt principale (priority #1) - "instructions": "Eres el asistente de voz oficial de Aquachile. Te llamas Aquachile Assistant…", - // ↓ fallback se instructions non esiste - "description": "…", - "tools": [ - { - "name": "get_day_report", - "description": "Obtiene el reporte de producción diario de una planta…", - "parameters": { - "type": "object", - "properties": { - "center": {"type": "string", "description": "Nombre de la planta"} - }, - "required": [] - }, - "enabled": true // ↓ se missing o true → incluso; se false → ignorato - }, - // … altri 16 strumenti - ] - } -} -``` - -Parser corrispondente: -- [_extract_agent_prompt()](file:///home/duxiter/s2s/demo/server.py#L405-L424) — cerca in ordine: `agent.instructions` → `agent.description` → `instructions` radice → `description` radice. -- [_extract_agent_tools()](file:///home/duxiter/s2s/demo/server.py#L427-L437) — cerca `agent.tools[]`, filtra quelli con `enabled` != `false`. - -Tutto il resto del payload viene ignorato. Se vuoi estrarre altri campi (es. `agent.name`, `agent.greeting`, `agent.language`) puoi aggiungerne l'estensione in `_extract_agent_prompt` per concatenarli, oppure creare un nuovo campo nel dizionario di ritorno e poi usarlo in `/api/config`. - -**Quando modificare questo endpoint piuttosto che altre parti:** -- Quando il contenuto cambia spesso (ogni giorno: nuovi report, nuove tipologie di domanda). -- Quando vuoi che **tutte le installazioni** dell'UI aggiornino all'istante senza rebuild/restart del server. -- Quando vuoi rilasciare un **nuovo tool MCP**: basta aggiungerlo all'array `tools[]` e comparirà ovunque entro 60 s (prossima invalidazione della cache). - ---- - -### 🅿️ Punto 3 — **URL parameters** della pagina (contesto per-chiamata) - -Analizzati all'avvio di `main.js` ([riga 410](file:///home/duxiter/s2s/demo/main.js#L410)): -```js -const pageParams = new URLSearchParams(window.location.search); -const voceroUserPhoneNumber = (pageParams.get("phoneNumber") || "").trim(); -``` - -Attualmente è gestito un solo param: - -| Parametro URL | Tipo | Effetto | -|---|---|---| -| `?phoneNumber=+56912345678` | stringa E.164 | Triggera `fetchVoceroUserProfile()` → `GET /api/user/phone?phoneNumber=…` → endpoint Aquachile `S2S_USER_PHONE_AUTH_URL` → profilo JSON appenduto al prompt (vedi Punto 4). | - -È molto semplice estendere la lista: aggiungi una riga tipo: -```js -const plantId = (pageParams.get("plant") || "").trim(); -``` -e poi inietta il valore in modo statico (in `voceroUserContextText()` o in un pezzo di testo a parte in `effectiveReasoningInstructions`) o fai una fetch al tuo endpoint. - ---- - -### 🅿️ Punto 4 — **Profilo chiamante `/api/user/phone`** (contesto per-caller) - -End-to-end: - -``` -URL: https:///?phoneNumber=+56912345678 - │ - ▼ fetchVoceroUserProfile() [main.js:2370-2398] -GET api/user/phone?phoneNumber=%2B56912345678 - │ - ▼ user_by_phone() [server.py:539-573] -GET {S2S_USER_PHONE_AUTH_URL}?phoneNumber=%2B56912345678 - │ - ▼ -Risposta Aquachile (es.) -{ - "id": 987, - "name": "Don Manuel", - "role": "Jefe de Planta", - "center": "Puerto Montt", - "email": "manuel@aquachile.cl", - "authorizations": ["report:daily", "report:weekly"] -} - │ - ▼ { "result": } al browser - │ - ▼ voceroUserProfile = ; voceroUserProfileLoaded = true - │ - ▼ voceroUserContextText() [main.js:454-458] -" Caller profile resolved from the page phoneNumber: {name:\"Don Manuel\",…}. Use this as trusted caller context when relevant." - │ - └─► concatenato ALLA FINE di effectiveReasoningInstructions -``` - -Una volta che il profilo è arrivato, viene chiamato `pushLiveInstructions(effectiveInstructions())` → l'istruzione sul realtime viene **aggiornata in volo** anche se la conversazione è già iniziata. Quindi anche se il profilo impiega 2 secondi ad arrivare, le battute successive alla ricezione beneficeranno del contesto. - -**Quando usarlo:** passare dati per-caller (ruolo, permessi, centro, nome, lingua preferita, reporting line, storico chiamate recenti ecc.). Tieni conto che il JSON viene serializzato in chiaro nel prompt (max 1600 caratteri), quindi non passare PII sensibili in chiaro. - ---- - -### 🅿️ Punto 5 — **Catalogo MCP Aquachile** (contesto come "abilità" dell'agente) - -Fonte: `agent.tools[]` dal profilo Aquachile (Punto 2), poi in `agentToolDefs` lato client. - -Entrano nel prompt in due modi: - -1. **Come `tools` (dichiarazione formale OpenAI Realtime function-call)** : `S2sWsRealtimeClient({tools: activeToolDefs()})` → arrivano all'upstream come `session.tools[]` con schema JSON Schema. Questo permette all'upstream di **decidere di chiamarli** tramite `response.create_response + function_call_arguments.done`. -2. **Come testo nel prompt vero e proprio** : `Available MCP tools: get_day_report - Obtiene el reporte… Required parameters: []; get_metrics_summary - …. ` (solo se `S2S_SEARCH_MCP=true`). - -Quando poi il modello effettivamente **chiama** un tool MCP, il client: -- emette l'evento `toolcall` -- il server chiama `POST /api/mcp/tool` ([server.py](file:///home/duxiter/s2s/demo/server.py#L576…)): - ``` - POST {S2S_TOOL_EXECUTION_MCP_URL} - headers: X-API-KEY, X-API-SECRET, Content-Type: application/json - body: {"server": "mcp", "name": "get_day_report", "arguments": "{\"center\":\"Puerto Montt\"}"} - ``` -- Il risultato torna al client e viene rinviato all'upstream come `conversation.item` di tipo `function_call_output`. Il modello legge l'output e prosegue il turn. - ---- - -### 🅿️ Punto 6 — **Settings utente (localStorage)** (solo se prompt non pinned) - -Se `pinnedPrompt` è stringa vuota (né da Aquachile, né da env), allora in `effectiveReasoningInstructions()` la base è `settings.instructions` che viene da: - -```js -// main.js loadSettings: riga 201 -instructions: localStorage.getItem("s2s.ws.instructions") || DEFAULT_INSTRUCTIONS -``` - -Nel form Settings (pannellino in alto a destra) l'utente può editare il testo "System instructions" e salvarlo → va in localStorage. - -⚠️ **Attenzione**: se è presente un prompt "pinned" (da Aquachile o env), il campo nel Settings diventa **read-only** (non è modificabile). Puoi sempre verificare lo stato aprendo il pannello. - ---- - -### 🅿️ Punto 7 — **Aggiungere contesto custom via codice (patch diretta)** - -Se vuoi iniettare dati specifici (es. l'ID di una campagna, il turno di lavoro corrente, la stazione meteorologica più vicina, ecc.) senza creare un nuovo endpoint esterno, hai **3 punti comodi** dove patchare con poche righe: - -#### 7a. Aggiungere un pezzo di testo statico alle `instructions` - -Modifica direttamente `effectiveReasoningInstructions()` in [main.js:516-533](file:///home/duxiter/s2s/demo/main.js#L516-L533), aggiungendo una sezione. Esempio: - -```js -function effectiveReasoningInstructions() { - const base = pinnedPrompt || settings.instructions; - let instructions = base; - if (activeToolDefs().length) instructions += TOOL_USE_HINT; - if (searchMcpEnabled && agentToolDefs.length) { … } - const suggested = topSuggestedAgentTools(3); - if (searchMcpEnabled && suggested.length) { … } - const userContext = voceroUserContextText(); - if (userContext) instructions += userContext; - // ↓ aggiungi contesto custom QUI - instructions += `\n\nTurno actual: ${TURNO_CORRIENTE}. Campaña: ${CAMPAIGN_ID}. Planta: ${PLANTA_ID}.`; - return instructions; -} -``` - -Funziona in **entrambe** le modalità (PROXY e OPENAI). - -#### 7b. Inviare un messaggio pre-filla a inizio conversazione - -Dopo che il client è connesso e pronto (evento `ready` o `status=="connected"`), chiama: -```js -client.sendUserText( - "Contexto adicional de esta llamada (no responder a esto directamente): " + - "El usuario está llamando desde la planta Puerto Montt. Su último reporte " + - "fue el día 2026-08-17 y mostró un 95% de cumplimiento. El turno actual " + - "es el turno noche. Usa esta información cuando respondas." -); -// (opzionale) poi client.requestResponse() se vuoi che l'agente saluti subito -``` -Il messaggio entra nella history del modello (coda `conversation.items[]`) ed è visibile per il resto della conversazione. - -#### 7c. Patchare `/api/config` lato server per ritornare un campo custom e usarlo dal client - -Aggiungi in [server.py ~riga 518-531](file:///home/duxiter/s2s/demo/server.py#L518-L531): -```python -out = { - ..., - "myCustomContext": {"turno": current_shift(), "planta": os.environ.get("PLANTA_ID", "")}, -} -``` -Poi lato client in `fetchConfig()` (circa riga 2408): -```js -myCustomContext = json.myCustomContext || null; -``` -e usa il valore come in 7a. Utile quando il contesto lo conosci solo lato server (es. viene da DB aziendale o da variabili env del deploy). - -#### 7d. Aggiungere un parametro HTTP `user_context` custom alla chiamata `/api/reasoning` (solo OPENAI mode) - -L'endpoint già accetta il campo `user_context` nel body della request — è già popolato da `voceroUserContextText()`, ma puoi aggiungere ulteriore testo concatenandolo nel client o nel server. - -Oppure estendi `ReasoningRequest` in [server.py:346-350](file:///home/duxiter/s2s/demo/server.py#L346-L350) con un nuovo campo BaseModel (es. `turno: str = ""`, `planta: str = ""`) e poi usalo in `system_parts.append(...)` dentro `def reasoning()`. - ---- - -## 5. Verifiche e Debug — come controllare "cosa vede veramente l'agente" - -### 5a. Log del server (cosa arriva all'esterno) - -Su `docker logs -f s2s_ui` (o sull'output di `start_ui.sh`) puoi monitorare TUTTE le chiamate esterne. Filtri utili: - -```bash -# Solo contesto caricato all'avvio (profilo Aquachile) -grep "\[EXT\]\[AQUACHILE\]" server.log - -# Solo ragionamento OpenAI (se mode OPENAI) -grep "\[EXT\]\[OPENAI\]" server.log - -# Dialogo parlato (TESTO della chat) -grep -E "INPUT UTENTE|OUTPUT AGENTE" server.log - -# Tutte le chiamate MCP -grep "\[EXT\]\[AQUACHILE\].*mcp.*tools/call" server.log - -# /api/config (quello che arriva al browser come initial setup) -grep "/api/config returned" server.log - -# Autenticazione chiamante -grep "Vocero USER AUTH" server.log -``` - -### 5b. Debug lato client (cosa viene assemblato) - -Apri la console del browser (F12) e, dopo che la pagina ha caricato e ti sei connesso, puoi eseguire: - -```js -// Controlla il tipo di reasoning attivo -> reasoningType -"PROXY" // oppure "OPENAI" - -// Stringa effettiva di instruzioni (copiala/incolala per ispezione manuale) -> copy(effectiveInstructions()) - -// Testo che è stato passato all'ultimo session.update -> liveInstructionsSnapshot.length -32456 - -// Elenco dei tool attivi che l'agente "vede" -> activeToolDefs().map(t => t.name) -(19) ['web_search', 'camera_snapshot', 'get_day_report', 'get_weekly_report', 'get_monthly_report', 'get_report_detail', … ] - -// Profilo chiamante caricato -> voceroUserProfileLoaded, voceroUserProfile -true, { id: 987, name: "Don Manuel", … } - -// Top 3 suggeriti per l'ultima domanda -> topSuggestedAgentTools(3).map(x => `${x.tool.name}:${x.score}`) -["get_day_report:38", "get_metrics_summary:22", "get_report_detail:15"] -``` - -### 5c. Cosa viene mandato a OpenAI in modalità OPENAI - -Basta guardare il log `[EXT][OPENAI] reasoning POST … systemLen=… transcriptLen=…` e saprai già il numero di token di sistema. Se vuoi vedere l'esatto system message, puoi aggiungere temporaneamente: -```python -# dentro def reasoning() dopo la costruzione di body -logger.debug("Reasoning system message PREVIEW:\n%s", - body["messages"][0]["content"][:3000]) -``` - ---- - -## 6. Priorità effettiva di tutte le sorgenti (chi vince se c'è conflitto) - -Tabella riassuntiva che risponde a: *"Se due punti dicono cose diverse, quale vince?"* - -| Cosa | Vincitore (priorità max → min) | -|---|---| -| **Identità / sistema prompt** | 1. `agent.instructions` da Aquachile `S2S_AGENT_PROFILE` → 2. `S2S_PRIMARY_PROMPT` env → 3. `settings.instructions` (localStorage utente) → 4. `DEFAULT_INSTRUCTIONS` hardcoded | -| **Catalogo MCP** | Aquachile `agent.tools[]` (unico fornitore). Gli unici tool aggiuntivi sono `web_search` e `camera_snapshot` (browser-native). | -| **Hint su come usare i tool** | Sempre `TOOL_USE_HINT` fisso se `tools>0`; se `searchMcpEnabled` si aggiunge `MCP_SEARCH_HINT` + catalogo testuale completo. | -| **Hint tool ranking (top 3)** | Calcolato lato client per ogni battuta; prompt dice "secondary signal, full catalog wins" | -| **Profilo chiamante** | `S2S_USER_PHONE_AUTH_URL` + URL param `phoneNumber` (nessun altro percorso attuale). | -| **Modalità di reasoning** | 1. `S2S_REASONING_TYPE` env normalizzato (`OPENAI` o default `PROXY`) | -| **URL endpoint upstream** | 1. `SPEECH_TO_SPEECH_URL` pinned direct → 2. `LOAD_BALANCER_URL` LB + queue → 3. URL inserito manualmente in Settings (solo allowDirect) | - ---- - -## 7. Troubleshooting: "L'agente non usa il contesto che mi aspetto" - -Checklist da fare in ordine: - -1. **`/api/config` cosa restituisce?** - ``` - curl -s http://localhost:8000/api/config | python -m json.tool - ``` - Verifica: `primaryPrompt` è valorizzato e lungo? `agentTools` quanti elementi ha? `reasoningType` è quello che ti aspetti? - -2. **Aquachile profile risponde?** Guarda `[EXT][AQUACHILE] agent_profile` nel log. Status 200? Cache HIT o MISS? `PARSED promptLen=… toolCount=…` ha i numeri attesi? - -3. **Il browser ha `phoneNumber` nella URL?** Apri DevTools → Network e cerca `user/phone`. C'è una richiesta? Torna 200? Che JSON ritorna? Il `result` viene inserito in `voceroUserProfile` (check console). - -4. **Hai cambiato qualcosa nel prompt in Aquachile ma non l'aggiornamento non si vede?** Il profilo ha cache 60 secondi. Aspetta o riavvia il server (la cache è in memoria). - -5. **In modalità PROXY i tool MCP non vengono chiamati:** - - Verifica che il **tool catalogo testuale** sia nel prompt (controlla `copy(effectiveInstructions())` e cerca la stringa `Available MCP tools`). - - Verifica che `S2S_SEARCH_MCP=true`. - - Guarda nella console del browser `[Vocero MCP MATCH]` e `[Vocero MCP RANK]` — se nessuno score è sopra la soglia (default 20), l'auto-invocazione lato client non scatta; il modello potrebbe comunque chiamarlo via function-call standard. - -6. **In modalità OPENAI non sente le MCP:** Corretto — attualmente `/api/reasoning` NON manda tools a OpenAI. Vedi §3.2. Se vuoi chiamare tool in OPENAI mode devi spezzare la catena: OpenAI deve dire quale tool chiamare, tu lo chiami via `/api/mcp/tool`, e poi reinietti il risultato in un nuovo reasoning turn. O, più semplicemente, usa la modalità PROXY quando servono i tool Aquachile. - -7. **Output lungo o ripetitivo:** Inserisci in coda al prompt un blocco tipo: `Limita la risposta a 2 frasi e parla in modo naturale. Non ripetere la domanda dell'utente.` — funziona in entrambe le modalità. - ---- - -## 8. Riferimenti rapidi (file e linee) - -| Concetto | File e righe | -|---|---| -| `.env` caricato | [start_ui.sh](file:///home/duxiter/s2s/start_ui.sh#L8-L12) | -| Variabili env parsate lato server | [server.py](file:///home/duxiter/s2s/demo/server.py#L71-L120) | -| `ReasoningRequest` body schema | [server.py:346-350](file:///home/duxiter/s2s/demo/server.py#L346-L350) | -| Fetch profilo Aquachile + cache 60 s | [_agent_profile_data](file:///home/duxiter/s2s/demo/server.py#L357-L397) | -| Parse istruzioni + tools dal JSON Aquachile | [_extract_agent_prompt](file:///home/duxiter/s2s/demo/server.py#L405-L424), [_extract_agent_tools](file:///home/duxiter/s2s/demo/server.py#L427-L437) | -| `/api/config` (bootstrap verso client) | [server.py:509-536](file:///home/duxiter/s2s/demo/server.py#L509-L536) | -| `/api/user/phone` (profilo chiamante) | [server.py:539-573](file:///home/duxiter/s2s/demo/server.py#L539-L573) | -| Esecuzione tool MCP (inoltro ad Aquachile) | [server.py /api/mcp/tool](file:///home/duxiter/s2s/demo/server.py#L576-L633) | -| `/api/reasoning` (OpenAI chat completions proxy) | [server.py:635-710](file:///home/duxiter/s2s/demo/server.py#L635-L710) | -| Proxy WS realtime, INPUT/OUTPUT text log | [_client_to_upstream](file:///home/duxiter/s2s/demo/server.py#L1112-L1171), [_upstream_to_client](file:///home/duxiter/s2s/demo/server.py#L1174-L1255) | -| `fetchConfig()` lato client | [main.js:2401-2439](file:///home/duxiter/s2s/demo/main.js#L2401-L2439) | -| `fetchVoceroUserProfile()` phone auth | [main.js:2370-2398](file:///home/duxiter/s2s/demo/main.js#L2370-L2398) | -| `effectiveReasoningInstructions()` assemblaggio prompt | [main.js:516-533](file:///home/duxiter/s2s/demo/main.js#L516-L533) | -| `effectiveInstructions()` (prompt per realtime, + OPENAI marker hint) | [main.js:537-539](file:///home/duxiter/s2s/demo/main.js#L537-L539) | -| Tool hint + MCP search hint costanti | [main.js:32-42](file:///home/duxiter/s2s/demo/main.js#L32-L42) | -| `voceroUserContextText()` caller profile injection | [main.js:454-458](file:///home/duxiter/s2s/demo/main.js#L454-L458) | -| `fetchOpenAiReasoningAnswer()` POST /api/reasoning client | [main.js:563-586](file:///home/duxiter/s2s/demo/main.js#L563-L586) | -| `maybeRunOpenAiReasoning()` trigger da transcript + inject `[VOCERO_RENDER_REPLY]` | [main.js:592-625](file:///home/duxiter/s2s/demo/main.js#L592-L625) | -| `pushLiveInstructions()` / `pushLiveToolPolicy()` update sessione live | [main.js:628-649](file:///home/duxiter/s2s/demo/main.js#L628-L649) | -| `doStart()` avvio sessione + invio istruzioni/tools iniziali | [main.js:2739-2788](file:///home/duxiter/s2s/demo/main.js#L2739-L2788) | -| Gestore transcript utente → trigger reasoning + ranking MCP | [main.js:2814-2821](file:///home/duxiter/s2s/demo/main.js#L2814-L2821) | diff --git a/s2s-client/ARCHITECTURE.md b/s2s-client/ARCHITECTURE.md deleted file mode 100644 index 0df02b9..0000000 --- a/s2s-client/ARCHITECTURE.md +++ /dev/null @@ -1,188 +0,0 @@ -# Demo S2S — schema di funzionamento - -> Documento orientativo del modulo `demo/` (UI + proxy S2S + reasoning). Non sostituisce -> il codice: serve a trovare il proprio posto quando si apre il progetto. - ---- - -## 1. Cosa c'è in `demo/` - -Il modulo fa **tre cose contemporaneamente**: - -| Ruolo | Cosa fa | Entry point | -|---|---|---| -| **HTTP server statico + API** | Serve l'UI, offre endpoint REST, gira un WebSocket proxy | [server.py](file:///home/duxiter/s2s/demo/server.py) | -| **Voice UI (browser)** | Orba, mic, transcriptioni, audio playback, pannelli | [index.html](file:///home/duxiter/s2s/demo/index.html) + [main.js](file:///home/duxiter/s2s/demo/main.js) | -| **Reasoning hook** | Inoltra transcript utente a un motore di ragionamento esterno (NODE_RED o OpenAI) | [server.py](file:///home/duxiter/s2s/demo/server.py#L658-L834) `/api/reasoning` | - -La configurazione (URL backend S2S, tipo di reasoning, chiavi API) viene presa dal file `.env` nella root del progetto. - ---- - -## 2. Architettura in un diagramma - -``` - ┌──────────────────────────────────────────────────┐ - │ BROWSER (demo UI) │ - │ [index.html] → [main.js] (ESM type=module) │ - │ │ ▲ │ - │ │ audio + WS events │ transcript chunks │ - │ ▼ │ │ - │ ┌──────────────────────────────────────────┐ │ - │ │ s2s-ws-client.js → WebSocket /v1/realtime │ │ - │ │ + codec.js + orb-visualizer.js │ │ - │ └──────────────────────────────────────────┘ │ - └─────────────────────────┬────────────────────────┘ - │ WebSocket /v1/realtime - ▼ - ┌───────────────────────────────────────────────┐ - │ server.py (FastAPI) │ - │ │ - │ ┌──────────────────────────────────────┐ │ - │ │ realtime_proxy ← TUNNEL → upstream │ │ - │ │ (WS relay puro, copia byte-per-byte)│ │ - │ │ _client_to_upstream ─┐ │ │ - │ │ _upstream_to_client ─┤ session_ctx │ │ - │ │ session_ctx{user,id} │ shared dict │ │ - │ └───────────────────────┴──────────────┘ │ - │ │ - │ endpoint REST: │ - │ GET / → index.html │ - │ GET /api/config → env flags │ - │ POST /api/reasoning → NODE_RED / │ - │ OPENAI │ - │ POST /api/auth/* → Aquachile │ - │ │ - └──────┬──────────────────────────────┬─────────┘ - │ POST /api/reasoning │ fire-and-forget - ▼ ▼ - ┌──────────────────────┐ ┌───────────────────────────────┐ - │ Node-RED (port 1881)│ │ Node-RED (port 1881) │ - │ POST /api/reasoning │ │ POST /api/log/system-response │ - │ log user transcript │ │ log assistant TTS + pairing │ - └──────────────────────┘ └───────────────────────────────┘ - ^ - │ forward 4 eventi realtime: - │ audio_transcript.done - │ content_part.done - │ output_item.done role=assistant - │ conversation.item.created role=assistant -``` - -> ### 📝 Nota importante sul flusso AUDIO con l'attuale `.env` -> -> Con `.env` attuale che ha `S2S_PROXY_TARGET=ws://ai-server:12345/v1/realtime`: -> -> ✅ **Sì, TUTTO l'AUDIO utente (PCM16 16kHz mono, eventi `input_audio_buffer.append`) arriva a `ws://ai-server:12345/v1/realtime`** — ma **non direttamente**: passa SEMPRE per il **tunnel 1:1 WebSocket di `server.py`** (`_client_to_upstream`), che copia byte-per-byte senza modifiche. -> -> ✅ Allo stesso modo l'AUDIO risposta (TTS, `response.output_audio.delta`) ritorna da `ai-server:12345` → tunnel `_upstream_to_client` → browser → playback nativo. -> -> ❌ **Cosa invece NON va a `ai-server:12345`** (canale HTTP separato parallelo, non tocca l'audio): -> - Il **transcript STT** viene mandato via HTTP a `http://localhost:1881/api/reasoning` (Node-RED, hook LOG_ONLY oggi) -> - Il **testo risposta TTS** viene mandato via HTTP a `http://localhost:1881/api/log/system-response` (Node-RED, forward fire-and-forget) -> - Chiamate **auth / profilo Aquachile** verso `aquachile.azurianlab.com` -> -> Questi 3 flussi REST sono **aggiuntivi** e **non alterano minimamente il tunnel audio**: browser ↔ server.py ↔ `ai-server:12345` rimane il percorso esclusivo per voce e risposta. - ---- - -## 3. Cose importanti di [server.py](file:///home/duxiter/s2s/demo/server.py) - -### File → ruoli -- **`/`** → StaticFast `StaticFiles` su `demo/` (index.html + assets) -- **`@app.middleware http` no_cache_static_assets** → `Cache-Control: no-store` per `.js/.html/.css/.mjs/.wasm` per sconfiggere cache browser durante sviluppo -- **`@app.get /api/config`** → manda al browser variabili env (`S2S_REASONING_TYPE`, `S2S_PROXY_TARGET`, auth, features). Il client decida da sé cosa mostrare in UI. -- **`@app.post /api/reasoning` ([L658-L834](file:///home/duxiter/s2s/demo/server.py#L658-L834))** → cuore del reasoning. Due modalità, scelta da env `S2S_REASONING_TYPE`: - - **Modalità A — NODE_RED**: inoltra `POST {NODE_RED_URL}/api/reasoning` timeout 30s. Accetta `log_only=true` + `answer=""` (Fase 1). - - **Modalità B — OPENAI**: chiamata diretta `POST $OPENAI_BASE_URL/chat/completions` (Fasi successive). -- **`@app.websocket /v1/realtime` ([L874-L980](file:///home/duxiter/s2s/demo/server.py#L874-L980))** → **tunnel S2S nativo**. Non traduce messaggi: copia + registra + forwarda. 2 task paralleli: - - `_client_to_upstream(ws, upstream, client_ip, session_ctx)`: browser → AI server - - `_upstream_to_client(ws, upstream, client_ip, session_ctx)`: AI server → browser - - `session_ctx = {last_user_transcript, last_item_id}` **dizionario mutabile condiviso** per accoppiare input↔output -- **`async def _forward_agent_text_to_nodered` ([L837-L873](file:///home/duxiter/s2s/demo/server.py#L837-L873))** → helper fire-and-forget. Tutti errori → `logger.debug` (non spezza il tunnel WS). -- **`_upstream_to_client` hook eventi ([L1305-L1500](file:///home/duxiter/s2s/demo/server.py#L1305-L1500))**: per ogni evento output agente avvia `asyncio.create_task(_forward_agent_text_to_nodered(...))` → non blocca lo streaming audio. -- **Sidecar Python locali**: [auth.py](file:///home/duxiter/s2s/demo/auth.py) (Aquachile profile+user+phone), [limiter.py](file:///home/duxiter/s2s/demo/limiter.py) (rate limiter). - -### Ordine di chiamata in un turno vocale -1. Browser clicca orb → `ws /v1/realtime` → `realtime_proxy()` accetta -2. Browser manda `session.update` → `input_audio_buffer.append` in loop -3. Upstream genera `conversation.item.input_audio_transcription.completed` → server cattura → **`session_ctx["last_user_transcript"] = transcript`** -4. `_upstream_to_client` vede transcript STT completo → server invoca in parallelo **`POST /api/reasoning`** con quel transcript -5. Upstream manda `response.output_audio.delta` audio chunks → tunnelati diretti al browser → playback nativo -6. Upstream manda `response.output_audio_transcript.done` → server cattura → `create_task(_forward_agent_text_to_nodered({tts, source_event, user_transcript, …}))` → Node-RED SYSTEM_RESPONSE log -7. Audio finisce → turno chiuso - ---- - -## 4. Cose importanti del lato client ([main.js](file:///home/duxiter/s2s/demo/main.js)) - -### Moduli ESM importati (tutti con `?v=VERSIONE` per cache-bust) -``` -main.js - ├─ dom.js → helper DOM (create, qs, bubble, ecc.) - ├─ chat.js → pannello messaggi + appendAssistantText - ├─ account.js → pannello auth + profilo utente - └─ ws/s2s-ws-client.js - ├─ codec.js → codec pcm + base64 - └─ orb-visualizer.js → animazione orba su eventi volume/state -``` - -### Funzioni chiave -| Funzione | Ruolo | -|---|---| -| `fetchOpenAiReasoningAnswer(transcript)` | `POST /api/reasoning`, ritorna `{answer, log_only, raw}` | -| `maybeRunOpenAiReasoning(transcript, itemId)` | guardia "ho già processato questo turn?" (`processedReasoningTurns`). Se `result.log_only === true` → **early return, zero side-effect**. Altrimenti branch standard (Fasi successive). | -| `cancelActiveResponse()` | Fasi successive: ferma risposta corrente prima di inject custom | -| `appendAssistantText(answer)` / `sendUserText(renderMarker)+requestResponse` | Fasi successive: sostituisce testo risposta backend nativo | -| `speechSynthesis.speak(utterance)` | Fasi successive: TTS *browser* per answer custom, invece del backend nativo | - -### Regole per non rompere Fase 1 -- Se `S2S_REASONING_TYPE=NODE_RED` **e** Node-RED torna `log_only=true` → il client non tocca nulla. Zero `cancelActiveResponse`, zero `speechSynthesis.speak`, zero `conversation.item.create` manuali. La voce è quella del backend S2S nativo. -- **Cache busting triplo**: `index.html` meta tag → `Cache-Control no-store` middleware → query-string `?v=20260825003` su ogni import. - ---- - -## 5. Node-RED (Fase 1 — LOG_ONLY) - -Risiede in [`s2s-reasoning-engine/flows.json`](file:///home/duxiter/s2s/s2s-reasoning-engine/flows.json). Espone 2 endpoint completamente indipendenti: - -| Endpoint | Payload | Output Node-RED | -|---|---|---| -| `POST /api/reasoning` | `{transcript, language, phoneNumber, …}` | `[S2S NODE_RED LOG_ONLY] ts=… lang=… phone=… transcript="..."` | -| `POST /api/log/system-response` | `{tts, source_event, user_transcript, role, item_id, …}` | `[S2S NODE_RED SYSTEM_RESPONSE] ts=… phone=… user="..." tts="..."` | - -Entrambi ritornano 200 `{log_only:true, intent:"..."}`. - ---- - -## 6. Worklets (non toccare) -- [worklets/mic-capture.js](file:///home/duxiter/s2s/demo/worklets/mic-capture.js) — sample-rate input 16kHz PCM mono, calcolo RMS per VAD visuale. -- [worklets/audio-playback.js](file:///home/duxiter/s2s/demo/worklets/audio-playback.js) — riproduzione audio 24kHz server side. - -> Nota: i worklets vengono caricati via `AudioWorklet.addModule()`, che usa script-context **non-ESM**. Non aggiungere `export function` a questi file: rompono il caricamento. - ---- - -## 7. Variabili ambiente che comandano tutto - -| Nome | Valore tipico oggi | Cosa fa | -|---|---|---| -| `S2S_REASONING_TYPE` | `NODE_RED` (Fase 1) / `OPENAI` (Fasi succ.) / `PROXY` disabilita | Scelta motore ragionamento in `/api/reasoning` | -| `S2S_REASONING_NODE_RED_URL` | `http://localhost:1881` | Endpoint base Node-RED reasoning engine | -| `S2S_PROXY_TARGET` | `ws://ai-server:12345/v1/realtime` | URL upstream tunnel WebSocket | -| `OPENAI_API_KEY` / `OPENAI_BASE_URL` / `OPENAI_REASONING_MODEL` | da .env | Usati in Modalità B OPENAI | -| `S2S_AGENT_PROFILE` / `S2S_USER_PHONE_AUTH_URL` / `S2S_TOOL_EXECUTION_MCP_URL` | `aquachile.azurianlab.com/api/v1/…` | URL provider esterni Aquachile | -| `LOG_LEVEL` | `INFO` / `DEBUG` | Livello uvicorn | - ---- - -## 8. Dove toccare per… - -| Obiettivo | File da aprire | -|---|---| -| Cambiare colori tema orb / UI | [style.css](file:///home/duxiter/s2s/demo/style.css) `:root` + [DESIGN.md](file:///home/duxiter/s2s/demo/DESIGN.md) | -| Aggiungere un pannello in UI | [index.html](file:///home/duxiter/s2s/demo/index.html) markup + [main.js](file:///home/duxiter/s2s/demo/main.js) render + nuovo modulo in [ui/](file:///home/duxiter/s2s/demo/ui) | -| Aggiungere un endpoint REST | [server.py](file:///home/duxiter/s2s/demo/server.py), dopo le route esistenti | -| Nuova logica Node-RED Fase 2 | [flows.json](file:///home/duxiter/s2s/s2s-reasoning-engine/flows.json) → Node-RED editor → export | -| Passare da LOG_ONLY a produzione di answer | Flip in flows.json `log_only=false` + riempire `answer`, il branch `result.log_only` del client si spegne automaticamente | -| Debugging SyntaxError browser `Unexpected token 'export'` | 1) Controlla `syntax AST` server.py (se crasha → 500 → browser riceve HTML invece di main.js) 2) Hard reload DevTools ✓ Disable cache 3) `node --check main.js` e import | diff --git a/s2s-client/CHANGELOG.es.md b/s2s-client/CHANGELOG.es.md deleted file mode 100644 index cf7c2cb..0000000 --- a/s2s-client/CHANGELOG.es.md +++ /dev/null @@ -1,859 +0,0 @@ -# Changelog — s2s-client (Azurian Vocero) - -Todos los cambios relevantes del proyecto están documentados en este archivo. -Formato basado en [Keep a Changelog](https://keepachangelog.com/es-ES/1.1.0/). - ---- - -## [2026-09-25] - -### Corregido — Lista ApiPilot tools AHORA TAMBIÉN se INYECTA en la WS Realtime (no sólo en /api/reasoning HTTP) - -**Síntoma inicial usuario (2026-09-25):** -> *"vedo arrivare su ai-server gli altri prompt, ma non quello di apipilot tools"* -> *(Veo llegar al ai-server los demás prompts, pero no el de apipilot tools)* - -El dump del log de `ai-server start_pipeline_rag` CONFIRMABA: `LLM REQUEST — model=Qwen3.6-35B-A3B` → `Session Prompt:` contenía profile / voice rules / today / summary, PERO **no había rastro de la sección `### Herramientas dinámicas disponibles (ApiPilot AquaPortal)`**. - -#### Root cause (3 bugs actuando juntos): -1. La lista de herramientas ApiPilot (PASADA-1) se inyectaba **SÓLO en la rama HTTP `/api/reasoning`** (`server.py:L3078-L3079, L3286-L3287`) pero **NUNCA en el builder de `session.update`** del canal Realtime WS (`/v1/realtime`), que es precisamente el que usa `ai-server` en la pipeline Qwen3.5-35B de voz. -2. El gate `S2S_INJECT_PROFILE` dejaba fuera ApiPilot en la rama `=false`. -3. Ningún marcador BEGIN/END de clasificación de bloque para el dedup/debug. - -#### Fix aplicado hoy (server.py): -| # | Qué | Referencia | -|---|---|---| -| 1 | **Fetch lista herramientas AL INICIO de CADA túnel WS Realtime** (inmediatamente después del connect, antes de `async with websockets.connect(upstream_url)`) | [server.py#L3930-L3973](file:///home/duxiter/s2s/s2s-client/server.py#L3930-L3973) | -| 2 | **Independiente de `S2S_INJECT_PROFILE`**. Ahora el gate `needs_apipilot = bool(S2S_APIPILOT_TOOLS_URL) or bool(S2S_APIPILOT_TOOLS_EXECUTE_URL)` corre también cuando `S2S_INJECT_PROFILE=false` | [server.py#L3813](file:///home/duxiter/s2s/s2s-client/server.py#L3813) | -| 3 | **`login_token` pasado como bearer fingerprint si está disponible** (usuarios autenticados); si no → `anon-ws-{ip}-{id(ws)}` demo session key = fingerprint cache por usuario anónimo | [server.py#L3939-L3942](file:///home/duxiter/s2s/s2s-client/server.py#L3939-L3942) | -| 4 | **`_patch_client_session_update_with_profile` extendido con 8º parámetro `apipilot_context_text_pass1`**. Añade bloque PASADA-1 **DESPUÉS** de profile/reports/episode/summary (mismo orden que en /api/reasoning) dentro de `session.instructions` (lugar que el LLM ve siempre con máxima prioridad). Nuevo gate: `S2S_INJECT_PROFILE=false` + apipilot no vacío → **el PATCH se ejecuta IGUAL** | [server.py#L2560-L2713](file:///home/duxiter/s2s/s2s-client/server.py#L2560-L2713) | -| 5 | **`session_ctx["injected_apipilot_pass1"]` + `["apipilot_tools_pass1"]`** guardados en el contexto del túnel y reusados en `_client_to_upstream` para parchear **cada** `session.update` del cliente (incluyendo parches tardíos) | [session_ctx @ server.py#L4028-L4042](file:///home/duxiter/s2s/s2s-client/server.py#L4028-L4042) | -| 6 | Call site client→upstream forward ahora pasa `apipilot_context_text_pass1=ctx_apipilot_pass1` al patch | [server.py#L4780-L4790](file:///home/duxiter/s2s/s2s-client/server.py#L4780-L4790) | -| 7 | **Logs siempre-activos** (no hace falta `S2S_DEBUG_PROMPT`) al connect WS: `[APIPILOT] REASONING PASS-1 (WS realtime): lista strumenti pronta N=… t=…ms auth=Y/anon` + `[INJECT-APIPILOT] ✅ WS connect: APIPILOT TOOLS list PASS-1 READY Ntools=… wrappedLen=…` + marcador `apipilotPass1=Y(len=…)` en el log patched | [L3954-L3961](file:///home/duxiter/s2s/s2s-client/server.py#L3954-L3961) · [L2668-L2676](file:///home/duxiter/s2s/s2s-client/server.py#L2668-L2676) | -| 8 | **Log S2S_DEBUG_PROMPT bloque COMPLETO** `[DEBUG-APIPILOT][WS session.update] FULL ApiPilot tools list PASS-1 block (len=…):` → muestra exactamente el texto que llega al LLM (sin más conjeturas). | [server.py#L2693-L2696](file:///home/duxiter/s2s/s2s-client/server.py#L2693-L2696) | -| 9 | **`client_query` extraído FUERA del bloque else de `S2S_INJECT_PROFILE`** (así existe incluso cuando profile=false para fingerprint x-demo-session) | [server.py#L3810-L3818](file:///home/duxiter/s2s/s2s-client/server.py#L3810-L3818) | - -#### Logs ESPERADOS AHORA en el servidor S2S (cada conexión de voz WS Realtime): -``` -[INJECT-APIPILOT] WS connect: fetching tools... -[APIPILOT] REASONING PASS-1 (WS realtime): lista strumenti pronta N=6 t=110ms auth=Y -[INJECT-APIPILOT] ✅ WS connect: APIPILOT TOOLS list PASS-1 READY Ntools=6 wrappedLen=1456 -[INJECT-PROFILE] WS connect FINAL: … injectApipilotPass1=True(Ntools=6) … apipilotCtxLen=1456 -… -[INJECT-PROFILE] ✅ WS session.update PATCHED → upstream instructions. origLen=1000 newLen=2456 injectedLen=1456 … apipilotPass1=True(len=1456) -``` - -Y en el log **ai-server `start_pipeline_rag`**, dentro de `>>> PROMPT: … Session Prompt:` al final, APARECERÁ AHORA: -``` -<<>> -### Herramientas dinámicas disponibles (ApiPilot AquaPortal) -REGLAS EJECUCIÓN OBLIGATORIAS: -1. … (reglas marcador) -Lista herramientas (name / description): -- name: get_user_briefing - requires_auth: true - required_parameters: [phone] - description: Devuelve el briefing diario de un usuario... -<<>> -``` - ---- - -### Corregido — 12+ fixes secuenciales PASADA-2 marker CALL, sanitize, flujo auth, SUPER API KEY bypass (25/09/2026) - -**Secuencia de bugs corregidos hoy, después del inject PASADA-1 WS (todos verificados con py_compile OK):** - -| # | Bug síntoma | Root cause | Fix | Referencia | -|---|---|---|---|---| -| 1 | AI emite texto social "Claro que sí. Voy a generar..." en lugar del marcador CALL | Reglas del prompt demasiado débiles para Qwen cuantizado | Regla #6 🔴 MODO EXCLUSIVO reforzada + 8 puntos + ejemplo correcto + 4 ejemplos ERROR en el system prompt de la PASADA-1 (3 capas de inject) | [server.py:L641-L781](file:///home/duxiter/s2s/s2s-client/server.py#L641-L781) + [s2s-ws-client.js:L119-L232](file:///home/duxiter/s2s/s2s-client/s2s-ws-client.js#L119-L232) | -| 2 | Marcador `<<>>` VISIBLE en UI/chat de usuario | Faltaba sanitización antes del render UI | `_sanitize_text_strip_apipilot_markers()` reemplaza el marcador por placeholder en español: *"Voy a consultar tus datos, un momento por favor."* | [server.py:L783-L837](file:///home/duxiter/s2s/s2s-client/server.py#L783-L837) | -| 3 | Marcador encontrado (markerFound=Y) pero PASADA-2 nunca inicia → ningún execute | **ORDEN DE CÓDIGO ERRÓNEO**: sanitize del marcador ocurría ANTES de la detección del mismo (borraba la señal) | Reordenado el bloque PASADA-2 WS: (1) PRE-sanitize detect marker + execute tool, (2) POST sanitize para UI/TTS de usuario | [server.py:L5608-L5760](file:///home/duxiter/s2s/s2s-client/server.py#L5608-L5760) | -| 4 | **NameError: _now_mono is not defined** (bloque PASADA-2 abortado) | Typo en 4 puntos: `_now_mono()` en lugar de `_monotonic_now()` | Alias global: `_monotonic_now = time.monotonic` + todos los typo corregidos | [server.py:L282](file:///home/duxiter/s2s/s2s-client/server.py#L282) | -| 5 | argsPhone = `+56912345678` (valor ejemplo del prompt) en lugar del Alessandro real +44 | Auto-fill tomaba el valor ejemplo del prompt en vez de datos reales | 2 capas de safety: (a) blacklist `_FAKE_PHONE_PLACEHOLDERS` (+56912345678, +1234567890, len<7, acabado en 00000) + (b) fallback directo `session_ctx.inject_phone` desde QS `?phoneNumber=` siempre extraído FUERA del gate S2S_INJECT_PROFILE | [server.py:L5614-L5636](file:///home/duxiter/s2s/s2s-client/server.py#L5614-L5636) | -| 6 | Regex del marcador no coincide con argumentos vacíos `ARGUMENTS=>>>` o JSON no estándar | Regex bloqueante exigía `{...}` obligatorio | Regex hecha flexible `.*?` non-greedy + **parser 5 tier fallback** (JSON estándar → comillas simples → key=value → llaves faltantes → vacío) + defaults auto-fill phone real | [server.py:L562-L638](file:///home/duxiter/s2s/s2s-client/server.py#L562-L638) | -| 7 | `session_ctx apipilot_defaults=None` → log `defaultsAutoFill=none` | Rama else needs_apipilot=False + excepción fetch tools no inicializaba clave vacía | `session_ctx_apipilot_defaults={}` SIEMPRE en todas las ramas (incluso needs_apipilot=False) | [server.py:L4094-L4108](file:///home/duxiter/s2s/s2s-client/server.py#L4094-L4108) | -| 8 | **404 route POST .../tools/execute** AquaPortal no existe | `S2S_APIPILOT_TOOLS_EXECUTE_URL` era ".../apipilot/tools" + append `/execute` → ruta errónea | `.env L45` corregido a `.../apipilot` + helper `_apipilot_resolve_execute_url()` auto-append `/execute` → ruta correcta `POST .../apipilot/execute` | [.env:L44-L45](file:///home/duxiter/s2s/.env#L44-L45) + [server.py:L321-L338](file:///home/duxiter/s2s/s2s-client/server.py#L321-L338) | -| 9 | Tool `get_user_briefing` recibe phone pero description dice *"Requires a valid session token"* | AquaPortal toma datos de usuario DESDE EL TOKEN, no quiere args para herramientas auth-only | Caso AUTH-ONLY en el validator: `requires_auth=true + parameters.properties={} + required=[] + description contiene "valid session token"` → cleaned_args={} (phone ELIMINADO). Log siempre activo. | [server.py:L518-L593](file:///home/duxiter/s2s/s2s-client/server.py#L518-L593) | -| 10 | **403 user=(anon) ToolNotFoundError** → demo session distinta entre discovery GET y execute POST | AquaPortal usa `x-demo-session` como binding autorizativo por-herramienta; clave distinta = tool no asociado al usuario | Propagación EXACTA de valores desde la DISCOVERY: `session_ctx["apipilot_exec_auth"] = apipilot_auth_header` + `session_ctx["apipilot_exec_demo"] = demo_session_key` → PASADA-2 execute usa MISMA identidad | [server.py:L3995-L4288](file:///home/duxiter/s2s/s2s-client/server.py#L3995-L4288) | -| 11 | **403 user=(anon)** última causa: token `login_by_phone` DEMASIADO CORTO (37 chars, NO JWT, mí­n ~150 chars) → AquaPortal user=null | Endpoint `S2S_LOGIN_BY_PHONE` aquachile devuelve session-id opaco (no JWT); `AUTH=YES len=44` = Bearer 7 chars + token corto 37 chars → NO válido como JWT | **SOLUCIÓN ELEGIDA HOY POR USUARIO: SUPER API KEY BYPASS TEMPORÁNEO** `S2S_APIPILOT_API_KEY=aqua3465#` + **3 formas headers SIMULTÁNEAMENTE** en discovery + execute: `X-API-Key: aqua3465#`, `Authorization: Bearer aqua3465#`, `x-demo-session: aqua3465#`. **PRIORIDAD MÁXIMA (encima de cualquier login).** Salta completamente login_by_phone en WS connect y PASADA-2 forced login. | [.env:L46-L50](file:///home/duxiter/s2s/.env#L46-L50) + [server.py:L259-L267](file:///home/duxiter/s2s/s2s-client/server.py#L259-L267) + [fetch_tools#L427-L444](file:///home/duxiter/s2s/s2s-client/server.py#L427-L444) + [execute_tool#L1004-L1037](file:///home/duxiter/s2s/s2s-client/server.py#L1004-L1037) | -| 12 | Diagnósticos insuficientes → debug imposible (10 formas distintas 403 hoy) | Faltaban logs SIEMPRE-ACTIVOS para estados intermedios críticos | Diagnósticos ALWAYS-ON añadidos: (1) Banner STARTUP `apipilotApiKeyBypass=YES head=aqua34... (3 FORME!)`, (2) WS connect `ESTADO INICIAL (siempre)`: phoneLen, phoneHead, loginTokenLen, loginByPhone, injectProfile, (3) login response: token len + head preview JWT, (4) validate auth-only mode log, (5) trigger PASADA-2 argsPhone, auth=APIKEY/Y, defaultsAutoFill, (6) **HTTP>=400 DIAGNOSTIC ALWAYS-ON**: requestPAYLOAD completo + AUTH len + RAW RESPONSE BODY 1800 chars. | [banner#L1170-L1198](file:///home/duxiter/s2s/s2s-client/server.py#L1170-L1198) + [WS INIT#L4094-L4108](file:///home/duxiter/s2s/s2s-client/server.py#L4094-L4108) + [execute 4xx#L1040-L1100](file:///home/duxiter/s2s/s2s-client/server.py#L1040-L1100) | - -#### Orden de prioridad AUTH hoy DEFINITIVO (MÁX → MÍN): -1. 🔴 **`S2S_APIPILOT_API_KEY`** (si tiene valor → LAS 3 formas headers, bypass completo, ningún login ejecutado) -2. 🟠 `S2S_APIPILOT_SERVICE_TOKEN` (override manual desde env) -3. 🟡 `session_ctx["apipilot_exec_auth"]` (bearer propagado directamente desde DISCOVERY fetch tools) -4. 🟢 **LOGIN FORZADO PASADA-2** si `requires_auth=true` y bearer existente NO JWT-like (<120 chars o <2 dots) -5. ⚫ ninguno (anónimo, sólo tools con requires_auth=false) - ---- - -### Corregido — TTS anti-leak MASIVO: 4 bloques sanitize universales + Tier6 phone + reglas prompt 9/10 anti marker pronunciado - -**Secuencia síntomas usuario hoy (post auth bypass SUPER API KEY) todos verificados en logs `start_pipeline_rag` y resueltos:** - -| # | Síntoma leak TTS | Root cause | Fix aplicado | Referencia | -|---|---|---|---|---| -| 1 | **TTS pronunciaba los marcadores PASADA-2 INTERNOS** `APIPILOT_RESULT:PASS2` + `### Resultado de la herramienta ApiPilot` + bloque ``` ```tool-output``` ``` + trailer *"Ahora debes reinterpretar…contenido final al usuario."* | `_sanitize_text_strip_apipilot_markers()` eliminaba SÓLO marcador CALL, NUNCA PASADA-2 RESULT (5 formas wrapper distintas) | **BLOQUE 1 sanitize**: 5 patrones de eliminación SILENCIOSA (ningún placeholder) aplicados en orden ancho→estrecho: (a) bloque completo PASADA-2 wrapper entero, (b) marcador PASADA-2 standalone, (c) título MD residuo, (d) bloque ``` ```tool-output``` ``` standalone residuo, (e) trailer re-instruction 3 tier fallback (estricto/ancho/broad-lenguaje-natural) + 2 patrones truncados sin cierre `>>>` + limpieza residuos `(arriba)` / `()`. | [server.py:L898-L1022](file:///home/duxiter/s2s/s2s-client/server.py#L898-L1022) | -| 2 | **Leak paths locales TRAE workspaceStorage** en TTS: `/home/duxiter/s2s/\home\duxiter\.trae-server\data\User\workspaceStorage\…\long-text\…\file.txt` (alucinación AI sobre paths mixtos Unix/Windows/TRAE tokens) | Ninguna sanitización universal de paths locales; TRAE inyecta en el context archivo workspace storage | **BLOQUE 3 sanitize** 4 patrones: (a) Unix paths absolutos con extensión + fallback ancho /home/tmp/var… len>20, (b) Windows C:\ / \Users\ / \.trae-server\ / separadores mixtos \ \\, (c) TRAE tokens específicos: `workspaceStorage`, `long-text`, `.trae-server`, `.trae`, `ckg_server`, `ai-agent`, (d) mixed catchall safety >5 separadores o /+\ mixtos → 100% path leak. | [server.py:L1022-L1077](file:///home/duxiter/s2s/s2s-client/server.py#L1022-L1077) | -| 3 | **LEAK MÁS GRAVE — pipeline upstream Qwen3-TTS / start_pipeline_rag NORMALIZA el marcador ELIMINANDO `<<< >>>`** y TTS pronuncia literalmente: *"APIPILOT CALL name get_user_briefing arguments phone +56912345678"* (fragmento marcador descrito como llamada de función) | Sanitize BLOQUE 2 original capturaba SÓLO formas con `<<<…>>>`; tras normalización TTS la cadena ya no contiene caracteres especiales | **BLOQUE 4 sanitize FRAGMENT-BASED 5 tier fallback**: (Tier1) forma normalizada completa `APIPILOT CALL + [marker/señal/herramienta/función] + [name/ID] + arguments + phone/teléfono`, (Tier2) token APIPILOT+CALL/_CALL/llamada/marker cualquier contexto 600 chars, (Tier3) singles servicio token ARGUMENTS=… / arguments de la llamada…, (Tier4) catchall frase entera APIPILOT+contexto kw (name/argument/phone/+56/+44/marker/call/herramienta), (Tier5) safety final APIPILOT CALL / APIPILOT_CALL → placeholder español. | [server.py:L1078-L1147](file:///home/duxiter/s2s/s2s-client/server.py#L1078-L1147) | -| 4 | **REGLA prompt anti-leak TTS marcador Faltante** → Qwen quantizado describía la llamada en vez de emitir sólo el marcador + explicaba la función en audio | PASADA-1 system prompt tenía solo reglas 1-8 (marcador sintáctico), ninguna regla audio/TTS explícita | **REGLA 9 🔴 TTS ANTI-LEAK + REGLA 10 EJERCICIO** inyectadas en PASADA-1 instructions (máxima prioridad): Regla 9 = lista palabras prohibidas NUNCA pronunciadas por audio TTS (APIPILOT,CALL,ARGUMENTS,tool,herramienta,ejecutar,función,marcador,marker) + canal TTS SÓLO puede contener placeholder español, canal transcript en cambio contiene marcador línea exacta. Regla 10 = EJERCICIO explícito *"Dammi il briefing → 1 sola línea marcador NADA MÁS"* con ejemplo correcto y prohibición absoluta de texto social. | [server.py:L641-L852](file:///home/duxiter/s2s/s2s-client/server.py#L641-L852) | -| 5 | **Leak phone residuo POST-marcador** → tras sustitución marcador CALL por placeholder español, el número de teléfono placeholder (`+56912345678`, `+1234567890`) o phone real Alessandro (`+44…`) PERMANECE en la MISMA FRASE porque Tier1/2 capturó sólo hasta el nombre tool o los arguments se parsearon después | Tier 1-4 no tocaban el phone si ya ocurrió parse o si el phone se encontraba después del punto de match de los tier | **TIER 6 — Phone contextual blacklist safety**: regex match phone (a) FORMAS COMPACTAS sin espacio (+56912345678 / +1234567890 / +447432477433 y sin +), (b) FORMAS ESPACIADAS/CON SIGNOS (paréntesis/guiones/espacios entre cifras), (c) FORMAS GENÉRICAS `phone:=/teléfono:=…` cualquiera. **Contexto safety (`_phone_ctx`) para NO falsos positivos**: strip phone SÓLO sobre UNA LÍNEA si la línea contiene al menos una palabra clave marcador (apipilot/call/arguments/marker/herramienta/función/llamada/marcador/señal) **O BIEN** contiene el placeholder español *"Voy a consultar tus datos, un momento por favor."* (el marcador acaba de ser sustituido en esta misma frase → phone = leak marcador 100%). → **CASO 7 TEST PASADO**: frase natural *"Alessandro… teléfono es +447432477433… reunión producción"* SIN contexto marcador/placeholders → PERMANECE INALTERADO (ningún falso positivo). | [server.py:L1148-L1190](file:///home/duxiter/s2s/s2s-client/server.py#L1148-L1190) | -| 6 | Fix rápido (1): marcador CALL truncado tipo `<<` se dejaba intacto | Regex `trunc_call_pattern` final exigía `>+` (1+ `>` obligatorios) pero marcador truncado no tiene cierre | Cambio regex `>+` → `>>*` (0 o más `>` opcionales) → marcador incluso sin cierre coincide y se sustituye por placeholder español. | [server.py:L988-L993](file:///home/duxiter/s2s/s2s-client/server.py#L988-L993) | -| 7 | Fix rápido (2): Tier4 catchall frase borraba FRASE ENTERA "Prima [marcador] Dopo." incluso tras Tier1/2/5 ya haber sustituido el marcador por placeholder español → se perdía el texto natural "Prima/Dopo." alrededor | Tier4 no comprobaba si el marcador ya había sido saneado en sede | Excepción en `_apipilot_frase` callback Tier4: **si la frase ya contiene "voy a consultar tus datos" (placeholder) → NO borrar, devuelve frase inalterada** (el marcador ya fue sustituido, borrar la frase entera sería excesivo). | [server.py:L1127-L1140](file:///home/duxiter/s2s/s2s-client/server.py#L1127-L1140) | - -#### Verificación test offline 11 casos post-fix: -✅ 7/11 casos PASADOS incluyendo **todos los casos REALES usuario**: -- (1a) leak +56912345678 residuo → **ELIMINADO** -- (2) bloque PASADA-2 RESULT completo + trailer → **TODOS ELIMINADOS** -- (3) path mixto workspaceStorage/.trae-server leak → **ELIMINADO** -- (4/6) marcador standard `<<>>` inline/raw → placeholder español ✅ -- **(7 🔴 FUNDAMENTAL) — Frase natural phone Alessandro real SIN marcador**: output **INALTERADO**, ningún falso positivo (phone mantenido) -- (9) texto natural sin ningún leak → **INALTERADO** -⚠️ 4/11 fallos restantes: son **casos EDGE artificiales** (marcador truncado combinado con Tier4/frase corta, o marcador APIPILOT escrito a mano sin llaves y con texto anexado) que no se presentan en el flujo standard (el LLM emite SIEMPRE el marcador standard completo `<<<…>>>`). Verificación end-to-end voz necesaria para confirmación práctica. - ---- - -## [2026-09-24] - -### Añadido — Integración ApiPilot AquaPortal EN EL MOTOR DE RAZONAMIENTO (2 pasadas: match description → execute vía S2S_APIPILOT_TOOLS_EXECUTE_URL → re-interpreta resultado text para el usuario por voz) - -**Objetivo explícito usuario**: -> *"Cuando se llama apipilot tools devuelve un array; cada elemento `{name, description, parameters, requires_auth}`. El campo `description` = contexto para que la AI entienda qué función llamar (campo `name`); si description hace match con la petición AI, [decide invocarla], luego mediante name y arguments llamamos a la función usando S2S_APIPILOT_TOOLS_EXECUTE_URL; el resultado que es un body text debe usarse para contárselo al usuario."* - ---- - -#### Arquitectura 2 PASADAS (lado servidor, /api/reasoning) -``` - Petición usuario (transcript voz → texto) - │ - ▼ - ┌────────────────────────────────────────────┐ - │ PASADA 1: Motor NODE_RED / OPENAI │ - │ • system/user_context = [ hoy + profile + │ - │ reports + summary + lista herramientas │ - │ ApiPilot (name/description) + REGLAS │ - │ marker <<>> ] │ - │ │ - │ Decisiones AI: │ - │ • match description → EMITE MARKER │ - │ • sin match → respuesta regular (FINAL) │ - └───────────────────┬────────────────────────┘ - │ marker ? NO ─────► return JSONResponse({"answer": "..."}) - ▼ SÍ - PARSE MARKER: _apipilot_parse_call_marker() - • name = nombre herramienta - • arguments = {parámetros JSON} - │ - ▼ - PRE-CHECK (§2.2 GUIDA_APIPILOT_CLIENTE.md): - (1) ¿Herramientas frescas? Forzar rediscovery si tool no encontrado - (2) requires_auth + token? BLOQUEA 401 si true - pero no hay token login presente - (3) Validación JSON-Schema estricta args → strip - extras + required fields check - │ - ▼ - POST {name, arguments} a **_apipilot_resolve_execute_url()**: - prioridad 1: S2S_APIPILOT_TOOLS_EXECUTE_URL (env override .env:45) - → si NO termina con "/execute" → append "/execute" - prioridad 2: S2S_APIPILOT_TOOLS_URL + "/execute" - │ - ▼ - Recibe body de respuesta (puede ser: stringa text puro / envelope estándar - {success,data,error} / JSON raw cualquiera / text error). - │ - Extrae texto herramienta: - • si envelope.data es **str** → úsala directamente - • si envelope.data es dict/list → json.dumps(, indent=2) - • si error: prepend [CODE] messaggio - │ - ▼ - ┌────────────────────────────────────────────┐ - │ PASADA 2: Mismo motor, MISMO transcript │ - │ • system/user_context = MISMOS profile + │ - │ hoy + reports + summary PERO REEMPLAZO │ - │ lista herramientas con bloque RESULTADO │ - │ ### Resultado herramienta NAME: │ - │ │ - │ + instrucción: "Ahora reinterpreta en │ - │ lenguaje natural para el usuario, en el │ - │ idioma solicitado, SIN mencionar la │ - │ herramienta internamente. Contesta │ - │ SOLAMENTE el contenido final." │ - │ │ - │ Respuesta PASADA 2 = CONTENIDO FINAL PARA │ - │ EL USUARIO (voz vía TTS). │ - └───────────────────┬────────────────────────┘ - │ - ▼ - return JSONResponse({ - "answer": "Contenido natural para usuario", - "apipilot_invoked": {"name":..., "success": bool, "result_length": N}, - "usage_pass2": {...}, (si disponible) - }) -``` - ---- - -#### Nueva env de override (respetada en L255 y en _apipilot_resolve_execute_url) -| Env | Default | Descripción | -|---|---|---| -| `S2S_APIPILOT_TOOLS_EXECUTE_URL` | `""` | **Override EXCLUSIVO** para el endpoint de execute. Si está definida tiene prioridad ABSOLUTA sobre `S2S_APIPILOT_TOOLS_URL` para construir la URL de POST execute. Normalizada con rstrip("/"). SI NO termina con `/execute` → se agrega `/execute`. | - -Ejemplo desde tu `.env` línea 45: -``` -S2S_APIPILOT_TOOLS_EXECUTE_URL=https://aquachile.azurianlab.com/api/v1/apipilot/tools -# URL RESUELTA FINAL = https://aquachile.azurianlab.com/api/v1/apipilot/tools/execute -``` -Banner startup confirma: `apipilotExecuteUrlOverride=https://aquachile.azurianlab.com/api/v1/apipilot/tools(resuelto:https://aquachile.azurianlab.com/api/v1/apipilot/tools/execute)` - ---- - -#### Referencias precisas de línea (server.py) -| # | Qué | Línea | -|---|---|---| -| 1 | Env `S2S_APIPILOT_TOOLS_EXECUTE_URL` parsing con ejemplos `.env:45` | [server.py#L247-L255](file:///home/duxiter/s2s/s2s-client/server.py#L247-L255) | -| 2 | Helper `_apipilot_resolve_execute_url()` (cálculo URL final, prioridad env override + append "/execute" si falta) | [server.py#L321-L338](file:///home/duxiter/s2s/s2s-client/server.py#L321-L338) | -| 3 | Regex marker captura + parse name/arguments (antimeta-comentario, JSON comillas dobles/simples) | [server.py#L562-L597](file:///home/duxiter/s2s/s2s-client/server.py#L562-L597) | -| 4 | Helper `_resolve_apipilot_reasoning_context_block(tools=None, call_result=None)`: genera texto a inyectar en el prompt. **call_result=None** = PASADA 1 (lista herramientas + reglas marker sintáctico); **call_result={name,text,error}** = PASADA 2 (bloque resultado + trailer re-interprete) | [server.py#L600-L688](file:///home/duxiter/s2s/s2s-client/server.py#L600-L688) | -| 5 | Función `_apipilot_execute_tool` actualizada: usa `_apipilot_resolve_execute_url()` en lugar de `f"{S2S_APIPILOT_TOOLS_URL}/execute"`; accept header `text/plain,*/*` para body text; control empty URL resuelta | [server.py#L639-L652](file:///home/duxiter/s2s/s2s-client/server.py#L639-L652) | -| 6 | Handler `/api/reasoning`: **FETCH herramientas PASADA 1** (gate global `needs_apipilot = bool(tools_url or execute_url)` + cache) inmediatamente antes de construir user_context → log `[APIPILOT] REASONING PASS-1: lista herramientas lista N=…` | [server.py#L3025-L3055](file:///home/duxiter/s2s/s2s-client/server.py#L3025-L3055) | -| 7 | Handler `/api/reasoning`: append inyección PASADA 1 a `user_context_parts` (junto a hoy/voice/profile/reports/summary) **y** en OPENAI `system_parts` | [server.py#L3078-L3079](file:///home/duxiter/s2s/s2s-client/server.py#L3078-L3079) · [L3286-L3287](file:///home/duxiter/s2s/s2s-client/server.py#L3286-L3287) | -| 8 | Branch **NODE_RED**: marker detection + execute apipilot + build user_context_pass2 con RESULTADO herramienta + SEGUNDA llamada HTTP `POST /api/reasoning` (X-S2S-Caller=demo-server-pass2) | [server.py#L3273-L3409](file:///home/duxiter/s2s/s2s-client/server.py#L3273-L3409) | -| 9 | Branch **OPENAI**: marker detection + execute apipilot + build system_pass2 con bloque resultado + SEGUNDA llamada HTTP `POST /chat/completions` (mismo model, mismo transcript, system message actualizado con resultado) | [server.py#L3502-L3656](file:///home/duxiter/s2s/s2s-client/server.py#L3502-L3656) | -| 10 | **FALLBACK de seguridad**: SI la PASADA 2 contesta vacía (NODE_RED respuesta invalida / OpenAI answer vacía) → la answer final usa el **body text RAW de ejecución apipilot** como última ratio (ningún silencio sobre el canal de voz) | [server.py#L3386-L3389](file:///home/duxiter/s2s/s2s-client/server.py#L3386-L3389) · [L3637-L3640](file:///home/duxiter/s2s/s2s-client/server.py#L3637-L3640) | -| 11 | Banner de STARTUP extendido: muestra `apipilotExecuteUrlOverride=…(resuelto:…)` + flag `apipilotReasoningPass2=Y` si integración activa | [server.py#L908-L951](file:///home/duxiter/s2s/s2s-client/server.py#L908-L951) | - ---- - -#### Formato marker PASADA 1 (debe ser PRIMERA LÍNEA de la respuesta) -``` -<<>> -``` -Reglas para la AI de razonamiento: -1. **UN SOLO marker** por petición (1 tool máximo por invocación) -2. Inmediatamente después del marker → **NINGÚN OTRO TEXTO** (el resto se ignora; el resultado se inyecta en la pasada 2) -3. `arguments` = **JSON VÁLIDO** con comillas DOBLES, solo campos `required_parameters:` o declarados en el tool. -4. Si más de un tool hace match, elige el más específico. - ---- - -#### Formato bloque inyector PASADA 2 (AI recibe) -``` -### Resultado de la herramienta ApiPilot invocada -<<>> - -```tool-output -Estimado/a Ana, aquí tienes tu briefing diario para 24-09-2026: - - Tienes 3 reportes de campo pendientes de aprobación. - - 2 llamadas perdidas de clientes ayer (contactar en las próximas 2h). -… (body text puro dell' execute upstream) -``` - -Ahora debes reinterpretar EL TEXTO RESULTADO (arriba) en lenguaje natural claro -y conciso, exclusivamente en el idioma del usuario (language field). -No menciones la herramienta internamente ni detalles técnicos. -Responde SOLAMENTE con el contenido final que le quieres transmitir al usuario. -``` - ---- - -### Añadido — Tracer consola debug siempre activo para TODAS las llamadas fetch lado navegador + eventos WebSocket anti-fuga/anti-spam + **PREFETCH AUTOMÁTICO APIPILOT A CADA INICIO SESIÓN REALTIME** - -**Objetivo**: insertar logging granular **SIEMPRE ACTIVO** (no requiere `?debug=true` -ni flag localStorage) sobre TODAS las llamadas de red realizadas por `s2s-client`. -Además, **a partir de v18:05**, GARANTIZAR que las herramientas ApiPilot AquaPortal -estén cargadas (cache calentada) AL INICIO DE CADA SESIÓN WS Realtime antes de que -el usuario empiece a hablar, para que el LLM las tenga disponibles inmediatamente -en las function-call sin la latencia de discovery al primer tool. - -**Arquitectura**: -- **HTTP fetch** → interceptación global via `window.fetch` monkey-patch (primer archivo cargado, `main.js`) para que TODAS las fetch del código (incluyendo módulos terceros) se tracen, sin modificar cada llamada individualmente. -- **WebSocket realtime (OpenAI Realtime protocol)** → logging dedicado en el cliente WS (`s2s-ws-client.js`) con anti-spam para chunks audio 25 Hz y anti-fuga token en la conexión. -- **Llamadas lado servidor (ej. `S2S_APIPILOT_TOOLS_URL` upstream AquaPortal)** → siguen logueadas por el backend con tags `[APIPILOT-DISCOVERY] →/←` y `[APIPILOT-EXEC] →/←` en el log servidor (ver sección Integración ApiPilot). En el navegador SÓLO se ve la capa proxy local `/api/apipilot/*`, según arquitectura passthrough. - ---- - -#### 1. Tags semánticos fetch (filtra Consola con `[FETCH:xxx]`) - -| Tag | Endpoint / Categoría | Trigger | -|---|---|---| -| `[FETCH:APIPILOT:TOOLS]` | `GET api/apipilot/tools?include_unauthorized=true` | Llamada demo fire-and-forget al arranque, **sólo si** `/api/config → apipilot=true` | -| `[FETCH:APIPILOT:EXEC]` | `POST api/apipilot/execute` body `{name, arguments}` | Ejecución manual herramienta frontend o LLM function-call via proxy | -| `[FETCH:CONFIG]` | `GET api/config` | Bootstrap cada page refresh | -| `[FETCH:REASONING]` | `POST api/reasoning` | RAG / context injection | -| `[FETCH:SEARCH]` | `POST api/search` | Serper web search | -| `[FETCH:PROFILE]` | `GET api/user/phone?phoneNumber=` | Datos perfil login-by-phone | -| `[FETCH:REPORTS]` | `GET api/user/reports?phoneNumber=` | Lista reportes (minimal TOC por defecto) | -| `[FETCH:SESSION:START]` / `SESSION:END` / `SESSION:HEARTBEAT` | `api/session*` | Handshake inicial + keepalive (heartbeat anti-spam: log único debug, sin group) | -| `[FETCH:QUEUE:POLL]` / `QUEUE:END` | `api/queue/{ticket}` / `api/queue/end` | Polling cola load balancer | -| `[FETCH:ACCOUNT:ME]` | `GET api/me` | Chip login + budget (llamada `account.refresh()`) | -| `[FETCH:FETCH]` | Cualquier otra URL | Fallback genérico si URL no coincide con ningún patrón | - -Cada log fetch contiene siempre (a menos que sea poll/end/heartbeat): -- `→ [FETCH:TAG] METHOD url` **group collapsed** (azul): method, URL completo, preview body request (max 240 chars JSON/TEXT/FORM/QS/BLOB) -- `← [FETCH:TAG] STATUS METHOD url (N ms)` **group collapsed**: status HTTP (verde 2xx, amarillo 3xx/4xx, rojo 5xx), duración ms via `performance.now()`, lista headers respuesta truncados, preview body respuesta (max 260 chars JSON/TEXT) -- `✗ [FETCH:TAG] NETWORK_ERROR (N ms)`: rojo, excepción capturada y re-lanzada - -#### 1bis. Prefetch automático ApiPilot a CADA inicio de sesión WS Realtime - -**Trigger**: método `connect()` de `S2SWebSocketClient` ejecutado TODAS las veces que -el usuario hace click en el orbe verde / inicia una nueva conversación vocal. -Se ejecuta en **paralelo** con `_setupAudio()` y `_openWebSocket()` (Promise.all), -por lo que **NO añade latencia** al handshake. - -| Característica | Valor | -|---|---| -| Endpoint cliente | `GET api/apipilot/tools?include_unauthorized=true` (cache: no-store) | -| Tag tracer fetch | `[FETCH:APIPILOT:TOOLS]` (misma categoría que la demo de bootstrap) | -| Tag tracer WS | `[S2S-WS:APIPILOT]` (estados: **MISS caché** / **HIT caché** / **READY** / **FALLIDO**) | -| Gating | Sólo si `window.__s2sApipilot = true` (del feature flag `/api/config → apipilot`) | -| TTL caché cliente | `_APIPILOT_CLIENT_TTL_MS = 240 s` = TTL servidor 300 s − 60 s margen | -| ¿Bloqueante? | **NUNCA** — `Promise.all([…, apipilotReady.catch(()=>{})])`; el fallo NO rompe `connect()` | -| Contador sesión | `_wsSessionCounter` creciente: cada sesión loguea `#1`, `#2`, … para correlacionar eventos | -| Identificador correlacionado | `this._sessionSeq` asignado a cada `connect()` para cross-ref en el resto de logs WS | - -Secuencia de log esperada en Consola a **CADA** nuevo inicio de conversación vocal: - -``` -%c[S2S-WS:SESSION]%c #1 handshake iniciado — status: creating-session -%c[S2S-WS:APIPILOT]%c #1 MISS caché → GET api/apipilot/tools (proxy a S2S_APIPILOT_TOOLS_URL servidor)... - → [FETCH:APIPILOT:TOOLS] GET api/apipilot/tools?include_unauthorized=true ← wrapper fetch - ← [FETCH:APIPILOT:TOOLS] 200 GET (123 ms) ← verde, con preview lista herramientas -%c[S2S-WS:APIPILOT]%c #1 READY herramientas APIPILOT cargadas: N=7, t=123ms [primeras 5: t1, t2, t3, t4, t5] -%c[S2S-WS:SESSION]%c #1 conexión establecida + audio pipeline + apipilot OK -``` - -Segunda sesión inmediatamente después (caché fresca): -``` -%c[S2S-WS:SESSION]%c #2 handshake iniciado — status: creating-session -%c[S2S-WS:APIPILOT]%c #2 HIT caché cliente herramientas (age=12s, N=7, TTL=240s) -%c[S2S-WS:SESSION]%c #2 conexión establecida + audio pipeline + apipilot OK -``` - -Feature flag desactivado servidor: -``` -%c[S2S-WS:APIPILOT]%c #1 feature flag apipilot=false en servidor — salto prefetch herramientas -``` - -Fallo proxy (ej. backend AquaPortal caído): -``` -%c[S2S-WS:APIPILOT]%c #1 prefetch FALLIDO: HTTP 503 — diagnóstico en log servidor [APIPILOT-DISCOVERY] -``` - -#### 2. Tags WebSocket (filtra Consola con `[S2S-WS:xxx]`) - -| Tag / Badge | Evento traceado | Notas anti-spam / anti-fuga | -|---|---|---| -| `🔵 [S2S-WS:CONNECT]` | `_openWebSocket()`: intento conexión WS | ✅ **Anti-fuga**: URL conexión loguea sólo host+path + params ENMASCARADOS: cada param con nombre `token\|session\|auth\|jwt\|secret\|key` ó valor `length > 16` → mostrado como `… len=` para no fugar el JWT en claro en la consola | -| `🟢 [S2S-WS:OPEN]` / `🔴 [S2S-WS:ERR]` | `onopen` / `onerror` | Badges coloreados, header respuesta (si disponible) | -| `⚪ [S2S-WS:SESSION]` | `connect()` inicio/fin + `_postSession()` grant/queued/402/503 | Ahora incluye contador `#N` sesión incrementado a cada `connect()` + log "establecida + audio + apipilot OK" final | -| `🔧 [S2S-WS:APIPILOT]` | `_prefetchApipilotTools()` a cada inicio sesión | estados: **flag off (warn)** / **HIT caché (ok)** / **MISS caché (connect)** / **READY (ok)** / **FALLIDO (err)** — SIEMPRE no bloqueante | -| `🟡 [S2S-WS:QUEUE]` | `_pollQueue()`: ticket / advancement / 402 / 404 | Log primer poll, cada 10°, cada avance posición | -| `⏺️ [S2S-WS:SEND]` | `_send()`: mensajes salientes | ✅ **Anti-spam**: `type=input_audio_buffer.append` (~25 Hz bulk audio) → log sólo cada **250 chunks** ó cada **2500 ms** (umbral regulable). Todos los demás tipos: siempre log con preview payload max 600 chars; para tool-call `response.function_call_arguments.done` preview separada 220 chars | -| `📥 [S2S-WS:MSG]` | `_onWsMessage()`: eventos recibidos | ✅ **High-signal always-on**: hace match regex para eventos críticos `session.*`, `error`, `conversation.item.*`, `response.* done`, `function_call`, `rate_limits.updated` → siempre logueados. Eventos transcript/partial `input_audio_buffer.speech_started/stopped` logueados pero a nivel info | -| `🟤 [S2S-WS:CLOSE]` | `_onWsClose()` / `close()` | Badge código: `1000/1001 = OK (gris)`, cualquier otro = ERR (rojo). Reason logueado si existe | - -Contador chunks audio global: `window.__s2sMicChunkCount` para diagnosticar saturación micrófono 25 Hz. -Contador sesiones totales: `window._wsSessionCounter` (módulo privado) incrementado a cada click de inicio conversación. - -#### 3. Llamada demo ApiPilot lado cliente - -Para garantizar que en la Consola se vea **siempre** el tracer activo para los endpoints proxy, tras recibir `/api/config` (línea 2513 de main.js) — si y sólo si el feature flag `json.apipilot = true` (es decir, `S2S_APIPILOT_TOOLS_URL` valorado en el servidor) — se envía una fetch `GET api/apipilot/tools?include_unauthorized=true` (fire-and-forget, cache: no-store). - -La demo produce: -- `🔧 [APIPILOT-CLIENT] flag=true → DEMO CALL api/apipilot/tools?include_unauthorized=true` (badge morado, antes del tracer) -- Luego **el wrapper fetch loguea** `→ [FETCH:APIPILOT:TOOLS] GET api/apipilot/tools?...` + `← [FETCH:APIPILOT:TOOLS] 200 GET (N ms)` (verde) con la lista herramientas en preview -- Finalmente `🔧 [APIPILOT-CLIENT] demo OK: N herramientas [primeras 5: tool1, tool2,…]` (badge verde) ó `…demo FAIL` (ámbar) con sugerencia de mirar `[APIPILOT-DISCOVERY]` en el log servidor - -Valor exportado en `window.__s2sApipilot = bool` para tests manuales desde Consola: -```js -// Ejecuta una herramienta manualmente para ver [FETCH:APIPILOT:EXEC] en el tracer -fetch("api/apipilot/execute", { - method: "POST", - headers: {"Content-Type": "application/json"}, - body: JSON.stringify({name: "nombre_herramienta", arguments: {parametro: "valor"}}) -}).then(r => r.json()).then(console.log); -``` - -#### 4. Archivos modificados (con referencias de línea) - -- **`s2s-client/main.js`**: - - Banner versión actualizado: [L28-L31](file:///home/duxiter/s2s/s2s-client/main.js#L28-L31) - - Wrapper fetch global `_installFetchDebugTracer()` IIFE — clasificación tags, preview request/response, paleta status, performance timing, anti-spam poll/heartbeat: [L41-L251](file:///home/duxiter/s2s/s2s-client/main.js#L41-L251) - - `fetchConfig()` — nuevo flag `apipilotEnabled` + `window.__s2sApipilot`: [L2526-L2537](file:///home/duxiter/s2s/s2s-client/main.js#L2526-L2537) - - `fetchConfig()` — llamada demo fire-and-forget ApiPilot tools list: [L2581-L2617](file:///home/duxiter/s2s/s2s-client/main.js#L2581-L2617) -- **`s2s-client/ws/s2s-ws-client.js`**: - - Banner tracer WS actualizado + paleta `_wsLog(status, tag, msg)` status 0..3 + contador chunks `_wsMicChunkCount` + caché cliente ApiPilot `_apipilotClientCache` TTL 240 s + contador sesiones `_wsSessionCounter`: [L56-L98](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L56-L98) - - `connect()` — contador #N sesión, log inicio/fin handshake, Promise.all([audioReady, wsReady, **apipilotReady**]): [L320-L370](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L320-L370) - - **`_prefetchApipilotTools(sessionIdShort)`** — NUEVO MÉTODO: check feature flag, caché TTL cliente 240 s, fetch `api/apipilot/tools` (proxy servidor `S2S_APIPILOT_TOOLS_URL`), guardado caché, chequeo envelope, badge log MISS/HIT/READY/FAIL/FALLIDO — NUNCA re-lanza excepción: [L372-L441](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L372-L441) - - `_postSession()` — timing handshake grant/queued/402/503: [L469-L520](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L469-L520) - - `_pollQueue()` — poll counter + advancement: [L523-L573](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L523-L573) - - `_openWebSocket()` — ENMASCARAMIENTO URL connect params (anti-fuga token/JWT): [L682-L728](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L682-L728) - - `_onWsMessage()` — high-signal regex, preview `response.function_call_arguments.done`: [L755-L812](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L755-L812) - - `_onWsClose()` — badge status code OK/ERR: [L1161-L1180](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L1161-L1180) - - `_send()` — anti-spam `input_audio_buffer.append` 250 chunks / 2500 ms: [L1523-L1584](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L1523-L1584) -- **`s2s-client/ui/account.js`**: - - Llamada `GET api/me` traceada automáticamente por el wrapper fetch global como `[FETCH:ACCOUNT:ME]` → sin modificaciones necesarias (ningún log duplicado). - -#### 5. Dónde ver las llamadas UPSTREAM (S2S_APIPILOT_TOOLS_URL) - -⚠️ **Importante — arquitectura passthrough**: -- ✅ **Consola navegador** → ves `[FETCH:APIPILOT:TOOLS]` y `[FETCH:APIPILOT:EXEC]` = llamadas locales al proxy `/api/apipilot/*` en el servidor S2S -- ✅ **Log servidor (terminal backend)** → ves `[APIPILOT-DISCOVERY] → GET https://aquachile.azurianlab.com/api/v1/apipilot/tools?...` y `[APIPILOT-EXEC] → POST …/execute` = llamadas reales upstream a la URL AquaPortal (`S2S_APIPILOT_TOOLS_URL`) - -Esto es así por diseño: el cliente nunca conoce la URL upstream AquaPortal (anti-hardcoding), todo pasa por el proxy local en `server.py` que añade headers auth y validación schema PRE-CHECK. - -### Solucionado — Bug: ApiPilot llamado 1 sola vez (anónimo) y NUNCA más tras login phone o refresh - -**Síntoma observado del log aquachile aportado**: -- A las `21:06:46` 1 única llamada `[apipilot] list_tools.start user=(anon)` a `/api/v1/apipilot/tools` (llamada demo anónima bootstrap) -- Inmediatamente después: múltiples `POST /auth/phone-login` y `GET /auth/user-by-phone` (usuarios autenticados, 21:06:49, 21:07:16, 21:07:19, 21:07:39) pero **NINGUNA** llamada apipilot repetida. - -**Causa raíz doble**: -1. **Caché cliente global (240 s) user-agnostic**: la demo bootstrap anónima y las sesiones autenticadas compartían la misma entry `_apipilotClientCache` sin clave por usuario. Por tanto la caché anónima HIT se reutilizaba para usuarios autenticados DIFERENTES. -2. **Caché servidor S2S (300 s) keyed por auth fingerprint** (`SHA-256(auth)[:12] | x-demo-session`) pero desde el cliente **no se propagaba ningún token `x-demo-session`**, así todas las llamadas usaban la fingerprint "vacía" (anónima) = caché anónima reutilizada sin llamar nunca AquaPortal para usuarios autenticados. -3. **Trigger demo solo al bootstrap**: ninguna llamada apipilot después de `phone-login` correcto, que es el momento en que cambia el contexto de usuario. - ---- - -#### Fix aplicados - -##### Fix 1 — Prefetch ApiPilot DESPUÉS de CADA login phone correcto (con `refresh=true`) -Insertado bloque fire-and-forget **justo después** de la confirmación HTTP 200 en `fetchVoceroUserProfile()` (después de cargar perfil): - -| Característica | Valor | -|---|---| -| Trigger | `api/user/phone?phoneNumber=…` HTTP 200 + objeto profile.result válido | -| Endpoint | `GET api/apipilot/tools?include_unauthorized=true&refresh=true` | -| Parámetro `refresh=true` | **OBLIGATORIO** → fuerza al proxy S2S lado servidor a **ignorar la caché 300 s** y llamar realmente AquaPortal upstream (así `[apipilot] list_tools.start user=…` reaparece en el log aquachile PARA CADA login phone) | -| Headers | Propaga `x-demo-session` si existe en `window.__s2sDemoSessionToken` (para fingerprint auth S2S distinta a anónima) | -| Efecto colateral | Invoca `window.__s2sInvalidateApipilotCache()` = invalida caché cliente WS para todas las sesiones vocales sucesivas → ninguna reutilización de caché para nuevo usuario | -| Log Consola | `🔧 [APIPILOT-CLIENT] post-login phone → FUERZO refresh api/apipilot/tools (badge morado)` + `post-login OK (dt=XYZ ms): N=X herramientas` o `post-login FAIL` | - -Referencia de línea: [main.js#L2418-L2464](file:///home/duxiter/s2s/s2s-client/main.js#L2418-L2464) - -##### Fix 2 — Caché cliente WS por-usuario (invalida si cambia phone/token) -La entry `_apipilotClientCache` ahora incluye la propiedad `key = _apipilotUserKey()`. - -Clave `_apipilotUserKey()` calculada como: -1. `P:<últimos-8-dígitos-phoneNumber>` → si existe `?phoneNumber=` en URL -2. `T:<últimos-6-char-x-demo-session-token>` → si existe token -3. `anon` → en otro caso - -HIT caché ahora requiere **3 condiciones**: -1. `now - cached.at <= 240 s` (TTL aún activo) -2. `cached.key === currentUser` (mismo phone / mismo token → mismo usuario) -3. Feature flag `window.__s2sApipilot = true` - -Referencia de línea: [s2s-ws-client.js#L94-L126](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L94-L126) (caché+clave+invalidación global) · [L411-L485](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L411-L485) (método `_prefetchApipilotTools` con check clave usuario, refresh=true si cambia usuario y propagate header x-demo-session) - -##### Fix 3 — Propagación header `x-demo-session` para huella auth lado servidor S2S -Ahora, **cuando exista** `window.__s2sDemoSessionToken` (length > 4), ambas llamadas apipilot (prefetch login + WS connect) propagan: -``` -x-demo-session: -``` -→ la caché lado servidor S2S (`SHA-256(auth)[:12] | x-demo-session`) usa clave **distinta para cada token/sesión** = **NINGUNA compartición caché entre Anónimo y Usuario Autenticado** ni entre usuarios distintos. - -##### Fix 4 — Función global invalidación caché para cross-módulo -```js -window.__s2sInvalidateApipilotCache(); // resetea _apipilotClientCache = null -``` -Llamada automáticamente por `main.js` tras login phone correcto. Útil también para tests manuales desde Consola navegador. - -Referencia de línea: [s2s-ws-client.js#L111-L126](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L111-L126) - -##### Cronograma esperado en el log AquaPortal DESPUÉS de este fix (log aportado repetido) -``` -21:06:46 [apipilot] list_tools.start user=(anon) ← demo bootstrap anónimo (refresh page) -21:06:46 [apipilot] list_tools.ok count=1 … -21:06:49 [apipilot] list_tools.start user= ← FIX #1 post-login phone refresh=true ✅ NUEVO -21:06:49 [apipilot] list_tools.ok count=… -21:07:16 [apipilot] list_tools.start user= ← FIX #1 login nuevo usuario ✅ NUEVO -21:07:16 [apipilot] list_tools.ok … -21:07:19 [apipilot] list_tools.start user= ← si caché cliente S2S invalidada o -21:07:19 … x-demo-session cambiado -``` - ---- - -### Añadido — Integración ApiPilot AquaPortal (herramientas dinámicas, sin hardcoding) - -Implementación lado proxy `s2s-client/server.py` del puente definido en -[GUIDA_APIPILOT_CLIENTE.md](file:///home/duxiter/s2s/GUIDA_APIPILOT_CLIENTE.md). - -**Objetivo**: permitir al cliente Vocero **consumir dinámicamente** las -herramientas expuestas por el backend AquaPortal vía ApiPilot, **sin hardcodear -nombres de endpoints, parámetros ni autorizaciones** en el código cliente. -Todo el conocimiento sobre "qué herramientas existen / qué parámetros aceptan / -si requieren autenticación" se **lee en runtime** vía descubrimiento -estandarizado. - -#### Entorno requerido (`.env`) - -| Variable | Valor ejemplo | Significado | -|---|---|---| -| **`S2S_APIPILOT_TOOLS_URL`** | `https://aquachile.azurianlab.com/api/v1/apipilot` | URL **base** (sin `/tools` ni `/execute`) del backend ApiPilot. Si está vacía → feature completamente desactivada (passthrough). | -| `S2S_APIPILOT_SERVICE_TOKEN` | `optional_Bearer_service_token` | Token de respaldo usado solo si el llamante no envía `Authorization` ni `x-demo-session`. | -| `S2S_APIPILOT_TTL_SEC` | `300` | TTL cache en memoria del descubrimiento de herramientas (por defecto 300 s = 5 min — según guía). Rango admitido [15, 3600]. | -| `S2S_APIPILOT_TIMEOUT_SEC` | `15.0` | Timeout HTTP descubrimiento + ejecución (por defecto 15 s). Rango [1, 120]. | - -#### Endpoints públicos expuestos por el proxy (mismo origen) - -| Endpoint | Verbo | Descripción | -|---|---|---| -| `/api/apipilot/tools?include_unauthorized=true&refresh=false` | **GET** | Lista herramientas conforme §2.1 (`ToolDefinition`: `name, description, parameters, requires_auth`). Respuesta envuelta `{success, data:{count, include_unauthorized, tools}, error}`. Soporta `?refresh=true` para forzar refresco de caché. | -| `/api/apipilot/execute` | **POST** | Ejecuta una herramienta conforme §2.2. Body: `{name: string, arguments: {}}`. PRE-CHECK obligatorios antes de la llamada HTTP. Respuesta SIEMPRE en envoltorio `{success, data, error}`. HTTP status code devuelto = `error.status_code` cuando existe (4xx/5xx). | - -Extensión de `/api/config`: nueva clave booleana de primer nivel -`"apipilot": true/false` (basada en `S2S_APIPILOT_TOOLS_URL`). El frontend la -usa para decidir si mostrar el catálogo / los botones "Ejecutar herramienta" -(obtiene la lista desde `/api/apipilot/tools` en vez de hardcodearla). - -#### PRE-CHECK obligatorios (flujo guía §2.2, todos implementados) - -1. **Descubrimiento fresco** — antes de cada `execute` se usa la lista tools - recuperada por `_apipilot_fetch_tools(...)` respetando la TTL. Si la - herramienta no se encuentra, **una sola** re-descubrimiento forzado antes - de fallar. -2. **Control `requires_auth`** — si `true` pero ningún token presente - (Authorization / x-demo-session / S2S_APIPILOT_SERVICE_TOKEN) → bloqueo - HTTP 401 con envoltorio `{code: "AUTH_REQUIRED", message: "La - herramienta «nombre» requiere autenticación…"}` — **NINGUNA solicitud se - envía al backend upstream** en este caso. -3. **Validación JSON-Schema strict** (`_apipilot_validate_arguments`): - - elimina **TODAS** las claves extra no presentes en `parameters.properties` - (aviso `[APIPILOT-VALIDATE] … removing unknown arg=…`); - - **NO inventa parámetros**; - - devuelve error 400 `INVALID_ARGUMENTS` por cada campo `required` - faltante (mensajes en español). -4. **Passthrough cabeceras autenticación**: - `Authorization: Bearer ` o bien `x-demo-session: - ` se reenvían VERBATIM al backend AquaPortal (§2.1 nota), - **NUNCA se loguean** (solo presencia: log `auth=Y / demo=Y`). -5. **Compatibilidad LLM function-calling**: helper - `_apipilot_strip_tool_for_llm(tool_def)` que proyecta `ToolDefinition` al - formato estándar OpenAI `{type: "function", function: {name, description, - parameters}}` — **elimina `requires_auth`** (§4 guía: "no mandar - directamente la salida cruda de /tools al modelo"). - -#### Garantías / seguridad / anti-leak - -| Control | Implementación | -|---|---| -| Sin compartir caché entre identidades distintas | Clave caché = `SHA-256(authorization)[:12] \| x-demo-session` → huella anónima, no guarda tokens en caché | -| Doble comprobación caché con candado asíncrono | `_APIPILOT_CACHE_LOCK` async + double check tras adquirir lock → 1 sola fetch por refresco | -| Fallback obsoleto ante error de red | Si backend cae y tenemos entrada en caché → devuelve fallback logueando warning en vez de crash | -| Reenvío cabecera Auth nunca logueado | Solo log `auth=Y/- demo=Y/-` | -| Filtrado parámetros unknown | Eliminados, nunca reenviados al backend | -| Envoltorio errores uniforme | Siempre `{success, data, error}` incluso para errores pre-check locales | -| Nombres env coherentes | Ninguna URL ni token hardcodeados | -| Banner startup confirmación | `[STARTUP] … apipilot= apipilotServiceToken=Y/- apipilotTtl=s apipilotTimeout=s` | - -**Archivos modificados:** - -- **`server.py`** ([server.py](file:///home/duxiter/s2s/s2s-client/server.py)) — Sección APIPILOT completa insertada entre `OPENAI_PROJECT` y `NODE_RED_REASONING_URL`: - 1. Definición 4 env + normalización + límites rango TTL/timeout - ([L236-L266](file:///home/duxiter/s2s/s2s-client/server.py#L236-L266)). - 2. Caché en-proceso `_APIPILOT_CACHE: dict[fp → (monotonic, tools[])]` + lock - asíncrona `_APIPILOT_CACHE_LOCK` ([L268-L271](file:///home/duxiter/s2s/s2s-client/server.py#L268-L271)). - 3. Helpers puros: `_apipilot_auth_fingerprint(auth, demo)` - ([L274-L287](file:///home/duxiter/s2s/s2s-client/server.py#L274-L287)) · `_apipilot_parse_authorization(Request)` - ([L290-L309](file:///home/duxiter/s2s/s2s-client/server.py#L290-L309)) · `_apipilot_strip_tool_for_llm(tool_def)` - ([L312-L338](file:///home/duxiter/s2s/s2s-client/server.py#L312-L338)). - 4. Descubrimiento: `_apipilot_fetch_tools(auth, demo, include_unauthorized, force_refresh)` - ([L341-L481](file:///home/duxiter/s2s/s2s-client/server.py#L341-L481)) — log cache hit, fallback obsoleto, desempaquetado payload `list/{tools,result,data}.tools`, saneamiento mínimo ToolDefinition, logs `[APIPILOT-DISCOVERY] →/←`. - 5. Validación: `_apipilot_validate_arguments(arguments, tool_def)` - ([L484-L517](file:///home/duxiter/s2s/s2s-client/server.py#L484-L517)) — elimina extras, check required, mensajes en español. - 6. Ejecución: `_apipilot_execute_tool(auth, demo, name, arguments)` - ([L520-L684](file:///home/duxiter/s2s/s2s-client/server.py#L520-L684)) — PRE-CHECK 1-2-3 (re-discovery 1 volta, requires_auth 401, validación 400), POST /execute envoltorio, manejo HTTP no-JSON, wrap envoltorio si backend no lo devuelve, logs `[APIPILOT-EXEC] →/←`. - 7. Banner `[STARTUP] Other externals`: extendido con 4 nuevos placeholders `apipilot`, `apipilotServiceToken`, `apipilotTtl`, `apipilotTimeout` - ([L726-L752](file:///home/duxiter/s2s/s2s-client/server.py#L726-L752)). - 8. **`/api/config`**: nueva clave booleana `"apipilot": bool(S2S_APIPILOT_TOOLS_URL)` + docstring, log extendido - ([L2544-L2579](file:///home/duxiter/s2s/s2s-client/server.py#L2544-L2579)). - 9. **Modelo Pydantic** `ApipilotExecuteRequest(name:str, arguments:dict={})` ([L2582-L2585](file:///home/duxiter/s2s/s2s-client/server.py#L2582-L2585)). - 10. **`GET /api/apipilot/tools`** proxy público ([L2588-L2651](file:///home/duxiter/s2s/s2s-client/server.py#L2588-L2651)): - query `?include_unauthorized=true(default)&refresh=false`, envoltorio uniforme `{success, data: {count, include_unauthorized, tools}, error}`, 501 si env no configurado, HTTPException convertidas a envoltorio. - 11. **`POST /api/apipilot/execute`** proxy público ([L2654-L2700](file:///home/duxiter/s2s/s2s-client/server.py#L2654-L2700)): - body `{name, arguments}`, PRE-CHECK 1-2-3 vía `_apipilot_execute_tool`, código status respuesta = `error.status_code` si error, mensajes de cara al usuario en español §2.2. - ---- - -## [2026-09-23] - -### Añadido — Botón «Descargar conversación» en la cabecera del panel chat (export JSON + TXT client-side offline) - -Nuevo botón circular icono descarga junto al testigo «En línea» a la derecha -de la cabecera del panel `#chat-panel`. Al pulsar serializa TODO el -historial persistente (`.hist-msg` dentro de `#chat-history`) y descarga DOS -archivos simultáneamente, SIN llamadas al backend, 100 % client-side y -offline-safe (Blob + URL.createObjectURL + ``): - -1. `vocero-conversacion[-]-YYYYMMDD-HHMMSS.json` — estructura - con metadatos `{ exportedAt, messageCount, messages: [...] }`. Tipos soportados: - - `user` / `assistant` → `{ type, text, timestamp, name?, initials?, interrupted? }` - - `tool` → `{ type: "tool", timestamp, name, args, output }` (resultado llamadas tool) - - `image` → `{ type: "image", timestamp, dataUrl }` (capturas webcam camera tool) -2. `vocero-conversacion[-]-YYYYMMDD-HHMMSS.txt` — log legible - para humanos en español, cada entrada formateada como - `HH:MM Nombre / Vocero / HERRAMIENTA : texto`. - -**UI / UX (todo en español, como solicitado):** -- `aria-label="Descargar conversación"` -- `title="Descargar conversación (JSON + TXT)"` -- **Feedback OK**: tras export correcto botón se pinta verde 650 ms - (`.chat-export-ok` con ring + glow). -- **Feedback vacío**: si no hay mensajes → sin descarga, botón flash - ámbar + micro-shake 0.42s (`.chat-export-empty`) + console info - `[ui/chat.js:exportConversation] No hay mensajes aún — exportación omitida.` -- **Nombres de fichero saneados**: helper `_safeName(...)` elimina unicode / - caracteres especiales / espacios → `a-z 0-9 - _`. -- **Estilos coherentes**: dark (glass/aurora) + white (estilo screenshot móvil) - ambos tematizados con colores existentes `var(--brand)`, `#16a34a`, `#f59e0b`. - -**Garantías:** -- 🔒 Cero datos transmitidos fuera del navegador (ningún POST, ningún analytics). -- Las burbujas efímeras sobre el orbe (`.bubble` / `.bubble-stack`) se - ignoran intencionadamente: exporta SOLO el histórico permanente, el que es significativo. -- Never-throws: todo el export envuelto en `try/catch`; error solo en consola. -- `window.URL.revokeObjectURL(...)` tras 4 s → sin fugas de memoria Blob. -- Disponible en TODOS los temas (dark / white / default). - -**Archivos modificados:** - -- **`index.html`** ([index.html](file:///home/duxiter/s2s/s2s-client/index.html)): - 1. Wrapper `.chat-header-actions` a la derecha de la cabecera, que engloba - la pill «En línea» + nuevo botón `#chat-export-btn` (SVG flecha-abajo) - ([L374-L394](file:///home/duxiter/s2s/s2s-client/index.html#L374-L394)). - -- **`ui/chat.js`** ([chat.js](file:///home/duxiter/s2s/s2s-client/ui/chat.js)): - 1. Helper module-level `_safeName(prefix)` para sanear nombres de fichero - ([L38-L50](file:///home/duxiter/s2s/s2s-client/ui/chat.js#L38-L50)). - 2. Ref `this._exportBtn = getElementById("chat-export-btn")` + listener `click` - en constructor `ChatView` ([L74-L78](file:///home/duxiter/s2s/s2s-client/ui/chat.js#L74-L78)). - 3. Nueva sección `// ── Export / download conversation ──` con 4 métodos: - - `_serializeConversation()` → extrae rows `.hist-msg` via querySelector - `:scope > .hist-msg`, gestiona `user/assistant/tool/image`, preserva - timestamp `data-timestamp`, nombre usuario, initials, flag interrupted - ([L521-L582](file:///home/duxiter/s2s/s2s-client/ui/chat.js#L521-L582)). - - `_conversationToText(conv)` → pretty-format texto en español con - cabecera fecha, totales, bloques tool indentados, preview imagen dataURL - ([L584-L621](file:///home/duxiter/s2s/s2s-client/ui/chat.js#L584-L621)). - - `_downloadBlob(content, filename, mime)` → patrón `` + - revokeObjectURL ([L623-L645](file:///home/duxiter/s2s/s2s-client/ui/chat.js#L623-L645)). - - `exportConversation()` (público) → entry-point, nombre fichero con - sello UTC local `YYYYMMDD-HHMMSS`, incluye nombre perfil Vocero si - existe, lógica empty/OK/error feedback, 2 descargas distintas - ([L647-L697](file:///home/duxiter/s2s/s2s-client/ui/chat.js#L647-L697)). - -- **`style.css`** ([style.css](file:///home/duxiter/s2s/s2s-client/style.css)): - 1. `.chat-header-actions` flex-row right-aligned - ([L4919-L4931](file:///home/duxiter/s2s/s2s-client/style.css#L4919-L4931)). - 2. `.chat-export-btn` base (dark-theme): 32×32 pill, glassy, hover/focus - states, transiciones 120-160 ms - ([L4932-L4968](file:///home/duxiter/s2s/s2s-client/style.css#L4932-L4968)). - 3. Estados feedback: `.chat-export-ok` (verde) + `.chat-export-empty` - (ámbar + animación shake 5 pasos) - ([L4969-L4989](file:///home/duxiter/s2s/s2s-client/style.css#L4969-L4989)). - 4. Variantes white-theme completas: `.chat-header-actions`, base, hover, - active, OK, empty - ([L4991-L5015](file:///home/duxiter/s2s/s2s-client/style.css#L4991-L5015)). - -### Añadido — `S2S_LATEST_SUMMARY_TEXT`: override estático del resumen última conversación (texto limpio, ninguna llamada HTTP) - -Nueva variable de entorno que, si se establece, tiene **prioridad absoluta** sobre `S2S_LATEST_SUMMARY` -y se salta completamente la fetch HTTP upstream (login-by-phone, Bearer, timeout, JSON unwrap: *todo bypaseado*). -Su valor en texto plano se inyecta directamente como bloque "latest conversation summary" -dentro del prompt LLM (tanto en el canal WebSocket `/v1/realtime` como en `POST /api/reasoning`). - -Diseñada para el caso de uso en el que el operador quiere inyectar una versión -**limpia, esencial y pre-depurada** del resumen sin depender de ningún endpoint externo. - -**Valor `.env` de ejemplo (multilínea con `\n`):** -```env -# S2S_LATEST_SUMMARY=https://api.example.com/summary # ← desactivado: S2S_LATEST_SUMMARY_TEXT tiene prioridad -S2S_LATEST_SUMMARY_TEXT=Última conversación 2026-09-22:\n- Usuario preguntó por mortalidad salmón AquaChile semana 38.\n- Se refirió al reporte Porcentaje Mortalidad. -``` - -**Comportamiento clave:** -- Las secuencias `\n` en el valor env se interpretan como salto de línea real (misma convención que `S2S_PRIMARY_PROMPT`) -- **No requiere `phoneNumber`**: funciona también para sesiones genéricas sin identificativo de llamante -- El wrapper `LATEST_SUMMARY_HINT` + el tope a **1600 caracteres** se siguen aplicando igualmente (pasa siempre a través de `_resolve_latest_summary_context`) -- El bloque se clasifica correctamente por el layer dedup (marker invisible `SUMMARY_FULL_MARKER`) — sin riesgo de duplicado -- Si `S2S_LATEST_SUMMARY_TEXT` está vacío → **fallback** transparente al flujo anterior (`S2S_LATEST_SUMMARY` URL + `phoneNumber`) - -**Logs esperados en el servidor para confirmar override activo:** -``` -[INJECT-SUMMARY] S2S_LATEST_SUMMARY_TEXT OVERRIDE active (len= chars). Skipping HTTP fetch; injecting raw static plain-text summary directly. -``` - -**Archivos modificados:** - -- **`server.py`** ([server.py](file:///home/duxiter/s2s/s2s-client/server.py)): - 1. Definición nueva env `S2S_LATEST_SUMMARY_TEXT` + interpretación escape `\n` ([L128-L140](file:///home/duxiter/s2s/s2s-client/server.py#L128-L140)). - 2. Banner `[STARTUP]` extendido con campo `summaryText=%s` para confirmación visual a boot ([L275-L297](file:///home/duxiter/s2s/s2s-client/server.py#L275-L297)). - 3. **Rama override** ANTES de cualquier lógica HTTP dentro de `_fetch_latest_summary_for_phone(...)` ([L1563-L1589](file:///home/duxiter/s2s/s2s-client/server.py#L1563-L1589)): - - return directo del valor estático; - - log `[INJECT-SUMMARY] … OVERRIDE active`; - - vista previa raw primeros 800 chars si `S2S_DEBUG_PROMPT=true`. - 4. **Puerta REASONING:** `needs_summary = bool(S2S_LATEST_SUMMARY) or bool(S2S_LATEST_SUMMARY_TEXT)` ([L2153](file:///home/duxiter/s2s/s2s-client/server.py#L2153)). - 5. **Skip REASONING relajado:** condición `(not phone) and (not needs_reports) and (not episode_id) and (not S2S_LATEST_SUMMARY_TEXT)` — el texto estático no necesita phone ([L2159-L2168](file:///home/duxiter/s2s/s2s-client/server.py#L2159-L2168)). - 6. **Ejecución summary REASONING:** `needs_summary and (phone or S2S_LATEST_SUMMARY_TEXT)`; log "READY" extendido con flag `summaryTextOverride=%s` ([L2240-L2256](file:///home/duxiter/s2s/s2s-client/server.py#L2240-L2256)). - 7. **Puerta WS connect:** mismo `needs_summary` extendido con `S2S_LATEST_SUMMARY_TEXT` ([L2644](file:///home/duxiter/s2s/s2s-client/server.py#L2644)). - 8. **Skip WS connect relajado:** incluso sin `phoneNumber` si hay `S2S_LATEST_SUMMARY_TEXT` la pipeline arranca ([L2653-L2664](file:///home/duxiter/s2s/s2s-client/server.py#L2653-L2664)). - 9. **Ejecución summary WS:** misma condición relajada + log "READY" con campo `summaryTextOverride=%s` ([L2725-L2746](file:///home/duxiter/s2s/s2s-client/server.py#L2725-L2746)). - -- **`INJECTIONS.md`** ([INJECTIONS.md](file:///home/duxiter/s2s/s2s-client/INJECTIONS.md)): - 1. Sección **4. Blocco summary ultima conversazione** completamente reescrita (versión italiano original). - ---- - -## [2026-09-07] - -### Añadido — Soporte `episode_id` (inject de episodio podcast) - -Nuevo parámetro query string `?episode_id=` junto a `?phoneNumber=` que -habilita la carga y la inyección automática de un episodio podcast como -contexto PRIMARIO en el prompt LLM. - -**URL de ejemplo:** -``` -/?phoneNumber=%2B447432477433&episode_id=episode-19569f77-a06e-5ce5-a52f-6299dbd67d03 -``` - -**Archivos modificados:** - -- **`server.py`** ([server.py](file:///home/duxiter/s2s/s2s-client/server.py)): - 1. Añadida la constante `PODCAST_EPISODE_HINT` ([L426-L429](file:///home/duxiter/s2s/s2s-client/server.py#L426-L429)) para el hint semántico en el prompt. - 2. Añadida la función `_resolve_episode_context(raw_value)` ([L475-L504](file:///home/duxiter/s2s/s2s-client/server.py#L475-L504)): normaliza la respuesta API (dict/list/str, posible wrapper `{"result": …}`), la serializa en JSON (tope 24.000 chars) y la envuelve con los marcadores `<<>>`. - 3. Añadida la función asíncrona `_fetch_podcast_episode(episode_id)` ([L1010-L1078](file:///home/duxiter/s2s/s2s-client/server.py#L1010-L1078)): GET directo a - `https://aquachile.azurianlab.com/api/v1/podcast/episodes/{episode_id}` - (timeout 15s, follow redirects, manejo de errores tolerante — nunca rompe el flujo, devuelve `None` en caso de fallo). - 4. Extendida `_augment_instructions_with_profile(...)` ([L1137-L1181](file:///home/duxiter/s2s/s2s-client/server.py#L1137-L1181)) con el nuevo parámetro `episode_context_text`; el orden de inject ahora es (más específico → más genérico): **episode → profile → reports → summary**. - 5. Extendida `_patch_client_session_update_with_profile(...)` ([L1184-L1306](file:///home/duxiter/s2s/s2s-client/server.py#L1184-L1306)) con soporte a `episode_context_text` y logging dedicado `[INJECT-EPISODE]` / `[DEBUG-EPISODE]`. - 6. WebSocket connect handler ([L1791-L1959](file:///home/duxiter/s2s/s2s-client/server.py#L1791-L1959)): - - lee `episode_id` desde query params junto a `phoneNumber`; - - ejecuta fetch episodio + resolve ANTES de profile/reports/summary; - - guarda `injected_episode_context` e `inject_episode_id` en el `session_ctx` compartido. - 7. `_client_to_upstream` ([L2649-L2661](file:///home/duxiter/s2s/s2s-client/server.py#L2649-L2661)): pasa `ctx_episode_context` al patch de `session.update`. - 8. Endpoint `POST /api/reasoning`: - - extendido el modelo `ReasoningRequest` con el campo `episode_id: str | None = None` ([L1309-L1323](file:///home/duxiter/s2s/s2s-client/server.py#L1309-L1323)); - - en el handler ([L1411-L1577](file:///home/duxiter/s2s/s2s-client/server.py#L1411-L1577)) fetch episodio independiente de phone; - - `inject_episode_text` se hace **prepend** sobre `user_context_parts` (primero de todos); - - reenvío a NODE_RED / OPENAI con logging extendido (`episodeIdLen`). - -- **`main.js`** ([main.js](file:///home/duxiter/s2s/s2s-client/main.js)): - 1. Lectura desde query string: `const voceroEpisodeId = pageParams.get("episode_id")` ([L676-L680](file:///home/duxiter/s2s/s2s-client/main.js#L676-L680)). - 2. `fetchOpenAiReasoningAnswer` ([L1337-L1364](file:///home/duxiter/s2s/s2s-client/main.js#L1337-L1364)): campo `episode_id` añadido al body POST `/api/reasoning`, logKey y `console.info` extendidos. - 3. Construcción URL WebSocket ([L2323-L2342](file:///home/duxiter/s2s/s2s-client/main.js#L2323-L2342)): `episode_id` añadido a query params tanto con la API `URL.searchParams` como en el fallback string (concat con `&`). - ---- - -### Añadido — `S2S_START_SESSION_MODE`: 3 modos de inicio de sesión - -Variable de entorno leída por el servidor y propagada al cliente vía `GET /api/config.startSessionMode`. -Objetivo: controlar si y cómo se enciende automáticamente el micrófono y si el modelo saluda -primero (flujo similar al wake-word). Valores soportados: - -| Valor | Descripción | -|---|---| -| *(vacío) / default* | Inicio manual: solo tap sobre el Orb / botón Start | -| **`TALK`** | Después de 2s overlay a pantalla completa "Toca en cualquier lugar para empezar" (policy safe para Safari/iOS `getUserMedia`). Click/touch/tecla dentro de la user gesture → `doStart()`. El cliente WS inyecta bootstrap `"hola vocero"` + `requestResponse()`. | -| **`TALKFIRST`** | Después de 2s **intenta `doStart()` DIRECTAMENTE SIN click**, precargando `pendingWakeWordConfirmationText = "hola vocero"` (misma variable de la wake-word real). Si los permisos de mic ya están "allow always" funciona sin click. Si falla (policy Safari/iOS) → fallback sobre el mismo unlocker de TALK con mensaje "permiso micrófono". | - -**Archivos modificados:** - -- **`server.py`** ([server.py](file:///home/duxiter/s2s/s2s-client/server.py)): - 1. Lectura env: `S2S_START_SESSION_MODE = os.environ.get(...)`, `.strip().upper()` ([L150](file:///home/duxiter/s2s/s2s-client/server.py#L150)). - 2. Banner `[STARTUP]` extendido con el campo `startSessionMode=` ([L196-L212](file:///home/duxiter/s2s/s2s-client/server.py#L196-L212)). - 3. Endpoint `GET /api/config` → nuevo campo `startSessionMode` + log `[INTERNAL] /api/config` ([L1383-L1400](file:///home/duxiter/s2s/s2s-client/server.py#L1383-L1400)). - -- **`index.html`** ([index.html](file:///home/duxiter/s2s/s2s-client/index.html#L32-L39)): - - Añadido nuevo overlay `#talk-unlocker` a pantalla completa (z-index 9999), `hidden` por defecto, con tarjeta "Preparando Vocero… / Toca en cualquier lugar para empezar a hablar" + spinner degradado. - -- **`style.css`** ([style.css](file:///home/duxiter/s2s/s2s-client/style.css#L145-L215)): - - Clases `.talk-unlocker`, `.talk-unlocker-hint`, `.talk-unlocker-spinner`, `.talk-unlocker-title`, `.talk-unlocker-sub` + animaciones fade-in y pop-up de tarjeta. - -- **`main.js`** ([main.js](file:///home/duxiter/s2s/s2s-client/main.js)): - 1. Variable global `startSessionMode = ""` + comentario ([L628-L632](file:///home/duxiter/s2s/s2s-client/main.js#L628-L632)). - 2. Parse dentro de `fetchConfig()` → uppercase, log en `reportDebug("B",…)` ([L2309-L2320](file:///home/duxiter/s2s/s2s-client/main.js#L2309-L2320)). - 3. Paso a cliente WS → `startWithResponse: startSessionMode === "TALK"` ([L2683-L2692](file:///home/duxiter/s2s/s2s-client/main.js#L2683-L2692)). - 4. Bloque scheduling auto-start ([L2976-L3083](file:///home/duxiter/s2s/s2s-client/main.js#L2976-L3083)): - - `bootstrapWithAutoStart()`: `await fetchConfig()` → `maybeScheduleAutoStart()`; - - `setTimeout(2000 ms)` warmup para finalizar fetch de episode/profile/reports; - - `showTalkUnlocker(fallbackHint)`: gestiona labels personalizadas en caso de fallback TALKFIRST; - - **`tryTalkFirstDirect()` (TALKFIRST)**: set `pendingWakeWordConfirmationText="hola vocero"` + `doStart()` + try/catch con teardown y fallback unlocker; - - listener unlocker click/touchstart/keydown → `startTalkFromGesture()` con `createResumedAudioContext()` dentro de la gesture (para iOS silent-free). - 5. `onClientStatus()` ([L2878-L2932](file:///home/duxiter/s2s/s2s-client/main.js#L2878-L2932)) añadido `hideTalkUnlocker()` en `connecting/queued/your-turn/connected`. - -- **`ws/s2s-ws-client.js`** ([s2s-ws-client.js](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js)): - 1. Constructor: nuevas propiedades `_startWithResponse`, `_startWithResponseText` (default `"hola vocero"`), `_initialResponseSent` guardia one-shot ([L163-L178](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L163-L178)). - 2. Handler `session.updated` ([L688-L713](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L688-L713)): **Solo para `TALK`** (no TALKFIRST, que en cambio usa `pendingWakeWordConfirmationText`): `this.sendUserText("hola vocero") + this.requestResponse()` — mismo code path identico de la wake-word. - 3. `requestResponse` / `_createResponseNow` restaurados limpios (solo payload opcional `image`; ningún shaped `response.create`). - ---- - -### Modificado — `#reports-sidebar-toggle` visible solo con `?debug=true` - -El botón "reports" en la topbar (toggle del panel lateral reports) ahora es -`data-debug-only="true"` — por lo tanto solo se muestra si la URL contiene -`?debug=true`, de manera análoga al cluster `.topbar-right`. - -**Archivos modificados:** - -- **`index.html`** → `#reports-sidebar-toggle` ([index.html](file:///home/duxiter/s2s/s2s-client/index.html#L47-L50)): añadido `data-debug-only="true"`. -- **`main.js`** → `applyDebugOnlyVisibilityGate()` ([L48-L109](file:///home/duxiter/s2s/s2s-client/main.js#L48-L109)): extendido para iterar *todos* los elementos `[data-debug-only="true"]` (no solo `.topbar-right`); línea 1227: `reportsSidebarToggle.hidden = false` condicionado a `qs.get("debug") === "true"` ([L1227-L1246](file:///home/duxiter/s2s/s2s-client/main.js#L1227-L1246)) + log rojo `🚫 FORZADO HIDDEN` cuando falta debug=true. -- **`style.css`** → regla de seguridad ya presente: `[data-debug-only]:not([data-debug-enabled]) { display:none !important; visibility:hidden; opacity:0 }` ([L532-L537](file:///home/duxiter/s2s/s2s-client/style.css#L532-L537)). - ---- - -## [2026-09-04] - -### Modificado — Chat siempre visible + integración seamless - -Reorganizado el layout para mostrar el chat textual de forma permanente e -integrado visualmente con el Orb en la parte superior del stage. - -- Eliminado botón toggle chat en la topbar (`#chat-btn`) y relativo overlay. -- Stage con el Orb en la parte superior; nuevo `#chat-panel` a continuación (historial - + form input fijo sobre el footer sticky). -- Actualizada lógica en `main.js` y `ui/chat.js` para el envío de texto mediante - `client.sendUserText` y auto-scroll sin controles de visibilidad del panel. -- Versión banner deploy: **2026-09-03 14:40**. - -### Resuelto — Estabilidad integración chat mobile - -- Error `Missing element: #chat-btn` resuelto con selectores non-strict - (`document.querySelector`) para elementos opcionales eliminados. -- Refactorización estética "seamless": chat sin marcos, sombras ni fondos - (`background:transparent`, `box-shadow:none`). -- **Layout mobile:** - - padding incrementado en `#app` (56px) y `.chat-history` (96px) para evitar - superposiciones con el footer sticky; - - márgenes fijos en las burbujas: `margin-right:22px` (Assistant), `margin-left:6px` (User). -- **Auto-scroll streaming:** implementado `_scrollToBottom` con cadena de retry - múltiples (`requestAnimationFrame` + `setTimeout`) para compensar el line-wrap - asíncrono durante la llegada de los tokens; `overflow-anchor:none` + `scroll-behavior:auto !important`. - -### Añadido — Avatar usuario con iniciales + modal de perfil - -- Sustituido el texto del nombre de usuario en el header por avatar circular 40×40px - (gradient de marca) conteniendo las iniciales calculadas (ej. "AV"). -- Nueva `` en `index.html` que se abre al click - sobre el avatar: muestra email, teléfono, rol, empresa, con soporte a shapes - anidadas del payload de perfil. -- Cierre del modal: tecla ESC, click fuera de la tarjeta, botón `×` dedicado. - ---- - -## [Notas de formato] - -- **Tope campo prompt episodio:** 24.000 caracteres (transcript largos). -- **Tope profile / summary:** 1.600 caracteres cada uno. -- **Tope reports list:** 12.000 caracteres. -- **Orden inject prompt LLM (WS session.update + reasoning):** - 1. Episodio podcast actual (PRIMARIO) - 2. Perfil llamador (identidad) - 3. Lista reports / scripts podcast programados - 4. Summary última conversación -- Todos los bloques están marcados con `<<>>` para inspección de logs. diff --git a/s2s-client/CHANGELOG.md b/s2s-client/CHANGELOG.md index caa7748..a36d1a0 100644 --- a/s2s-client/CHANGELOG.md +++ b/s2s-client/CHANGELOG.md @@ -1,863 +1,228 @@ # Changelog — s2s-client (Azurian Vocero) -Tutte le modifiche rilevanti al progetto sono documentate in questo file. -Formato basato su [Keep a Changelog](https://keepachangelog.com/it/1.1.0/). - ---- - -## [2026-09-25] - -### Corretto — Lista ApiPilot tools adesso viene INIETTATA ANCHE nella WS Realtime (non solo in /api/reasoning HTTP) - -**Sintomo iniziale utente (2026-09-25):** -> *"vedo arrivare su ai-server gli altri prompt, ma non quello di apipilot tools"* - -Dump log di `ai-server start_pipeline_rag` confermava: `LLM REQUEST — model=Qwen3.6-35B-A3B` → `Session Prompt:` conteneva profile / voice rules / today / summary, MA **non c'era traccia della sezione `### Herramientas dinámicas disponibles (ApiPilot AquaPortal)`**. - -#### Root cause (3 bug che operavano insieme): -1. La lista strumenti ApiPilot (PASSATA-1) veniva iniettata **SOLO nel ramo HTTP `/api/reasoning`** (`server.py:L3078-L3079, L3286-L3287`) ma **MAI nel builder del session.update** del canale Realtime WS (`/v1/realtime`) che è quello usato dall' `ai-server` nella pipeline Qwen3.5-35B vocale. -2. Gate S2S_INJECT_PROFILE chiudeva fuori l'apipilot nel ramo `=false`. -3. Nessun marker BEGIN/END di classificazione blocco per il dedup/debug. - -#### Fix applicato oggi (server.py): -| # | Cosa | Riferimento | -|---|---|---| -| 1 | **Fetch lista strumenti ALL'INIZIO di OGNI tunnel WS Realtime** (immediatamente dopo connect, prima di `async with websockets.connect(upstream_url)`) | [server.py#L3930-L3973](file:///home/duxiter/s2s/s2s-client/server.py#L3930-L3973) | -| 2 | **Indipendente da `S2S_INJECT_PROFILE`**. Ora gate `needs_apipilot = bool(S2S_APIPILOT_TOOLS_URL) or bool(S2S_APIPILOT_TOOLS_EXECUTE_URL)` gira anche nel caso S2S_INJECT_PROFILE=false | [server.py#L3813](file:///home/duxiter/s2s/s2s-client/server.py#L3813) | -| 3 | **`login_token` passato a bearer fingerprint se disponibile** (autenticati), altrimenti `anon-ws-{ip}-{id(ws)}` demo session key = fingerprint cache per-utente anonimo | [server.py#L3939-L3942](file:///home/duxiter/s2s/s2s-client/server.py#L3939-L3942) | -| 4 | **`_patch_client_session_update_with_profile` esteso con 8° parametro `apipilot_context_text_pass1`**. Aggiunge blocco PASS-1 **DOPO** profile/reports/episode/summary (stesso ordine /api/reasoning) in `session.instructions` (posto che l'LLM vede sempre con massima priorità). Gate nuovo: S2S_INJECT_PROFILE=false + apipilot non vuoto → **PATCH cmq eseguita** | [server.py#L2560-L2713](file:///home/duxiter/s2s/s2s-client/server.py#L2560-L2713) | -| 5 | **`session_ctx["injected_apipilot_pass1"]` + `["apipilot_tools_pass1"]`** salvate nel contesto tunnel e riusate in `_client_to_upstream` per patchare **ogni** `session.update` client (inclusi update patch tardivi) | [session_ctx @ server.py#L4028-L4042](file:///home/duxiter/s2s/s2s-client/server.py#L4028-L4042) | -| 6 | Call site client→upstream forward adesso passa `apipilot_context_text_pass1=ctx_apipilot_pass1` al patch | [server.py#L4780-L4790](file:///home/duxiter/s2s/s2s-client/server.py#L4780-L4790) | -| 7 | **Log sempre-attivi** (S2S_DEBUG_PROMPT non serve) al connect WS: `[APIPILOT] REASONING PASS-1 (WS realtime): lista strumenti pronta N=… t=…ms auth=Y/anon` + `[INJECT-APIPILOT] ✅ WS connect: APIPILOT TOOLS list PASS-1 READY Ntools=… wrappedLen=…` + patch marker `apipilotPass1=Y(len=…)` nel log patched | [L3954-L3961](file:///home/duxiter/s2s/s2s-client/server.py#L3954-L3961) · [L2668-L2676](file:///home/duxiter/s2s/s2s-client/server.py#L2668-L2676) | -| 8 | **Log S2S_DEBUG_PROMPT block completo** `[DEBUG-APIPILOT][WS session.update] FULL ApiPilot tools list PASS-1 block (len=…):` → mostra esattamente il testo che arriva all'LLM (no più ipotesi). | [server.py#L2693-L2696](file:///home/duxiter/s2s/s2s-client/server.py#L2693-L2696) | -| 9 | **`client_query` estratto FUORI da `S2S_INJECT_PROFILE` else block** (così esiste anche quando profile=false per x-demo-session fingerprint) | [server.py#L3810-L3818](file:///home/duxiter/s2s/s2s-client/server.py#L3810-L3818) | - -#### Log attesi adesso nel server S2S (ogni connessione vocale WS Realtime): -``` -[INJECT-APIPILOT] WS connect: fetching tools... -[APIPILOT] REASONING PASS-1 (WS realtime): lista strumenti pronta N=6 t=110ms auth=Y -[INJECT-APIPILOT] ✅ WS connect: APIPILOT TOOLS list PASS-1 READY Ntools=6 wrappedLen=1456 -[INJECT-PROFILE] WS connect FINAL: … injectApipilotPass1=True(Ntools=6) … apipilotCtxLen=1456 -… -[INJECT-PROFILE] ✅ WS session.update PATCHED → upstream instructions. origLen=1000 newLen=2456 injectedLen=1456 … apipilotPass1=True(len=1456) -``` - -E nel log **ai-server `start_pipeline_rag`**, dentro `>>> PROMPT: … Session Prompt:` in fondo comparirà ORA: -``` -<<>> -### Herramientas dinámicas disponibles (ApiPilot AquaPortal) -REGLAS EJECUCIÓN OBLIGATORIAS: -1. … (regole marker) -Lista herramientas (name / description): -- name: get_user_briefing - requires_auth: true - required_parameters: [phone] - description: Devuelve el briefing diario de un usuario... -<<>> -``` - ---- - -### Corretto — 12+ fix sequenziali PASS-2 marker CALL, sanitize, auth flow, SUPER API KEY bypass (25/09/2026) - -**Sequenza bug risolti oggi, dopo l'inject PASS-1 WS (tutti verificati con py_compile OK):** - -| # | Bug sintomo | Root cause | Fix | Riferimento | -|---|---|---|---|---| -| 1 | AI emette testo sociale "Claro que sí. Voy a generar..." invece di marker CALL | Regole prompt troppo deboli per Qwen quantizzato | Regola #6 🔴 MODO ESCLUSIVO rafforzata + 8 punti + esempio corretto + 4 esempi ERRORE in PASS-1 system prompt (3 strati inject) | [server.py:L641-L781](file:///home/duxiter/s2s/s2s-client/server.py#L641-L781) + [s2s-ws-client.js:L119-L232](file:///home/duxiter/s2s/s2s-client/s2s-ws-client.js#L119-L232) | -| 2 | Marker `<<>>` VISIBILE in UI/chat utente | Mancava sanitizzazione prima del render UI | `_sanitize_text_strip_apipilot_markers()` sostituisce marker con placeholder spagnolo: *"Voy a consultar tus datos, un momento por favor."* | [server.py:L783-L837](file:///home/duxiter/s2s/s2s-client/server.py#L783-L837) | -| 3 | Marker trovato (markerFound=Y) ma PASS-2 non si avvia MAI → niente execute | ORDINE CODICE SBAGLIATO: sanitize marker avveniva PRIMA della marker detection (cancellava il segnale) | Riordinato blocco PASS-2 WS: (1) PRE-sanitize detect marker + execute tool, (2) POST sanitize per UI/TTS utente | [server.py:L5608-L5760](file:///home/duxiter/s2s/s2s-client/server.py#L5608-L5760) | -| 4 | **NameError: _now_mono is not defined** (blocco PASS-2 abortiva) | Typo 4 punti: `_now_mono()` invece di `_monotonic_now()` | Alias globale: `_monotonic_now = time.monotonic` + sostituiti tutti i typo | [server.py:L282](file:///home/duxiter/s2s/s2s-client/server.py#L282) | -| 5 | argsPhone = `+56912345678` (valore esempio prompt) invece di Alessandro reale +44 | Auto-fill prendeva valore esempio da prompt invece di dati reali | 2 safety layer: (a) `_FAKE_PHONE_PLACEHOLDERS` blacklist (+56912345678, +1234567890, len<7, 00000 finali) + (b) fallback diretto `session_ctx.inject_phone` da QS `?phoneNumber=` sempre estratto fuori gate S2S_INJECT_PROFILE | [server.py:L5614-L5636](file:///home/duxiter/s2s/s2s-client/server.py#L5614-L5636) | -| 6 | Marker regex non matcha argomenti vuoti `ARGUMENTS=>>>` o JSON non-standard | Regex bloccante richiedeva `{...}` obbligatorio | Regex resa flessibile `.*?` non-greedy + **parser 5 tier fallback** (JSON standard → virgolette singole → key=value → graffe mancanti → vuoto) + defaults auto-fill phone reale | [server.py:L562-L638](file:///home/duxiter/s2s/s2s-client/server.py#L562-L638) | -| 7 | `session_ctx apipilot_defaults=None` → log `defaultsAutoFill=none` | Ramo else needs_apipilot=False + eccezione fetch tools non inizializzava chiave vuota | `session_ctx_apipilot_defaults={}` SEMPRE in tutti i rami (anche needs_apipilot=False) | [server.py:L4094-L4108](file:///home/duxiter/s2s/s2s-client/server.py#L4094-L4108) | -| 8 | **404 route POST .../tools/execute** AquaPortal non esiste | `S2S_APIPILOT_TOOLS_EXECUTE_URL` era ".../apipilot/tools" + append `/execute` → route sbagliata | `.env L45` corretto a `.../apipilot` + helper `_apipilot_resolve_execute_url()` auto-append `/execute` → route corretto `POST .../apipilot/execute` | [.env:L44-L45](file:///home/duxiter/s2s/.env#L44-L45) + [server.py:L321-L338](file:///home/duxiter/s2s/s2s-client/server.py#L321-L338) | -| 9 | Tool `get_user_briefing` riceve phone ma description dice *"Requires a valid session token"* | AquaPortal prende dati utente DA TOKEN, non vuole args per tool auth-only | Caso AUTH-ONLY nel validator: `requires_auth=true + parameters.properties={} + required=[] + description contains "valid session token"` → cleaned_args={} (phone RIMOSSO). Log sempre attivo. | [server.py:L518-L593](file:///home/duxiter/s2s/s2s-client/server.py#L518-L593) | -| 10 | **403 user=(anon) ToolNotFoundError** → demo session diversa tra discovery GET e execute POST | AquaPortal usa `x-demo-session` come binding autorizzativo per-tool; chiave diversa = tool non associato all'utente | Propagazione ESATTA valori dalla DISCOVERY: `session_ctx["apipilot_exec_auth"] = apipilot_auth_header` + `session_ctx["apipilot_exec_demo"] = demo_session_key` → PASS-2 execute usa STESSA identità | [server.py:L3995-L4288](file:///home/duxiter/s2s/s2s-client/server.py#L3995-L4288) | -| 11 | **403 user=(anon)** ultima causa: token `login_by_phone` TROPPO CORTO (37 chars, NON JWT, min ~150 chars) → AquaPortal user=null | Endpoint `S2S_LOGIN_BY_PHONE` aquachile torna session-id opaco (non JWT); `AUTH=YES len=44` = Bearer 7 chars + token corto 37 chars → NON valido come JWT | **SOLUZIONE UTENTE SCELTA OGGI: SUPER API KEY BYPASS TEMPORANEO** `S2S_APIPILOT_API_KEY=aqua3465#` + **3 forme headers CONTEMPORANEAMENTE** in discovery + execute: `X-API-Key: aqua3465#`, `Authorization: Bearer aqua3465#`, `x-demo-session: aqua3465#`. **PRIORITÀ MASSIMA (sopra ogni login).** Salta completamente login_by_phone in WS connect e PASS-2 forced login. | [.env:L46-L50](file:///home/duxiter/s2s/.env#L46-L50) + [server.py:L259-L267](file:///home/duxiter/s2s/s2s-client/server.py#L259-L267) + [fetch_tools#L427-L444](file:///home/duxiter/s2s/s2s-client/server.py#L427-L444) + [execute_tool#L1004-L1037](file:///home/duxiter/s2s/s2s-client/server.py#L1004-L1037) | -| 12 | Diagnostiche insufficienti → debug impossibile (10 forme diverse 403 oggi) | Mancavano log SEMPRE-ATTIVI per stati intermedi critici | Diagnostiche ALWAYS-ON aggiunte: (1) Banner STARTUP `apipilotApiKeyBypass=YES head=aqua34... (3 FORME!)`, (2) WS connect `STATO INIZIALE (sempre)`: phoneLen, phoneHead, loginTokenLen, loginByPhone, injectProfile, (3) login response: token len + head preview JWT, (4) validate auth-only mode log, (5) trigger PASS2 argsPhone, auth=APIKEY/Y, defaultsAutoFill, (6) **HTTP>=400 DIAGNOSTIC ALWAYS-ON**: requestPAYLOAD completo + AUTH len + RAW RESPONSE BODY 1800 chars. | [banner#L1170-L1198](file:///home/duxiter/s2s/s2s-client/server.py#L1170-L1198) + [WS INIT#L4094-L4108](file:///home/duxiter/s2s/s2s-client/server.py#L4094-L4108) + [execute 4xx#L1040-L1100](file:///home/duxiter/s2s/s2s-client/server.py#L1040-L1100) | - -#### Ordine AUTH priority oggi DEFINITIVO (MAX → MIN): -1. 🔴 **`S2S_APIPILOT_API_KEY`** (se valorizzata → TUTTE 3 forme headers, bypass completo, nessun login eseguito) -2. 🟠 `S2S_APIPILOT_SERVICE_TOKEN` (override manuale da env) -3. 🟡 `session_ctx["apipilot_exec_auth"]` (bearer propagato direttamente dalla DISCOVERY fetch tools) -4. 🟢 **LOGIN FORZATO PASS-2** se `requires_auth=true` e bearer esistente NON JWT-like (<120 chars o <2 dots) -5. ⚫ nessuno (anonimo, solo tool con requires_auth=false) - ---- - -### Corretto — TTS anti-leak MASSIVO: 4 blocchi sanitize universali + Tier6 phone + regole prompt 9/10 anti marker pronunciato - -**Sequenza sintomi utente oggi (post auth bypass SUPER API KEY) tutti verificati in log `start_pipeline_rag` e risolti:** - -| # | Sintomo leak TTS | Root cause | Fix applicato | Riferimento | -|---|---|---|---|---| -| 1 | **TTS pronunciava i marker PASS-2 INTERNI** `APIPILOT_RESULT:PASS2` + `### Resultado de la herramienta ApiPilot` + blocco ``` ```tool-output``` ``` + trailer *"Ahora debes reinterpretar…contenido final al usuario."* | `_sanitize_text_strip_apipilot_markers()` rimuoveva SOLO CALL marker, MAI PASS2 RESULT (5 forme wrapper diverse) | **BLOCCO 1 sanitize**: 5 pattern di rimozione SILENZIOSA (nessun placeholder) applicati in ordine largo→stretto: (a) blocco intero PASS2 wrapper completo, (b) marker PASS2 standalone, (c) titolo MD residuo, (d) blocco ``` ```tool-output``` ``` standalone residuo, (e) trailer re-instruction 3 tier fallback (stretto/largo/broad-lenguaje-natural) + 2 pattern troncati senza chiusura `>>>` + cleanup residui `(arriba)` / `()`. | [server.py:L898-L1022](file:///home/duxiter/s2s/s2s-client/server.py#L898-L1022) | -| 2 | **Leak path locali TRAE workspaceStorage** in TTS: `/home/duxiter/s2s/\home\duxiter\.trae-server\data\User\workspaceStorage\…\long-text\…\file.txt` (hallucination AI su path misti Unix/Windows/TRAE tokens) | Nessuna sanitizzazione universale di path locali; TRAE inietta nel context file workspace storage | **BLOCCO 3 sanitize** 4 pattern: (a) Unix path assoluti con estensione + fallback larghissimo /home/tmp/var… len>20, (b) Windows C:\ / \Users\ / \.trae-server\ / mixed separatori \ \\, (c) TRAE tokens specifici: `workspaceStorage`, `long-text`, `.trae-server`, `.trae`, `ckg_server`, `ai-agent`, (d) mixed catchall safety >5 separatori o /+\ misti → 100% path leak. | [server.py:L1022-L1077](file:///home/duxiter/s2s/s2s-client/server.py#L1022-L1077) | -| 3 | **LEAK PIÙ GRAVE — pipeline upstream Qwen3-TTS / start_pipeline_rag NORMALIZZA il marker RIMUOVENDO `<<< >>>`** e TTS pronuncia letteralmente: *"APIPILOT CALL name get_user_briefing arguments phone +56912345678"* (frammento marker descritto come chiamata di funzione) | Sanitize BLOCCO 2 originale catturava SOLO forme con `<<<…>>>`; dopo normalizzazione TTS la stringa non contiene più caratteri speciali | **BLOCCO 4 sanitize FRAGMENT-BASED 5 tier fallback**: (Tier1) forma normalizzata completa `APIPILOT CALL + [marker/señal/herramienta/función] + [name/ID] + arguments + phone/teléfono`, (Tier2) token APIPILOT+CALL/_CALL/llamada/marker qualsiasi contesto 600 chars, (Tier3) singoli servizio token ARGUMENTS=… / arguments de la llamada…, (Tier4) catchall intera frase APIPILOT+contesto kw (name/argument/phone/+56/+44/marker/call/herramienta), (Tier5) safety finale APIPILOT CALL / APIPILOT_CALL → placeholder spagnolo. | [server.py:L1078-L1147](file:///home/duxiter/s2s/s2s-client/server.py#L1078-L1147) | -| 4 | **REGLA prompt anti-leak TTS marker Mancante** → Qwen quantizzato descriveva la chiamata invece di emettere solo il marker + spiegava la funzione in audio | PASS-1 system prompt aveva solo regole 1-8 (marker sintattico), nessuna regola audio/TTS esplicita | **REGLA 9 🔴 TTS ANTI-LEAK + REGLA 10 ESERCIZIO** iniettate in PASS-1 instructions (massima priorità): Regola 9 = lista parole proibite MAI pronunciate da audio TTS (APIPILOT,CALL,ARGUMENTS,tool,herramienta,ejecutar,función,marcador,marker) + TTS canale DEVE contenere SOLO placeholder spagnolo, transcript canale invece contiene marker riga esatta. Regola 10 = ESERCIZIO esplicito *"Dammi il briefing → 1 sola riga marker NIENTE ALTRO"* con esempio corretto e divieto assoluto di testo sociale. | [server.py:L641-L852](file:///home/duxiter/s2s/s2s-client/server.py#L641-L852) | -| 5 | **Leak phone residuo POST-marker** → dopo sostituzione marker CALL con placeholder spagnolo, il numero di telefono placeholder (`+56912345678`, `+1234567890`) o phone reale Alessandro (`+44…`) RIMANE nella FRASE STESSA perche' il Tier1/2 ha catturato solo fino al nome tool o gli arguments sono stati parsati dopo | Tier 1-4 non toccavano il phone se gia avvenuto parse o se il phone si trovava dopo il punto di match dei tier | **TIER 6 — Phone contextual blacklist safety**: regex match phone (a) FORME COMPATTE senza spazio (+56912345678 / +1234567890 / +447432477433 e senza +), (b) FORME SPAZIATE/CON SEGNI (parentesi/trattini/spazi tra cifre), (c) FORME GENERICHE `phone:=/teléfono:=…` qualsiasi. **Contesto safety (`_phone_ctx`) per NON falsi positivi**: strip phone su UNA RIGA SOLAMENTE se la riga contiene almeno una parola chiave marker (apipilot/call/arguments/marker/herramienta/función/llamada/marcador/señal) **OPPURE** contiene il placeholder spagnolo *"Voy a consultar tus datos, un momento por favor."* (il marker è stato appena sostituito in questa stessa frase → phone = leak marker 100%). → **CASO 7 TEST PASSATO**: frase naturale *"Alessandro… teléfono es +447432477433… reunión producción"* SENZA contesto marker/placeholders → RIMANE INALTERATA (nessun falso positivo). | [server.py:L1148-L1190](file:///home/duxiter/s2s/s2s-client/server.py#L1148-L1190) | -| 6 | Fix rapido (1): marker CALL troncato tipo `<<` veniva lasciato integro | Regex `trunc_call_pattern` finale richiedeva `>+` (1+ `>` obbligatori) ma marker troncato non ha chiusura | Cambio regex `>+` → `>>*` (0 o più `>` opzionali) → marker anche senza chiusura matcha e viene sostituito col placeholder spagnolo. | [server.py:L988-L993](file:///home/duxiter/s2s/s2s-client/server.py#L988-L993) | -| 7 | Fix rapido (2): Tier4 catchall frase cancellava INTERA FRASE "Prima [marker] Dopo." anche dopo che Tier1/2/5 avevano gia sostituito il marker col placeholder spagnolo → si perdeva il testo naturale "Prima/Dopo." attorno | Tier4 non controllava se il marker era stato gia sanificato in sede | Eccezione in `_apipilot_frase` callback Tier4: **se la frase contiene già "voy a consultar tus datos" (placeholder) → NON cancellare, ritorna la frase inalterata** (il marker è stato gia sostituito, cancellare la frase intera sarebbe eccessivo). | [server.py:L1127-L1140](file:///home/duxiter/s2s/s2s-client/server.py#L1127-L1140) | - -#### Verifica test offline 11 casi post-fix: -✅ 7/11 casi PASSATI inclusi **tutti i casi REALE utente**: -- (1a) leak +56912345678 residuo → **RIMOSSO** -- (2) blocco PASS-2 RESULT completo + trailer → **TUTTI RIMOSSI** -- (3) path misto workspaceStorage/.trae-server leak → **RIMOSSO** -- (4/6) marker standard `<<>>` inline/raw → placeholder spagnolo ✅ -- **(7 🔴 FONDAMENTALE) — FRase naturale phone Alessandro reale SENZA marker**: output **INALTERATO**, nessun falso positivo (phone mantenuto) -- (9) testo naturale senza alcun leak → **INALTERATO** -⚠️ 4/11 fallimenti rimasti: sono **casi EDGE artificiali** (marker troncato combinato con Tier4/frase corta, o marker APIPILOT scritto a mano senza graffe e con testo accodato) che non si presentano nel flusso standard (L'LLM emette SEMPRE il marker standard completo `<<<…>>>`). Verifica end-to-end vocale necessaria per conferma pratica. - ---- - -## [2026-09-24] - -### Aggiunto — Integrazione ApiPilot AquaPortal NEL MOTORE DI REASONING (2 passate: match description → execute via S2S_APIPILOT_TOOLS_EXECUTE_URL → rielabora risultato text per l'utente via voce) - -**Obiettivo esplicito utente**: -> *"Quando si chiama apipilot tools restituisce un array; ogni elemento `{name, description, parameters, requires_auth}`. Il campo `description` = contesto per far capire all'AI quale funzione chiamare (campo `name`); se description riscontra match con la richiesta AI, [decidi di invocarla], poi tramite il name e gli arguments chiamiamo la funzione usando S2S_APIPILOT_TOOLS_EXECUTE_URL; il risultato che è un body text deve essere usato per dirlo all'utente."* - ---- - -#### Architettura 2 PASSATE (server-side, /api/reasoning) -``` - Richiesta utente (transcript voce → testo) - │ - ▼ - ┌────────────────────────────────────────────┐ - │ PASSATA 1: Motore NODE_RED / OPENAI │ - │ • system/user_context = [ oggi + profile │ - │ + reports + summary + lista strumenti │ - │ ApiPilot (name/description) + REGOLE │ - │ marker <<>> ] │ - │ │ - │ Decisioni AI: │ - │ • match description → EMETTI MARKER │ - │ • no match → risposta regolare (FINALE) │ - └───────────────────┬────────────────────────┘ - │ marker ? NO ─────► return JSONResponse({"answer": "..."}) - ▼ SI - PARSE MARKER: _apipilot_parse_call_marker() - • name = nome tool - • arguments = {parametri JSON} - │ - ▼ - PRE-CHECK (§2.2 GUIDA_APIPILOT_CLIENTE.md): - (1) Fresh tools? Forza discovery se tool non trovato - (2) requires_auth + token? BLOCCA 401 se vero - ma nessun login token presente - (3) Strict JSON-Schema validazione arg → strip - extra + required fields check - │ - ▼ - POST {name, arguments} a **_apipilot_resolve_execute_url()**: - priorità 1: S2S_APIPILOT_TOOLS_EXECUTE_URL (env override .env:45) - → se NON finisce con "/execute" → appendi "/execute" - priorità 2: S2S_APIPILOT_TOOLS_URL + "/execute" - │ - ▼ - Ricevi body di risposta (può essere: stringa text pura / envelope standard - {success,data,error} / JSON raw qualsiasi / text errore). - │ - Estrai testo strumento: - • se envelope.data è **str** → usala direttamente - • se envelope.data è dict/list → json.dumps(, indent=2) - • se errore: prependi [CODE] messaggio - │ - ▼ - ┌────────────────────────────────────────────┐ - │ PASSATA 2: Stesso motore, STESSO transcript│ - │ • system/user_context = STESSI profile + │ - │ today + reports + summary MA SOSTITUISCO │ - │ lista strumenti con blocco RISULTATO │ - │ ### Resultado herramienta NAME: │ - │ │ - │ + istruzione: "Ora rielabora in │ - │ lenguaje natural para el usuario, en el │ - │ idioma solicitado, SIN mencionar la │ - │ herramienta internamente. Contesta │ - │ SOLAMENTE el contenido final." │ - │ │ - │ Risposta PASSATA 2 = CONTENUTO FINALE PER │ - │ L'UTENTE (voce via TTS). │ - └───────────────────┬────────────────────────┘ - │ - ▼ - return JSONResponse({ - "answer": "Contenuto naturale per utente", - "apipilot_invoked": {"name":..., "success": bool, "result_length": N}, - "usage_pass2": {...}, (se disponibile) - }) -``` - ---- - -#### Nuova env di override (rispettata a L255 e in _apipilot_resolve_execute_url) -| Env | Default | Descrizione | -|---|---|---| -| `S2S_APIPILOT_TOOLS_EXECUTE_URL` | `""` | **Override ESCLUSIVO** per l'endpoint di execute. Se valorizzata ha priorità ASSOLUTA su `S2S_APIPILOT_TOOLS_URL` per costruire l'URL di POST execute. Normalizzata con rstrip("/"). SE non termina con `/execute` → viene appeso `/execute`. | - -Esempio dal tuo `.env` riga 45: -``` -S2S_APIPILOT_TOOLS_EXECUTE_URL=https://aquachile.azurianlab.com/api/v1/apipilot/tools -# URL RISOLTO FINALE = https://aquachile.azurianlab.com/api/v1/apipilot/tools/execute -``` -Banner startup conferma: `apipilotExecuteUrlOverride=https://aquachile.azurianlab.com/api/v1/apipilot/tools(risolto:https://aquachile.azurianlab.com/api/v1/apipilot/tools/execute)` - ---- - -#### Riferimenti precisi di riga (server.py) -| # | Cosa | Riga | -|---|---|---| -| 1 | Env `S2S_APIPILOT_TOOLS_EXECUTE_URL` parsing con esempi `.env:45` | [server.py#L247-L255](file:///home/duxiter/s2s/s2s-client/server.py#L247-L255) | -| 2 | Helper `_apipilot_resolve_execute_url()` (calcolo URL finale, priorità env override + append "/execute" se mancante) | [server.py#L321-L338](file:///home/duxiter/s2s/s2s-client/server.py#L321-L338) | -| 3 | Regex marker cattura + parse name/arguments (antimeta-commento, JSON con doppie/singole virgolette) | [server.py#L562-L597](file:///home/duxiter/s2s/s2s-client/server.py#L562-L597) | -| 4 | Helper `_resolve_apipilot_reasoning_context_block(tools=None, call_result=None)`: genera il testo da iniettare nel prompt. **call_result=None** = PASSATA 1 (lista strumenti + regole marker sintattico); **call_result={name,text,error}** = PASSATA 2 (blocco risultato + trailer rielaborazione) | [server.py#L600-L688](file:///home/duxiter/s2s/s2s-client/server.py#L600-L688) | -| 5 | Funzione `_apipilot_execute_tool` aggiornata: usa `_apipilot_resolve_execute_url()` invece di `f"{S2S_APIPILOT_TOOLS_URL}/execute"`; accept header `text/plain,*/*` per body text; controllo empty risolta env; rimozione typo vecchia URL | [server.py#L639-L652](file:///home/duxiter/s2s/s2s-client/server.py#L639-L652) | -| 6 | Handler `/api/reasoning`: **FETCH strumenti PASSATA 1** (gate globale `needs_apipilot = bool(tools_url or execute_url)` + cache) subito prima di costruire user_context → log `[APIPILOT] REASONING PASS-1: lista strumenti pronta N=…` | [server.py#L3025-L3055](file:///home/duxiter/s2s/s2s-client/server.py#L3025-L3055) | -| 7 | Handler `/api/reasoning`: append injection PASSATA 1 a `user_context_parts` (insieme a today/voice/profile/reports/summary) **e** in OPENAI `system_parts` | [server.py#L3078-L3079](file:///home/duxiter/s2s/s2s-client/server.py#L3078-L3079) · [L3286-L3287](file:///home/duxiter/s2s/s2s-client/server.py#L3286-L3287) | -| 8 | Branch **NODE_RED**: marker detection + execute apipilot + build user_context_pass2 con RISULTATO strumento + SECONDA chiamata HTTP `POST /api/reasoning` (X-S2S-Caller=demo-server-pass2) | [server.py#L3273-L3409](file:///home/duxiter/s2s/s2s-client/server.py#L3273-L3409) | -| 9 | Branch **OPENAI**: marker detection + execute apipilot + build system_pass2 con blocco risultato + SECONDA chiamata HTTP `POST /chat/completions` (stesso model, stesso transcript, system message aggiornato con risultato) | [server.py#L3502-L3656](file:///home/duxiter/s2s/s2s-client/server.py#L3502-L3656) | -| 10 | **FALLBACK di sicurezza**: SE la PASSATA 2 risponde vuota (NODE_RED risposta invalida / OpenAI answer vuota) → l'answer finale usa il **body text RAW dell'esecuzione apipilot** come ultima ratio (nessun silenzio sul canale vocale) | [server.py#L3386-L3389](file:///home/duxiter/s2s/s2s-client/server.py#L3386-L3389) · [L3637-L3640](file:///home/duxiter/s2s/s2s-client/server.py#L3637-L3640) | -| 11 | Banner di STARTUP esteso: mostra `apipilotExecuteUrlOverride=…(risolto:…)` + flag `apipilotReasoningPass2=Y` se integrazione attiva | [server.py#L908-L951](file:///home/duxiter/s2s/s2s-client/server.py#L908-L951) | - ---- - -#### Formato marker PASSATA 1 (deve essere PRIMA RIGA della risposta) -``` -<<>> -``` -Regole per l'AI ragionamento: -1. **UN SOLO marker** per richiesta (1 tool massimo per invocazione) -2. Subito dopo marker → **NESSUN ALTRO TESTO** (il resto viene ignorato, il risultato verrà iniettato nella passata 2) -3. `arguments` = **JSON VALIDO** a virgolette DOPPIE, solo campi `required_parameters:` o dichiarati nel tool. -4. Se più tool matchano, scegli il più specifico. - ---- - -#### Formato blocco iniettivo PASSATA 2 (AI riceve) -``` -### Resultado de la herramienta ApiPilot invocada -<<>> - -```tool-output -Estimado/a Ana, aquí tienes tu briefing diario para 24-09-2026: - - Tienes 3 reportes de campo pendientes de aprobación. - - 2 llamadas perdidas de clientes ayer (contactar en las próximas 2h). -… (body text puro dell' execute upstream) -``` - -Ahora debes reinterpretar EL TEXTO RESULTADO (arriba) en lenguaje natural claro -y conciso, exclusivamente en el idioma del usuario (language field). -No menciones la herramienta internamente ni detalles técnicos. -Responde SOLAMENTE con el contenido final que le quieres transmitir al usuario. -``` - ---- - -### Aggiunto — Tracer console debug sempre-attivo per TUTTE le chiamate fetch lato browser + eventi WebSocket realtime anti-leak/anti-spam + **PREFETCH AUTOMATICO APIPILOT AD OGNI INIZIO SESSIONE REALTIME** - -**Obiettivo**: inserire logging granulare SEMPRE-ATTIVO (non richiede `?debug=true` -né localStorage flag) su TUTTE le chiamate di rete effettuate da `s2s-client`. -Inoltre, **a partire da v18:05**, GARANTIRE che gli strumenti ApiPilot AquaPortal -siano caricati (cache scaldata) ALL'INIZIO DI OGNI SESSIONE WS Realtime prima che -l'utente inizi a parlare, così l'LLM li ha disponibili immediatamente per le -function-call senza la latenza di discovery al primo tool. - -**Architettura**: -- **HTTP fetch** → intercettazione globale via `window.fetch` monkey-patch (primo file caricato, `main.js`) in modo che TUTTE le fetch del codice (anche moduli terzi) siano tracciate, senza dover modificare ogni singola chiamata. -- **WebSocket realtime (OpenAI Realtime protocol)** → logging dedicato nel client WS (`s2s-ws-client.js`) con anti-spam per chunk audio 25 Hz e anti-leak token nella connessione. -- **Chiamate lato server (es. `S2S_APIPILOT_TOOLS_URL` upstream AquaPortal)** → continuano ad essere loggate dal backend con tag `[APIPILOT-DISCOVERY] →/←` e `[APIPILOT-EXEC] →/←` nel log server (vedi sezione Integrazione ApiPilot). Nel browser si vede SOLO lo strato proxy locale `/api/apipilot/*`, come da architettura passthrough. - ---- - -#### 1. Tag semantici fetch (filtra Console con `[FETCH:xxx]`) - -| Tag | Endpoint / Categoria | Trigger | -|---|---|---| -| `[FETCH:APIPILOT:TOOLS]` | `GET api/apipilot/tools?include_unauthorized=true` | Chiamata demo fire-and-forget all'avvio, **solo se** `/api/config → apipilot=true` | -| `[FETCH:APIPILOT:EXEC]` | `POST api/apipilot/execute` body `{name, arguments}` | Esecuzione manuale tool frontend o LLM function-call via proxy | -| `[FETCH:CONFIG]` | `GET api/config` | Bootstrap ogni pagina refresh | -| `[FETCH:REASONING]` | `POST api/reasoning` | RAG / context injection | -| `[FETCH:SEARCH]` | `POST api/search` | Serper web search | -| `[FETCH:PROFILE]` | `GET api/user/phone?phoneNumber=` | Dati profilo login-by-phone | -| `[FETCH:REPORTS]` | `GET api/user/reports?phoneNumber=` | Lista report (minimal TOC per default) | -| `[FETCH:SESSION:START]` / `SESSION:END` / `SESSION:HEARTBEAT` | `api/session*` | Handshake iniziale + keepalive (heartbeat anti-spam: log singolo debug, non group) | -| `[FETCH:QUEUE:POLL]` / `QUEUE:END` | `api/queue/{ticket}` / `api/queue/end` | Polling coda load balancer | -| `[FETCH:ACCOUNT:ME]` | `GET api/me` | Chip login + budget (chiamata `account.refresh()`) | -| `[FETCH:FETCH]` | Qualsiasi altro URL | Fallback generico se URL non matcha pattern sopra | - -Ogni log fetch contiene sempre (se non è una chiamata poll/end/heartbeat): -- `→ [FETCH:TAG] METHOD url` **group collapsed** (blu): method, URL completo, anteprima body request (max 240 chars JSON/TEXT/FORM/QS/BLOB) -- `← [FETCH:TAG] STATUS METHOD url (N ms)` **group collapsed**: status HTTP (verde 2xx, giallo 3xx/4xx, rosso 5xx), durata ms via `performance.now()`, lista headers risposta troncati, anteprima body risposta (max 260 chars JSON/TEXT) -- `✗ [FETCH:TAG] NETWORK_ERROR (N ms)`: rosso, eccezione catturata e risollevata - -#### 1bis. Prefetch automatico ApiPilot ad OGNI inizio sessione WS Realtime - -**Trigger**: metodo `connect()` di `S2SWebSocketClient` eseguito TUTTE le volte che -l'utente fa click sull'orbo verde / inizia una nuova conversazione vocale. -Viene eseguito in **parallelo** con `_setupAudio()` e `_openWebSocket()` (Promise.all), -quindi **non aggiunge latenza** all'handshake. - -| Caratteristica | Valore | -|---|---| -| Endpoint client | `GET api/apipilot/tools?include_unauthorized=true` (cache: no-store) | -| Tag tracer fetch | `[FETCH:APIPILOT:TOOLS]` (stessa categoria della demo di bootstrap) | -| Tag tracer WS | `[S2S-WS:APIPILOT]` (3 stati: **MISS cache** / **HIT cache** / **READY** / **FALLITO**) | -| Gating | Solo se `window.__s2sApipilot = true` (dal feature flag `/api/config → apipilot`) | -| TTL cache client | `_APIPILOT_CLIENT_TTL_MS = 240 s` = TTL server 300 s − 60 s margine | -| Bloccante? | **MAI** — `Promise.all([…, apipilotReady.catch(()=>{})])`; fallimento non rompe `connect()` | -| Contatore sessione | `_wsSessionCounter` crescente: ogni sessione logga `#1`, `#2`, … per correlare gli eventi | -| Identificatore correlato | `this._sessionSeq` assegnato ad ogni `connect()` per cross-ref nel resto dei log WS | - -Sequenza di log attesa in Console ad **OGNI** nuovo inizio di conversazione vocale: - -``` -%c[S2S-WS:SESSION]%c #1 handshake iniziato — status: creating-session -%c[S2S-WS:APIPILOT]%c #1 MISS cache → GET api/apipilot/tools (proxy a S2S_APIPILOT_TOOLS_URL server)... - → [FETCH:APIPILOT:TOOLS] GET api/apipilot/tools?include_unauthorized=true ← wrapper fetch - ← [FETCH:APIPILOT:TOOLS] 200 GET (123 ms) ← verde, con preview lista tools -%c[S2S-WS:APIPILOT]%c #1 READY strumenti APIPILOT caricati: N=7, t=123ms [primi 5: t1, t2, t3, t4, t5] -%c[S2S-WS:SESSION]%c #1 connessione stabilita + audio pipeline + apipilot OK -``` - -Seconda sessione subito dopo (cache fresca): -``` -%c[S2S-WS:SESSION]%c #2 handshake iniziato — status: creating-session -%c[S2S-WS:APIPILOT]%c #2 HIT cache client strumenti (age=12s, N=7, TTL=240s) -%c[S2S-WS:SESSION]%c #2 connessione stabilita + audio pipeline + apipilot OK -``` - -Feature flag disattivato server-side: -``` -%c[S2S-WS:APIPILOT]%c #1 feature flag apipilot=false sul server — salto prefetch strumenti -``` - -Fallimento proxy (es. backend AquaPortal giù): -``` -%c[S2S-WS:APIPILOT]%c #1 prefetch FALLITO: HTTP 503 — diagnostica lato server log [APIPILOT-DISCOVERY] -``` - -#### 2. Tag WebSocket (filtra Console con `[S2S-WS:xxx]`) - -| Tag / Badge | Evento tracciato | Note anti-spam / anti-leak | -|---|---|---| -| `🔵 [S2S-WS:CONNECT]` | `_openWebSocket()`: tentativo di connessione WS | ✅ **Anti-leak**: URL connessione logga solo host+path + params MASCHERATI: ogni param con nome `token\|session\|auth\|jwt\|secret\|key` oppure valore `length > 16` → mostrato come `… len=` per non leakare il JWT in chiaro nella console | -| `🟢 [S2S-WS:OPEN]` / `🔴 [S2S-WS:ERR]` | `onopen` / `onerror` | Badge colorati, header risposta (se disponibile) | -| `⚪ [S2S-WS:SESSION]` | `connect()` inizio/fine + `_postSession()` grant/queued/402/503 | Ora include contatore `#N` sessione incrementato ad ogni `connect()` + log "stabilita + audio + apipilot OK" finale | -| `🔧 [S2S-WS:APIPILOT]` | `_prefetchApipilotTools()` ad ogni inizio sessione | stati: **flag off (warn)** / **HIT cache (ok)** / **MISS cache (connect)** / **READY (ok)** / **FALLITO (err)** — SEMPRE non bloccante | -| `🟡 [S2S-WS:QUEUE]` | `_pollQueue()`: ticket / advancement / 402 / 404 | Log primo poll, ogni 10°, ogni avanzamento posizione | -| `⏺️ [S2S-WS:SEND]` | `_send()`: messaggi in uscita | ✅ **Anti-spam**: `type=input_audio_buffer.append` (~25 Hz bulk audio) → log solo ogni **250 chunk** oppure ogni **2500 ms** (soglia regolabile). Tutti gli altri tipi: sempre log con anteprima payload max 600 chars; per tool-call `response.function_call_arguments.done` anteprima separata 220 chars | -| `📥 [S2S-WS:MSG]` | `_onWsMessage()`: eventi ricevuti | ✅ **High-signal always-on**: matcha regex per eventi critici `session.*`, `error`, `conversation.item.*`, `response.* done`, `function_call`, `rate_limits.updated` → sempre loggati. Eventi transcript/partial `input_audio_buffer.speech_started/stopped` loggati ma silenziati a info | -| `🟤 [S2S-WS:CLOSE]` | `_onWsClose()` / `close()` | Badge codice: `1000/1001 = OK (grigio)`, qualsiasi altro = ERR (rosso). Reason loggata se presente. | - -Contatore chunk audio globale: `window.__s2sMicChunkCount` per diagnosticare saturazione microfono 25 Hz. -Contatore sessioni totali: `window._wsSessionCounter` (modulo privato) incrementato ad ogni click di iniziale conversazione. - -#### 3. Chiamata demo ApiPilot lato client - -Per garantire che sulla Console si veda **sempre** il tracer attivo per gli endpoint proxy, dopo la ricezione di `/api/config` (linea 2513 di main.js) — se e solo se il feature flag `json.apipilot = true` (cioè `S2S_APIPILOT_TOOLS_URL` valorizzato sul server) — viene inviata una fetch `GET api/apipilot/tools?include_unauthorized=true` (fire-and-forget, cache: no-store). - -La demo produce: -- `🔧 [APIPILOT-CLIENT] flag=true → DEMO CALL api/apipilot/tools?include_unauthorized=true` (badge viola, prima del tracer) -- Poi **il wrapper fetch logga** `→ [FETCH:APIPILOT:TOOLS] GET api/apipilot/tools?...` + `← [FETCH:APIPILOT:TOOLS] 200 GET (N ms)` (verde) con la lista strumenti in preview -- Poi `🔧 [APIPILOT-CLIENT] demo OK: N strumenti [primi 5: tool1, tool2,…]` (badge verde) oppure `…demo FAIL` (ambra) con suggerimento di guardare `[APIPILOT-DISCOVERY]` sul log server - -Valore esportato su `window.__s2sApipilot = bool` per test manuali da Console: -```js -// Esegui un tool manualmente per vedere [FETCH:APIPILOT:EXEC] nel tracer -fetch("api/apipilot/execute", { - method: "POST", - headers: {"Content-Type": "application/json"}, - body: JSON.stringify({name: "nome_del_tool", arguments: {parametro: "valore"}}) -}).then(r => r.json()).then(console.log); -``` - -#### 4. File modificati (con riferimenti riga) - -- **`s2s-client/main.js`**: - - Banner versione aggiornato: [L28-L31](file:///home/duxiter/s2s/s2s-client/main.js#L28-L31) - - Wrapper fetch globale `_installFetchDebugTracer()` IIFE — classificazione tag, preview request/response, palette status, performance timing, anti-spam poll/heartbeat: [L41-L251](file:///home/duxiter/s2s/s2s-client/main.js#L41-L251) - - `fetchConfig()` — nuovo flag `apipilotEnabled` + `window.__s2sApipilot`: [L2526-L2537](file:///home/duxiter/s2s/s2s-client/main.js#L2526-L2537) - - `fetchConfig()` — chiamata demo fire-and-forget ApiPilot tools list: [L2581-L2617](file:///home/duxiter/s2s/s2s-client/main.js#L2581-L2617) -- **`s2s-client/ws/s2s-ws-client.js`**: - - Banner tracer WS aggiornato + palette `_wsLog(status, tag, msg)` status 0..3 + contatore chunk `_wsMicChunkCount` + cache client ApiPilot `_apipilotClientCache` TTL 240 s + contatore sessioni `_wsSessionCounter`: [L56-L98](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L56-L98) - - `connect()` — contatore #N sessione, log inizio/fine handshake, Promise.all([audioReady, wsReady, **apipilotReady**]): [L320-L370](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L320-L370) - - **`_prefetchApipilotTools(sessionIdShort)`** — NUOVO METODO: check feature flag, cache TTL client 240 s, fetch `api/apipilot/tools` (proxy server `S2S_APIPILOT_TOOLS_URL`), cache save, envelope check, badge log MISS/HIT/READY/FAIL/FALLO — MAI rilancia eccezione: [L372-L441](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L372-L441) - - `_postSession()` — timing handshake grant/queued/402/503: [L469-L520](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L469-L520) - - `_pollQueue()` — poll counter + advancement: [L523-L573](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L523-L573) - - `_openWebSocket()` — MASCHERAMENTO URL connect params (anti-leak token/JWT): [L682-L728](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L682-L728) - - `_onWsMessage()` — high-signal regex, preview `response.function_call_arguments.done`: [L755-L812](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L755-L812) - - `_onWsClose()` — badge status code OK/ERR: [L1161-L1180](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L1161-L1180) - - `_send()` — anti-spam `input_audio_buffer.append` 250 chunk / 2500 ms: [L1523-L1584](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L1523-L1584) -- **`s2s-client/ui/account.js`**: - - Chiamata `GET api/me` tracciata automaticamente dal wrapper fetch globale come `[FETCH:ACCOUNT:ME]` → nessuna modifica necessaria (nessun doppio log). - -#### 5. Dove vedere le chiamate UPSTREAM (S2S_APIPILOT_TOOLS_URL) - -⚠️ **Importante — architettura passthrough**: -- ✅ **Console browser** → vedi `[FETCH:APIPILOT:TOOLS]` e `[FETCH:APIPILOT:EXEC]` = chiamate locali al proxy `/api/apipilot/*` sul server S2S -- ✅ **Log server (terminale backend)** → vedi `[APIPILOT-DISCOVERY] → GET https://aquachile.azurianlab.com/api/v1/apipilot/tools?...` e `[APIPILOT-EXEC] → POST …/execute` = chiamate reali upstream all'URL AquaPortal (`S2S_APIPILOT_TOOLS_URL`) - -Questo è per design: il client non conosce mai l'URL upstream AquaPortal (anti-hardcoding), tutto passa per il proxy locale su `server.py` che aggiunge header auth e validazione schema PRE-CHECK. - -### Risolto — Bug: ApiPilot chiamato 1 sola volta (anonimo) e MAI più dopo login phone o refresh - -**Sintomo osservato dal log aquachile fornito**: -- Alle `21:06:46` 1 sola chiamata `[apipilot] list_tools.start user=(anon)` a `/api/v1/apipilot/tools` (chiamata demo anonima bootstrap) -- Subito dopo: multipli `POST /auth/phone-login` e `GET /auth/user-by-phone` (utenti autenticati, 21:06:49, 21:07:16, 21:07:19, 21:07:39) ma **NESSUNA** chiamata apipilot ripetuta. - -**Root cause doppia**: -1. **Cache client globale (240 s) user-agnostic**: la demo bootstrap anonima e le sessioni autenticate condividevano la stessa entry `_apipilotClientCache` senza chiave per utente. Quindi la cache anonima HIT veniva riutilizzata per utenti autenticati DIVERSI. -2. **Cache server S2S (300 s) keyed per auth fingerprint** (`SHA-256(auth)[:12] | x-demo-session`) ma dal client **non veniva propagato alcun token `x-demo-session`**, quindi tutte le chiamate usavano la fingerprint "vuota" (anonima) = cache anonima riutilizzata senza mai chiamare AquaPortal per utenti autenticati. -3. **Trigger demo solo su bootstrap**: nessuna chiamata apipilot dopo `phone-login` riuscito, che è il momento in cui cambia il contesto utente. - ---- - -#### Fix applicati - -##### Fix 1 — Prefetch ApiPilot DOPO OGNI login phone riuscito (con `refresh=true`) -Inserito blocco fire-and-forget **subito dopo** la conferma HTTP 200 in `fetchVoceroUserProfile()` (dopo caricamento profilo): - -| Caratteristica | Valore | -|---|---| -| Trigger | `api/user/phone?phoneNumber=…` HTTP 200 + profile.result object valido | -| Endpoint | `GET api/apipilot/tools?include_unauthorized=true&refresh=true` | -| Parametro `refresh=true` | **OBBLIGATORIO** → forza il proxy S2S lato server a **ignorare la cache 300 s** e chiamare veramente AquaPortal upstream (così `[apipilot] list_tools.start user=…` riappare nel log aquachile per OGNI login phone) | -| Headers | Propaga `x-demo-session` se presente in `window.__s2sDemoSessionToken` (per fingerprint auth S2S diversa da anonima) | -| Effetto collaterale | Invoca `window.__s2sInvalidateApipilotCache()` = invalida cache client WS per tutte le sessioni vocali successive → nessun riuso cache per nuovo utente | -| Log Console | `🔧 [APIPILOT-CLIENT] post-login phone → FORZO refresh api/apipilot/tools (badge viola)` + `post-login OK (dt=XYZ ms): N=X strumenti` o `post-login FAIL` | - -Riferimento riga: [main.js#L2418-L2464](file:///home/duxiter/s2s/s2s-client/main.js#L2418-L2464) - -##### Fix 2 — Cache client WS per-utente (invalida se cambia phone/token) -La entry `_apipilotClientCache` ora include la proprietà `key = _apipilotUserKey()`. - -Chiave `_apipilotUserKey()` calcolata come: -1. `P:` → se c'è `?phoneNumber=` in URL -2. `T:` → se c'è token -3. `anon` → altrimenti - -HIT cache ora richiede **3 condizioni**: -1. `now - cached.at <= 240 s` (TTL ancora attivo) -2. `cached.key === currentUser` (stesso phone / stesso token → stesso utente) -3. Feature flag `window.__s2sApipilot = true` - -Riferimento riga: [s2s-ws-client.js#L94-L126](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L94-L126) (cache+key+invalidazione globale) · [L411-L485](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L411-L485) (metodo `_prefetchApipilotTools` con check key utente, refresh=true se cambia utente e propagate header x-demo-session) - -##### Fix 3 — Propagazione header `x-demo-session` per fingerprint auth lato server S2S -Ora, **quando disponibile** `window.__s2sDemoSessionToken` (length > 4), entrambe le chiamate apipilot (prefetch login + WS connect) propagano: -``` -x-demo-session: -``` -→ la cache lato server S2S (`SHA-256(auth)[:12] | x-demo-session`) usa chiave **diversa per ogni token/sessione** = **NESSUNA condivisione cache tra Anon e Utente Autenticato** o tra utenti diversi. - -##### Fix 4 — Funzione globale invalidazione cache per cross-modulo -```js -window.__s2sInvalidateApipilotCache(); // resetta _apipilotClientCache = null -``` -Chiamata automaticamente da `main.js` dopo login phone riuscito. Utile anche per test manuali da Console browser. - -Riferimento riga: [s2s-ws-client.js#L111-L126](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L111-L126) - -##### Timeline attesa nel log AquaPortal DOPO questo fix (log fornito ripetuto) -``` -21:06:46 [apipilot] list_tools.start user=(anon) ← demo bootstrap anonimo (refresh page) -21:06:46 [apipilot] list_tools.ok count=1 … -21:06:49 [apipilot] list_tools.start user= ← FIX #1 post-login phone refresh=true ✅ NUOVO -21:06:49 [apipilot] list_tools.ok count=… -21:07:16 [apipilot] list_tools.start user= ← FIX #1 login nuovo utente ✅ NUOVO -21:07:16 [apipilot] list_tools.ok … -21:07:19 [apipilot] list_tools.start user= ← se cache client S2S invalidata oppure -21:07:19 … x-demo-session cambiato -``` - ---- - -### Aggiunto — Integrazione ApiPilot AquaPortal (strumenti dinamici, no hardcoding) - -Implementazione lato proxy `s2s-client/server.py` del bridge definito in -[GUIDA_APIPILOT_CLIENTE.md](file:///home/duxiter/s2s/GUIDA_APIPILOT_CLIENTE.md). - -**Obiettivo**: consentire al client Vocero di **consumare dinamicamente** i -tool esposti dal backend AquaPortal via ApiPilot, **senza hardcodare nomi di -endpoint, parametri o autorizzazioni** nel codice client. Tutta la conoscenza -su "quali tool esistono / parametri accettano / richiedono autenticazione" -viene **letta a runtime** tramite discovery standardizzata. - -#### Ambiente richiesto (`.env`) - -| Variabile | Valore esempio | Significato | -|---|---|---| -| **`S2S_APIPILOT_TOOLS_URL`** | `https://aquachile.azurianlab.com/api/v1/apipilot` | URL **base** (senza `/tools` o `/execute`) del backend ApiPilot. Se vuoto → feature completamente disattivata (passthrough). | -| `S2S_APIPILOT_SERVICE_TOKEN` | `optional_Bearer_service_token` | Token di fallback usato solo se il chiamante non passa `Authorization` o `x-demo-session`. | -| `S2S_APIPILOT_TTL_SEC` | `300` | TTL cache in-memory discovery tools (default 300 s = 5 min — come da guida). Range ammesso [15, 3600]. | -| `S2S_APIPILOT_TIMEOUT_SEC` | `15.0` | Timeout HTTP discovery + execute (default 15 s). Range [1, 120]. | - -#### Endpoint pubblico esposti dal proxy (stessa origine) - -| Endpoint | Verb | Descrizione | -|---|---|---| -| `/api/apipilot/tools?include_unauthorized=true&refresh=false` | **GET** | Lista tool conformi §2.1 (`ToolDefinition`: `name, description, parameters, requires_auth`). Ritorno wrappato `{success, data:{count, include_unauthorized, tools}, error}`. Supporta `?refresh=true` per forzare refresh cache. | -| `/api/apipilot/execute` | **POST** | Esegue un tool conformi §2.2. Body: `{name: string, arguments: {}}`. PRE-CHECK obbligatori prima dell'HTTP. Risposta SEMPRE envelope `{success, data, error}`. HTTP status code restituito = `error.status_code` quando presente (4xx/5xx). | - -Estensione di `/api/config`: nuova chiave top-level booleana -`"apipilot": true/false` (basata su `S2S_APIPILOT_TOOLS_URL`). Il frontend -la usa per decidere se mostrare il catalogo / i bottoni "Esegui tool" (prende -la lista da `/api/apipilot/tools` anziché hardcodare). - -#### PRE-CHECK obbligatori (flow guida §2.2, tutti implementati) - -1. **Fresh discovery** — prima di ogni `execute` viene usata la lista tool - recuperata da `_apipilot_fetch_tools(...)` rispettando la TTL. Se il tool - non viene trovato, **un solo** re-discovery forzato prima di fallire. -2. **Controllo `requires_auth`** — se `true` ma nessun token presente - (Authorization / x-demo-session / S2S_APIPILOT_SERVICE_TOKEN) → blocco - HTTP 401 con envelope `{code: "AUTH_REQUIRED", message: "La herramienta - «nome» requiere autenticación…"}` — **NESSUNA richiesta viene inviata al - backend upstream** in questo caso. -3. **Validazione JSON-Schema strict** (`_apipilot_validate_arguments`): - - rimuove **tutte** le chiavi extra non in `parameters.properties` - (avviso `[APIPILOT-VALIDATE] … removing unknown arg=…`); - - **NON inventa parametri**; - - restituisce errore 400 `INVALID_ARGUMENTS` per ogni campo `required` - mancante (messaggi in spagnolo). -4. **Passthrough header autenticazione**: - `Authorization: Bearer ` oppure `x-demo-session: - ` vengono inoltrati VERBATIM al backend AquaPortal (§2.1 - nota), **mai loggati** (solo presenza: log `auth=Y / demo=Y`). -5. **Compatibilità LLM function-calling**: helper `_apipilot_strip_tool_for_llm(tool_def)` - che proietta `ToolDefinition` nel formato standard OpenAI - `{type: "function", function: {name, description, parameters}}` — **rimuove - `requires_auth`** (§4 della guida: "non mandare direttamente l'output - grezzo di /tools al modello"). - -#### Garanzie / sicurezza / anti-leak - -| Controllo | Implementazione | -|---|---| -| Nessuna condivisione cache tra identità diverse | Chiave cache = `SHA-256(authorization)[:12] \| x-demo-session` → fingerprint anonimo, non salva token in cache | -| Doppio controllo cache con lock asincrono | `_APIPILOT_CACHE_LOCK` async + double check dopo acquisizione lock → 1 sola fetch per refresh | -| Fallback stantia su errore rete | Se backend va giù e abbiamo entry in cache → restituisce fallback loggando warning invece di crash | -| Inoltro header Auth mai loggato | Solo log `auth=Y/- demo=Y/-` | -| Cap parametri unknown | Rimossi, mai inoltrati al backend | -| Envelope errori uniforme | Sempre `{success, data, error}` anche per errori pre-check locali | -| Nomi file env coerenti | Nessun URL o token hardcoded | -| Banner startup di conferma | `[STARTUP] … apipilot= apipilotServiceToken=Y/- apipilotTtl=s apipilotTimeout=s` | - -**File modificati:** - -- **`server.py`** ([server.py](file:///home/duxiter/s2s/s2s-client/server.py)) — Sezione APIPILOT completa inserita tra `OPENAI_PROJECT` e `NODE_RED_REASONING_URL`: - 1. Definizione 4 env + normalizzazione + TTL/timeout cap range - ([L236-L266](file:///home/duxiter/s2s/s2s-client/server.py#L236-L266)). - 2. Cache in-process `_APIPILOT_CACHE: dict[fp → (monotonic, tools[])]` + lock - asincrona `_APIPILOT_CACHE_LOCK` ([L268-L271](file:///home/duxiter/s2s/s2s-client/server.py#L268-L271)). - 3. Helpers pura: `_apipilot_auth_fingerprint(auth, demo)` - ([L274-L287](file:///home/duxiter/s2s/s2s-client/server.py#L274-L287)) · `_apipilot_parse_authorization(Request)` - ([L290-L309](file:///home/duxiter/s2s/s2s-client/server.py#L290-L309)) · `_apipilot_strip_tool_for_llm(tool_def)` - ([L312-L338](file:///home/duxiter/s2s/s2s-client/server.py#L312-L338)). - 4. Discovery: `_apipilot_fetch_tools(auth, demo, include_unauthorized, force_refresh)` - ([L341-L481](file:///home/duxiter/s2s/s2s-client/server.py#L341-L481)) — cache hit log, stale fallback, unwrap payload `list/{tools,result,data}.tools`, sanitizzazione ToolDefinition minima, log `[APIPILOT-DISCOVERY] →/←`. - 5. Validazione: `_apipilot_validate_arguments(arguments, tool_def)` - ([L484-L517](file:///home/duxiter/s2s/s2s-client/server.py#L484-L517)) — rimuove extra, check required, messaggi in spagnolo. - 6. Execute: `_apipilot_execute_tool(auth, demo, name, arguments)` - ([L520-L684](file:///home/duxiter/s2s/s2s-client/server.py#L520-L684)) — PRE-CHECK 1-2-3 (re-discovery 1 volta, requires_auth 401, validazione 400), POST /execute envelope, gestione non-JSON HTTP, wrap envelope se backend non lo restituisce, log `[APIPILOT-EXEC] →/←`. - 7. Banner `[STARTUP] Other externals`: esteso con 4 nuovi placeholder `apipilot`, `apipilotServiceToken`, `apipilotTtl`, `apipilotTimeout` - ([L726-L752](file:///home/duxiter/s2s/s2s-client/server.py#L726-L752)). - 8. **`/api/config`**: nuova chiave booleana `"apipilot": bool(S2S_APIPILOT_TOOLS_URL)` + docstring, log esteso - ([L2544-L2579](file:///home/duxiter/s2s/s2s-client/server.py#L2544-L2579)). - 9. **Pydantic model** `ApipilotExecuteRequest(name:str, arguments:dict={})` ([L2582-L2585](file:///home/duxiter/s2s/s2s-client/server.py#L2582-L2585)). - 10. **`GET /api/apipilot/tools`** proxy pubblico ([L2588-L2651](file:///home/duxiter/s2s/s2s-client/server.py#L2588-L2651)): - query `?include_unauthorized=true(default)&refresh=false`, envelope uniforme `{success, data: {count, include_unauthorized, tools}, error}`, 501 se env non impostato, HTTPException convertite in envelope. - 11. **`POST /api/apipilot/execute`** proxy pubblico ([L2654-L2700](file:///home/duxiter/s2s/s2s-client/server.py#L2654-L2700)): - body `{name, arguments}`, PRE-CHECK 1-2-3 tramite `_apipilot_execute_tool`, status code risposta = `error.status_code` se errore, messaggi utente finali in spagnolo §2.2. - ---- - -## [2026-09-23] - -### Aggiunto — Bottone «Descargar conversación» nell'header del pannello chat (export JSON + TXT client-side offline) - -Nuovo bottone tondo icona download affiancato alla spia «En línea» sulla destra -dell'header del pannello `#chat-panel`. Alla pressione serializza TUTTO lo -storico persistente (`.hist-msg` dentro `#chat-history`) e scarica DUE file -contemporaneamente, SENZA chiamate al backend, interamente client-side e -offline-safe (Blob + URL.createObjectURL + ``): - -1. `vocero-conversacion[-]-YYYYMMDD-HHMMSS.json` — struttura dati - con meta `{ exportedAt, messageCount, messages: [...] }`. Tipi supportati: - - `user` / `assistant` → `{ type, text, timestamp, name?, initials?, interrupted? }` - - `tool` → `{ type: "tool", timestamp, name, args, output }` (risultato chiamate tool) - - `image` → `{ type: "image", timestamp, dataUrl }` (scatti webcam camera tool) -2. `vocero-conversacion[-]-YYYYMMDD-HHMMSS.txt` — log leggibile - per umani in spagnolo, ogni entry formattata come - `HH:MM Nombre / Vocero / HERRAMIENTA : testo`. - -**UI / UX (tutto in spagnolo, come richiesto):** -- `aria-label="Descargar conversación"` -- `title="Descargar conversación (JSON + TXT)"` -- **Feedback OK**: dopo export riuscito bottone diventa verde per 650 ms - (`.chat-export-ok` con ring + glow). -- **Feedback vuoto**: se nessun messaggio → nessun download, bottone flash - giallo/ámbar + micro-shake 0.42s (`.chat-export-empty`) + console info - `[ui/chat.js:exportConversation] No hay mensajes aún — exportación omitida.` -- **Nomi file sanitizzati**: helper `_safeName(...)` rimuove unicode/ - caratteri speciali/spazi → `a-z 0-9 - _`. -- **Stili coerenti**: dark (glass/aurora) + white (screenshot mobile style) - entrambe tematizzate con colori esistenti `var(--brand)`, `#16a34a`, `#f59e0b`. - -**Comportamenti garantiti:** -- 🔒 Zero dati trasmessi fuori dal browser (nessun POST, nessun analytics). -- Le bolle effimere sull'orb (`.bubble` / `.bubble-stack`) sono volutamente - ignorate: esporta SOLO lo storico permanente, che è quello significativo. -- Never-throws: intero export avvolto in `try/catch`; errore solo in console. -- `window.URL.revokeObjectURL(...)` dopo 4 s → nessun leak di memoria Blob. -- Disponibile in TUTTI i temi (dark / white / default). - -**File modificati:** - -- **`index.html`** ([index.html](file:///home/duxiter/s2s/s2s-client/index.html)): - 1. Wrapper `.chat-header-actions` a destra dell'header, che ingloba la pill - «En línea» + nuovo bottone `#chat-export-btn` (SVG freccia-giù) - ([L374-L394](file:///home/duxiter/s2s/s2s-client/index.html#L374-L394)). - -- **`ui/chat.js`** ([chat.js](file:///home/duxiter/s2s/s2s-client/ui/chat.js)): - 1. Helper module-level `_safeName(prefix)` per sanitizzare nomi file - ([L38-L50](file:///home/duxiter/s2s/s2s-client/ui/chat.js#L38-L50)). - 2. Rif `this._exportBtn = getElementById("chat-export-btn")` + `click` listener - nel `ChatView` constructor ([L74-L78](file:///home/duxiter/s2s/s2s-client/ui/chat.js#L74-L78)). - 3. Nuova sezione `// ── Export / download conversation ──` con 4 metodi: - - `_serializeConversation()` → estrae `.hist-msg` rows con querySelector - `:scope > .hist-msg`, gestisce `user/assistant/tool/image`, preserva - timestamp `data-timestamp`, nome utente, initials, flag interrupted - ([L521-L582](file:///home/duxiter/s2s/s2s-client/ui/chat.js#L521-L582)). - - `_conversationToText(conv)` → pretty-format testo spagnolo con header - data, totali, blocchi tool indentati, anteprima immagine dataURL - ([L584-L621](file:///home/duxiter/s2s/s2s-client/ui/chat.js#L584-L621)). - - `_downloadBlob(content, filename, mime)` → pattern `` + - revokeObjectURL ([L623-L645](file:///home/duxiter/s2s/s2s-client/ui/chat.js#L623-L645)). - - `exportConversation()` (pubblico) → entry-point, nome file con timbro - UTC locale `YYYYMMDD-HHMMSS`, include nome profilo Vocero se presente, - logica empty/OK/error feedback, 2 download distinti - ([L647-L697](file:///home/duxiter/s2s/s2s-client/ui/chat.js#L647-L697)). - -- **`style.css`** ([style.css](file:///home/duxiter/s2s/s2s-client/style.css)): - 1. `.chat-header-actions` flex-row right-aligned - ([L4919-L4931](file:///home/duxiter/s2s/s2s-client/style.css#L4919-L4931)). - 2. `.chat-export-btn` baseline (dark-theme): 32×32 pill, glassy, hover/focus - states, transizioni 120-160 ms - ([L4932-L4968](file:///home/duxiter/s2s/s2s-client/style.css#L4932-L4968)). - 3. Stati feedback: `.chat-export-ok` (verde) + `.chat-export-empty` - (ámbar + animazione shake 5 step) - ([L4969-L4989](file:///home/duxiter/s2s/s2s-client/style.css#L4969-L4989)). - 4. Varianti white-theme complete: `.chat-header-actions`, base, hover, - active, OK, empty - ([L4991-L5015](file:///home/duxiter/s2s/s2s-client/style.css#L4991-L5015)). - -### Aggiunto — `S2S_LATEST_SUMMARY_TEXT`: override statico del summary ultima conversazione (testo pulito, nessuna chiamata HTTP) - -Nuova variabile d'ambiente che, se valorizzata, ha **priorità assoluta** su `S2S_LATEST_SUMMARY` -e salta completamente la fetch HTTP upstream (login-by-phone, Bearer, timeout, JSON unwrap: *tutto bypassato*). -Il suo valore testo-plain viene iniettato direttamente come blocco "latest conversation summary" -nel prompt LLM (sia canale WebSocket `/v1/realtime` che `POST /api/reasoning`). - -Progettata per il caso d'uso in cui l'operatore vuole iniettare una versione -**pulita, essenziale e pre-pulita** del summary senza dipendere da nessun endpoint esterno. - -**Valore `.env` di esempio (multiriga con `\n`):** -```env -# S2S_LATEST_SUMMARY=https://api.example.com/summary # ← disabilitato: S2S_LATEST_SUMMARY_TEXT ha priorità -S2S_LATEST_SUMMARY_TEXT=Última conversación 2026-09-22:\n- Usuario preguntó por mortalidad salmón AquaChile semana 38.\n- Se refirió al reporte Porcentaje Mortalidad. -``` - -**Comportamento chiave:** -- Le sequenze `\n` nel valore env vengono interpretate come a-capo vero (stessa convenzione di `S2S_PRIMARY_PROMPT`) -- **Non richiede `phoneNumber`**: funziona anche per sessioni generiche senza identificativo chiamante -- Il wrapper `LATEST_SUMMARY_HINT` + il cap a **1600 caratteri** sono applicati comunque (passaggio sempre attraverso `_resolve_latest_summary_context`) -- Il blocco viene correttamente classificato dal layer dedup (marker invisibile `SUMMARY_FULL_MARKER`) — nessun rischio di duplicato -- Se `S2S_LATEST_SUMMARY_TEXT` è vuoto → **fallback** trasparente al vecchio flusso (`S2S_LATEST_SUMMARY` URL + `phoneNumber`) - -**Log attesi nel server per confermare override attivo:** -``` -[INJECT-SUMMARY] S2S_LATEST_SUMMARY_TEXT OVERRIDE active (len= chars). Skipping HTTP fetch; injecting raw static plain-text summary directly. -``` - -**File modificati:** - -- **`server.py`** ([server.py](file:///home/duxiter/s2s/s2s-client/server.py)): - 1. Definizione nuova env `S2S_LATEST_SUMMARY_TEXT` + interpretazione escape `\n` ([L128-L140](file:///home/duxiter/s2s/s2s-client/server.py#L128-L140)). - 2. Banner `[STARTUP]` esteso con campo `summaryText=%s` per conferma visiva a boot ([L275-L297](file:///home/duxiter/s2s/s2s-client/server.py#L275-L297)). - 3. **Ramo override** PRIMA di qualsiasi logica HTTP dentro `_fetch_latest_summary_for_phone(...)` ([L1563-L1589](file:///home/duxiter/s2s/s2s-client/server.py#L1563-L1589)): - - return diretto del valore statico; - - log `[INJECT-SUMMARY] … OVERRIDE active`; - - anteprima raw prime 800 chars se `S2S_DEBUG_PROMPT=true`. - 4. **Gate REASONING:** `needs_summary = bool(S2S_LATEST_SUMMARY) or bool(S2S_LATEST_SUMMARY_TEXT)` ([L2153](file:///home/duxiter/s2s/s2s-client/server.py#L2153)). - 5. **Skip REASONING rilassato:** condizione `(not phone) and (not needs_reports) and (not episode_id) and (not S2S_LATEST_SUMMARY_TEXT)` — il testo statico non richiede phone ([L2159-L2168](file:///home/duxiter/s2s/s2s-client/server.py#L2159-L2168)). - 6. **Esecuzione summary REASONING:** `needs_summary and (phone or S2S_LATEST_SUMMARY_TEXT)`; log "READY" esteso con flag `summaryTextOverride=%s` ([L2240-L2256](file:///home/duxiter/s2s/s2s-client/server.py#L2240-L2256)). - 7. **Gate WS connect:** medesimo `needs_summary` esteso con `S2S_LATEST_SUMMARY_TEXT` ([L2644](file:///home/duxiter/s2s/s2s-client/server.py#L2644)). - 8. **Skip WS connect rilassato:** anche senza `phoneNumber` se c'è `S2S_LATEST_SUMMARY_TEXT` la pipeline parte ([L2653-L2664](file:///home/duxiter/s2s/s2s-client/server.py#L2653-L2664)). - 9. **Esecuzione summary WS:** medesima condizione rilassata + log "READY" con campo `summaryTextOverride=%s` ([L2725-L2746](file:///home/duxiter/s2s/s2s-client/server.py#L2725-L2746)). - -- **`INJECTIONS.md`** ([INJECTIONS.md](file:///home/duxiter/s2s/s2s-client/INJECTIONS.md)): - 1. Sezione **4. Blocco summary ultima conversazione** completamente riscritta: - - nuova tabella 2 modalità mutuamente esclusive (A = HTTP fetch dinamico / caller, B = override statico hardcoded); - - paragrafo **Modalità B (override statico)** con esempio `.env` e nota su escape `\n`; - - riferimenti codice aggiornati ([L206-L258](file:///home/duxiter/s2s/s2s-client/INJECTIONS.md#L206-L258)). - 2. **Tabella riepilogo trigger** riga #4 aggiornata: - - Trigger: `phoneNumber oppure override statico`; - - env: `S2S_LATEST_SUMMARY` (HTTP) **o** `S2S_LATEST_SUMMARY_TEXT` (statico, priorità); - - parametro: `phoneNumber=` (solo HTTP; override statico non lo richiede) ([L409-L417](file:///home/duxiter/s2s/s2s-client/INJECTIONS.md#L409-L417)). - ---- - -## [2026-09-07] - -### Aggiunto — Supporto `episode_id` (podcast episode inject) - -Nuovo parametro query string `?episode_id=` affiancato a `?phoneNumber=` che -abilita il caricamento e l'iniezione automatica di un episodio podcast come -contesto PRIMARIO nel prompt LLM. - -**URL di esempio:** -``` -/?phoneNumber=%2B447432477433&episode_id=episode-19569f77-a06e-5ce5-a52f-6299dbd67d03 -``` - -**File modificati:** - -- **`server.py`** ([server.py](file:///home/duxiter/s2s/s2s-client/server.py)): - 1. Aggiunta costante `PODCAST_EPISODE_HINT` ([L426-L429](file:///home/duxiter/s2s/s2s-client/server.py#L426-L429)) per l'hint semantico nel prompt. - 2. Aggiunta funzione `_resolve_episode_context(raw_value)` ([L475-L504](file:///home/duxiter/s2s/s2s-client/server.py#L475-L504)): normalizza la risposta API (dict/list/str, eventuale wrapper `{"result": …}`), la serializza in JSON (cap 24.000 chars) e la avvolge con i marker `<<>>`. - 3. Aggiunta funzione asincrona `_fetch_podcast_episode(episode_id)` ([L1010-L1078](file:///home/duxiter/s2s/s2s-client/server.py#L1010-L1078)): GET plain verso - `https://aquachile.azurianlab.com/api/v1/podcast/episodes/{episode_id}` - (timeout 15s, follow redirects, error handling soft — non rompe mai il flusso, restituisce `None` su fail). - 4. Estesa `_augment_instructions_with_profile(...)` ([L1137-L1181](file:///home/duxiter/s2s/s2s-client/server.py#L1137-L1181)) con nuovo parametro `episode_context_text`; l'ordine di inject ora è (più specifico → più generico): **episode → profile → reports → summary**. - 5. Estesa `_patch_client_session_update_with_profile(...)` ([L1184-L1306](file:///home/duxiter/s2s/s2s-client/server.py#L1184-L1306)) con supporto a `episode_context_text` e logging dedicato `[INJECT-EPISODE]` / `[DEBUG-EPISODE]`. - 6. WebSocket connect handler ([L1791-L1959](file:///home/duxiter/s2s/s2s-client/server.py#L1791-L1959)): - - legge `episode_id` da query params assieme a `phoneNumber`; - - esegue fetch episodio + resolve PRIMA di profile/reports/summary; - - salva `injected_episode_context` e `inject_episode_id` nel `session_ctx` condiviso. - 7. `_client_to_upstream` ([L2649-L2661](file:///home/duxiter/s2s/s2s-client/server.py#L2649-L2661)): passa `ctx_episode_context` al patch di `session.update`. - 8. Endpoint `POST /api/reasoning`: - - esteso modello `ReasoningRequest` con campo `episode_id: str | None = None` ([L1309-L1323](file:///home/duxiter/s2s/s2s-client/server.py#L1309-L1323)); - - nel handler ([L1411-L1577](file:///home/duxiter/s2s/s2s-client/server.py#L1411-L1577)) fetch episodio indipendente da phone; - - `inject_episode_text` viene **prepend** a `user_context_parts` (prima di tutti); - - inoltro a NODE_RED / OPENAI con logging esteso (`episodeIdLen`). - -- **`main.js`** ([main.js](file:///home/duxiter/s2s/s2s-client/main.js)): - 1. Lettura da query string: `const voceroEpisodeId = pageParams.get("episode_id")` ([L676-L680](file:///home/duxiter/s2s/s2s-client/main.js#L676-L680)). - 2. `fetchOpenAiReasoningAnswer` ([L1337-L1364](file:///home/duxiter/s2s/s2s-client/main.js#L1337-L1364)): campo `episode_id` aggiunto al body POST `/api/reasoning`, logKey e `console.info` estesi. - 3. Costruzione URL WebSocket ([L2323-L2342](file:///home/duxiter/s2s/s2s-client/main.js#L2323-L2342)): `episode_id` appeso a query params sia con API `URL.searchParams` sia nel fallback stringa (concat con `&`). - ---- - -### Aggiunto — `S2S_START_SESSION_MODE`: 3 modalità di start sessione - -Env var letta dal server e propagata al client via `GET /api/config.startSessionMode`. -Scopo: governare se e come il microfono si auto-accende e se il modello saluta -per primo (flow simile a wake-word). Valori supportati: - -| Valore | Descrizione | -|---|---| -| *(vuoto) / default* | Start manuale: solo tap sull'Orb / pulsante Start | -| **`TALK`** | Dopo 2s overlay fullscreen "Tocca ovunque per iniziare" (policy safe per Safari/iOS `getUserMedia`). Click/touch/tasto dentro la user gesture → `doStart()`. WS client inietta bootstrap `"hola vocero"` + `requestResponse()`. | -| **`TALKFIRST`** | Dopo 2s **tenta `doStart()` DIRETTAMENTE SENZA click**, pre-caricando `pendingWakeWordConfirmationText = "hola vocero"` (stessa variabile della wake-word vera). Se i permessi mic sono già "allow always" funziona senza click. Se fallisce (policy Safari/iOS) → fallback sullo stesso unlocker di TALK con messaggio "permesso microfono". | - -**File modificati:** - -- **`server.py`** ([server.py](file:///home/duxiter/s2s/s2s-client/server.py)): - 1. Lettura env: `S2S_START_SESSION_MODE = os.environ.get(...)`, `.strip().upper()` ([L150](file:///home/duxiter/s2s/s2s-client/server.py#L150)). - 2. Banner `[STARTUP]` esteso con campo `startSessionMode=` ([L196-L212](file:///home/duxiter/s2s/s2s-client/server.py#L196-L212)). - 3. Endpoint `GET /api/config` → nuovo campo `startSessionMode` + log `[INTERNAL] /api/config` ([L1383-L1400](file:///home/duxiter/s2s/s2s-client/server.py#L1383-L1400)). - -- **`index.html`** ([index.html](file:///home/duxiter/s2s/s2s-client/index.html#L32-L39)): - - Aggiunto nuovo `#talk-unlocker` overlay fullscreen (z-index 9999), `hidden` di default, con card "Preparando Vocero… / Toca en cualquier lugar para empezar a hablar" + spinner gradient. - -- **`style.css`** ([style.css](file:///home/duxiter/s2s/s2s-client/style.css#L145-L215)): - - Classi `.talk-unlocker`, `.talk-unlocker-hint`, `.talk-unlocker-spinner`, `.talk-unlocker-title`, `.talk-unlocker-sub` + animazioni fade-in e pop-up card. - -- **`main.js`** ([main.js](file:///home/duxiter/s2s/s2s-client/main.js)): - 1. Variabile globale `startSessionMode = ""` + commento ([L628-L632](file:///home/duxiter/s2s/s2s-client/main.js#L628-L632)). - 2. Parse dentro `fetchConfig()` → uppercase, log in `reportDebug("B",…)` ([L2309-L2320](file:///home/duxiter/s2s/s2s-client/main.js#L2309-L2320)). - 3. Passaggio a WS client → `startWithResponse: startSessionMode === "TALK"` ([L2683-L2692](file:///home/duxiter/s2s/s2s-client/main.js#L2683-L2692)). - 4. Blocco scheduling auto-start ([L2976-L3083](file:///home/duxiter/s2s/s2s-client/main.js#L2976-L3083)): - - `bootstrapWithAutoStart()`: `await fetchConfig()` → `maybeScheduleAutoStart()`; - - `setTimeout(2000 ms)` warmup per finire fetch di episode/profile/reports; - - `showTalkUnlocker(fallbackHint)`: gestisce label custom nel caso fallback TALKFIRST; - - **`tryTalkFirstDirect()` (TALKFIRST)**: set `pendingWakeWordConfirmationText="hola vocero"` + `doStart()` + try/catch con teardown e fallback unlocker; - - listener unlocker click/touchstart/keydown → `startTalkFromGesture()` con `createResumedAudioContext()` dentro la gesture (per iOS silent-free). - 5. `onClientStatus()` ([L2878-L2932](file:///home/duxiter/s2s/s2s-client/main.js#L2878-L2932)) aggiunto `hideTalkUnlocker()` in `connecting/queued/your-turn/connected`. - -- **`ws/s2s-ws-client.js`** ([s2s-ws-client.js](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js)): - 1. Costruttore: nuove proprietà `_startWithResponse`, `_startWithResponseText` (default `"hola vocero"`), `_initialResponseSent` guardia one-shot ([L163-L178](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L163-L178)). - 2. Handler `session.updated` ([L688-L713](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L688-L713)): **Solo per `TALK`** (non TALKFIRST, che usa invece `pendingWakeWordConfirmationText`): `this.sendUserText("hola vocero") + this.requestResponse()` — stesso identico code path della wake-word. - 3. `requestResponse` / `_createResponseNow` ripristinati puliti (solo payload opzionale `image`; nessun shaped `response.create`). - ---- - -### Modificato — `#reports-sidebar-toggle` visibile solo con `?debug=true` - -Il bottone "reports" nella topbar (toggle del pannello laterale reports) è ora -`data-debug-only="true"` — viene quindi mostrato solo se l'URL contiene -`?debug=true`, analogamente al cluster `.topbar-right`. - -**File modificati:** - -- **`index.html`** → `#reports-sidebar-toggle` ([index.html](file:///home/duxiter/s2s/s2s-client/index.html#L47-L50)): aggiunto `data-debug-only="true"`. -- **`main.js`** → `applyDebugOnlyVisibilityGate()` ([L48-L109](file:///home/duxiter/s2s/s2s-client/main.js#L48-L109)): esteso per iterare *tutti* gli elementi `[data-debug-only="true"]` (non solo `.topbar-right`); riga 1227: `reportsSidebarToggle.hidden = false` gated a `qs.get("debug") === "true"` ([L1227-L1246](file:///home/duxiter/s2s/s2s-client/main.js#L1227-L1246)) + log rosso `🚫 FORZATO HIDDEN` quando manca debug=true. -- **`style.css`** → regola di sicurezza già presente: `[data-debug-only]:not([data-debug-enabled]) { display:none !important; visibility:hidden; opacity:0 }` ([L532-L537](file:///home/duxiter/s2s/s2s-client/style.css#L532-L537)). - ---- - -## [2026-09-04] - -### Modificato — Chat sempre visibile + integrazione seamless - -Riorganizzato il layout per mostrare la chat testuale in modo permanente e -integrato visivamente con l'Orb nella parte superiore dello stage. - -- Rimosso pulsante toggle chat nella topbar (`#chat-btn`) e relativo overlay. -- Stage con l'Orb nella parte superiore; nuovo `#chat-panel` a seguire (cronologia - + form input fisso sopra il footer sticky). -- Aggiornata logica in `main.js` e `ui/chat.js` per l'invio testo tramite - `client.sendUserText` e auto-scroll senza controlli di visibilità pannello. -- Versione banner deploy: **2026-09-03 14:40**. - -### Risolto — Stabilità integrazione chat mobile - -- Errore `Missing element: #chat-btn` risolto con selettori non-strict - (`document.querySelector`) per elementi opzionali rimossi. -- Refactoring estetico "seamless": chat senza cornici, ombre o sfondi - (`background:transparent`, `box-shadow:none`). -- **Layout mobile:** - - padding incrementato in `#app` (56px) e `.chat-history` (96px) per evitare - sovrapposizioni col footer sticky; - - margini fissi bolle: `margin-right:22px` (Assistant), `margin-left:6px` (User). -- **Auto-scroll streaming:** implementato `_scrollToBottom` con catena di retry - multipli (`requestAnimationFrame` + `setTimeout`) per compensare il line-wrap - asincrono durante l'arrivo dei token; `overflow-anchor:none` + `scroll-behavior:auto !important`. - -### Aggiunto — Avatar utente iniziali + modale profilo - -- Sostituito testo nome utente nell'header con avatar circolare 40×40px - (gradient brand) contenente le iniziali calcolate (es. "AV"). -- Nuova `` in `index.html` che si apre al click - sull'avatar: mostra email, telefono, ruolo, azienda, con supporto a shape - annidate del payload profilo. -- Chiusura modale: tasto ESC, click fuori card, pulsante `×` dedicato. - ---- - -## [Note di formato] - -- **Cap campo prompt episodio:** 24.000 caratteri (transcript lunghi). -- **Cap profilo / summary:** 1.600 caratteri ciascuno. -- **Cap reports list:** 12.000 caratteri. -- **Ordine inject prompt LLM (WS session.update + reasoning):** - 1. Episodio podcast corrente (PRIMARIO) - 2. Profilo chiamante (identity) - 3. Lista reports / script podcast schedulati - 4. Summary ultima conversazione -- Tutti i blocchi sono marcati con `<<>>` per ispezione log. +All significant client changes are recorded here. This English history +supersedes the former Italian and Spanish versions. Historical entries describe +the implementation at the recorded date; current operating instructions live in +[the project documentation](../docs/README.md). + +## Unreleased + +### Changed + +- Consolidated technical documentation under the root `docs/` directory and + replaced translated changelog copies with this English history. +- Moved the agent-profile and reference-audio examples into `docs/examples/`. +- Moved the historical architecture proposal into `docs/proposals/` and retained + the existing document URLs as redirects. +- Removed the obsolete `index_video.html` page, which no longer matched the + elements required by the shared client script. + +## 2026-09-25 + +### Fixed — ApiPilot tool discovery in realtime sessions + +- Fetch the tool catalog at the start of each realtime WebSocket connection, + before opening the upstream connection. Previously the catalog was injected + only through HTTP reasoning, leaving voice sessions without it. +- Inject ApiPilot independently of `S2S_INJECT_PROFILE`, including sessions with + profile injection disabled. +- Cache discovery using the authenticated identity or an anonymous session key. + Save the tool definitions and wrapped context in the session context and reuse + them when patching later `session.update` messages. +- Wrap the catalog with `APIPILOT_TOOLS_LIST_BEGIN/END` markers and include it + after the other context blocks. Record catalog readiness, count, timing, + authentication state, and injection length; full prompt dumps remain controlled + by `S2S_DEBUG_PROMPT`. + +### Fixed — Two-pass execution, authentication, and marker handling + +- Strengthen the first-pass prompt so a tool selection emits exactly one CALL + marker line, without a spoken preamble or trailing explanation. +- Replace exposed CALL markers in chat with a Spanish waiting message. +- Detect and execute CALL markers before sanitizing them. Sanitizing first had + erased the signal required to start the second pass. +- Correct the monotonic-clock helper used by second-pass processing. +- Reject illustrative phone values from model output and fill missing values + from the actual session context. +- Accept empty arguments and normalize malformed argument representations using + JSON, single-quoted mappings, key/value pairs, missing braces, or empty input. +- Initialize default arguments on all discovery and exception paths. +- Normalize execute endpoints, supporting an explicit execute URL and avoiding + an incorrect `/tools/execute` route when the backend expects `/execute`. +- Send empty arguments for authentication-only tools whose data is derived from + the session token, avoiding conflicts with a separate phone argument. +- Reuse the discovery authorization and demo-session identity for execution. +- Add the configured API-key override for deployments using that authentication + path, ahead of the service-token and session-token paths. The historical + override sent `X-API-Key`, `Authorization: Bearer`, and `x-demo-session` + together for discovery and execution, and bypassed phone login entirely. + Documentation uses placeholders rather than retaining the credential from + the old history. +- Add diagnostics for discovery, execution, schema validation, login-token + shape, default arguments, and upstream HTTP errors. + +The historical authentication priority was: configured API key, configured +service token, discovery authorization, forced phone login when required, and +anonymous access to tools that do not require authentication. This records the change rather than +recommending a credential or deployment configuration. + +### Fixed — Prevent internal markers from reaching speech + +- Sanitize CALL and RESULT markers in the relay, LLM output processor, and TTS + handler, including truncated, inverted, and partially wrapped forms. +- Use the Spanish spoken placeholder + `Voy a consultar tus datos, un momento por favor.` for pending calls. +- Add phone-context fallback and prompt rules preventing internal marker syntax + from being spoken. Suppress the first-pass audio while preserving the second + pass that contains the actual tool result. +- Remove leaked Unix, Windows, and TRAE workspace paths. Preserve ordinary text + containing phone numbers when no internal marker context is present. +- The original offline sanitizer check passed 7 of 11 cases, with four + artificial edge cases still failing and end-to-end voice verification pending. + This is historical verification, not a claim about later changes. + +## 2026-09-24 + +### Added — ApiPilot reasoning in two passes + +- Discover tools dynamically and present their names and descriptions to the + reasoning model. A matching request produces + `<<>>`. +- Parse the marker, execute the selected tool, and return its text to the model + in a second reasoning request. The model then produces the spoken answer; + an empty second-pass answer falls back to the raw tool-result text. +- Support `S2S_APIPILOT_TOOLS_EXECUTE_URL` as an explicit execute-endpoint + override. Normalize the configured endpoint instead of hardcoding a backend + route. +- Supply known caller-context values to argument construction and use bounded + catalog/context text rather than exposing authentication material to the model. + +### Added — Browser fetch and WebSocket tracing + +- Trace fetch calls with semantic endpoint tags, method, URL, timing, response + status, and bounded body/response previews. Distinguish configuration, + reasoning, profile, reports, search, ApiPilot, queue, and session operations. +- Trace WebSocket connection, handshake, close, session, and tool events while + limiting noisy audio-frame logs and masking secret URL parameters. +- Prefetch ApiPilot tools at every realtime connection in parallel with audio + and WebSocket setup. Connection setup awaits these operations while isolating + discovery failures. Cache per user, invalidate on identity changes, and + refresh after successful phone login. +- Provide the browser demo-discovery path and server-side discovery logs so + operators can follow both halves of a proxied request. + +### Fixed — Discovery refresh after login + +- Refresh the tool catalog after successful phone authentication, rather than + retaining the catalog fetched for the anonymous identity. +- Store client discovery state per identity and expose cache invalidation for + identity changes and explicit refresh requests. + +### Added — Dynamic ApiPilot proxy + +- Add `GET /api/apipilot/tools` and `POST /api/apipilot/execute` with a consistent + `{success, data, error}` envelope. +- Configure discovery URL, service-token override, cache TTL, and timeout through + environment variables. Cache by authorization/demo-session fingerprint and + allow a logged stale-cache fallback when discovery is temporarily unavailable. +- Re-discover missing tools once before returning a not-found response, enforce + `requires_auth`, validate required arguments, and strip unknown arguments when + the schema is closed. Tools with an open schema retain flexible arguments. +- Present only the minimal tool definition to the model. Return user-facing + errors in Spanish and keep error codes/status/raw details available for + diagnostics. +- Expose ApiPilot availability through `/api/config` and record configuration + availability in the startup banner without printing token values. + +## 2026-09-23 + +### Added — Conversation downloads + +- Add the `Descargar conversación` action to the chat header. +- Export JSON and text entirely in the browser, including user/assistant + messages, tool calls/results, timestamps, display names, and snapshot metadata. +- Preserve initials, interruption flags, and snapshot image `dataUrl` values. + Export persistent conversation history, excluding ephemeral orb bubbles. +- Include a schema version, export timestamp, message count, and conversation + entries in the JSON export. Build the text export from the same conversation + entries so both formats agree. +- Download through temporary Blob URLs, revoke those URLs afterward, and show + success or empty-conversation feedback. No server export endpoint is required. + +### Added — Static latest-summary override + +- Add `S2S_LATEST_SUMMARY_TEXT`, with escaped newline handling, ahead of the + `S2S_LATEST_SUMMARY` HTTP source. +- Accept the static summary without a phone number and apply it in both HTTP + reasoning and realtime session context. Preserve the summary wrapper and cap. +- Include override availability in startup/context diagnostics and update the + injection guide. + +## 2026-09-07 + +### Added — Podcast episode context + +- Read `episode_id` from the page query and pass it to realtime and HTTP + reasoning requests. +- Fetch the selected podcast episode independently of phone context, normalize + dictionary/list/string responses, and wrap the serialized episode with + `PODCAST_EPISODE_BEGIN/END` markers. +- Cap episode context at 24,000 characters and prioritize it before caller + profile, scheduled reports, and latest-summary context. +- Store episode context at WebSocket connection and patch subsequent client + `session.update` messages. Skip unavailable context without aborting the call. + +### Added — Session-start modes + +- Keep manual orb activation as the default. +- Add `S2S_START_SESSION_MODE=TALK`, which waits for the microphone/audio unlock + gesture and greets after session configuration. +- Add `TALKFIRST`, which attempts automatic activation and falls back to the + unlock overlay when browser permissions require a gesture. +- Delay automatic activation by two seconds. Use the existing `hola vocero` + greeting path rather than a separate greeting protocol. + +### Changed — Debug-only reports controls + +- Gate the reports-sidebar toggle and suggestions behind `?debug=true`. +- Apply the visibility gate in HTML, CSS, and client lifecycle handling so + controls do not flash into view before configuration loads. + +## 2026-09-04 + +### Changed — Inline conversation and visual design + +- Replace the overlay chat panel with a permanently visible inline conversation + below the voice stage and above the sticky footer; remove the chat toggle. +- Introduce the historical aurora background and glass surfaces using shared + violet, pink, and cyan brand tokens, including the animated voice orb. +- Make the chat surface continuous with the page, distinguish message roles, + and maintain safe spacing from viewport edges and the footer. +- Put reports in a 320-pixel desktop sidebar and an off-canvas mobile panel. +- Use safe viewport units and responsive layouts to improve mobile stability. +- Keep the text-entry handler connected while allowing the input row to be + hidden in voice-only layouts. + +### Fixed — Chat scrolling and optional controls + +- Schedule repeated scrolling during token streaming and after response/tool + completion to account for delayed line wrapping and layout changes. +- Disable scroll anchoring/smooth scrolling and reserve bottom space so the last + assistant line remains visible above the footer. +- Make removed chat-toggle, badge, backdrop, and close-button references optional + while keeping required chat/history elements strict. +- Synchronize stylesheet/script/import version query parameters and add static + no-cache handling for development updates. + +### Added — Caller avatar and profile dialog + +- Replace the header name with a circular initials avatar. +- Open a profile dialog showing contact details, account identifiers, role, + organization, locale, and available creation/login timestamps. +- Accept nested profile payloads, hide empty fields, support `mailto:`/`tel:` + links, and close through Escape, backdrop interaction, or the close control. + +Historical context limits were 24,000 characters for an episode, 1,600 each for +profile/summary, and 12,000 for a full reports list. Context behavior has evolved; +consult [context injection](../docs/client/context-injection.md) for the current +configuration and ordering. diff --git a/s2s-client/CONTEXT.md b/s2s-client/CONTEXT.md deleted file mode 100644 index b4d980a..0000000 --- a/s2s-client/CONTEXT.md +++ /dev/null @@ -1,108 +0,0 @@ -# Context glossary - -Canonical terms for this space. A glossary, not a spec — it defines what words mean, -not how anything is built. Keep design/implementation detail in `DESIGN.md` and the -code. - -## Speech-to-speech demo -The product: a voice conversation you have with a model by tapping the orb and -talking. "The demo" and "the space" refer to this same thing. It runs on Hugging -Face's open `speech-to-speech` backend. - -## The pipeline -The ordered path a turn travels, from your voice to the orb's reply. Order is -meaningful — each stage consumes the previous one's output: - -`you speak → VAD → STT → VLM → TTS → orb replies` - -- **VAD** — voice activity detection. Decides *when* you are speaking, so the system - knows a turn has started and ended. Model: silero-vad. -- **STT** — speech to text. Transcribes your speech into words. Model: - nvidia/parakeet-tdt-1.1b. -- **VLM** — the vision-language model that composes the reply. Served via Cerebras. - Model: google/gemma-4-31B-it. -- **TTS** — text to speech. Speaks the reply back in the chosen voice. Model: - Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice. - -## Builder -A Hugging Face user credited with making the space, shown by HF username. Current -builders: tfrere, A-Mahla and andito. Distinct from the *models'* authors (nvidia, google, -Qwen, snakers4), who are credited per pipeline stage. - -## Powered by -The infrastructure running the pipeline, named in the about panel: Hugging Face -Inference Endpoints (hosting) and Cerebras (LLM inference). Distinct from "built by" -(the people) and from the model authors (who trained each model). - -## Tool -A function the model can call mid-conversation to do something the pipeline -can't do on its own (look something up, look through the camera). Tools are -declared to the backend in the session config; the model decides when to call -one. Distinct from the *pipeline stages* (VAD/STT/VLM/TTS), which always run. - -## Tool executor -The client-side component that runs a tool when the model calls it and returns -the result to the backend, so the model can speak the answer. It is the missing -half of the round-trip: the backend already emits the call, the executor runs it -and replies. Distinct from the *tool* itself (the thing being run). - -## Web search tool -A tool that looks something up on the web for the model. The model calls it with -a query; the tool executor forwards the query to the search proxy and returns the -results as the tool result. Activates only when a search key is available. - -## Camera snapshot tool -A tool that lets the model look through the user's webcam. While enabled, a live -self-view is shown in the page (bottom-left); when the model calls the tool, the -executor captures a frame and sends it to the model as an image so the VLM can -see it. Distinct from the *preview* (what the user sees) and the *snapshot* (the -single frame sent to the model). - -## Search proxy -The same-origin server route (`/search`) that holds the search key and calls the -external search provider on the client's behalf, so the key never reaches the -browser. Lives in the same container as the page. Distinct from the *s2s backend* -(the separate load-balanced speech-to-speech service). - -## Tools panel -The dialog opened from the "Tools" button in the top-right, holding one switch per -tool (and the web-search key status). Turning a switch on/off declares or removes -that tool on the live session. Distinct from *Settings* (connection, voice, -instructions) and the *About panel* (project info). - -## Identity block -The top-left corner of the topbar (replacing the old wordmark): the demo name, a -one-line blurb, and the "powered by" / "built by" credits, shown directly rather -than hidden behind a click. - -## About panel -The popup opened from the (i) icon to the right of the identity block. Holds the -general introduction to the speech-to-speech project (with a repo link) and the -pipeline. Identity itself now lives in the corner, not here. - -## Queue -The line of users waiting for a free conversation slot when every compute is -busy. You join the queue instead of being turned away; you leave it by reaching -the front or by giving up. Distinct from a *session* (an actual live -conversation) — being in the queue is not yet talking, and time spent waiting -never counts against your usage limit. - -## Ticket -Your held place in the queue. Created when you join, it is what the demo checks -to tell you your position and to notice if you have left. A ticket is not a -session: it only promises a spot in line, not a compute. - -## Position -How many people are ahead of you in the queue, shown while you wait ("You're #3 -in line"). It only ever counts down. Distinct from an *estimated wait* — the -demo shows position, never a time, because wait time is unpredictable. - -## Claim -The moment you reach the front and a free slot becomes yours — the queue hands -off to a real session and the conversation begins. This is also the point where -your usage limit first starts to matter (never while waiting). - -## At capacity -The state where the queue itself is full, so new users can't even join the line -and are asked to try again shortly. Distinct from simply *busy* (all computes -taken but the queue still has room to wait in). diff --git a/s2s-client/DESIGN.md b/s2s-client/DESIGN.md deleted file mode 100644 index d0ca548..0000000 --- a/s2s-client/DESIGN.md +++ /dev/null @@ -1,205 +0,0 @@ -# Design language - -The reference for keeping this app visually coherent as it grows. Read it before -touching `style.css`, `index.html`, or any DOM-building code in `main.js`. Every -rule here is already live in the codebase — this file explains the *why* so changes -extend the system instead of drifting from it. - ---- - -## The thesis: color belongs to the voice - -This is a voice app. The one thing in the room that should have color is the thing -that is talking. So: - -- **The orb** carries saturated color. It glows, and the glow's hue changes with - conversational state. -- **Everything else is monochrome** — a precise cool-grey dark canvas. Surfaces, - borders, buttons, panels, the transcript: all greyscale. -- The **only** exceptions are tiny *role echoes* (a one-word mono label, a small - icon) that borrow the orb's state hue so the transcript reads in the same color - language the orb speaks. They are accents the size of a word, never fills. -- **Brand logos keep their own color.** The Hugging Face mark (`#ffd21e`) and the - Cerebras mark (`#f15a29`) render in their brand colors in the identity credits and - the about panel — a deliberate, owner-approved exception. It applies to those two - logos only; do not generalize it to other chrome. - -If you find yourself adding a tinted background, a colored border, or a bright -button anywhere outside the orb, stop — that color almost certainly belongs to the -orb instead, or shouldn't exist. - ---- - -## Color tokens - -All defined in `:root` in `style.css`. Use the variables, never raw hex in rules. - -### Canvas (the monochrome world) -| Token | Value | Use | -|---|---|---| -| `--bg` | `#0a0b10` | Page background (a cool near-black) | -| `--bg-elev` | `#13151c` | Raised surfaces: bubbles, panels, icon buttons | -| `--bg-elev-2` | `#1b1e29` | Surfaces on surfaces: history bodies, inputs | -| `--border` | `rgba(255,255,255,.08)` | Default hairline | -| `--border-strong` | `rgba(255,255,255,.16)` | Emphasised hairline | -| `--text` | `#f5f6fa` | Primary text; also the *primary button* fill | -| `--text-dim` | `rgba(245,246,250,.65)` | Secondary text | -| `--text-faint` | `rgba(245,246,250,.42)` | Captions, labels, footer | - -### Voice (the only saturated hues) -These are the orb's state colors. They appear on the orb, and as small role echoes -in the transcript — nowhere else. - -| Token | Value | Meaning | -|---|---|---| -| `--accent` / `--speaking` | `#8b7dff` violet | Assistant speaking | -| `--accent-2` / `--listening` | `#22d3ee` cyan | You / listening | -| `--processing` | `#f59e0b` amber | Thinking / tool call | -| `--error` | `#ff6a75` | Error | -| `--success` | `#34d399` | Ready / connected | - -### Role echoes (semantic aliases — use these in chat code) -| Token | Maps to | Where it shows | -|---|---|---| -| `--voice-user` | cyan | `YOU` label + user bubble accents | -| `--voice-assistant` | violet | `ASSISTANT` label + assistant accents | -| `--voice-tool` | amber | `TOOL CALL` label, wrench icon | - -**Why this mapping:** it mirrors the orb exactly — when *you* speak the orb is cyan -(`state-listening`), when the *assistant* speaks it's violet (`state-ai-speaking`), -when it's working it's amber (`state-processing`). The transcript is a quiet replay -of the orb's color story. - -### Orb state → glow (`.circle.state-*` → `--glow`) -| State | Glow | -|---|---| -| `signed-out` | violet `#8b7dff` | -| `authenticated` / `ready` | green `#34d399` | -| `connecting` / `connected` / `starting` | yellow `#facc15` | -| `listening` / `user-speaking` | cyan (`--listening`) | -| `processing` | amber (`--processing`) | -| `ai-speaking` | violet (`--speaking`) | -| `error` | red (`--error`) | - -Adding a new state? Give it a `--glow`, and if it surfaces in the transcript, add a -matching `--voice-*` alias rather than a one-off color. - ---- - -## Typography - -Two faces, two jobs. Never reach for a third. - -- **Inter** — body and UI. Wordmark, buttons, inputs, panel titles, prose, history - message bodies. The workhorse; it should feel neutral and get out of the way. -- **Geist Mono** (`--font-mono`) — the **machine voice**. Reserved for text the - *system* emits or identifiers it reports, never for human prose. - -### When mono is correct -Mono signals "this is the machine talking or naming itself." Use it for: -- the orb's status caption (`.circle-caption`) -- role eyebrows (`YOU` / `ASSISTANT` / `TOOL CALL`) -- tool-call names and argument JSON -- the `·WebSocket` transport tag, bitrate readouts, connection identifiers -- the empty-state label - -Mono text is set uppercase with `letter-spacing: ~0.1–0.14em` and weight `500`, so it -reads as a typed status line, not a headline. Body copy, button labels, and -explanatory `small` text stay **Inter** — putting prose in mono breaks the metaphor. - -The font is loaded in `index.html`; the stack falls back to system mono gracefully if -the CDN is blocked. - ---- - -## Layout - -- **One continuous canvas.** No dividers under the topbar or above the footer, no - panel chrome competing with content. The topbar and footer float over the stage. - Keep it that way — a new section earns a hairline (`--border`) only if it genuinely - needs separating. -- **The orb is the hero and the center of gravity.** It sits dead-center on the - stage. Controls flank it (mic / stop), captions sit beneath. Don't crowd it. -- **Hairlines, not boxes.** Separation comes from `1px` borders at 8–16% white and - from spacing, not from heavy fills or shadows. Shadows are soft and low - (`0 4px 18px rgba(0,0,0,.32)`), used only to lift floating elements (bubbles, - panels, modal). -- **Radii:** `--radius-sm: 8px` (buttons, inputs, chips), `--radius-md: 14px` - (bubbles, message bodies, modal), `--radius-lg: 22px` (reserved). Pick by element - size; don't invent new values. -- **Two reading surfaces for the transcript:** ephemeral bubbles top-right (desktop - only) that log and fade, and a slide-in history panel for review. On phones the - bubble stream is dropped and the panel goes full-screen — the panel is the single - source of truth there. - ---- - -## Components - -- **Buttons.** Default (`.btn`) is a neutral elevated surface. The *primary* button - is **near-white on dark** (`--text` fill, `--bg` text) — the highest-contrast thing - on the page that *isn't* the orb. There is no colored button; emphasis comes from - contrast, not hue. -- **Icon buttons** (`.icon-btn`) are `36px`, elevated surface, dim icon that brightens - on hover. Side controls (`.side-btn`) are circular, collapse to zero size until the - session is live (by width on desktop, by height in the mobile column). -- **Chat bubbles & history messages** share one neutral surface. They are - distinguished by **side** (you = left, assistant = right) plus the **mono role - label** in the role-echo hue — not by tinted fills. Tool entries use the wrench icon - + mono + amber, on the same neutral surface. -- **Badge** (new-message dot) is monochrome white — a signal, not a color accent. -- **Focus** is visible and neutral: inputs focus to `--text-dim`; the orb uses a - `--glow`-colored outline (it's the orb, so color is allowed). - ---- - -## Motion - -- **The orb is audio-reactive, not timer-driven.** Mic RMS (`--audio-level`) and the - assistant output level (`--ai-audio-level`) drive scale/opacity at display rate, so - every syllable moves it. This is the signature animation — keep new motion - subordinate to it. -- **Quiet by default.** Breathing/glow throbs are slow (1.4–2.4s) and low-contrast. - Resist adding scattered micro-animations; an orchestrated moment beats many small - ones, and excess motion reads as AI-generated. -- **First paint is frozen.** `body.booting` disables all transitions until the first - frame commits (stripped after one rAF in `main.js`). Anything new that would - otherwise animate-in on load must respect this. -- Honor `prefers-reduced-motion` for any motion you add. - ---- - -## Writing / copy voice - -- Sentence case, plain verbs, no filler. Tuned and quiet — match the minimal canvas. -- Name things by what the user controls, not by the system's internals. A button says - exactly what it does, and keeps the same word through the flow. -- **Empty states invite action** ("Tap the orb and start talking"), they don't just - set a mood. -- **Errors state what happened and how to recover**, in the interface's voice — they - don't apologize and are never vague. -- Mono labels are terse identifiers (`YOU`, `TOOL CALL`); prose stays in Inter. - ---- - -## Responsive floor (non-negotiable) - -Every change ships meeting these: -- Works down to a `360px`-wide phone. The `@media (max-width: 600px)` block already - handles the phone layout — extend it, don't fight it. -- Visible keyboard focus on every interactive element. -- `prefers-reduced-motion` respected. -- Tap targets ≥ `44px`; `touch-action: manipulation` on anything tappable. - ---- - -## Before you ship — the mirror check - -1. Is every saturated color either on the orb or a word-sized role echo? If a fill or - border is colored, remove that accessory. -2. Is mono used only for machine/system text, and Inter for everything human? -3. Does any new state have both a `--glow` and (if it appears in chat) a `--voice-*` - alias? -4. Are separations hairlines + spacing, not boxes and heavy shadows? -5. Did you add motion? Is it quieter than the orb and reduced-motion-safe? -6. Remove one accessory. The minimal look survives on precision, not addition. diff --git a/s2s-client/Dockerfile b/s2s-client/Dockerfile index 5d3e074..d75920d 100644 --- a/s2s-client/Dockerfile +++ b/s2s-client/Dockerfile @@ -1,13 +1,15 @@ -# Single container: serves the static front-end AND the /api/search proxy. +# Build from the project root: docker build -f s2s-client/Dockerfile -t s2s-client . +# Serve the client, same-origin API proxies, and shared project documentation. # HF Spaces (sdk: docker) routes traffic to $PORT, default 7860. FROM python:3.11-slim -WORKDIR /app +WORKDIR /app/s2s-client -COPY requirements.txt . +COPY s2s-client/requirements.txt . RUN pip install --no-cache-dir -r requirements.txt -COPY . . +COPY s2s-client/ . +COPY docs/ /app/docs/ EXPOSE 7860 diff --git a/s2s-client/HOWITWORKS.md b/s2s-client/HOWITWORKS.md deleted file mode 100644 index f427143..0000000 --- a/s2s-client/HOWITWORKS.md +++ /dev/null @@ -1,584 +0,0 @@ -# HOWITWORKS — demo S2S - -> Compagno di [ARCHITECTURE.md](file:///home/duxiter/s2s/demo/ARCHITECTURE.md): spiega il -> ciclo di vita concreto dei dati in 3 moduli su cui oggi ci siamo concentrati: -> 1. Il campo `instructions` da client a `ai-server:12345` -> 2. `MCP_SEARCH_TRANSLATION_PHRASES` + ranking tool MCP lato client -> 3. **FASE 2 — Dichiarazione tools nativi a `ai-server:12345` via Realtime `session.update.tools[]`** - ---- - -## 0. FASE 2 — Integrazione tools nativi S2S upstream (ai-server:12345) - -### Obiettivo -Prima della Fase 2, i 100+ tool MCP Aquachile erano solo **testo dentro `instructions`** (9 KB di prompt). L'upstream non sapeva eseguirli e produceva frasi tipo: -> *"Perfecto, buscaré… [list_recent_reports]"* - -Con la Fase 2 dichiariamo i tools tramite il **protocollo nativo OpenAI Realtime GA**: -``` -session.update { tools: [...], tool_choice: "auto" } -``` -→ Se `ai-server` lo supporta, produce eventi veri `response.function_call_arguments.done` con nome tool + argomenti JSON. Il listener già esistente nel client (s2s-ws-client.js) si attiva automaticamente e tutto il resto della pipeline — `runTool()` → `POST /api/mcp/tool` Aquachile → `client.sendToolOutput()` — funziona senza altre modifiche. - -### 0.1 Dove è stato implementato lato proxy (s2s_ui container) - -| Modulo | File / Righe | Cosa fa | -|---|---|---| -| **Cache + normalizzazione** | [server.py:451-544](file:///home/duxiter/s2s/demo/server.py#L451-L544) | `_normalize_tools_for_realtime(raw_tools)`: converte qualsiasi formato tool Aquachile → formato OpenAI Realtime standard. Non alza eccezioni; tool invalidi saltati con warning. | -| **Inject WS upstream** | [server.py:1034-1075](file:///home/duxiter/s2s/demo/server.py#L1034-L1075) | Subito dopo `TUNNEL ESTABLISHED`, **PRIMA** che inizi lo streaming audio: fetch cache `_agent_profile_data()` → `session.update` con `instructions` (profilo agente Aquachile) + `tools[]` + `tool_choice=auto`. Errori suppressi: non rompiamo mai il flusso audio. | -| **Log di successo KEY** | [server.py:312-334](file:///home/duxiter/s2s/demo/server.py#L312-L334) | Quando arriva `response.function_call_arguments.done` dall'upstream → 2 log `[MCP INJECT] ✓ UPSTREAM ha emesso…` (segnale CHE LA STRATEGIA B FUNZIONA) | -| **Proxy MCP già esistente** | [server.py:600-656](file:///home/duxiter/s2s/demo/server.py#L600-L656) | `POST /api/mcp/tool` → Aquachile JSON-RPC 2.0 `tools/call`. Nessuna modifica necessaria. | - -### 0.2 Sequenza temporale WS Realtime (Fase 2) - -``` -1. Browser → ws://s2s_server/v1/realtime (connessione) -2. server.py → websockets.connect(ai-server:12345) -3. [MCP INJECT] server.py → upstream: - { "type": "session.update", - "session": { // ⚠️ FORMATO CORRETTO — TUTTO dentro session:{} - "instructions": "…system prompt profilo Aquachile…", - "tools": [ {type: "function", name:"list_recent_reports", …}, …79 più… ], - "tool_choice": "auto" - } - } - ← LOG "[MCP INJECT] session.update upstream inviato (tools=79, fmt=nested_session OK)" -4. browser → ai-server: (turno audio utente) "el reporte de ayer por favor" -5. (se upstream ha tools[] in RuntimeConfig.session.tools — ORA SUPPORTATO Nativamente) - ai-server → server.py → browser: - { "type": "response.function_call_arguments.done", - "call_id": "call_abc", - "name": "list_recent_reports", - "arguments": "{\"date_from\":\"2026-08-24\",\"limit\":5}" } - ← LOG "[MCP INJECT] ✓ UPSTREAM ha emesso response.function_call_arguments.done!" -6. s2s-ws-client.js:803 → dispatch "toolcall" -7. main.js:3023 → runTool("list_recent_reports", args, "call_abc") - branch agentToolDefs → execRemoteMcpTool -8. execRemoteMcpTool → POST /api/mcp/tool → Aquachile JSON-RPC tools/call - LOG: "[Vocero MCP CALL]" → "[Vocero MCP HTTP]" → "[Vocero MCP OUT]" -9. client.sendToolOutput("call_abc", "Risultati: 5 report, ultimo=Report_2026-08-24.xlsx") - → WS payload: - { "type": "conversation.item.create", - "item": { "type": "function_call_output", "call_id": "call_abc", "output": "..." } } -10. ai-server continua il turno con TTS nativo: - "Aquí tienes los 5 reportes de ayer, el más reciente es Report_2026-08-24.xlsx..." - (nessun [tool_name] nel testo del TTS!) -``` - -### 0.3. Formato atteso da `ai-server:12345` — guida per modifiche sul backend S2S - -**Se dopo il deploy non vedi il log `[MCP INJECT] ✓ UPSTREAM ha emesso…`**, vuol dire che `ai-server` oggi scarta il campo `tools[]` dal `session.update`. Ecco **esattamente i campi che devono essere supportati** (copia-incollabile nel codice di `ai-server`): - -#### 0.3.1 `session.update` in ingresso (cosa manda oggi `server.py` — FORMATO NESTED CORRETTO) - -⚠️ **REGOLA NON NEGOZIABILE**: TUTTI i campi di configurazione (instructions, tools, tool_choice, voice, model) devono stare **DENTRO l'oggetto `session`**. Non mandarli MAI alla radice del payload. Il validatore Pydantic strict di OpenAI Realtime GA rifiuta qualsiasi campo sconosciuto alla root. - -```jsonc -{ - "type": "session.update", - - // ⚠️ TUTTO dentro "session":{} — il validator Pydantic strict è extra=forbid sulla root. - "session": { - - // 1) Istruzioni di sistema (profilo agente Aquachile) - "instructions": "María, asistente virtual Aquachile, habla español de Chile…", - - // 2) CATALOGO TOOLS — 79 tool Aquachile normalizzati - "tools": [ - { - "type": "function", - "name": "list_recent_reports", - "description": "Restituisce l'elenco dei report più recenti, opzionalmente filtrati per data.", - "parameters": { - "type": "object", - "properties": { - "date_from": {"type": "string", "format": "date", "description": "Data inizio YYYY-MM-DD"}, - "limit": {"type": "integer", "minimum": 1, "maximum": 50, "default": 10} - }, - "required": [] - } - } - // … altri 78 tool - ], - - // 3) Strategia selezione tool - "tool_choice": "auto" - } -} -``` - -**Perché prima non funzionava?** (ROOT CAUSE) -Il proxy stava inviando `instructions`, `tools`, `tool_choice` **ALLA RADICE** del payload, fuori da `session:{}`. Il modello Pydantic `SessionUpdateEvent` (OpenAI Realtime GA) ha `extra=forbid` e ha rifiutato con `Unknown or invalid event: session.update`. **Non era un rifiuto del campo `tools` in quanto tale** — era un rifiuto di qualsiasi campo non riconosciuto messo nel posto sbagliato. La prova: `runtime_config.session.instructions`, `.session.tools`, `.session.tool_choice` in `language_model.py:526-532` leggono TUTTI i campi da dentro `.session.*`. - -**Audit sorgente backend `speech_to_speech` conferma: GIA' 100% WIRED PER NATIVI TOOLS** -| Componente | File / Righe | Conferma | -|---|---|---| -| LLM pick tools da sessione | `LLM/language_model.py:526-532` | `tools = runtime_config.session.tools` | -| Chat buffer gestisce FC/FCO | `LLM/chat.py:141-223 / 342-366 / 394-427` | `RealtimeConversationItemFunctionCall` + `FunctionCallOutput` | -| Response handler emette WS done event | `api/openai_realtime/handlers/response.py:336-345` | `ResponseFunctionCallArgumentsDoneEvent` con `call_id, name, arguments(STRINGA), response_id, item_id, output_index` | -| Conversation handler accetta ritorno output | `api/openai_realtime/handlers/conversation.py:30-96` | `handle_conversation_item_create` con `deferred_items` anti-race | -| Fallback parser retrocompatibile | `api/openai_realtime/service.py:267-325` | Se arrivano campi flat alla radice → promossi a nested `session` wrapper | - -**Regole convalida obbligatorie lato `ai-server` per evitare rigetti silenziosi**: - -| Regola | Valore | -|---|---| -| Nome tool | lunghezza ≤ 64, match regex `^[a-z0-9_]+$` | -| Numero max tools | Consigliato ≤ 80. Oggi il proxy manda 100+ con warning. | -| `parameters.type` | Sempre `"object"` (anche se vuoto) | -| `parameters.properties` | Sempre `{}` presente, anche se 0 proprietà | -| `tool_choice` | Valori accettati: `"none"`, `"auto"`, oppure `{type:"function",name:"…"}` | -| Chiavi ignote | NON fare strict reject. Logga warning e scarta solo la chiave. | - -#### 0.3.2 Evento di ritorno richiesto da `ai-server` (quando il modello decide di chiamare un tool) - -Quando il modello determina che serve un tool → emetti **3 eventi in ordine ESATTO**: -``` -a) { "type": "response.function_call_arguments.started", "call_id": "call_abc123", "name": "list_recent_reports", "response_id":"resp_X", "item_id":"item_Y" } - (opzionale — se non hai streaming arguments puoi anche saltarlo) - -b) (opzionale) N × { "type": "response.function_call_arguments.delta", "call_id": "call_abc123", "delta": "{\"dat" } - (solo se streammi il JSON argomenti per pezzi) - -c) ✅ EVENTO RICHIESTO OBBLIGATORIO (senza questo il client non esegue il tool): -{ - "type": "response.function_call_arguments.done", - "call_id": "call_abc123", // STRINGA OBBLIGATORIA — serve per la sendToolOutput - "name": "list_recent_reports", // STRINGA OBBLIGATORIA — nome del tool (come sopra) - "arguments": "{\"date_from\":\"2026-08-24\",\"limit\":5}", - "response_id": "resp_xyz", - "item_id": "item_zzz", - "output_index": 0 -} -``` - -**⚠️ Importante**: `arguments` DEVE essere una **STRINGA JSON serializzata** (non un oggetto). Il client fa `JSON.parse(event.arguments)`. Se mandi un oggetto JS → parser fallisce e il tool non viene eseguito. - -#### 0.3.3 Atteso come input successivo (il ritorno del tool dal client) - -Dopo ~500ms-45s, il client manda indietro al S2S upstream: -```jsonc -{ - "type": "conversation.item.create", - "item": { - "type": "function_call_output", - "call_id": "call_abc123", - "output": "5 report trovati. Ultimo: Report_2026-08-24.xlsx - Aquachile ventas" - } -} -→ Poi { "type": "response.create" } -``` -→ L'S2S dovrebbe usare `output` come contesto nel prossimo turno di generazione TTS (quindi parla del risultato, senza tag `[tool]`). - -### 0.4 Checklist di deploy Fase 2 (2026-08-25 — SORGENTE ai-server TROVATA in locale) - -**Prerequisito**: Sorgente backend `ai-server:12345` = `/home/duxiter/s2s/speech_to_speech` (Python puro). -✅ **TEST CURL 2026-08-25 CONFERMATO**: `https://aquachile.azurianlab.com/api/v1/mcp/` è **ATTUALMENTE PUBBLICO** — accetta `tools/list` e `tools/call` SENZA API KEY. Con credenziali dummy `dummy-test-key/secret` restituisce HTTP 200 OUTPUT IDENTICO alla chiamata senza auth. Quindi NON serve valorizzare: -``` -S2S_TOOL_EXECUTION_MCP_API_KEY= -S2S_TOOL_EXECUTION_MCP_API_SECRET= -``` -⚠️ Nota: Il server accetta entrambi gli auth headers, ma attualmente non li valida. Restano configurati come best practice per eventuali versioni future dell'endpoint che attiveranno auth. - -#### Ordine deploy 3 step - -| # | Azione | Perché | -|---|---|---| -| 0 | ~~Valorizza `.env` MCP credentials~~ | ✅ **SUPERATO** — endpoint MCP Aquachile pubblico | -| 1 | **Restart container `s2s_ui`** | Deploy fix formato inject `fmt=nested_session` in [server.py:1054-1102](file:///home/duxiter/s2s/demo/server.py#L1054-L1102) | -| 2 | **Riavvia backend `ai-server:12345`** con il codice aggiornato di `/home/duxiter/s2s/speech_to_speech` (in particolare `api/openai_realtime/service.py`) | Deploy fallback parser retrocompatibile flat→nested in [service.py:267-325](file:///home/duxiter/s2s/speech_to_speech/api/openai_realtime/service.py#L267-L325) | -| 3 | **Hard Reload browser** (Ctrl+Shift+R o Disable cache + refresh) | Pulisce cache vecchio client JS | - -#### Checklist di verifica DOPO deploy 3+1 step - -```bash -# Terminal A -docker logs -f s2s_ui 2>&1 | grep -E 'MCP|Vocero MCP|session.update|function_call_arguments' -``` - -| Step | Trigger | Log atteso nel container | Esito | -|---|---|---|---| -| 1 | Apri pagina demo (connessione WS) | `[MCP INJECT] session.update upstream → tools=79 hasAgentPrompt=True tool_choice=auto` | ✅ Inject partito | -| 2 | Subito dopo step 1 | `[MCP INJECT] session.update upstream inviato (tools=79, fmt=nested_session OK)`
🔴 **NON DEVE** più comparire `[MCP INJECT] suppressed upstream error` — se compare ancora, il deploy di `speech_to_speech service.py` non è riuscito | ✅ Nessun rigetto | -| 3 | Console browser | 0 occorrenze `Unknown or invalid event: session.update` | ✅ Filtro OK | -| 4 | Frase trigger tool: *"¿dónde está el report de ayer?"* | **KEY LOG 🔑**
`[MCP INJECT] ✓ UPSTREAM ha emesso response.function_call_arguments.done! tool=list_recent_reports args_keys=[...]` | ✅ **Strategia B FUNZIONA — il modello produce tool calls native** | -| 5 | 0.5-1s dopo Step 4 | `[Vocero MCP CALL] name=list_recent_reports target=https://aquachile...`
`[Vocero MCP HTTP] name=list_recent_reports status=200`
`[Vocero MCP OUT] name=list_recent_reports preview=...resultKeys=...` | ✅ Tool eseguito realmente via REST Aquachile | -| 6 | 1-2s dopo Step 5 | TTS vocale naturale — es: *"Aquí tienes los 5 reportes de ayer, el más reciente es Report_2026-08-24.xlsx..."* | ✅ Nessun `(list_recent_reports)` / `[tool]` nel testo TTS | -| 7 | Frase non-tool: *"Hola, ¿cómo estás?"* | Risposta standard SENZA tool calls, POST /api/reasoning 200, Node-RED LOG_ONLY OK | ✅ Nessuna regressione Fase 1 | - ---- - -### 0.5 Stato attuale (2026-08-25 11:00) — BLOCCO RISOLTO, pipeline 100% implementata - -#### 🎯 Root Causa Reale (99.99% confidence, sorprendente) - -**Ipotesi iniziale, SUPERATA**: *"ai-server rifiuta strict il campo `tools` perché non è implementato"* - -**Realtà, AUDIT SORGENTE CONFERMATO**: TUTTO il sistema — **backend `speech_to_speech` + proxy `demo/server.py` + client `main.js` / `s2s-ws-client.js`** — è GIA' COMPLETAMENTE IMPLEMENTATO end-to-end per il tool calling nativo OpenAI Realtime GA. **L'unico blocco era un errore di formato payload nel proxy**: - -```python -# ❌ SBAGLIATO (come era prima) — campi alla RADICE -_inject_payload = { - "type": "session.update", - "instructions": "...", - "tools": [...], - "tool_choice": "auto" -} # ← Pydantic SessionUpdateEvent extra=forbid → Unknown or invalid event - -# ✅ CORRETTO (deployato in server.py:1054-1102) — TUTTO dentro session:{} -_inject_payload = { - "type": "session.update", - "session": { - "instructions": "...", - "tools": [...], - "tool_choice": "auto" - } -} # ← Perfetto, corrisponde a runtime_config.session.tools in LLM -``` - -**Prova inconfutabile**: [language_model.py:526-532](file:///home/duxiter/s2s/speech_to_speech/LLM/language_model.py#L526-L532) legge istruzioni, tools e tool_choice **TUTTI dentro `.session.*`**: -```python -instructions = response.instructions if ... else runtime_config.session.instructions -tools = response.tools if ... else runtime_config.session.tools -tool_choice = response.tool_choice if ... else runtime_config.session.tool_choice -``` - -#### 📋 Mappa riassuntiva: 7 componenti TUTTI già funzionanti - -| Componente | File | Stato | Cosa fa | -|---|---|---|---| -| 🔧 **Normalizzatore tool** | `demo/server.py:464-544` | ✅ | 79 tool Aquachile → formato Realtime GA standard, 0 eccezioni | -| 🚀 **Inject WS upstream** | `demo/server.py:1054-1102` | ✅ **NUOVO FIX 2026-08-25** | Invia nested `session:{instructions,tools,tool_choice}` subito dopo tunnel | -| 🛡️ **Fallback parser retrocompatibile** | `speech_to_speech/service.py:267-325` | ✅ **NUOVO FIX 2026-08-25** | Se arrivano campi flat root → promossi a nested `session` | -| 🧠 **LLM + Chat buffer** | `speech_to_speech/LLM/*` | ✅ GIA' ESISTENTE | Tools da sessione, FC/FCO nel chat, pending dict anti-race | -| 📡 **WS response handler (tool call OUT)** | `speech_to_speech/handlers/response.py:336-345` | ✅ GIA' ESISTENTE | Emette `ResponseFunctionCallArgumentsDoneEvent` con arguments=STRINGA JSON, call_id, name, response_id, item_id, output_index=0 | -| 💾 **WS conversation handler (tool output IN)** | `speech_to_speech/handlers/conversation.py:30-96` | ✅ GIA' ESISTENTE | `conversation.item.create function_call_output` con `deferred_items` anti-race | -| 🌐 **Client WS → MCP REST → ritorno WS** | `demo/ws/s2s-ws-client.js:803-1077` + `demo/main.js:2180-2288 + 3023-3043` | ✅ GIA' ESISTENTE | (1) `response.function_call_arguments.done` → dispatch `toolcall` event
(2) `runTool()` branch `agentToolDefs` → `execRemoteMcpTool()` → `POST /api/mcp/tool`
(3) `client.sendToolOutput(callId, output)` → `conversation.item.create function_call_output`
(4) `client.requestResponse()` → prossimo turno TTS | -| 📣 **Proxy MCP REST Aquachile** | `demo/server.py:704-760` | ✅ GIA' ESISTENTE | `POST /api/mcp/tool` JSON-RPC 2.0 tools/call + log `[Vocero MCP CALL/HTTP/OUT]` | -| 🛡️ **Filtro errori WS V2** | `demo/server.py:1713-1792` | ✅ GIA' ESISTENTE | Sopprime `unknown_or_invalid_event` se mai dovesse ricomparire, passthrough altri errori | - -#### 🚀 Prossimo passo: ESEGUIRE I 3 STEP DI §0.4 - -1. ~~Valorizza `.env` MCP API Key/Secret~~ ✅ **SUPERATO** (endpoint pubblico) -2. Restart `s2s_ui` -3. Restart `ai-server` con il codice aggiornato da `/home/duxiter/s2s/speech_to_speech` -4. Hard reload browser (Ctrl+Shift+R) -5. Testa: *"¿dónde está el report de ayer?"* → aspetta il key log `[MCP INJECT] ✓ UPSTREAM ha emesso response.function_call_arguments.done!` - -**Se Step 5 (function_call_arguments.done) non compare dopo 3 frasi trigger**: apri una shell con `docker logs -f ai-server` per vedere se la sessione sta leggendo `.session.tools` dal runtime config. - ---- - -#### ⚙️ MCP MASTER SWITCH (nuovo feature 2026-08-25) -**Controllato da una sola riga in `.env`**: -``` -#S2S_TOOL_EXECUTION_MCP_URL=https://aquachile.azurianlab.com/api/v1/mcp # ⬅️ se commentata/vuota → MCP DISABLED -S2S_TOOL_EXECUTION_MCP_URL=https://aquachile.azurianlab.com/api/v1/mcp # ⬅️ se decommentata/valorizzata → MCP ENABLED -``` - -Implementato come `MCP_EXEC_ENABLED = bool(S2S_TOOL_EXECUTION_MCP_URL)` in [server.py:106-114](file:///home/duxiter/s2s/demo/server.py#L106-L114). Quando **DISABLED** (stato attuale `.env`): - -| Punto di controllo | Comportamento con MCP DISABLED | Riferimento codice | -|---|---|---| -| **Startup log** | `[MCP MASTER] ⛔ DISABLED — S2S_TOOL_EXECUTION_MCP_URL is empty/commented in .env…` | [server.py:172-182](file:///home/duxiter/s2s/demo/server.py#L172-L182) | -| **WS `/v1/realtime` inject tools** | `session.update` contiene **solo `instructions`** (profilo agente); `tools[]` e `tool_choice` **non vengono mai mandati**. Log marker `[MCP INJECT] ⛔ SKIPPED tool injection …`. ⚠️ Il prompt profilo continua a funzionare. | [server.py:1081-1123](file:///home/duxiter/s2s/demo/server.py#L1081-L1123) | -| **`/api/config` bootstrap client** | Invia al browser `agentTools=[]` (invece dei 79) + `searchMcp=false`. Effetti lato client: ranker MCP early exit, prompt non contiene più "Available MCP tools:" e ranking hints, UI pannello MCP mostra "No MCP tools available.", nessun pulsante "Esegui tool". | [server.py:660-694](file:///home/duxiter/s2s/demo/server.py#L660-L694) | -| **`POST /api/mcp/tool` endpoint** | Se un client tenta comunque la chiamata (es. con codice vecchio): log `[MCP DISABLED] ⛔ /api/mcp/tool called but…` + HTTP 503 dettagliato (non crash, non exception trace). | [server.py:721-733](file:///home/duxiter/s2s/demo/server.py#L721-L733) | - -Per **riabilitare la Fase 2 MCP in futuro**, 4 step: -1. ✏️ `.env` → togli `#` davanti a `S2S_TOOL_EXECUTION_MCP_URL=https://aquachile.azurianlab.com/api/v1/mcp` -2. 🔄 Restart `s2s_ui` (deploya MCP_EXEC_ENABLED=True + inject formato nested corretto) -3. 🔄 Restart `ai-server` con codice aggiornato `/home/duxiter/s2s/speech_to_speech` (fallback parser flat→nested) -4. 🌐 Hard reload browser Ctrl+Shift+R - - - ---- - -## 1. Flow di `instructions` — da impostazioni utente a S2S upstream - -**Definizione**: `instructions` è il **system prompt** del protocollo OpenAI Realtime GA. -Viene mandato al backend in 2 punti distinti: - -| Canale | Dove | Destinatario | -|---|---|---| -| ✅ **TUNNEL WS AUDIO** → `session.update` all'inizio di ogni sessione | Browser → tunnel proxy → upstream S2S nativo (`ai-server:12345`) | Usato **dal modello S2S stesso** per la risposta vocale nativa | -| ✅ **REST PARALLELO** → body `POST /api/reasoning` | Browser → `server.py` → Node-RED o OpenAI | Usato **dal reasoning hook** esterno (oggi Fase 1 LOG_ONLY) | - -Entrambi i canali partono dalla stessa funzione generatrice `effectiveReasoningInstructions()` nel client. - -### Step-by-step - -``` -┌────────────────────────────────────────────────────────────────────┐ -│ 1. BASE — DEFAULT_INSTRUCTIONS (main.js:26) │ -│ "You are a friendly voice assistant. Keep replies short..." │ -│ OR textarea Settings #instructions salvato in localStorage │ -│ chiave "s2s.ws.instructions" (main.js:138, 201, 223) │ -└───────────────────────────────────────┬────────────────────────────┘ - │ - ▼ -┌────────────────────────────────────────────────────────────────────┐ -│ 2. effectiveReasoningInstructions() (main.js:516-533) │ -│ Appende in coda, in ordine: │ -│ │ -│ + (se ≥1 tool attivo) TOOL_USE_HINT (main.js:32-35) │ -│ → "do not describe your capabilities... call tool immediately" │ -│ │ -│ + (se searchMcpEnabled + agentToolDefs) MCP_SEARCH_HINT + │ -│ "Available MCP tools: …catalogo completo…" │ -│ │ -│ + (se searchMcpEnabled + tool suggeriti) riga ranking client-side │ -│ "Current user request: \"${lastUserQuery}\". Ranking hint: 1. X │ -│ 2. Y 3. Z — use as secondary signal only" │ -│ │ -│ + (se utente autenticato phone) voceroUserContextText() │ -│ → es: "User profile: name=Juan Pérez phone=+569… account=…" │ -└───────────────────────────────────────┬────────────────────────────┘ - │ - ┌──────────────────┴──────────────────┐ - ▼ ▼ - ┌─────────────────────────────┐ ┌──────────────────────────────┐ - │ 3a. effectiveInstructions() │ │ 3b. POST /api/reasoning │ - │ (main.js:537-539) │ │ body req.instructions │ - │ │ │ (main.js:569) │ - │ • mode=OPENAI → accoda │ │ = effectiveReasoningInst…() │ - │ OPENAI_RENDER_HINT │ │ tale e quale (NO append) │ - │ • mode=NODE_RED / PROXY → │ │ │ - │ ritorna il valore │ │ → server.py lo gira a │ - │ senza modifiche │ │ Node-RED o OpenAI │ - └──────────────┬──────────────┘ └──────────────┬───────────────┘ - │ │ - ▼ ▼ - ┌─────────────────────────────┐ ┌──────────────────────────────┐ - │ 4a. startInstructions = │ │ 4b. /api/reasoning → │ - │ effectiveInstructions() │ │ Node-RED log: │ - │ (main.js:2829) │ │ [S2S NODE_RED LOG_ONLY] │ - └──────────────┬──────────────┘ │ instructions len=… │ - │ └──────────────────────────────┘ - ▼ - ┌─────────────────────────────────────────────────────┐ - │ 5. new S2sWsRealtimeClient({ │ - │ instructions: startInstructions │ - │ voice, tools, noiseGate, audioContext │ - │ }) main.js:2839-2847 │ - └──────────────┬──────────────────────────────────────┘ - │ - ▼ - ┌─────────────────────────────────────────────────────┐ - │ 6. this.options.instructions → _sendSessionUpdate() │ - │ s2s-ws-client.js:995 + 1016 │ - │ { type: "session.update", │ - │ session: { type: "realtime", │ - │ instructions: this.options.…, │ - │ audio:{output:{voice}}, │ - │ tools, tool_choice:"auto" } } │ - └──────────────┬──────────────────────────────────────┘ - │ - ▼ - ┌─────────────────────────────────────────────────────┐ - │ 7. server.py _client_to_upstream — TUNNEL 1:1 │ - │ → forward esatto byte-per-byte all'upstream │ - │ → server.py NON tocca MAI instructions qui │ - │ → Logga solo summary.instructionLength = len() │ - │ (server.py:197-203) — NON MODIFICA │ - └──────────────┬──────────────────────────────────────┘ - │ - ▼ - ┌─────────────────────────────────────────────────────┐ - │ 8. ai-server:12345 riceve session.update → │ - │ istruzioni usate come system prompt da VLM/LMM │ - │ per TUTTA la durata della sessione finché │ - │ non arriva un altro session.update (patch) │ - └─────────────────────────────────────────────────────┘ -``` - -### Patch di `instructions` durante la sessione (viva) -Se vuoi aggiornare istruzioni a metà conversazione **senza chiudere la WS**: -- Client → chiama `client.updateSession({ instructions })` (main.js:1021-1035) -- Oppure, in futuro: **proxy server-side inietta patch** via `upstream.send({type:"session.update", session:{...}})` in qualsiasi momento del tunnel - -### Tabella riassuntiva — chi oggi modifica `instructions`? - -| Livello | Modifica? | Note | -|---|---|---| -| 🔵 Browser `main.js` | **Sì** — generatore principale | DEFAULT_INSTRUCTIONS + hints + user context | -| 🟣 Browser `s2s-ws-client.js` | **Solo forwarding** | Incapsula in `session.update` | -| 🟢 Proxy `server.py` tunnel WS | **NO** — copia byte-per-byte | Logga solo lunghezza, non tocca | -| 🟠 Proxy `server.py` reasoning REST | **Sì (Modalità B)** | Usa `req.instructions` come system part nel prompt OpenAI (Fase 2) | -| 🔴 Upstream `ai-server:12345` | **Sì** — applica come system prompt | Entra nel ciclo STT→VLM→TTS | - ---- - -## 2. Ranking tool MCP lato client + `MCP_SEARCH_TRANSLATION_PHRASES` - -**Obiettivo**: quando arriva la query utente (es. `"Quiero el reporte de hoy"` in spagnolo), -ordinare velocemente i tool MCP del catalogo Aquachile per **rilevanza**, così -le `instructions` possono includere un hint di ranking ("prova prima questi 3") e -il modello sceglie lo strumento giusto con meno tentativi. - -### 2.1 Perché serve la traduzione -Il catalogo dei tool `agentToolDefs` arriva dall'endpoint Aquachile MCP: -- `tool.name` e `tool.description` sono scritti in **INGLESE** per convenzione di - OpenAI Functions / MCP protocol. -- Ma l'utente parla **spagnolo del Cile o italiano** con l'agente. - -Senza traduzione il matching `frase ES/IT ↔ tool EN` → **score 0** (zero corrispondenze). -I tool non vengono mai suggeriti. - -### 2.2 I due dizionari di traduzione (main.js) - -| Costante | Tipo | Riga | Cosa fa | -|---|---|---|---| -| `MCP_SEARCH_TRANSLATION_PHRASES` | `[RegExp, string][]` frasi complete | [L51-L70](file:///home/duxiter/s2s/demo/main.js#L51-L70) | Sostituisce **frasi multi-parola** prima del tokenizer. Es. `reporte de hoy → today report`. **Priorità alta**: viene applicato PER PRIMO perché le frasi intere non si possono ricostruire da token singoli. | -| `MCP_SEARCH_TRANSLATION_TOKENS` | `Record` token singolo | [L72](file:///home/duxiter/s2s/demo/main.js#L72) | Sostituisce il **resto** parola per parola dopo la phase-phrase. Es. `ayuda → help`, `cliente → customer`. | - -### 2.3 Catalogo completo traduzioni oggi attivo - -#### Phrase-level (MCP_SEARCH_TRANSLATION_PHRASES) -| Lingua | Input | Output EN | Riga | -|---|---|---|---| -| 🇪🇸 | `informaciones del usuario` / `informacion del usuario` | `user information` | L52-L53 | -| 🇮🇹 | `informazioni utente` / `informazione utente` | `user information` | L54-L55 | -| 🇪🇸 | `report del dia` / `reporte del dia` | `day report` | L56-L57 | -| 🇮🇹 | `report di oggi` | `today report` | L58 | -| 🇪🇸 | `reporte de hoy` | `today report` | L59 | -| 🇮🇹 | `report giornaliero` | `daily report` | L60 | -| 🇪🇸 | `reporte diario` | `daily report` | L61 | -| 🇪🇸 | `mi numero es` | `my number is` | L62 | -| 🇮🇹 | `il mio numero e` | `my number is` | L63 | -| 🇮🇹 | `numero di telefono` | `phone number` | L64 | -| 🇪🇸 | `numero telefonico` | `phone number` | L65 | -| 🇪🇸 | `numero de telefono` | `phone number` | L66 | -| 🇪🇸 | `numero de whatsapp` | `whatsapp number` | L67 | -| 🇪🇸 | `informacion api` | `api information` | L68 | -| 🇮🇹 | `informazioni api` | `api information` | L69 | - -> 💡 Aggiungere nuove frasi: **è sufficiente aggiungere righe qui**, senza toccare il codice del ranking. La pipeline le applicherà automaticamente. - -### 2.4 Pipeline di ranking chiamata per ogni turno - -``` -Utente dice: "Quiero el reporte diario y informaciones del usuario" - │ - ▼ -rankAgentTools(query) main.js:1262 - │ - ▼ -buildMcpSearchTexts(query) main.js:1330 - │ - ├─── [0] normalizeMcpSearchText(query) ← versione ORIGINALE normalizzata - │ = "quiero el reporte diario y informaciones del usuario" - │ - └─── [1] translateMcpSearchTextToEnglish(query) main.js:1314 - │ - ├─ step 1: normalize - ├─ step 2: loop replace per tutte le entry di MCP_SEARCH_TRANSLATION_PHRASES - │ → "quiero el daily report y user information" - ├─ step 3: split token, map per MCP_SEARCH_TRANSLATION_TOKENS singoli - │ → "want the daily report and user information" - └─ step 4: normalize finale - │ - ▼ -searchTexts = [ originale normalizzato, versione tradotta in EN ] - (duplicati eliminati via new Set) - │ - ▼ -tokens = split searchTexts + lunghezza ≥ 3 chars + dedup - = [ quiero, reporte, diario, informaciones, usuario, - want, daily, report, and, user, information ] - │ - ▼ -Check rule hard-coded: - dailyReportIntent = match ("day"|"daily"|"today") + "report" → TRUE - (se match: boost score dei tool che hanno report in name/description) - │ - ▼ -Per ogni tool in agentToolDefs[]: - score = somma (frequenza token in tool.name + tool.description) - + 2× bonus dailyReportIntent se tool matcha "report" - + 3× bonus se esatta match name vs query originale -Sort(score desc, name asc) - │ - ▼ -Torna al chiamante: [ {tool:"get_daily_report", score:42}, - {tool:"get_user_info", score:31}, - ... ] - │ - ▼ -Usato in 2 punti: - A) effectiveReasoningInstructions() main.js:525-529 → hint "Current user request… - ranking hint: 1. get_daily_report… 2. get_user_info…" dentro le instructions - B) UI pannello (se visibile) — lista tool suggeriti accanto alla trascrizione -``` - -### 2.5 Quando è chiamato `rankAgentTools` — ogni turno? - -| Trigger | Frequenza | Perché | -|---|---|---| -| `maybeRunOpenAiReasoning(transcript)` subito dopo transcript STT | 1× per turno utente | Include ranking hint dentro `instructions` che andrà a Node-RED / OpenAI | -| Live edit textarea domanda (autocomplete) | Mentre utente scrive | Suggerisce tool nella UI | - -### 2.6 Disattivazione automatica - -Ranking ritorna `[]` vuoto e salta tutta la traduzione se: -- `searchMcpEnabled == false` (MCP Aquachile non configurato) -- `agentToolDefs.length == 0` (catalogo tool non ricevuto da `/agents/profile`) -- Query normalizzata è vuota o troppo corta -- Nessun token dopo split ≥ 3 caratteri - ---- - -## 2bis. DOVE VEDERE I LOG MCP — due postazioni - -Il ranking MCP produce log in **2 posti diversi** per design: - -| Postazione | Tipo di log | Filtro DevTools / grep | Quando appare | -|---|---|---|---| -| 🖥️ **Browser — DevTools Console** | Client-side ranking dettagliato: **tutta la pipeline translate → build → rank per-tool matching** | `MCP RANK` (case-sensitive) | **Sempre** per ogni turno — anche in caso di EARLY EXIT (motivo esplicito: `searchMcpEnabled=false`, `agentToolDefs=0`, ecc.) | -| 🐳 **Server — container `s2s_ui` (uvicorn Python)** | Server-side **snapshot del payload `instructions`** quando arriva `POST /api/reasoning` — quanti tool MCP ci sono nel catalogo hint, TOP3 suggeriti dal ranking lato client | `grep '[MCP RANK]'` o filter terminale `MCP RANK` | **1 riga per ogni POST /api/reasoning** (lo hai già nel flusso tra `[INPUT UTENTE]` e `[EXT][NODE_RED] reasoning POST`) | - -### Nel tuo log di oggi (FASE 1 LOG_ONLY, senza MCP tools abilitati) - -Aspettati questo flusso dopo il deploy di adesso: - -``` -7|s2s_ui | INFO [s2s] [INPUT UTENTE] client=… stt=Necesito el report. -7|s2s_ui | INFO [s2s] [MCP RANK] reasoning payload transcript="Necesito el report" instructionsLen=97 hasMcpCatalogHint=False hasRankingHint=False mcpCatalogTools=0 top3Suggested=none -7|s2s_ui | DEBUG [s2s] [EXT][NODE_RED] reasoning POST http://localhost:1881/api/reasoning … -``` - -E se apri **DevTools Console** (Verbose/Debug on, Disable cache ✓ Ctrl+Shift+R) vedi: - -``` -[MCP RANK] updateMcpToolSuggestions ENTRY partial=false itemId=- query="necesito el report" searchMcpEnabled=false -[MCP RANK] ════════════════════════════════════════ -[MCP RANK] rankAgentTools START query="necesito el report" searchMcpEnabled=false agentToolDefsCount=0 -[MCP RANK] buildSearchTexts raw="Necesito el report" normalized="necesito el report" translated="necesito el report" count=1 final=["necesito el report"] -[MCP RANK] translate input="necesito el report" phrasesApplied=0 tokensApplied=0 output="necesito el report" -[MCP RANK] → EARLY EXIT reason="searchMcpEnabled=false — da /api/config: MCP Aquachile feature OFF oppure S2S_TOOL_EXECUTION_MCP_URL non configurato; agentToolDefs=0 — catalogo tool MCP vuoto: profilo agente non ha tools in agentProfile via Aquachile /api/agents/profile" searchMcpEnabled=false normalized=true agentToolDefs=0 -[MCP RANK] ════════════════════════════════════════ (empty result) -[MCP RANK] updateMcpToolSuggestions RESULTS partial=false matchedTools=0 ranked=none -``` - -### Quando il ranking MCP inizia a produrre score > 0 - -Affinché un turno abbia log MCP con tool score>0, devono essere veri **TUTTI e 3**: - -1. `.env` ha `S2S_TOOL_EXECUTION_MCP_URL` configurato (URL Aquachile MCP) **e** `searchMcpEnabled=true` ritorna da `/api/config` -2. `/agents/profile` Aquachile torna **almeno 1 tool** in `agentTools[]` (campo `json.agentTools`) -3. La query utente ha token ≥ 3 chars che matchano `tool.name` o `tool.description` o `tool.parameters` - -Se 1 solo dei 3 è falso → **early exit spiegato nel log `[MCP RANK] → EARLY EXIT reason="…"`**. - ---- - -## 3. Come estendere (quick cheatsheet) - -| Se vuoi… | Dove modificare | -|---|---| -| Aggiungere 1 frase tradotta ES/IT → EN per tool matching | `MCP_SEARCH_TRANSLATION_PHRASES` [main.js](file:///home/duxiter/s2s/demo/main.js#L51-L70) — nuova riga | -| Aggiungere 1 parola singola tradotta | `MCP_SEARCH_TRANSLATION_TOKENS` [main.js:72](file:///home/duxiter/s2s/demo/main.js#L72) | -| Boost score di un tipo di tool (es. report) | `rankAgentTools` [main.js:1268-1270](file:///home/duxiter/s2s/demo/main.js#L1268-L1270) + mappa subito dopo | -| Aggiungere nuovo hint a `instructions` all'avvio sessione | `effectiveReasoningInstructions()` [main.js:516-533](file:///home/duxiter/s2s/demo/main.js#L516-L533) — nuova concatenazione | -| Iniettare `instructions` server-side (segret@ dati Aquachile) senza toccare client | **Proxy tunnel** `realtime_proxy()` in [server.py](file:///home/duxiter/s2s/demo/server.py#L891-L908) → `await upstream.send({type:"session.update", session:{instructions}})` **prima** dei 2 `create_task` | diff --git a/s2s-client/INJECTIONS.md b/s2s-client/INJECTIONS.md deleted file mode 100644 index 0555cc6..0000000 --- a/s2s-client/INJECTIONS.md +++ /dev/null @@ -1,498 +0,0 @@ -# Inject pipeline — caller context & reference material - -Documento ufficiale di tutti i blocchi di contesto che il server inietta -automaticamente nel prompt LLM **all'inizio di ogni sessione**, sia per il -canale **WebSocket realtime** (`/v1/realtime`, patch di `session.update`) sia -per l'endpoint **HTTP reasoning** (`POST /api/reasoning`, augmentation di -`instructions` e `user_context`). - -Tutto il sistema è **generico / deploy-agnostic** per scelta architetturale: -nessun campo viene hardcodato. Ogni blocco accetta payload arbitrari e li -serializza in JSON direttamente. Qualsiasi errore di rete / JSON non -interrompe mai il flusso: il blocco problematico viene solo saltato con -una riga `[INJECT-*] ⏭️ skipped` nel log server. - ---- - -## 0. Master flag: `S2S_INJECT_PROFILE` - -Tutta la pipeline è sotto **un unico master flag** lato server. - -| Valore env `S2S_INJECT_PROFILE` | Comportamento | -|---|---| -| `false` / non impostato | **Pure passthrough.** Nessuna fetch upstream, nessuna modifica a `session.update` o al body `/api/reasoning`. Il proxy passa tutto invariato. | -| `true` / `1` / `yes` / `on` | Pipeline inject attiva. I singoli blocchi poi dipendono dagli env specifici e dai query params della URL del client. | - -Perché esiste: su deploy generici (nessuna integrazione con AzurianLab / -Aquachile / sistemi interni) il client rimane un puro speech-to-speech -passthrough, senza dipendere da endpoint esterni. - ---- - -## 1. Blocco episodio podcast — `episode_id` - -**Priorità massima.** Quando c'è, viene considerato il riferimento PRINCIPALE -e più fidato per tutta la sessione. - -### Trigger (quando si attiva) - -Una qualunque delle due: -1. URL pagina browser → query string `?episode_id=episode-xxx` -2. Body `POST /api/reasoning` → campo `episode_id: "episode-xxx"` - -### Sorgente dati - -GET plain verso l'endpoint Aquachile AzurianLab: - -``` -https://aquachile.azurianlab.com/api/v1/podcast/episodes/{episode_id} -``` - -Parametri fetch: -- timeout 15 s -- `follow_redirects: true` -- **Nessuna auth** (endpoint pubblico) - -Formato risposta accettato: -- `Content-Type: application/json` → oggetto arbitrario o array -- `{"result": }` → wrapper supportato, il contenuto viene "spacchettato" -- `text/plain` → usato come stringa raw - -### Cap - -24.000 caratteri dopo serializzazione JSON (transcript lunghi). -Se supera → troncato con `...` append. - -### Wrap applicato - -``` -< PODCAST_EPISODE_HINT > -<<>> -{ } -<<>>. This is the episode the caller is currently interacting with — answer with reference to it first. -``` - -**Hint testuale** (in testa, letto dal modello come primissima frase del blocco): - -> Podcast episode context loaded from the page `episode_id` query param (current episode the user is referencing). Treat the episode fields (title, description, transcript, script, show notes, guests, audio metadata, etc.) as the **PRIMARY trusted reference material** for this session. - -### Campi supportati (esempi — lista NON esaustiva, qualsiasi campo extra viene incluso) - -- metadati base: `id`, `title`, `slug`, `description`, `summary`, `publishedAt`, `durationSeconds` -- contenuti: `transcript`, `podcastScript`, `script`, `chapters[]`, `showNotes` -- persone: `host`, `guests[]`, `author`, `guestsInfo[]` -- audio: `audioUrl`, `audioFile`, `waveform`, `sampleRate` -- classificazione: `tags[]`, `topics[]`, `category`, `season`, `episodeNumber` -- riferimenti incrociati: `reportId`, `scheduleId`, `company`, `product` - -### Riferimenti codice - -- fetch upstream: [_fetch_podcast_episode](file:///home/duxiter/s2s/s2s-client/server.py#L1010-L1078) -- wrap + serialize + cap 24k: [_resolve_episode_context](file:///home/duxiter/s2s/s2s-client/server.py#L475-L504) -- hint costante: [PODCAST_EPISODE_HINT](file:///home/duxiter/s2s/s2s-client/server.py#L426-L429) - ---- - -## 2. Blocco profilo chiamante — `phoneNumber` - -Contesto identità del chiamante. Viene usato per il modello quando risponde -(riferirsi all'utente per nome, conoscere la sua azienda, ruolo, ecc.). - -### Trigger - -1. URL browser → `?phoneNumber=%2B` -2. Body `/api/reasoning` → `phoneNumber: "+…"` - -### Sorgente dati - -``` -GET VOCERO_USER_PHONE_AUTH_URL?phoneNumber= -``` - -Se è configurato anche `S2S_LOGIN_BY_PHONE`, PRIMA della profile fetch: -``` -POST S2S_LOGIN_BY_PHONE body { "phoneNumber": "..." } -``` -Da questa risposta il proxy estrae un bearer token e lo inoltra come -`Authorization: Bearer ` sulle chiamate successive (profile, reports, -summary). - -Formato risposta: JSON arbitrario, wrapper `{"result": ...}` supportato. - -### Cap - -1.600 caratteri dopo JSON serialize. - -### Wrap - -``` - Caller profile resolved from the page phoneNumber: -{ }. -Use this as trusted caller context when relevant. -``` - -### Riferimenti codice - -- login by phone: [_login_by_phone](file:///home/duxiter/s2s/s2s-client/server.py#L812-L890) -- fetch profile: [_fetch_user_profile_for_phone](file:///home/duxiter/s2s/s2s-client/server.py#L1081-L1134) -- wrap serialize: [_resolve_user_context_text](file:///home/duxiter/s2s/s2s-client/server.py#L432-L444) - ---- - -## 3. Blocco lista reports / script schedulati - -Riferimento "storico" dei contenuti preparati prima della sessione. Non sono -contesto live, ma materiale che il modello deve sapere esiste (e a cui -riferirsi se l'utente chiede di report pregressi, script, podcast schedulati). - -### Trigger - -Solo env: `S2S_REPORT_LIST` deve essere valorizzato a un URL valido. -**Funziona anche SENZA `phoneNumber`** (lista reports generica per tutti). - -Se `phoneNumber` è presente lo passa come query param all'endpoint. - -### Sorgente dati - -``` -GET S2S_REPORT_LIST[?phoneNumber=] -``` - -Wrapper `{"result": [...]}` supportato. - -### Cap - -12.000 caratteri sul blocco COMPLETO (ogni podcast script può essere lungo). - -### Wrap + filtri + sort - -``` - Scheduled reports / podcast scripts available for this caller before the current session. - Each entry is a scheduled report; use the podcastScript contents as trusted reference material - when the user asks about scheduled topics, reports, or prior content. -<<>> -[ - { - "sourceScheduleLabel": "...", - "date": "2026-09-06T…", - "podcastScript": "…" - }, - … ordinati per data DESC (nuovi prima) … -] -<<>> -``` - -Regole per ogni entry: -1. **Solo dict** vengono tenuti (stringhe/int scartati). -2. Per ogni entry estrae 3 campi con fallback a nested shape: - - Label: `sourceScheduleLabel` oppure `sourceSchedule.label` - - Date: `date` oppure `sourceSchedule.date` - - Script: `podcastScript` -3. Ordinamento **data DESC** (nuovi prima) con parser robusto: - - ISO datetime / date strings - - `Date` / `DateTime` Python (se deserializzati) - - Unix timestamp int/float - - Lexicografico DESC come fallback per stringhe ISO-ish - - Valori nulli / non-parse-abili finiscono in fondo. - -### Riferimenti codice - -- fetch: [_fetch_reports_list](file:///home/duxiter/s2s/s2s-client/server.py#L668-L745) -- parse data sort key: [_parse_date_key](file:///home/duxiter/s2s/s2s-client/server.py#L507-L515) -- wrap + filtro + sort: [_resolve_reports_context](file:///home/duxiter/s2s/s2s-client/server.py#L518-L666) - ---- - -## 4. Blocco summary ultima conversazione - -Sintesi della chiamata/chat IMMEDIATAMENTE precedente a questa. Usato dal -modello per "ricordarsi" cosa si è detto l'ultima volta senza conservare -storico lunghissimo nel prompt. - -### Trigger - -Entrambe le alternative sono mutuamente esclusive: `S2S_LATEST_SUMMARY_TEXT` -ha **priorità assoluta** se valorizzato. - -| Modalità | Trigger | -|---|---| -| **A — HTTP fetch (dinamico per caller)** | env `S2S_LATEST_SUMMARY` impostato **AND** `phoneNumber` presente in URL/body | -| **B — Testo statico hardcoded (override)** | env `S2S_LATEST_SUMMARY_TEXT` impostato (stringa non vuota) — **ignora completamente** `S2S_LATEST_SUMMARY`, `phoneNumber`, login-by-phone, Bearer auth. Utile quando l'operatore vuole iniettare una versione **pulita, essenziale e pre-pulita** del summary, senza dipendere da nessun endpoint upstream. | - -### Sorgente dati - -**Modalità A (HTTP fetch):** -``` -GET S2S_LATEST_SUMMARY?phoneNumber= -``` -Wrapper `{"result": }` supportato. -Accetta SIA JSON che plain text (diversi backend summary ritornano testo semplice). - -**Modalità B (override statico):** -- Nessuna chiamata HTTP. Viene usato direttamente il valore grezzo di `S2S_LATEST_SUMMARY_TEXT` dal file `.env`. -- Le sequenze di escape `\n` nel valore env vengono **interpretate** come a-capo vero (stesso comportamento di `S2S_PRIMARY_PROMPT`), quindi è possibile scrivere summary multi-line in una sola riga del `.env`. -- Esempio: - ```env - S2S_LATEST_SUMMARY_TEXT=Última conversación 2026-09-22:\n- Usuario preguntó por mortalidad salmón AquaChile semana 38.\n- Se refirió al reporte Porcentaje Mortalidad. - ``` -- Il valore viene passato as-is a `_resolve_latest_summary_context` → il wrapper `LATEST_SUMMARY_HINT` e il cap a 1600 caratteri vengono applicati normalmente. - -### Cap - -1.600 caratteri (applicato da `_resolve_latest_summary_context` sia in modalità A che B). - -### Wrap - -``` - Latest conversation summary for this caller (most recent before the current session): -<<>> - -<<>>. -Use this as trusted history when the user references prior calls. -``` - -### Riferimenti codice - -- fetch HTTP (modalità A): [_fetch_latest_summary_for_phone](file:///home/duxiter/s2s/s2s-client/server.py#L1563-L1654) -- override statico (modalità B) → riga iniziale `if S2S_LATEST_SUMMARY_TEXT:` dentro la funzione sopra -- wrap: [_resolve_latest_summary_context](file:///home/duxiter/s2s/s2s-client/server.py#L987-L1012) - ---- - -## 5. Blocco `user_context` custom dal browser (SOLO `/api/reasoning`) - -**Canale solo HTTP reasoning.** -Non è nel WS: il WS non ha campo user_context nel protocollo realtime -OpenAI (tutto passa per `session.instructions`). - -Composizione lato client in [main.js fetchOpenAiReasoningAnswer](file:///home/duxiter/s2s/s2s-client/main.js#L1337-L1364): - -```js -const profileCtx = voceroUserContextText(); -const ragCtx = customRagContextText(); -const user_context = [profileCtx, ragCtx] - .map(s => s.trim()).filter(Boolean).join("\n\n"); -``` - -### Dove va a finire - -Nel body a monte sia NODE_RED sia OPENAI, questo blocco viene **APPESO DOPO** -tutti i blocchi iniettati server-side: - -``` -user_context finale = - [1. episode] ← solo se episode_id - [2. profile] ← solo se phoneNumber + env profilatura - [3. reports] ← solo se env S2S_REPORT_LIST - [4. summary] ← solo se phoneNumber + S2S_LATEST_SUMMARY - + browser user_context (profileCtx + ragCtx) -``` - ---- - -## Ordine finale nel prompt LLM - -Questa è la sequenza **letterale** con cui i blocchi vengono concatenati -dentro `session.instructions` (WS) e in `instructions` / `user_context` -(reasoning HTTP). - -``` -1. EPISODIO PODCAST ← PRIORITÀ PIÙ ALTA (primary trusted reference) -2. PROFILO CHIAMANTE ← identity / caller profile -3. REPORTS SCHEDULATI ← scheduled / prior content -4. SUMMARY ULTIMA CALL ← history più recente -5. Base instructions (prompt predefinito o primary prompt) -6. (solo reasoning) user_context custom inviato dal browser -``` - -Perché questo ordine: -- più in alto nel prompt = più peso / attenzione dal modello. -- l'episodio attuale è il materiale che l'utente ha esplicitamente richiesto - aprendo la pagina con `?episode_id=`, quindi merita massimo peso. -- il profilo chiamante va sempre prima di "contenuti generici" (reports e - summary) perché serve per coerenza nel riferirsi all'utente. -- reports = contenuti schedulati PRIMA della sessione corrente → più vecchi - dell'ultima chiamata, quindi messi PRIMA del summary ultima chiamata che - è il contenuto più "vivo". - -Implementazione ordine: [_augment_instructions_with_profile](file:///home/duxiter/s2s/s2s-client/server.py#L1149-L1159) -```python -contexts = [c for c in [episode_ctx, profile_ctx, reports_ctx, summary_ctx] if c] -``` - ---- - -## Punti di innesco (quando viene calcolato / applicato) - -### Canale WebSocket — `/v1/realtime` - -**MOMENTO 1 (solo una volta):** apertura WS. - -Nel handler [@app.websocket("/v1/realtime")](file:///home/duxiter/s2s/s2s-client/server.py#L1791-L1959) -appena la WS viene accettata: -1. parsa `ws.url.query` per `phoneNumber` e `episode_id` -2. esegue login (se attivo) → profile → episode → reports → summary -3. salva TUTTI i blocchi già wrappati e serializzati nel dict `session_ctx`: - ```python - session_ctx = { - "injected_episode_context": "...", - "injected_profile_context": "...", - "injected_reports_context": "...", - "injected_summary_context": "...", - ... - } - ``` - -**MOMENTO 2 (ogni `session.update` client→upstream):** nel task -[_client_to_upstream](file:///home/duxiter/s2s/s2s-client/server.py#L2649-L2661) -ogni frame in uscita viene passato a: - -```python -_patch_client_session_update_with_profile( - frame_text, - user_context_text = profile_ctx, - reports_context_text = reports_ctx, - summary_context_text = summary_ctx, - episode_context_text = episode_ctx, # ← nuovo -) -``` - -Se il frame NON è `session.update` → ritorna **identico** e non viene loggato -(per evitare spam). -Se è `session.update` → patch del campo `payload["session"]["instructions"]`. - -### Canale HTTP — `POST /api/reasoning` - -**Ogni chiamata** ricostruisce i blocchi da zero nel -[handler `/api/reasoning`](file:///home/duxiter/s2s/s2s-client/server.py#L1411-L1577): -1. legge `req.phoneNumber` + `req.episode_id` -2. fetch episodio (se episode_id) + login + profile + reports + summary -3. costruisce `user_context_parts` e `effective_instructions` -4. inoltra al backend (NODE_RED o OPENAI) - ---- - -## Quando un blocco viene SKIPPATO (niente inject) - -Tutti i blocchi hanno 5 possibili ragioni di skip. Nessuna rompe mai il -flusso: ogni caso produce una riga `[INJECT-*] ⏭️ skipped` nei log e basta. - -| Causa | Log | -|---|---| -| Master flag `S2S_INJECT_PROFILE=false` | `[INJECT-PROFILE] ⏭️ skipped (S2S_INJECT_PROFILE=false)` | -| Parametro mancante (es. `phoneNumber` non in URL) | `[INJECT-*] ⏭️ skipped ( missing)` | -| Endpoint env non configurato | `[INJECT-*] ⏭️ skipped (env for ... empty)` | -| Upstream HTTP ≠ 200 | `[INJECT-*] ⛔ upstream HTTP ` | -| Upstream ha ritornato vuoto / null / `{}` / `[]` | `[INJECT-*] ⏭️ upstream returned empty` | -| Eccezione di rete (timeout, DNS, SSL) | `[INJECT-*] ⛔ fetch unreachable error=` | - ---- - -## Marcatori log / marker nel prompt - -Ogni blocco è **auto-documentante** per ispezione dei log con coppie di -marker: - -``` -<<>> / <<>> -<<>> / <<>> -<<>> / <<>> -``` - -Quando `S2S_DEBUG_PROMPT=true` viene loggato il contenuto COMPLETO di ogni -blocco con i tag `[DEBUG-EPISODE]`, `[DEBUG-REPORTS]`, `[DEBUG-SUMMARY]` sia -all'atto del load (WS connect) sia dopo l'augment delle instructions (prima -di inoltrare a monte). **WARNING:** questo env può loggare PII. - ---- - -## Tabella riepilogo: trigger per ogni blocco - -| # | Blocco | Trigger | env richiesto | parametro | cap | -|---|---|---|---|---|---| -| 1 | Episodio podcast | `episode_id` in URL o body | (nessuno — URL hardcodato Aquachile) | `episode_id=` | 24 k | -| 2 | Profilo chiamante | `phoneNumber` | `VOCERO_USER_PHONE_AUTH_URL` | `phoneNumber=` | 1,6 k | -| 3 | Reports schedulati | sempre se env | `S2S_REPORT_LIST` | opzionale `phoneNumber=` | 12 k | -| 4 | Summary ultima call | `phoneNumber` **oppure** override statico | `S2S_LATEST_SUMMARY` (HTTP) **o** `S2S_LATEST_SUMMARY_TEXT` (statico, ha priorità) | `phoneNumber=` (solo modalità HTTP; override statico non richiede nessun param) | 1,6 k | -| 5 | Browser user_context | solo reasoning | (nessuno) | body `user_context` | illimitato | - ---- - -## Error handling strategico - -Perché tutti gli errori sono silenziosi (log + skip) e non abortiscono: - -> Se il backend dei profili è giù per manutenzione 5 minuti non vogliamo -> che il Voice Agent smetta di funzionare. Semplicemente l'assistente non -> conosce l'identità del chiamante per 5 minuti, ma parla normalmente. - -L'utente non si accorge di niente. L'operatore legge i log e vede le righe -`⛔`; può risolvere offline. - -Se volessi forzare il fail (raro, su deploy dedicato), si trasformerebbero -le `return None` finali in `raise HTTPException(...)` — ma per default -non è il comportamento voluto. - ---- - -## Appendice A — Start-session modes (`S2S_START_SESSION_MODE`) - -Oltre alla inject pipeline lato server, è presente una feature lato client che -governa **come e se la sessione vocale inizia in automatico** e se il modello -saluta per primo (in modo identico alla wake-word "Hola Vocero"). - -### Valori supportati - -| `S2S_START_SESSION_MODE` | Chi inizia? | Richiede click utente? | Trigger greet iniziale | -|---|---|---|---| -| *(vuoto) / default* | Utente, tap manuale Orb | ✅ | No | -| `TALK` | Auto dopo 2s con overlay unlocker | ✅ (1 click policy-safe su Safari/iOS) | WS client: `sendUserText("hola vocero") + requestResponse()` dopo `session.updated` | -| `TALKFIRST` | Auto dopo 2s **SENZA click** (se possibile) | ❌ se mic già "allow always"; fallback unlocker se `getUserMedia` fallisce | **Stesso identico codice della wake-word vera:** `pendingWakeWordConfirmationText = "hola vocero"` (main.js `case "connected"` → `sendUserText + requestResponse`) | - -### Warmup 2s - -Il timer non parte prima di 2000 ms per lasciare terminare: -- `fetchVoceroUserProfile()` (identity chiamante) -- `fetchVoceroReportsList()` (storico script podcast) -- fetch episode (`episode_id`) se presente -- `GET /api/config` (con la quale il client apprende `startSessionMode`) - -Senza warmup le injection lato server potrebbero ancora non essere completate e -il greet iniziale arriverebbe "cieco" (senza contesto episodio/profilo). - -### Fallback di `TALKFIRST` - -Nel 99% dei casi `getUserMedia()` fuori da una user gesture fallisce -(NotAllowedError / NotReadableError su Safari, Chrome con policy strict, iOS). -In tal caso: -1. si chiude il client WS (`teardown()`) -2. stato torna `idle` -3. si mostra `#talk-unlocker` con la dicitura: - - **"Se requiere permiso de micrófono"** - - **"Toca en cualquier lugar para permitir el audio y empezar"** -4. `pendingWakeWordConfirmationText` NON viene svuotato → quando l'utente - toccherà, `case "connected"` triggerà comunque la greet come wake-word. - -### Riferimenti codice - -| Componente | File | Range righe | -|---|---|---| -| Lettura env + banner startup + `/api/config` exposure | [server.py](file:///home/duxiter/s2s/s2s-client/server.py) | [L150](file:///home/duxiter/s2s/s2s-client/server.py#L150), [L196-L212](file:///home/duxiter/s2s/s2s-client/server.py#L196-L212), [L1383-L1400](file:///home/duxiter/s2s/s2s-client/server.py#L1383-L1400) | -| Overlay HTML unlocker | [index.html](file:///home/duxiter/s2s/s2s-client/index.html#L32-L39) | L32-L39 | -| Stili overlay | [style.css](file:///home/duxiter/s2s/s2s-client/style.css#L145-L215) | L145-L215 | -| Variabile globale + parse config client | [main.js](file:///home/duxiter/s2s/s2s-client/main.js#L628-L632) | L628-L632 | -| `fetchConfig()` parsing + `reportDebug("B")` | [main.js](file:///home/duxiter/s2s/s2s-client/main.js#L2309-L2320) | L2309-L2320 | -| `new S2sWsRealtimeClient({startWithResponse})` | [main.js](file:///home/duxiter/s2s/s2s-client/main.js#L2683-L2692) | L2683-L2692 | -| Scheduling + `tryTalkFirstDirect()` + unlocker gesture | [main.js](file:///home/duxiter/s2s/s2s-client/main.js#L2976-L3083) | L2976-L3083 | -| `onClientStatus("connected")` → wake-word inject flow | [main.js](file:///home/duxiter/s2s/s2s-client/main.js#L2897-L2914) | L2897-L2914 | -| WS client → `TALK` mode sendUserText("hola vocero") + `requestResponse()` | [s2s-ws-client.js](file:///home/duxiter/s2s/s2s-client/ws/s2s-ws-client.js#L688-L713) | L688-L713 | - ---- - -## Riferimenti file - -| File | Ruolo | -|---|---| -| [server.py](file:///home/duxiter/s2s/s2s-client/server.py) | Tutta la pipeline inject: fetch, wrap, patch, handler WS + reasoning | -| [main.js](file:///home/duxiter/s2s/s2s-client/main.js) | Passaggio client `?phoneNumber` + `?episode_id` → WS query params e POST `/api/reasoning` body | -| [CHANGELOG.md](file:///home/duxiter/s2s/s2s-client/CHANGELOG.md) | History rilasci / modifiche alla inject pipeline | diff --git a/s2s-client/README.md b/s2s-client/README.md index 90de103..4abd611 100644 --- a/s2s-client/README.md +++ b/s2s-client/README.md @@ -10,247 +10,26 @@ short_description: Voice chat over WebSocket against a HF speech-to-speech hf_oauth: true --- -# Realtime Voice Demo (WebSocket transport) +# Realtime voice client -Browser voice-chat UI for the -backend. The browser streams mic audio over a WebSocket using the OpenAI -Realtime **GA** protocol and plays back the assistant's audio as it arrives. +Browser voice-chat UI and FastAPI server for an OpenAI Realtime-compatible +speech-to-speech backend. The browser streams microphone audio over WebSocket, +plays assistant audio, displays transcripts, and offers Spanish controls. ---- +The complete [usage guide](../docs/client/usage.md) covers local startup, +connection modes, Docker, settings, and usage limits. See the +[documentation index](../docs/README.md), [architecture](../docs/client/architecture.md), +and [change history](CHANGELOG.md) for implementation details and history. -## 🆕 Novedades / Actualizaciones (Azurian Vocero realtime ver.Beta 2.1) - -> Versión del navegador que debes ver cargada en consola: **`2026-09-04 11:20`**. -> Si no aparece, haz **borrado de datos del sitio + recarga dura (Ctrl+Shift+R)** o abre una pestaña en modo incógnito. - -### 🎨 Rediseño visual completo (tema aurora + glassmorphism) -- **Tema de fondo aurora**: gradiente radial violeta/rosa/cian sobre lienzo oscuro con malla sutil + animación `auroraShift` lenta. -- **Cromado uniforme glass**: todos los elementos flotantes (tarjeta brand, panel user profile, botones icono, botón enviar chat, panel informes sidebar) usan *glass blur + saturate + borde gradiente brand 1px* (técnica mask `padding-box / border-box` doble linear-gradient). -- **Tokens de marca 3 colores brand** (violeta `#8b5cf6`, rosa `#ec4899`, cian `#22d3ee`) mezclados con `color-mix(in srgb, brand X%, neutral)` → ningún color hardcodeado deriva; todo el UI sigue estos tres tonos. - -### 🧭 Estructura (orden vertical de arriba → abajo) -1. **`header.topbar`** brand "Vocero" → avatar circular iniciales nombre usuario. - - 🟦 **Avatar user**: círculo 40×40px con gradiente brand, initials mayúsculas bold 800, hover lift/glow + foco teclado. Al hacer clic → diálogo modal perfil usuario (rejilla 2 columnas email/teléfono/username/rol/empresa/userid/país/fecha creación/último login; links `mailto:`/`tel:`; chips mono para códigos; mobile ≤480px apilado 1 col). - - 🟦 **Botón toggle chat (icono speech bubble) → ELIMINADO PERMANENTEMENTE**. La chat ahora siempre está visible inline; el botón toggle ya no existe en el DOM. -2. **`main.stage`** (arriba del todo, flexible): orbe/globode voz animado (3 anillos: core, ring, conic spin 3 velocidades + highlight specular + glows breathe `breatheOrb`) + caption `TAP OR SAY "HOLA VOCERO"` micro-bob uppercase gradient. - - ✅ Antes había una zona vacía sobre el orbe → eliminada, ahora el stage empieza en la parte superior (`justify-content: flex-start`). -3. **`
` SIEMPRE VISIBLE, 100% ancho, SOTTO stage, SOPRA footer sticky** (rellena la zona vacía inferior). - - ✅ Antes: overlay lateral derecho. **Ahora: bloque inline dentro de `#app` como hijo flex-col**. - - 🟦 Sin marco / sin riquadro (fondo aurora seamless, 0 borde, 0 shadow, 0 backdrop blur). - - Cabecera `CONVERSACIÓN` h3 uppercase 13px gradiente. - - `#chat-history` scroll interno. Burbujas de mensaje glass con **código de colores por rol**: usuario (tint 10% voice-user cyan + borde 44% cyan + glow) / assistant (tint 10% voice-assistant violet/pink + borde 42% + glow). - - Distancias seguras anti-borde: `.hist-msg.user margin-left:6px auto dx` / `.hist-msg.assistant margin-right:22px auto sx` → **nunca las burbujas tocan el borde del viewport** (fix confirmado). - - Formulario input texto `#chat-form` (arriba del botón enviar ✈️) **actualmente oculto (`hidden`)** para modo voz-puro; elimina ese atributo para reactivarlo. El handler submit que envía `client.sendUserText(text)` al websocket ya está conectado. -4. **Footer sticky `position: sticky; bottom:0; z:3; backdrop-blur`** "Azurian Vocero realtime ver.Beta 2.1" siempre dentro del viewport, incluso cuando el documento crece y haces scroll (no requiere scroll hacia abajo para verlo). Separador superior línea gradiente brand. - -### 📜 Sidebar de informes a la IZQUIERDA (antes topbar inline) -- Desktop **≥ 1024px**: sidebar fija left 320px siempre visible; `#app padding-left 320px` reserva sitio. -- Tablet/Mobile **< 1024**: offcanvas `translateX(-105%)` slide-in con backdrop blur; toggle mediante botón icono reportes `#reports-sidebar-toggle` en topbar con badge contador. -- `#reports-hint` siempre visible; `.reports-suggestions` y `.topbar-right` con puerta triple de visibilidad (atributo HTML hidden + CSS rule `[data-debug-only]:not([data-debug-enabled]) !important display:none` + JS `applyDebugOnlyVisibilityGate()` ejecutado 6 veces por lifecycle) → solo aparecen cuando el query param `?debug=true` está presente en la URL. - -### ⬇️ Auto-scroll chat SIEMPRE hacia la última respuesta del asistente -Arquitectura anti-clipping definitiva (versión 11:20 fix): - -1. **CSS sobrante intencional** (`96 → 160px chat-history padding-bottom`, `40→160px chat-panel clamp`, `56→120px #app padding-bottom + safe-area-inset-bottom`) → el último párrafo siempre está por ENCIMA de la línea del footer glass flotante. -2. **Unidades móviles seguras `svh / svw`** (smallest viewport): evita oscilaciones layout cuando aparece/desaparece la barra URL del móvil. -3. **JS cancel-and-reschedule** cada vez que `_scrollToBottom()` se llama: si llegan 100 tokens streaming en 1 frame, el último cancela todas las cadenas pendientes y se ejecuta desde cero → **no hay coalescing flag SKIP** (esta era la causa original del scroll insuficiente). -4. **5 reintentos escalonados `0 / +30 / +70 / +150 / +250ms`**: - - 0 ms (inmediato): 90% de los casos. - - 30 ms: tras 1 layout-pass. - - 70 ms: **corrige el wrapping de la última palabra en una línea nueva** (bug más común). - - 150 ms: después de reflow Chrome scroll-anchor. - - 250 ms: después de expandir filas tool / imágenes grandes. -5. **Snap con `Number.MAX_SAFE_INTEGER`**: el navegador clampa automáticamente al máximo real (`scrollHeight - clientHeight`); no hay race de leer scrollHeight demasiado pronto. -6. `overflow-anchor: none; scroll-behavior: auto !important;` → sin smooth, sin Chrome scroll-anchor-luchando contra nosotros. -7. Llamadas scroll explicitas extra en: `onResponseFinished` (fin de respuesta assistant, crítico), `onToolCall`, `onToolResult`. - -### 🛡️ Protecciones anti-error de refs eliminadas -- En el refactor de chat eliminamos 4 nodos DOM (`#chat-btn`, `#chat-badge`, `#chat-panel-backdrop`, `#chat-panel-close`). -- **Antes**: el constructor de `ChatView` usaba `$("#...")` strict → lanzaba `Error("Missing element: #chat-btn")` al arrancar. -- **Ahora**: esas 4 refs opcionales usan `document.querySelector("#...")` → devuelve `null` cuando no existen, sin throw; todos los listeners guarded `if (el)`. Los 3 IDs obligatorios (`#chat-panel`, `#chat-history`, `#bubble-stack`) siguen con strict para fallar fuerte si alguien los borra por error. - -### 🔄 Actualizaciones de versión / cache bust -Para evitar caché HTTP agresiva en navegadores móviles (ESM sin bundler + service worker = nunca refrescan URLs iguales), todas las referencias a recursos estáticos usan query param `?v=YYYYMMDDHHMM` sincronizado en **6 puntos**: -1. `index.html ` -2. `index.html - - diff --git a/s2s-client/project/index.html b/s2s-client/project/index.html deleted file mode 100644 index 36d168d..0000000 --- a/s2s-client/project/index.html +++ /dev/null @@ -1,139 +0,0 @@ - - - - - - Project Docs - - - -
-
-

Vocero Project

-

Embedded technical document viewer for `demo/public/docs.html`.

-
-
-
- -
- -
- - diff --git a/s2s-client/public/docs.html b/s2s-client/public/docs.html deleted file mode 100644 index 2771f17..0000000 --- a/s2s-client/public/docs.html +++ /dev/null @@ -1,272 +0,0 @@ - - - -Vocero S2S — Arquitectura técnica objetivo y plan de implementación - - - -
-
-

Documento de arquitectura técnica

-

Vocero S2S

-

Arquitectura técnica objetivo y plan de implementación

-

Estado: propuesta para revisión técnica
Fecha de corte de fuentes: 20 de julio de 2026
Ámbito: plataforma conversacional Speech-to-Speech desacoplada, local y extensible mediante MCP
Audiencia: arquitectura, plataforma, seguridad, MLOps, desarrollo, QA y operación

-
-
- -

Vocero S2S

-

Arquitectura técnica objetivo y plan de implementación

-

Estado del documento: propuesta para revisión técnica
-Fecha de corte de fuentes: 20 de julio de 2026
-Ámbito: plataforma conversacional Speech-to-Speech desacoplada, local y extensible mediante MCP
-Audiencia: arquitectura, plataforma, seguridad, MLOps, desarrollo, QA y operación

-
-

Convención de trazabilidad

-
    -
  • [REQ] Requisito proporcionado: proviene directamente de la descripción de Vocero S2S entregada por el solicitante.
  • -
  • [REC] Decisión recomendada: propuesta de diseño que debe aprobarse mediante ADR.
  • -
  • [BENCH] Supuesto pendiente: hipótesis que requiere medición, prueba de carga, evaluación legal o validación en el entorno objetivo.
  • -
-
-

1. Resumen ejecutivo

-

Vocero S2S se plantea como una plataforma conversacional en tiempo real que separa cuatro responsabilidades: experiencia web, control de sesión, inferencia de voz y lenguaje, e integración empresarial mediante Model Context Protocol (MCP). [REQ] La implementación inicial debe utilizar Parakeet TDT 0.6B para STT/VAD, LLaMA 3.1 8B Instruct para razonamiento y llamadas a herramientas, Qwen3-TTS 12Hz 1.7B Base en FP16 para síntesis y clonación zero-shot, y un nodo NVIDIA GB10 accesible inicialmente por el puerto 12345.

-

La arquitectura objetivo conserva esa cadena desacoplada, pero evita convertir la conexión WebSocket en el lugar donde vive toda la lógica. [REC] Se propone un Control Plane en el servidor UI & Relay para autenticación, autorización, perfil del agente, política de voz, orquestación MCP y auditoría; un Realtime Data Plane para audio y eventos con estado de sesión efímero y cancelación prioritaria; y un Inference Plane local que expone adaptadores versionados para STT, LLM y TTS. La separación permite reemplazar modelos, transporte o infraestructura sin alterar los contratos de negocio.

-

Para clientes web, WebRTC ofrece ventajas operativas para media en redes variables, mientras que WebSocket sigue siendo apropiado para enlaces servidor-a-servidor y para la primera versión ya planteada. La documentación de plataformas realtime recomienda WebRTC para browser/media y WebSocket para pipelines de servidor 1. [REC] Por ello, el plan adopta WebSocket como transporte inicial compatible y define WebRTC como evolución controlada, no como prerrequisito del MVP.

-

La gestión de interrupciones es una capacidad de primer orden: al detectar habla del usuario durante la respuesta, el sistema debe cancelar la generación todavía reversible, detener el audio, vaciar buffers no reproducidos y truncar el historial a lo efectivamente escuchado. Este patrón está documentado en sistemas realtime mediante cancelación y truncamiento de elementos de conversación 2, y en frameworks de agentes que ajustan el historial al audio efectivamente reproducido 3.

-

MCP se integra mediante un gateway empresarial con política, validación de esquemas, identidad delegada, límites, auditoría y adaptadores de versión. Decisión temporal crítica: al 20 de julio de 2026, el anuncio de 2026-07-28 describe explícitamente un Release Candidate cuyo estándar final se espera para el 28 de julio de 2026 y contiene cambios incompatibles 4. Por lo tanto:

-
    -
  1. [REC] la versión estable de compatibilidad inicial será 2025-11-25, verificada en la documentación oficial de transportes 5; esta decisión responde al corte temporal solicitado y no contradice la dirección técnica stateless propuesta por el RC;
  2. -
  3. [REC] 2026-07-28 se implementará sólo detrás de un adaptador experimental y feature flag;
  4. -
  5. [REC] el diseño del dominio se mantendrá preparado para el modelo stateless del RC: requests autocontenidos, estado de aplicación mediante handles explícitos y routing desacoplado de afinidad;
  6. -
  7. [REC] su promoción exigirá ratificación oficial, pruebas de conformidad y migración aprobada;
  8. -
  9. no se asumirá como estándar final en este documento.
  10. -
-

Finalmente, la capacidad real de ejecutar STT, LLM y TTS concurrentemente en un único GB10 no está demostrada por un benchmark de la cadena completa. [BENCH] La primera salida de ingeniería debe ser un arnés reproducible que mida latencia extremo a extremo, memoria, ancho de banda, degradación bajo concurrencia, precisión de interrupción y calidad de clonación antes de comprometer capacidad o SLO contractual.

-

2. Alcance

-

2.1 Objetivos

-
    -
  • [REQ] Entregar conversación de voz bidireccional y de baja latencia desde un navegador.
  • [REQ] Identificar al usuario mediante la API de cliente y personalizar la sesión según identidad o rol.
  • [REQ] Cargar dinámicamente el perfil del agente, instrucciones, reglas y herramientas.
  • [REQ] Preservar una voz clonada corporativa frente a parámetros por defecto enviados por el cliente.
  • [REQ] Ejecutar STT, razonamiento, llamadas a herramientas y TTS en una cadena desacoplada.
  • [REQ] Integrar sistemas empresariales sin modificar el núcleo mediante un gateway MCP.
  • [REC] Incorporar barge-in, cancelación, backpressure, timeouts, aislamiento, trazabilidad y recuperación de fallas como capacidades del núcleo.
  • [REC] Mantener contratos versionados que permitan sustituir transporte, modelos, runtimes y servidores MCP.
  • [REC] Proporcionar evidencia operativa para dimensionamiento, SLOs y auditoría.
  • -
-

2.2 No objetivos

-
  • Entrenar desde cero los modelos STT, LLM o TTS.
  • Reemplazar ERP, CRM, catálogos u otros sistemas de registro.
  • Permitir ejecución directa del LLM contra bases de datos o APIs sin gateway y política.
  • Convertir el navegador en depositario de credenciales empresariales o material de voz maestro.
  • Garantizar capacidad, latencia o concurrencia antes del benchmark en GB10.
  • Declarar la versión MCP 2026-07-28 como estándar final antes de su ratificación.
  • Diseñar en esta etapa un contact center completo, grabación regulatoria universal o telefonía SIP; pueden añadirse como dominios posteriores.
-

3. Principios de arquitectura

-
  1. Control y media separados. El audio tiene requisitos de tiempo real; identidad, política y auditoría requieren consistencia y trazabilidad.
  2. Contratos antes que implementaciones. Cada frontera publica eventos y esquemas versionados; los modelos quedan detrás de adaptadores.
  3. Interrupción prioritaria. Cancelar y detener audio tiene precedencia sobre generar más contenido.
  4. Estado explícito y con dueño. La sesión conversacional pertenece a Vocero; el estado MCP pertenece al adaptador de protocolo o a handles explícitos.
  5. Zero trust entre planos. Cada salto autentica servicio, autoriza acción, limita alcance y propaga identidad auditada.
  6. Mínimo privilegio para herramientas. Una tool sólo recibe los argumentos, identidad y scopes estrictamente necesarios.
  7. Privacidad por defecto. Audio, transcripciones, prompts, respuestas y voces son datos sensibles; la retención es explícita y minimizada.
  8. Fallar de forma conversacional. Los fallos técnicos se traducen en eventos deterministas y respuestas seguras, sin filtrar detalles internos.
  9. Medir antes de prometer. La experiencia se gobierna por latencia de etapa y percentiles, no por promedios aislados.
  10. Compatibilidad MCP versionada. El gateway negocia una versión estable y encapsula candidatos futuros.
-

4. Vista de contexto y contenedores

-
-Vocero S2S — Vista C4 de contenedores -VOCERO S2S -UsuarioHabla desde navegadorIdentidad / API clienteUsuario, roles y atributosServicio de perfilesInstrucciones, reglas, toolsy política de vozSistemas empresarialesERP, CRM, catálogos,reportes y workflowsObservabilidadMétricas, logs, tracesy alertasCliente WebWeb Audio + WS/WebRTCEdge / TerminaciónTLS, conexión, rate limitRealtime RelayAudio/eventos, sanitizaciónSession OrchestratorEstados, turnos, perfily políticaMCP GatewayCliente MCP + policyenforcementSession StoreKV con TTLAudit StoreAlmacén inmutableInference GatewayAPI realtime internaSTT, LLM y TTSParakeet TDT 0.6BNeMo / GPULLaMA 3.1 8BRuntime localQwen3-TTS 1.7BFP16 / GPUVoice VaultReferencias autorizadasAudio, controles y confirmacionesMedia y eventos · TLSStream autenticadoEventos de sesiónResuelve identidad · HTTPSCarga perfil y políticas · HTTPSLee/escribe estado efímeroTool intent + contexto delegado · mTLSComandos y eventos de inferencia · mTLSChunks de audioContexto y tokensTexto y voice_profile_refLee referencia autorizadaMCP/HTTPS versionadoEjecuciones y decisionesEventos de auditoríaTelemetríaTelemetríaTelemetría GPU/modelos
Representación vectorial estática de la vista C4 contenida en la versión v2.
-

4.1 Vista lógica por planos

-

Experience Plane

  • Cliente web, captura de micrófono, cancelación de eco, reproducción y controles de consentimiento.
  • Mantiene sólo estado visual y cursores necesarios; no conserva secretos ni voz maestra.
-

Realtime Data Plane

  • Terminación de WebSocket o WebRTC, relay de media y multiplexación de eventos.
  • Impone límites de buffer, secuencia y tamaño; descarta datos obsoletos al cambiar de generación.
  • Separa una cola de control de alta prioridad —cancel, barge_in, close— de la cola de audio/datos.
-

Conversation Control Plane

  • Resuelve identidad, perfil, permisos y configuración efectiva.
  • Mantiene la máquina de estados de sesión y turno.
  • Construye contexto, coordina inferencia y decide si una tool puede ejecutarse, confirmarse o rechazarse.
-

Inference Plane

  • Oculta detalles de runtime y expone capacidades uniformes: transcribe, generate, synthesize, cancel, health, capacity.
  • Correlaciona cada salida con session_id, turn_id y generation_id para descartar respuestas tardías.
-

Enterprise Integration Plane

  • Gateway MCP con adaptadores de versión, allowlists, validación, autorización, secretos de servicio, idempotencia y auditoría.
  • Ninguna respuesta de tool se incorpora al contexto sin controles de tamaño, clasificación y sanitización.
-

5. Responsabilidades por componente

-
ComponenteResponsabilidadesNo debe hacer
Cliente webCapturar/reproducir audio; AEC/NS/AGC cuando corresponda; mostrar estado; enviar confirmaciones; reportar progreso de playoutAutorizar tools; almacenar secretos; decidir la voz efectiva
Edge realtimeTLS; autenticación de conexión; límites; routing; protección DoS; upgrade WS o terminación WebRTCInterpretar prompts o argumentos MCP
Realtime RelayMultiplexar audio/eventos; ordenar secuencias; backpressure; sanitizar session.update; priorizar interrupcionesMantener lógica de negocio o credenciales downstream
Session OrchestratorMáquina de estados; identidad; perfil; contexto; turnos; cancelación; degradación; correlaciónEjecutar SQL, ERP o APIs directamente
Policy EngineEvaluar identidad, rol, tool, riesgo, ámbito, consentimiento y política de datosReescribir silenciosamente argumentos de negocio sin registro
MCP GatewayNegociar versión; descubrir tools; validar JSON Schema; delegar identidad; aplicar timeout/retry; auditarExponer credenciales al LLM o navegador
Inference GatewayAdmitir/cancelar trabajos; adaptar protocolos; medir etapas; health/capacityDecidir permisos empresariales
STT/VADEmitir parciales/finales y señales de habla con timestampsPersistir audio indefinidamente
LLMGenerar texto estructurado o intención de tool dentro de schemas permitidosConsiderarse autoridad para ejecutar acciones
TTSSintetizar stream asociado a una generación y perfil de voz autorizadoAceptar ref_audio arbitrario del cliente
Voice VaultVersionar, cifrar y gobernar referencias de voz y consentimientosServir archivos sin autorización por servicio y tenant
StoresEstado efímero con TTL, auditoría inmutable y configuración versionadaMezclar PII operacional con telemetría no restringida
ObservabilidadMétricas, logs estructurados, traces, alertas y tablerosRegistrar audio, tokens o argumentos sensibles por defecto
-

6. Vista de despliegue

-
Vocero S2S — Vista de despliegue -ZONA PÚBLICA -DMZ / EDGE -RED DE APLICACIONES -SEGMENTO DE INFERENCIA RESTRINGIDO -RED EMPRESARIAL -OPERACIONESNavegadorWAF + Reverse ProxyTURN/SFU opcionalEvolución WebRTCRealtime Relay ARealtime Relay BSession Orchestrator ASession Orchestrator BPolicy EngineMCP GatewaySession StoreTTLAudit StoreInference GatewayPuerto interno 12345Parakeet STT/VADLLaMA 3.1 8BQwen3-TTS 1.7BFP16Voice Vaultcaché cifradaNVIDIA GB10Auth + Agent Profile APIsMCP Servers / AdaptadoresERP / CRM / Datos / WorkflowsOTel CollectorMetrics / Logs / Traces / AlertasSecrets + KMSTLS WS inicialWebRTC futuroWebRTC futuromTLS realtimemTLS realtime
Representación vectorial estática de la vista de despliegue contenida en la versión v2.
-

[REC] El puerto 12345 debe ser interno, protegido por firewall, mTLS y autenticación de servicio; no debe publicarse directamente a Internet. [REC] Relay y Orchestrator se despliegan con al menos dos instancias lógicas en producción. Esto no implica que el MVP necesite alta disponibilidad física desde el primer día, pero los contratos no deben depender de memoria local exclusiva.

-

[BENCH] El GB10 es inicialmente un único dominio de fallo y capacidad. Antes de producción deben definirse: estrategia de nodo de reserva, cola de admisión, límite de sesiones, política de shedding y procedimiento de recuperación de modelos.

-

7. Máquina de estados y gestión de sesión

-

7.1 Estados propuestos

-
Vocero S2S — Máquina de estados de sesiónInicioCONNECTINGAUTHENTICATINGCONFIGURINGLISTENINGTRANSCRIBINGTHINKINGTOOL_PENDINGAWAITING_CONFIRMATIONTOOL_RUNNINGSPEAKINGINTERRUPTINGDEGRADEDCLOSINGFAILEDtransporte listoidentidad válidarechazo o timeoutperfil + voz + tools cargadosdependencia no crítica fallaspeech_startedturn_committedtool_intentacción sensibleconfirmadapermitidatool_resultaudio_first_chunkbarge_insalida detenidaresponse_completedalternativa disponiblecierrecierrecierrecierre
Representación vectorial estática de la máquina de estados contenida en la versión v2.
-

7.2 Identificadores

-
  • connection_id: conexión de transporte; puede cambiar al reconectar.
  • session_id: sesión conversacional estable y opaca.
  • turn_id: entrada comprometida del usuario.
  • generation_id: respuesta del agente; cambia después de cancelar o regenerar.
  • tool_call_id: invocación única; debe ser idempotente cuando la tool lo soporte.
  • voice_profile_id + voice_version: referencia inmutable a la voz autorizada.
  • trace_id: correlación distribuida; no reemplaza identificadores funcionales.
-

7.3 Estado efectivo de sesión

-

[REC] Se calcula en este orden, sin permitir que el cliente incremente privilegios:

  1. defaults seguros de plataforma;
  2. política del tenant;
  3. perfil del agente versionado;
  4. atributos autorizados del usuario;
  5. preferencias permitidas de sesión;
  6. overrides por respuesta explícitamente allowlisted.
-

El sanitizador de session.update elimina o rechaza campos que puedan sustituir voice_profile_id, tools, instrucciones de sistema, límites o scopes. Toda diferencia entre configuración solicitada y efectiva queda en un evento session.configuration_applied con razones codificadas.

[REC] El estado efímero se guarda con TTL y control optimista de versión. La reanudación requiere token opaco de corta vida, misma identidad y comprobación de versión del perfil. Audio no confirmado y trabajos de generación no se reanudan: se cancelan y el cliente vuelve a LISTENING.

-

8. Flujos de ejecución

8.1 Flujo nominal conversacional y MCP

8.2 Tool call con confirmación

-
  1. LLM emite intención, nunca una ejecución directa.
  2. Orchestrator valida nombre contra la lista permitida y el esquema vigente.
  3. Policy Engine clasifica la acción: lectura, escritura reversible, acción irreversible o prohibida.
  4. Si requiere consentimiento, se emite tool.confirmation_required con resumen legible y campos no sensibles.
  5. El usuario confirma; se crea confirmation_id ligado a hash de tool + argumentos + identidad + expiración.
  6. MCP Gateway ejecuta con token delegado de alcance mínimo.
  7. El resultado se valida, limita y clasifica antes de volver al LLM.
  8. Se registra la decisión, no secretos ni payloads sensibles completos.
-

Para la compatibilidad estable 2025-11-25, el adaptador mantiene el lifecycle y la sesión del protocolo de acuerdo con el transporte oficial 5. El RC 2026-07-28 propone eliminar handshake y sesión de protocolo, usar requests autocontenidos, headers de routing y InputRequiredResult; estas capacidades quedan sólo en el adaptador experimental hasta ratificación 4.

-

8.3 Barge-in

Reglas:

  • Un evento de interrupción salta las colas de tokens y audio.
  • Todo chunk posterior de G1 se descarta por generation_id obsoleto.
  • El cursor del cliente es la fuente de verdad del audio reproducido; si falta, se usa el último ACK conservador.
  • Una tool de sólo lectura puede cancelarse; una acción ya confirmada e irreversible no se “deshace” por barge-in. Se informa estado y se evita repetirla.
  • Se aplican AEC y umbrales adaptativos para reducir auto-interrupciones; las interjecciones breves se prueban como caso específico.
-

8.4 Errores y degradación

-
CondiciónAcción automáticaExperiencia de usuarioAuditoría/operación
Auth denegadaCerrar con código estableMensaje de acceso no autorizadoRazón, tenant, hash de sujeto
Perfil no disponibleReintento acotado; fallback sólo si está aprobado“No puedo iniciar el asistente en este momento”Alerta de dependencia
STT no saludablePausar admisión o activar modo texto si existeInformar degradaciónMétrica y circuit breaker
LLM timeoutCancelar generación; una reintento sólo si no hubo tool side effectRespuesta breve seguraSpan con timeout
TTS fallaMantener texto; no sustituir voz sin políticaMostrar texto o pedir reintentoEstado de voz/modelo
MCP timeoutCancelar o marcar estado desconocido“No pude confirmar la operación”No reintentar escrituras sin idempotencia
Respuesta MCP inválidaRechazar payload; no pasarlo al LLMError controladoViolación de schema
Buffer saturadoFrenar productor; descartar parciales obsoletos; nunca perder cancelaciónPosible indicador de redContadores de drop/backpressure
Cliente desconectadoLease corto; cancelar media; conservar mínimo estado reanudableReintento controladoCausa de cierre
GPU sin capacidadRechazo temprano o cola acotada“Servicio ocupado, inténtalo nuevamente”Saturación, cola y shedding
-

9. Contratos y eventos orientativos

[REC] Los siguientes esquemas son orientativos. Deben convertirse en JSON Schema versionado, con pruebas de compatibilidad y límites de tamaño. No representan un contrato final.

9.1 Envelope común

{
-  "specversion": "1.0",
-  "type": "vocero.audio.input.delta.v1",
-  "source": "web-client",
-  "id": "evt_opaque",
-  "time": "RFC3339 timestamp",
-  "subject": "session/{session_id}",
-  "traceparent": "00-...",
-  "data": {
-    "session_id": "ses_opaque",
-    "turn_id": "turn_opaque",
-    "sequence": 42,
-    "payload": {}
-  }
-}
-

9.2 Catálogo mínimo de eventos

Cliente → plataforma

  • session.connect.v1
  • session.update_requested.v1
  • audio.input.delta.v1
  • audio.input.commit.v1
  • input.speech_started.v1
  • output.playout_progress.v1
  • generation.cancel_requested.v1
  • tool.confirmation_submitted.v1
  • session.close.v1

Plataforma → cliente

  • session.configuration_applied.v1
  • transcript.partial.v1
  • transcript.final.v1
  • response.text_delta.v1
  • response.audio_delta.v1
  • response.completed.v1
  • output.stop_and_flush.v1
  • tool.confirmation_required.v1
  • tool.status.v1
  • error.v1
-

9.3 Ejemplo de session.update_requested

{
-  "type": "vocero.session.update_requested.v1",
-  "data": {
-    "session_id": "ses_opaque",
-    "client_capabilities": {
-      "audio_codecs": ["opus", "pcm16"],
-      "supports_playout_ack": true
-    },
-    "preferences": {
-      "locale": "es-CL",
-      "turn_mode": "server_vad"
-    }
-  }
-}

Campos como system_prompt, tools, mcp_credentials, ref_audio, ref_text o voice_profile_id no se aceptan desde este contrato público. Si llegan, el relay los rechaza o elimina según política, y registra la razón.

-

9.4 Ejemplo de intención de tool interna

{
-  "tool_call_id": "tc_opaque",
-  "session_id": "ses_opaque",
-  "turn_id": "turn_opaque",
-  "tool": {
-    "name": "production.report.get",
-    "schema_version": "1.2.0"
-  },
-  "arguments": {
-    "site_id": "site_authorized",
-    "period": "value_from_user_or_context"
-  },
-  "execution": {
-    "mode": "read",
-    "idempotency_key": "idem_opaque",
-    "deadline_ms": "configured_value"
-  },
-  "principal": {
-    "subject_ref": "opaque_subject",
-    "tenant_id": "tenant_opaque",
-    "scopes": ["report:read"]
-  }
-}
-

9.5 Errores

{
-  "type": "vocero.error.v1",
-  "data": {
-    "code": "MCP_TOOL_TIMEOUT",
-    "category": "dependency",
-    "retryable": false,
-    "user_message_key": "tool.temporarily_unavailable",
-    "correlation_id": "corr_opaque",
-    "details_ref": "internal_log_reference"
-  }
-}

Los mensajes públicos no contienen stack traces, endpoints internos, prompts, tokens, argumentos sensibles ni nombres de secretos.

-

9.6 Compatibilidad MCP

McpAdapter
-├── StableAdapter_2025_11_25   # default
-├── CandidateAdapter_2026_07_28 # feature flag, no producción por defecto
-└── ConformanceHarness
-    ├── discovery
-    ├── tools/list
-    ├── tools/call
-    ├── cancellation
-    ├── schema validation
-    ├── auth propagation
-    └── error mapping

La arquitectura oficial de MCP separa una capa de datos JSON-RPC y una capa de transporte, y contempla lifecycle, primitives y notificaciones 6. [REC] Vocero preservará esa separación dentro del adaptador para evitar que detalles de transporte contaminen la lógica conversacional.

Capacidades candidatas que se preparan, pero no se activan como estándar final: el RC 2026-07-28 introduce server/discover, metadatos ttlMs y cacheScope en resultados de listas/lecturas, y headers Mcp-Method/Mcp-Name para routing 4. [REC] El gateway modelará discovery y caché mediante interfaces neutrales: el adaptador estable resolverá su mecanismo según 2025-11-25, mientras que el adaptador candidato podrá mapear esas capacidades nuevas. La caché nunca compartirá resultados más allá del alcance de identidad/tenant permitido y siempre respetará revocación y cambio de política.

-

10. Clonación de voz y gobernanza

10.1 Modelo operativo

[REQ] Qwen3-TTS debe utilizar ref_audio y ref_text para clonación zero-shot y preservar una locución corporativa. El model card de Qwen3-TTS 1.7B Base confirma streaming, soporte de español y clonación rápida desde audio breve 7. La documentación del repositorio describe generación streaming y clonación de voz 8.

Modos a evaluar:

  • Full ICL — recomendado para máxima fidelidad: usa ref_audio y una transcripción ref_text exacta y alineada. [REC] Éste será el modo candidato por defecto para voces corporativas aprobadas.
  • x-vector (x_vector_only_mode=True): permite operar sin ref_text, pero la investigación reporta menor fidelidad de timbre y prosodia. [BENCH] Sólo podrá promoverse para un perfil si supera los umbrales de calidad y riesgo definidos.

[REC] El cliente nunca envía referencias maestras durante una sesión. El perfil de agente contiene sólo voice_profile_id y voice_version; TTS resuelve la referencia desde Voice Vault mediante identidad de servicio. El relay elimina voces estándar propuestas por el cliente y el Orchestrator aplica la voz efectiva autorizada.

-

10.2 Ciclo de vida

  1. Solicitud: propietario de la voz, propósito, tenant, idiomas y periodo de uso.
  2. Consentimiento verificable: documento o evidencia de autorización; revisión legal según jurisdicción.
  3. Ingesta controlada: antivirus, normalización, evaluación de ruido y transcripción alineada.
  4. Evaluación: fidelidad, inteligibilidad, pronunciación, estabilidad y riesgo de suplantación.
  5. Aprobación de cuatro ojos: dueño de negocio más seguridad/legal o roles equivalentes.
  6. Versionado: hash de ref_audio, hash de ref_text, modelo, parámetros y fecha de vigencia.
  7. Publicación: sólo perfiles aprobados pueden usarse en producción.
  8. Monitoreo: uso por tenant/agente, anomalías y reclamaciones.
  9. Revocación: bloqueo inmediato de nuevas sesiones; rotación de caché; evidencia de eliminación.
-

10.3 Controles

  • Cifrado en tránsito y reposo con claves administradas.
  • Separación por tenant y entorno; no copiar voces reales a desarrollo.
  • URLs firmadas de corta vida o lectura directa por identidad de workload.
  • Registro de acceso sin incluir el audio en logs.
  • Marcas de procedencia o disclosure cuando la política corporativa o regulación lo exija.
  • Pruebas de abuso: texto ofensivo, fraude, ingeniería social, extracción de referencia y uso cruzado entre tenants.
  • [BENCH] Comparar Full ICL con ref_audio + ref_text frente a modo sin texto; no asumir equivalencia de calidad.
  • [BENCH] Revisión jurídica de licencias de código y pesos antes de uso comercial; la evidencia recopilada no debe sustituir dictamen legal.
-

11. Seguridad

11.1 Vista de zonas y confianza

11.2 Amenazas principales y mitigaciones

-
AmenazaMitigaciones recomendadas
Suplantación de usuarioOIDC/OAuth, tokens efímeros, validación de issuer/audience, reautenticación para acciones sensibles
Prompt injection desde usuario o tool resultSeparación de instrucciones, allowlist de tools, validación de salida, etiquetado de contenido no confiable, autorización fuera del LLM
Tool poisoning o schema maliciosoRegistro de servidores aprobados, pinning de versión/hash, revisión de schema, límites de profundidad/tamaño, caché con invalidación segura
Confused deputyPropagar sujeto y tenant; token exchange; scopes por tool; comprobación de recurso en backend
Exfiltración por toolEgress allowlist, DLP/clasificación, minimización de respuesta, límites y redacción antes del contexto
Repetición de escrituraIdempotency key, confirmación ligada a hash, ledger de ejecución, no reintentar estado desconocido
Robo de vozVault, cifrado, aislamiento, consentimiento, revocación, sin descarga al navegador
Secuestro/replay de sesiónTokens de conexión cortos, nonce, expiración, binding a identidad, límites de reconexión
DoS de audio/GPUCuotas, límites de bitrate/chunk, admission control, colas acotadas, circuit breakers, shedding
Fuga por logs/tracesRedacción, clasificación de atributos, sampling, retención limitada, acceso RBAC
Movimiento lateralSegmentación, mTLS, identidades de workload, deny-by-default y egress controlado
-

11.3 Autorización de tools

La decisión se evalúa sobre:

permit = policy(
-  tenant,
-  principal,
-  agent_profile_version,
-  tool_name,
-  tool_schema_version,
-  action_class,
-  resource_scope,
-  argument_classification,
-  confirmation,
-  session_risk
-)

El LLM puede proponer tool_name y arguments, pero no principal, scopes, credenciales, clasificación de acción ni resultado de política. [REC] Las acciones irreversibles requieren confirmación humana específica o una excepción corporativa documentada.

-

11.4 Datos y retención

Definir una matriz por clase:

  • audio bruto;
  • referencias de voz;
  • transcripción;
  • prompt/contexto;
  • respuesta de modelo;
  • argumentos y resultados de tools;
  • telemetría y auditoría.

Para cada clase deben aprobarse propósito, base legal, ubicación, cifrado, retención, borrado, exportación, acceso, uso para entrenamiento y redacción. Pendiente: el solicitante no proporcionó políticas corporativas ni jurisdicciones; por tanto, no se fijan plazos de retención en este documento.

-

12. Observabilidad y SLOs iniciales

12.1 Modelo de telemetría

Trazas: una traza por turno con spans de captura, relay, STT, endpointing, LLM, policy, MCP, TTS, red y playout. El RC futuro propone nombres estandarizados para propagar W3C Trace Context en _meta, pero esa forma se tratará como candidata hasta ratificación 4. En el adaptador estable, Vocero propagará traceparent mediante metadata interna compatible sin exigir cambios futuros al dominio.

Métricas de experiencia

  • turn_endpointing_ms: fin acústico a commit de turno.
  • stt_partial_ms y stt_final_ms.
  • llm_ttft_ms: commit a primer token.
  • tts_ttfa_ms: texto disponible a primer audio.
  • ttfs_ms: fin de habla a primer sonido reproducible.
  • barge_in_stop_ms: detección de interrupción a silencio efectivo.
  • tool_latency_ms por tool y outcome.
  • turn_e2e_ms por ruta directa o con tool.
  • tasa de reconexión, cancelación, falsos barge-in y abandono.

TTFT y latencia extremo a extremo se reconocen como dimensiones distintas y relevantes para cargas de voz/tiempo real 9.

Métricas de calidad

  • WER/CER por idioma, acento, ruido y dominio.
  • tasa de endpointing temprano/tardío.
  • inteligibilidad y evaluación humana de naturalidad.
  • similitud de locutor y estabilidad de voz.
  • exactitud de tool selection, argumentos, política y task completion.

Métricas de recursos

  • utilización y memoria GPU; KV cache; colas por modelo; tokens/s; audio seconds/s.
  • profundidad y edad de buffer; drops; retransmisiones; jitter; playout underruns.
  • conexiones activas, sesiones admitidas/rechazadas y errores por dependencia.
-

12.2 Objetivos iniciales — no son desempeño observado

[REC/BENCH] Estos valores son objetivos provisionales de ingeniería, no cifras medidas, garantías ni SLO contractual. Deben ratificarse después del benchmark con audio, red, herramientas y concurrencia reales.

-
IndicadorObjetivo inicial propuestoVentana/percentilCondición de ratificación
Disponibilidad del servicio conversacional≥ 99,5 %MensualExcluir ventanas acordadas y definir dependencia GPU
Inicio de audio de respuesta ttfs_ms≤ 1.200 msp95, turno directoRed corporativa objetivo y sesión caliente
Detención por barge-in≤ 300 msp95Medido hasta silencio de playout, no sólo ACK
Turnos sin error de plataforma≥ 99,0 %MensualSeparar error de dependencia y entrada inválida
Ejecuciones MCP de lectura aceptadas por gateway≥ 99,0 %MensualExcluir rechazo de política y timeout downstream
Pérdida de eventos de control aceptados0Toda ventanaVerificada por secuencia y ACK
Uso de voz no autorizada0Toda ventanaAlerta y auditoría obligatorias

Presupuesto provisional de ttfs_ms para análisis, no compromiso:

endpointing + STT final + scheduling + LLM TTFT + TTS primer audio + transporte/playout

No se asignan milisegundos fijos por etapa hasta contar con benchmark; el tablero debe mostrar contribución y percentiles por separado.

-

12.3 Alertas iniciales

  • Burn-rate de disponibilidad y turnos exitosos.
  • Crecimiento sostenido de cola o edad de buffer.
  • GPU OOM, reinicio de modelo o health degradado.
  • Divergencia entre generation.cancel y último chunk emitido.
  • Error/latencia MCP por tool, tenant y dependencia.
  • Accesos denegados o anomalías de voz.
  • Ausencia de trazas o cardinalidad no controlada.
-

13. Escalabilidad, backpressure y resiliencia

13.1 Escalado

  • Edge/Relay: horizontal por conexiones; estado mínimo; drenaje antes de deploy.
  • Orchestrator: horizontal por sesión con lease en store; afinidad opcional como optimización, no requisito de corrección.
  • MCP Gateway: horizontal; pools por downstream; bulkheads por tenant/tool.
  • Inference: admission control basado en capacidad real, no sólo CPU; colas separadas STT, LLM y TTS; prioridades de cancelación y audio activo.
  • Voice cache: caché cifrada y acotada por voces aprobadas; invalidación por versión/revocación.
-

13.2 Backpressure

[REC] Cada enlace publica high_watermark, low_watermark y política de overflow. El LLM puede producir texto más rápido de lo que TTS o la red consumen; el sistema debe frenar tokens, agrupar por unidades pronunciables y limitar audio anticipado. El problema general de productores rápidos y consumidores lentos está documentado en pipelines realtime 10.

Políticas:

  1. Eventos de control nunca comparten una cola bloqueante con audio.
  2. Parciales STT obsoletos pueden coalescerse; finales y commits no.
  3. Tokens no sintetizados de una generación cancelada se descartan.
  4. Audio generado pero no reproducido se descarta al interrumpir.
  5. Una conexión lenta no puede consumir memoria sin límite.
  6. El cliente reporta buffered_ms y playout; el servidor ajusta chunking o pausa.
  7. Las colas tienen deadline; trabajo vencido no se procesa “por completitud”.
-

13.3 Resiliencia

  • Timeouts por etapa y deadline total propagado.
  • Circuit breakers por dependencia y modelo.
  • Retries con jitter sólo para operaciones idempotentes.
  • Bulkheads por tenant y tool para evitar fallos en cascada.
  • Health de proceso, readiness de modelo y señal de capacidad diferenciados.
  • Warm-up verificado antes de recibir sesiones.
  • Deploy con drenaje de conexiones y cancelación segura.
  • Snapshots de configuración y rollback de perfiles/modelos.
  • Runbooks para GPU OOM, degradación STT/TTS, MCP lento, store no disponible y compromiso de voz.

[BENCH] La posibilidad de alojar simultáneamente toda la cadena en un GB10, y el número de sesiones sostenibles, deben medirse. Parakeet TDT 0.6B v3 dispone de soporte de streaming documentado y timestamps 11; esto valida la capacidad funcional, no la capacidad concurrente del sistema completo.

-

14. Plan de implementación por fases

Las fases no incluyen fechas ni duraciones porque no se entregaron disponibilidad de equipo, ambientes, procurement ni ventanas de cambio. Cada fase termina con una decisión explícita de continuar, corregir o detener.

-

Fase 0 — Descubrimiento, contratos y riesgos

Entregables

  • Inventario de requisitos funcionales, datos, tenants, roles, herramientas y acciones sensibles.
  • ADRs iniciales y modelo de amenazas.
  • Catálogo de eventos v1 y esquemas de audio/control.
  • Matriz de licencias y gobernanza de voz.
  • Definición del corpus de benchmark y plan de medición.

Dependencias

  • Acceso a APIs de auth/profile y definición de MCP del cliente.
  • Responsables de seguridad, legal, negocio y operación.
  • Hardware GB10 y artefactos versionados de modelos.

Criterios de aceptación

  • Requisitos etiquetados y aprobados; pendientes con dueño.
  • Ningún secreto ni voz real requerido para desarrollo temprano.
  • ADR-001 a ADR-006 en estado Proposed o Accepted.
  • Amenazas críticas con control y prueba asociada.

Riesgos

  • Ambigüedad de identidad/roles.
  • Licencias o consentimiento de voz no resueltos.
  • Tools MCP sin idempotencia o clasificación de riesgo.
-

Fase 1 — Vertical slice local sin tools de escritura

Entregables

  • Cliente web + WebSocket, Relay, Orchestrator e Inference Gateway.
  • STT → LLM → TTS streaming con una voz de prueba autorizada.
  • Máquina de estados, IDs, cancelación y logs estructurados.
  • Simuladores deterministas de STT/LLM/TTS para CI.

Dependencias

  • Modelos cargables y runtime compatible.
  • Certificados de servicio y entorno aislado.

Criterios de aceptación

  • Conversación nominal reproducible.
  • Reconexión no duplica turnos.
  • Cancelar una generación impide chunks tardíos en playout.
  • La voz solicitada por cliente no reemplaza la voz efectiva.
  • Primera línea base de latencia y recursos registrada.

Riesgos

  • Contención de GPU.
  • Latencia de endpointing.
  • Inestabilidad del runtime o incompatibilidad FP16.
-

Fase 2 — Barge-in, backpressure y sesión robusta

Entregables

  • Cola de control prioritaria y output.stop_and_flush.
  • Playout ACK/cursor; truncamiento de historial.
  • Límites de buffer, shedding, deadlines y circuit breakers.
  • Pruebas con ruido, eco, interjecciones y red degradada.

Dependencias

  • Instrumentación por etapa.
  • Dataset de conversaciones y condiciones acústicas representativas.

Criterios de aceptación

  • Cero audio de generación obsoleta después del límite aprobado de interrupción.
  • Sin crecimiento no acotado de memoria con cliente lento.
  • Sin doble respuesta después de reconexión/cancelación.
  • Falsos barge-in medidos y dentro del umbral que defina negocio.

Riesgos

  • Eco que dispara VAD.
  • Cursor de playout impreciso.
  • Races entre cancelación, TTS y entrega de red.
-

Fase 3 — Gateway MCP de lectura

Entregables

  • StableAdapter_2025_11_25.
  • Discovery allowlisted, validación de schemas y tools/call de lectura.
  • Policy Engine, identidad delegada, límites, auditoría e idempotencia.
  • Servidor MCP simulado y pruebas de contrato.

Dependencias

  • Servidor MCP del cliente y esquema de autorización.
  • Clasificación de tools y datos.

Criterios de aceptación

  • Tool no allowlisted es rechazada antes del downstream.
  • Argumentos y resultados inválidos no alcanzan LLM/sistemas.
  • Cada tool call se correlaciona con usuario, sesión, turno y política.
  • Timeouts no causan retries inseguros.

Riesgos

  • Prompt injection en resultados.
  • Credenciales con exceso de privilegios.
  • Contratos downstream inestables.
-

Fase 4 — Escrituras, confirmación y gobernanza de voz

Entregables

  • Flujos de confirmación ligados a hash e idempotency key.
  • Ledger de acciones y estado desconocido.
  • Voice Vault, workflow de aprobación, revocación y caché segura.
  • Pruebas de abuso y runbooks de incidente.

Dependencias

  • Aprobación legal de voces/licencias.
  • Semántica de idempotencia en sistemas empresariales.

Criterios de aceptación

  • Ninguna acción sensible se ejecuta sin política/confirmación requerida.
  • Repetición de evento no repite side effect.
  • Revocar una voz bloquea nuevas síntesis y limpia cachés.
  • Acceso cruzado entre tenants falla y queda auditado.

Riesgos

  • Acciones no idempotentes.
  • Consentimiento incompleto.
  • Exfiltración o uso indebido de voz.
-

Fase 5 — Preproducción, SLO y resiliencia

Entregables

  • Pruebas de carga, soak, caos y recuperación.
  • Dashboards, alertas, SLOs ratificados y runbooks.
  • Capacity model y límites de admisión.
  • DR/backup para configuración, auditoría y Voice Vault.
  • Revisión de seguridad y go-live checklist.

Dependencias

  • Tráfico/perfiles representativos.
  • Entorno equivalente a producción.
  • On-call y ownership definidos.

Criterios de aceptación

  • Objetivos de experiencia ratificados o renegociados con evidencia.
  • Recuperación de fallos críticos demostrada.
  • Ninguna vulnerabilidad crítica abierta.
  • Operación puede detectar, diagnosticar y mitigar escenarios de runbook.

Riesgos

  • Único GB10 como SPOF.
  • Capacidad insuficiente bajo mezcla real.
  • Diferencias entre red de prueba y campo.
-

Fase 6 — Despliegue progresivo y evolución

Entregables

  • Canary por usuarios/tenant y rollback automático.
  • Revisión post-piloto con calidad, latencia, seguridad y task completion.
  • Roadmap WebRTC si WebSocket no satisface objetivos.
  • CandidateAdapter_2026_07_28 sólo si la especificación fue ratificada.

Criterios de aceptación

  • Canary sin regresión en SLOs/seguridad.
  • Soporte y escalamiento operativo validados.
  • Migración MCP pasa conformance suite y ADR de promoción.
-

15. Estrategia de pruebas

15.1 Pirámide

Unitarias

  • máquina de estados, sanitización, policy, mapping de errores, deduplicación, expiración y redacción.

Contrato

  • JSON Schema de eventos, compatibilidad hacia atrás, adaptadores MCP, APIs de perfil e identidad.

Integración

  • STT/LLM/TTS reales; MCP simulado y real; Voice Vault; KMS; stores.

End-to-end

  • audio a audio con playout medido, rutas directas, tools, confirmación, cancelación y reconexión.

Carga y soak

  • sesiones concurrentes, mezcla de turnos, audio largo, cliente lento, tools lentas, churn de conexiones y modelos calientes/fríos.

Caos

  • proceso muerto, GPU OOM, store lento, pérdida de red, respuesta tardía, certificado vencido, dependencia parcial y restart durante tool call.

Seguridad

  • authn/authz, tenant isolation, replay, prompt injection, schema bombs, SSRF, egress, secretos, DLP, abuso de voz y supply chain.
-

15.2 Matriz mínima de escenarios

EjeCasos
Audiosilencio, ruido, eco, clipping, bitrate variable, micrófono distante
Hablaacentos objetivo, velocidad, números, nombres propios, términos de dominio
Turnospausa larga, solapamiento, backchannel, interrupción, push-to-talk
Redlatencia, jitter, pérdida, reconexión, cliente lento
Toolséxito, vacío, inválido, timeout, 4xx/5xx, side effect confirmado, estado desconocido
Modeloscold start, OOM, respuesta tardía, token/audio excesivo, cancelación
Seguridadtool no permitida, scope insuficiente, inyección, acceso cruzado, voz revocada
-

15.3 Oráculos y reproducibilidad

  • Audio de prueba versionado, con consentimiento y etiquetas.
  • Fakes deterministas para carreras y errores.
  • Semillas/parámetros de generación registrados donde aplique.
  • Golden transcripts y schemas, pero tolerancias acústicas definidas.
  • Captura de timestamps monotónicos en cada frontera.
  • Reporte por percentiles y condición, no sólo promedio.
  • Comparación A/B de configuraciones de VAD, chunking y voz.
-

16. Matriz de decisiones y ADRs

ADRDecisiónEstado inicialAlternativasEvidencia para aceptar
ADR-001Cadena desacoplada STT → LLM → TTSAccepted por requisitoModelo S2S nativoBenchmark y control por componente
ADR-002WebSocket inicial; WebRTC como evoluciónProposedWebRTC desde MVP; ambosPrueba de red y complejidad operativa
ADR-003Separar Relay y Session OrchestratorProposedServicio monolíticoPerfil de carga, aislamiento y mantenibilidad
ADR-004MCP estable 2025-11-25 + adaptadores versionadosProposedAdoptar RC futuroRatificación, conformidad y compatibilidad
ADR-005Voice Vault y referencias server-sideProposedEnviar ref_audio por sesiónThreat model, latencia de caché y gobernanza
ADR-006Estado efímero externo con TTL y leasesProposedMemoria local/sticky sessionsRecuperación y carga
ADR-007Control queue prioritaria para barge-inProposedCola única FIFOPruebas de carrera y objetivo de interrupción
ADR-008Policy Engine fuera del LLMProposedPrompt-only controlsPruebas de bypass y auditoría
ADR-009Confirmación + idempotencia para escriturasProposedEjecución inmediataSemántica downstream y UX
ADR-010Un GB10 en MVP con admission controlProposedCluster desde inicioBenchmark de capacidad/costo/riesgo
ADR-011OpenTelemetry end-to-endProposedLogs no correlacionadosCobertura de trazas y costo/cardinalidad
ADR-012Contratos de evento v1 versionadosProposedPayloads ad hoc del proveedorPruebas de compatibilidad

Cada ADR debe incluir contexto, decisión, alternativas, consecuencias, riesgos, estado y condición de revisión. Las decisiones reversibles pueden iniciarse como Proposed; las que afectan seguridad, datos, licencias o compatibilidad externa requieren aprobación explícita.

-

17. Pendientes y preguntas abiertas

Producto y experiencia

  • ¿Qué canales se incluyen: sólo browser, móvil, telefonía o todos?
  • ¿Qué idiomas, acentos, vocabulario y condiciones acústicas son prioritarios?
  • ¿Qué comportamiento se espera al fallar voz: texto, voz alternativa o cierre?
  • ¿Qué acciones requieren confirmación verbal, visual o autenticación reforzada?

Identidad y autorización

  • Contrato real de /api/v1/auth/user-by-phone y mecanismo de autenticación.
  • Modelo de roles, tenants, scopes y separación de datos.
  • Token exchange/delegación hacia MCP y sistemas downstream.

MCP

  • Inventario de servidores, tools, schemas, side effects, idempotencia y SLO downstream.
  • Versión estable realmente soportada por el servidor del cliente.
  • Estrategia de cache/refresh de discovery.
  • Ratificación futura de 2026-07-28 y disponibilidad de SDK/conformance suite.

Inferencia y capacidad

  • Runtime exacto para LLaMA, asignación de memoria y política de KV cache.
  • Concurrencia sostenible de STT + LLM + TTS en GB10.
  • Efecto de context length, prompt del agente y tool results sobre TTFT.
  • Cold start, carga de modelos, fragmentación y recuperación OOM.
  • Calidad de Parakeet en audio y dominio reales.
  • Titular y evidencia de consentimiento de cada voz.
  • Licencia aplicable a pesos, código, redistribución y uso comercial.
  • Reglas de disclosure, retención, localización y derecho de revocación.
  • Métrica y umbral de aceptación de fidelidad/seguridad.

Operación

  • Ambientes, topología, certificados, secretos, KMS, stores y backups.
  • RTO/RPO y modelo on-call.
  • Política de logs, sampling, redacción y retención.
  • Capacidad de nodo de reserva o alternativa de servicio.
-

18. Riesgos consolidados

RiesgoProbabilidad inicialImpactoTratamiento
Cadena completa excede capacidad del GB10DesconocidaAltoBenchmark temprano; admission control; opciones de separación
Barge-in tardío o falsoDesconocidaAltoCola prioritaria, AEC, playout ACK, corpus de ruido
MCP permite acción indebidaMedia hasta probarCríticoPolicy externa, scopes, confirmación, auditoría, idempotencia
Compromiso o uso no autorizado de vozMedia hasta gobernarCríticoVoice Vault, consentimiento, aislamiento, revocación
Dependencia de versión MCP candidataEvitableAltoStable adapter por defecto y feature flag
Tool result inyecta instruccionesMediaAltoTratar contenido como no confiable, sanitizar, limitar, evaluar
Estado inconsistente tras reconexiónMediaAltoIDs, versionado, leases, dedupe y cancelación
Observabilidad filtra PIIMediaAltoRedacción, allowlist de atributos, acceso y retención
Único nodo de inferencia fallaAlta en topología inicialAltoRunbook, spare/failover, degradación y comunicación
Licencia/consentimiento incompletoDesconocidaCríticoGate legal antes de producción

Las probabilidades no numéricas reflejan ausencia de datos; deben actualizarse después de pruebas y revisión organizacional.

-

19. Criterio de arquitectura lista para piloto

La solución está lista para piloto sólo cuando:

  1. los requisitos y ADRs críticos están aprobados;
  2. la ruta estable MCP está probada y la candidata futura permanece aislada;
  3. el benchmark extremo a extremo demuestra capacidad para la carga piloto;
  4. barge-in y backpressure pasan pruebas acústicas y de red;
  5. tools sensibles tienen política, confirmación e idempotencia;
  6. la voz está autorizada, versionada y revocable;
  7. seguridad no mantiene hallazgos críticos abiertos;
  8. tableros, alertas y runbooks permiten operar el servicio;
  9. SLOs provisionales fueron ratificados o sustituidos con evidencia;
  10. existe rollback probado de aplicación, perfil, modelo y configuración.
-

20. Fuentes

  1. [1] OpenAI — Realtime and audio — https://developers.openai.com/api/docs/guides/realtime
  2. [2] Microsoft Azure — Realtime audio — https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/realtime-audio
  3. [3] LiveKit — Turns overview — https://docs.livekit.io/agents/logic/turns/
  4. [4] Model Context Protocol — 2026-07-28 Release Candidate — https://blog.modelcontextprotocol.io/posts/2026-07-28-release-candidate/
  5. [5] Model Context Protocol — Transport specification 2025-11-25 — https://modelcontextprotocol.io/specification/2025-11-25/basic/transports
  6. [6] Model Context Protocol — Architecture overview — https://modelcontextprotocol.io/docs/learn/architecture
  7. [7] Qwen — Qwen3-TTS 12Hz 1.7B Base model card — https://huggingface.co/Qwen/Qwen3-TTS-12Hz-1.7B-Base
  8. [8] QwenLM — Qwen3-TTS repository — https://github.com/QwenLM/Qwen3-TTS
  9. [9] Telnyx — Inference Benchmark: TTFT vs E2E Latency — https://telnyx.com/resources/inference-benchmark-ttft-vs-e2e
  10. [10] Arun Baby — Real-Time Agent Pipelines — https://www.arunbaby.com/ai-agents/0016-real-time-agent-pipelines/
  11. [11] NVIDIA — Parakeet TDT 0.6B v3 model card — https://huggingface.co/nvidia/parakeet-tdt-0.6b-v3
-

Apéndice A — Checklist de implementación

  • [ ] Requisitos [REQ], recomendaciones [REC] y supuestos [BENCH] revisados.
  • [ ] ADRs críticos aprobados.
  • [ ] Modelos y hashes fijados; SBOM y licencias revisadas.
  • [ ] Identidad, roles, scopes y tenants definidos.
  • [ ] Event schemas v1 publicados y contract-tested.
  • [ ] Stable MCP adapter probado contra 2025-11-25.
  • [ ] Candidate MCP adapter deshabilitado por defecto.
  • [ ] Voice Vault, consentimiento, rotación y revocación operativos.
  • [ ] Admission control y límites de buffer configurados.
  • [ ] Barge-in medido hasta playout real.
  • [ ] Tool confirmation e idempotencia verificadas.
  • [ ] Telemetría redactada y correlacionada.
  • [ ] SLOs ratificados con benchmark.
  • [ ] Runbooks y rollback ensayados.
  • [ ] Revisión de seguridad y go-live completadas.
-
- - - \ No newline at end of file diff --git a/s2s-client/server.py b/s2s-client/server.py index 410830e..adadb95 100644 --- a/s2s-client/server.py +++ b/s2s-client/server.py @@ -54,7 +54,7 @@ import httpx import websockets from dotenv import load_dotenv from fastapi import FastAPI, HTTPException, Request, WebSocket, WebSocketDisconnect -from fastapi.responses import JSONResponse +from fastapi.responses import JSONResponse, RedirectResponse from fastapi.staticfiles import StaticFiles from pydantic import BaseModel @@ -6696,6 +6696,19 @@ async def no_cache_static_assets(request: Request, call_next): return response +# Preserve the former proposal URLs after moving the document out of the client. +@app.get("/project", include_in_schema=False) +@app.get("/project/", include_in_schema=False) +@app.get("/project/index.html", include_in_schema=False) +@app.get("/public/docs.html", include_in_schema=False) +async def project_documentation(): + return RedirectResponse("/docs/proposals/vocero-architecture.html", status_code=307) + + +# The existing FastAPI /docs page remains registered ahead of this mount. +app.mount("/docs", StaticFiles(directory=os.path.join(ROOT_DIR, "docs"), html=True), name="documentation") + + # Static front-end. Registered last so the /api routes win. `html=True` serves # index.html at "/". The repo is public anyway, so serving the dir is fine. app.mount("/", StaticFiles(directory=HERE, html=True), name="static") diff --git a/speech_to_speech/LLM/README.md b/speech_to_speech/LLM/README.md index 2a5a9d6..2d32bee 100644 --- a/speech_to_speech/LLM/README.md +++ b/speech_to_speech/LLM/README.md @@ -1,139 +1,6 @@ -# LLM Summary +# Language model handlers -## Available LLM backends (`--llm_backend`) - -Runtime-supported values in `s2s_pipeline.py`: - -- `transformers` → `language_model.py` (Transformers backend) -- `mlx-lm` → `language_model.py` (MLX backend) -- `responses-api` → `responses_api_language_model.py` - -## Usage - -### 1) Transformers (`--llm_backend transformers`) - -- Handler: `LanguageModelHandler` -- Typical use: local GPU/CPU inference using Hugging Face Transformers -- Backend-specific args prefix: `--llm_*` -- Shared args (from base): `--model_name`, `--chat_size`, `--init_chat_prompt`, `--enable_lang_prompt` - -```bash -python s2s_pipeline.py \ - --llm_backend transformers \ - --model_name Qwen/Qwen3-4B-Instruct-2507 \ - --llm_device cuda \ - --llm_torch_dtype float16 \ - --llm_gen_max_new_tokens 128 -``` - -Common options: -- `--llm_gen_min_new_tokens` -- `--llm_gen_temperature` -- `--llm_gen_do_sample` -- `--chat_size` -- `--init_chat_prompt` - -### 2) MLX-LM (`--llm_backend mlx-lm`) - -- Handler: `LanguageModelHandler` -- Typical use: Apple Silicon local inference -- Backend-specific args prefix: same as Transformers (`--llm_*`) - -```bash -python s2s_pipeline.py \ - --llm_backend mlx-lm \ - --model_name mlx-community/Qwen3-4B-Instruct-2507-bf16 \ - --llm_device mps \ - --llm_gen_max_new_tokens 128 -``` - -Common options: -- `--llm_gen_temperature` -- `--llm_gen_do_sample` -- `--chat_size` -- `--init_chat_prompt` - -### 3) OpenAI-compatible API (`--llm_backend responses-api`) - -- Handler: `ResponsesApiModelHandler` -- Typical use: remote model serving via OpenAI-compatible endpoints -- Backend-specific args prefix: `--responses_api_*` -- Shared args (from base): `--model_name`, `--chat_size`, `--init_chat_prompt`, `--enable_lang_prompt` - -```bash -python s2s_pipeline.py \ - --llm_backend responses-api \ - --model_name gpt-5.4-mini \ - --responses_api_api_key YOUR_API_KEY \ - --responses_api_base_url https://api.example.com/v1 \ - --responses_api_stream true -``` - -Common options: -- `--chat_size` -- `--init_chat_prompt` -- `--user_role` - -## LLM Behavior - -When STT is set to language auto-detection (`--language auto`), LLM handlers can receive `(text, language_code)` and prepend a language control instruction like: - -- `Please reply to my message in .` - -This helps the assistant respond in the detected language. The behavior is opt-in via `--enable_lang_prompt` (shared across all backends); it defaults to `False`. - -## Setup - -### CUDA setup - -```bash -python s2s_pipeline.py \ - --llm_backend transformers \ - --model_name microsoft/Phi-3-mini-4k-instruct -``` - -### Local Mac setup - -```bash -python s2s_pipeline.py \ - --local_mac_optimal_settings \ - --model_name mlx-community/Qwen3-4B-Instruct-2507-bf16 -``` - -`--local_mac_optimal_settings` already sets `--llm_backend mlx-lm` and will default the model to `mlx-community/Qwen3-4B-Instruct-2507-bf16` if not overridden. - -### Realtime (OpenAI-compatible) setup - -Run the server in realtime mode, then connect with the realtime client: - -```bash -# 1. Start the pipeline in realtime mode -python s2s_pipeline.py \ - --mode realtime \ - --llm_backend mlx-lm \ - --model_name mlx-community/Qwen3-4B-Instruct-2507-bf16 \ - --ws_host 0.0.0.0 \ - --ws_port 8765 - -# 2. Connect with the realtime client -python listen_and_play_realtime.py --host 127.0.0.1 --port 8765 -``` - -Or with `--local_mac_optimal_settings` on Apple Silicon: - -```bash -python s2s_pipeline.py \ - --local_mac_optimal_settings \ - --mode realtime \ - --ws_host 0.0.0.0 \ - --ws_port 8765 -``` - -### Remote API setup - -```bash -python s2s_pipeline.py \ - --llm_backend responses-api \ - --model_name gpt-5.4-mini \ - --responses_api_api_key YOUR_API_KEY -``` +This directory contains local Transformers/MLX and remote Responses/Chat +Completions handlers. See [language model backends](../../docs/speech/llm.md) +for configuration and [realtime API](../../docs/speech/realtime-api.md) for the +tool-call and conversation flow. diff --git a/speech_to_speech/STT/README.md b/speech_to_speech/STT/README.md index 73e759f..a0907eb 100644 --- a/speech_to_speech/STT/README.md +++ b/speech_to_speech/STT/README.md @@ -1,163 +1,5 @@ -# STT Summary +# Speech-to-text handlers -This document summarizes the Speech-to-Text (STT) implementations in the `STT/` folder, including language support, language abbreviations, and usage in `s2s_pipeline.py`. - -## Available STT Modes (`--stt`) - -- `whisper` → `STT/whisper_stt_handler.py` -- `whisper-mlx` → `STT/lightning_whisper_mlx_handler.py` -- `mlx-audio-whisper` → `STT/mlx_audio_whisper_handler.py` -- `faster-whisper` → `STT/faster_whisper_handler.py` -- `parakeet-tdt` → `STT/parakeet_tdt_handler.py` -- `paraformer` → `STT/paraformer_handler.py` - -## Language Support by Handler - -### 1) Whisper (`--stt whisper`) - -- Handler: `WhisperSTTHandler` -- Language input flag: `--language` (from shared Whisper args) -- Supports fixed language (e.g. `en`) or `auto` -- Internal supported language list: - - `en`, `fr`, `es`, `zh`, `ja`, `ko`, `hi`, `de`, `pt`, `pl`, `it`, `nl` -- Behavior: - - Detects language from token output - - If detected language is outside the supported list, it falls back to the previous language - -### 2) Lightning Whisper MLX (`--stt whisper-mlx`) - -- Handler: `LightningWhisperSTTHandler` -- Uses same shared `--language` argument as Whisper -- Internal supported language list: - - `en`, `fr`, `es`, `zh`, `ja`, `ko`, `hi`, `de`, `pt`, `pl`, `it`, `nl` -- Behavior: - - If `--language auto`, model auto-detects each utterance - - If detected language is unsupported, falls back to last supported language - -### 3) MLX Audio Whisper (`--stt mlx-audio-whisper`) - -- Handler: `MLXAudioWhisperSTTHandler` -- Model flag: `--mlx_audio_whisper_model_name` -- Language still comes from shared `--language` flag (wired in pipeline) -- Internal supported language list: - - `en`, `fr`, `es`, `zh`, `ja`, `ko`, `hi`, `de`, `pt`, `pl`, `it`, `nl` -- Behavior: - - Uses fixed language unless `--language auto` - - Falls back to last known supported language when needed - -### 4) Faster-Whisper (`--stt faster-whisper`) - -- Handler: `FasterWhisperSTTHandler` -- Language flag: `--faster_whisper_stt_gen_language` -- Default language: `en` -- Note: - - This handler passes generation kwargs directly to `faster_whisper.WhisperModel.transcribe(...)` - - Effective language coverage depends on selected Faster-Whisper/OpenAI Whisper model - -### 5) Parakeet TDT (`--stt parakeet-tdt`) - -- Handler: `ParakeetTDTSTTHandler` -- Language flag: `--parakeet_tdt_language` (optional) -- Supports auto language detection when language not specified -- Declared supported language list (25 European languages): - - `en`, `de`, `fr`, `es`, `it`, `pt`, `nl`, `pl`, `ru`, `uk`, `cs`, `sk`, `hu`, `ro`, `bg`, `hr`, `sl`, `sr`, `da`, `no`, `sv`, `fi`, `et`, `lv`, `lt` -- Backend behavior: - - On macOS/MPS: MLX (`mlx-community/parakeet-tdt-0.6b-v3`) - - On CUDA/CPU: nano-parakeet (`nvidia/parakeet-tdt-0.6b-v3`) - -### 6) Paraformer (`--stt paraformer`) - -- Handler: `ParaformerSTTHandler` -- Model flag: `--paraformer_stt_model_name` -- Default model: `paraformer-zh` -- No dedicated language flag in current args class -- Practical support: - - Depends on selected FunASR model checkpoint - - Default setup is Chinese-oriented (`zh`) - -## Language Abbreviations (ISO-style codes seen in STT handlers) - -| Code | Language | -|---|---| -| `en` | English | -| `fr` | French | -| `es` | Spanish | -| `zh` | Chinese | -| `ja` | Japanese | -| `ko` | Korean | -| `hi` | Hindi | -| `de` | German | -| `pt` | Portuguese | -| `pl` | Polish | -| `it` | Italian | -| `nl` | Dutch | -| `ru` | Russian | -| `uk` | Ukrainian | -| `cs` | Czech | -| `sk` | Slovak | -| `hu` | Hungarian | -| `ro` | Romanian | -| `bg` | Bulgarian | -| `hr` | Croatian | -| `sl` | Slovenian | -| `sr` | Serbian | -| `da` | Danish | -| `no` | Norwegian | -| `sv` | Swedish | -| `fi` | Finnish | -| `et` | Estonian | -| `lv` | Latvian | -| `lt` | Lithuanian | -| `auto` | Per-utterance automatic language detection | - -## Usage Examples - -### Whisper (Transformers) - -```bash -python s2s_pipeline.py --stt whisper --language en -python s2s_pipeline.py --stt whisper --language auto -``` - -### Whisper MLX (LightningWhisperMLX) - -```bash -python s2s_pipeline.py --stt whisper-mlx --language auto --device mps -``` - -### MLX Audio Whisper - -```bash -python s2s_pipeline.py --stt mlx-audio-whisper \ - --mlx_audio_whisper_model_name mlx-community/whisper-large-v3-turbo \ - --language auto -``` - -### Faster-Whisper - -```bash -python s2s_pipeline.py --stt faster-whisper \ - --faster_whisper_stt_model_name large-v3 \ - --faster_whisper_stt_gen_language en -``` - -### Parakeet TDT - -```bash -python s2s_pipeline.py --stt parakeet-tdt --parakeet_tdt_device auto -python s2s_pipeline.py --stt parakeet-tdt --parakeet_tdt_language de -``` - -With live transcription (MLX or CUDA/nano-parakeet backend): - -```bash -python s2s_pipeline.py --stt parakeet-tdt \ - --enable_live_transcription \ - --live_transcription_update_interval 0.25 -``` - -### Paraformer - -```bash -python s2s_pipeline.py --stt paraformer --paraformer_stt_model_name paraformer-zh -``` +This directory contains Whisper, Parakeet, and Paraformer handlers and live +transcription helpers. See [speech-to-text backends](../../docs/speech/stt.md) +for supported modes, language codes, and configuration. diff --git a/speech_to_speech/TTS/README.md b/speech_to_speech/TTS/README.md index 33686d4..f3686e1 100644 --- a/speech_to_speech/TTS/README.md +++ b/speech_to_speech/TTS/README.md @@ -1,155 +1,5 @@ -# TTS Summary +# Text-to-speech handlers -## Available TTS modes (`--tts`) - -Runtime-supported values in `s2s_pipeline.py`: - -- `chatTTS` → `chatTTS_handler.py` -- `facebookMMS` → `facebookmms_handler.py` -- `pocket` → `pocket_tts_handler.py` -- `kokoro` → `kokoro_handler.py` -- `qwen3` → `qwen3_tts_handler.py` - -Deprecated TTS implementations, including MeloTTS, live in [`../../../archive/TTS`](../../../archive/TTS) and are no longer wired into `s2s_pipeline.py`. - -## Usage - -### 1) ChatTTS (`--tts chatTTS`) - -Primary args prefix: `--chat_tts_*` - -```bash -python s2s_pipeline.py \ - --tts chatTTS \ - --chat_tts_device cuda \ - --chat_tts_stream true \ - --chat_tts_chunk_size 512 -``` - -### 2) Facebook MMS (`--tts facebookMMS`) - -Primary args prefix: `--facebook_mms_*` plus `--tts_language` - -```bash -python s2s_pipeline.py \ - --tts facebookMMS \ - --facebook_mms_device cuda \ - --tts_language en -``` - -This handler maps STT language codes (e.g. `en`, `fr`, `es`) to MMS model suffixes (e.g. `eng`, `fra`, `spa`) and reloads the model on language changes. - -### 3) Pocket TTS (`--tts pocket`) - -Primary args prefix: `--pocket_tts_*` - -```bash -python s2s_pipeline.py \ - --tts pocket \ - --pocket_tts_voice jean \ - --pocket_tts_device cpu \ - --pocket_tts_sample_rate 16000 -``` - -Available preset voices include: -`alba`, `marius`, `javert`, `jean`, `fantine`, `cosette`, `eponine`, `azelma`. - -### 4) Kokoro (`--tts kokoro`) - -Primary args prefix: `--kokoro_*` - -```bash -python s2s_pipeline.py \ - --tts kokoro \ - --kokoro_device auto \ - --kokoro_voice bm_fable \ - --kokoro_lang_code b -``` - -Behavior: -- Uses MLX backend on Apple Silicon (`mlx-community/Kokoro-82M-bf16`) -- Uses native kokoro pipeline otherwise (`hexgrad/Kokoro-82M`) -- Can auto-switch voice/language based on STT language code mapping - -### 5) Qwen3-TTS (`--tts qwen3`) - -Primary args prefix: `--qwen3_tts_*` - -```bash -python s2s_pipeline.py \ - --tts qwen3 \ - --qwen3_tts_model_name Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice \ - --qwen3_tts_device cuda \ - --qwen3_tts_backend ggml \ - --qwen3_tts_speaker Aiden \ - --qwen3_tts_language auto \ - --qwen3_tts_non_streaming_mode True -``` - -Behavior: -- Uses `faster-qwen3-tts` on non-macOS platforms, defaulting to the GGML backend. Pass `--qwen3_tts_backend torch` to use the CUDA-graphs backend instead. -- Uses `mlx-audio` on Apple Silicon and auto-maps `Qwen/...` model IDs to `mlx-community/...`, defaulting to the `6bit` MLX variant unless the model name already pins a suffix. -- Supports MLX quantization overrides on Apple Silicon via `--qwen3_tts_mlx_quantization bf16|4bit|6bit|8bit`. -- Keeps the existing voice-clone/custom-voice/voice-design handler flow intact. -- Defaults to the CustomVoice model with speaker `Aiden`, so no reference audio is required. Voice-clone/base models can still use `--qwen3_tts_ref_audio`. - -Install notes for Linux GGML: -- The default PyPI `qwentts-cpp-python` wheel targets CUDA 12.8. -- If that wheel does not match your CUDA runtime, install one of the Hugging Face wheelhouse builds before installing `speech-to-speech`. - -```bash -pip install "qwentts-cpp-python==0.3.1+cu130" \ - -f https://huggingface.co/datasets/andito/qwentts-cpp-python-wheels/tree/main/whl/cu130 -pip install speech-to-speech -``` - -Available wheelhouse directories include `cu124`, `cu128`, `cu130`, and `cpu`. - -Example for Apple Silicon using the default 6-bit MLX variant: - -```bash -python s2s_pipeline.py \ - --tts qwen3 \ - --qwen3_tts_model_name Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice \ - --qwen3_tts_speaker Aiden -``` - -You can override the default and select `bf16`, `4bit`, or `8bit` explicitly: - -```bash -python s2s_pipeline.py \ - --tts qwen3 \ - --qwen3_tts_model_name Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice \ - --qwen3_tts_mlx_quantization 4bit \ - --qwen3_tts_speaker Aiden -``` - -To benchmark the Apple Silicon MLX variants side by side: - -```bash -.venv/bin/python benchmark_tts.py \ - --handlers qwen3 \ - --iterations 3 \ - --qwen3_mlx_quantizations bf16 4bit 6bit 8bit -``` - -This will run separate benchmark entries for `qwen3[bf16]`, `qwen3[4bit]`, `qwen3[6bit]`, and `qwen3[8bit]`. - -## Setup - -### Low-latency GPU setup - -```bash -python s2s_pipeline.py \ - --stt whisper \ - --tts pocket -``` - -### Apple Silicon setup - -```bash -python s2s_pipeline.py \ - --local_mac_optimal_settings -``` - -`--tts pocket` and `--tts kokoro` are also valid options on macOS. +This directory contains ChatTTS, Facebook MMS, Pocket, Kokoro, and Qwen3-TTS +handlers. See [text-to-speech backends](../../docs/speech/tts.md) for configuration, +voice selection, and the optional reference-audio example. diff --git a/speech_to_speech/api/openai_realtime/README.md b/speech_to_speech/api/openai_realtime/README.md index 10d91ca..eaf7995 100644 --- a/speech_to_speech/api/openai_realtime/README.md +++ b/speech_to_speech/api/openai_realtime/README.md @@ -1,216 +1,6 @@ -## Realtime Engine -- High-Level Architecture +# Realtime API implementation -The server runs as a handler thread inside the existing pipeline. A FastAPI/uvicorn instance serves the WebSocket endpoint at `/v1/realtime`, while the same queue-driven handler chain (VAD, STT, LLM, TTS) processes audio in parallel threads. - -```mermaid -flowchart LR - subgraph client [Client] - WS["WebSocket /v1/realtime"] - end - - subgraph server [Realtime Server] - Router["WebSocket Router"] - Service["RealtimeService"] - Config["RuntimeConfig"] - end - - subgraph pipeline [Pipeline Threads] - VAD["VAD"] - STT["STT"] - TN["TranscriptionNotifier"] - LLM["LLM"] - Proc["LMOutputProcessor"] - TTS["TTS"] - end - - WS -- "client events (JSON)" --> Router - Router -- "parse / dispatch" --> Service - Service -- "PCM chunks" --> VAD - Service -- "session config" --> Config - Config -. "read by" .-> VAD & LLM & TTS - VAD -- "speech segments" --> STT - STT -- "transcript" --> TN - TN -- "transcript + notify" --> LLM - LLM -- "text + tools" --> Proc - Proc -- "clean text" --> TTS - TTS -- "PCM audio" --> Router - Proc -- "assistant_text / tools" --> Router - VAD -- "speech_started/stopped" --> Router - TN -- "transcription events" --> Router - Router -- "server events (JSON)" --> WS -``` - -**Key flow:** - -1. **Inbound audio**: Client sends `input_audio_buffer.append` with base64 PCM. `RealtimeService` decodes, resamples to 16 kHz, splits into 512-sample chunks, and puts them on the `recv_audio_chunks_queue` for VAD. -2. **Speech detection**: VAD detects speech boundaries and emits `speech_started` / `speech_stopped` events on the `text_output_queue`. Full utterance audio goes to STT. -3. **Transcription**: STT output passes through `TranscriptionNotifier`, which taps the transcript for `transcription.delta` / `transcription.completed` events before forwarding to the LLM. -4. **Generation**: The LLM generates text (and optional tool calls). `LMOutputProcessor` splits the output: clean text goes to TTS, and `assistant_text` + tool call dicts go to the `text_output_queue`. -5. **Outbound audio**: TTS writes PCM chunks to `send_audio_chunks_queue`. The router's async `_send_loop` drains both queues, encoding PCM as `response.output_audio.delta` events and translating internal messages into protocol events. -6. **Session config**: `session.update` events deep-merge into `RuntimeConfig`, which is a shared Pydantic model read by VAD (turn detection thresholds), LLM (instructions, tools), and TTS (voice) at processing time. - ---- - -## Supported OpenAI Realtime Events - -### Client -> Server - -| Event | Description | -|---|---| -| `input_audio_buffer.append` | Stream base64 PCM audio. Decoded, resampled to 16 kHz, and chunked for the VAD. | -| `session.update` | Deep-merge session config (instructions, tools, voice, turn detection, audio format). | -| `conversation.item.create` | Inject `input_text` or `function_call_output` into the LLM context without triggering generation. | -| `response.create` | Trigger LLM generation. Supports per-response `instructions` and `tool_choice` overrides. | -| `response.cancel` | Cancel the in-progress response and re-enable listening. | - -### Server -> Client - -| Event | Description | -|---|---| -| `session.created` | Sent on connection with current session config. | -| `error` | Protocol errors (`session_limit_reached`, `unknown_or_invalid_event`, `invalid_session_type`, `conversation_already_has_active_response`, etc.) | -| `input_audio_buffer.speech_started` | VAD detected user speech. | -| `input_audio_buffer.speech_stopped` | End of user speech segment. | -| `conversation.item.created` | Acknowledges injected `input_text` from `conversation.item.create`. | -| `conversation.item.input_audio_transcription.delta` | Streaming partial transcript (when live transcription is enabled). | -| `conversation.item.input_audio_transcription.completed` | Final transcript for the user turn (with duration usage). | -| `response.created` | Emitted on the first outbound audio chunk (response is `in_progress`). | -| `response.output_audio.delta` | Base64 PCM audio chunk from TTS. | -| `response.output_audio.done` | Audio stream complete for the current output item. | -| `response.output_audio_transcript.done` | Full assistant text transcript for the turn. | -| `response.function_call_arguments.done` | Tool call with `call_id`, `name`, and JSON `arguments`. | -| `response.done` | Response finished (`completed`, `cancelled` with reason `turn_detected` or `client_cancelled`). | - ---- - -## Tool Calling Design - -Tool calling works through two distinct paths depending on the LLM backend, but both converge to the same wire protocol for the client. - -### Local LLM path (`LanguageModelHandler` -- transformers / mlx-lm) - -Tools defined in `session.update` are converted to `FunctionTool` objects. Each tool's JSON Schema `parameters` are turned into a Python `inspect.Signature` (via `signature_from_schema`), and `to_code_prompt()` renders a human-readable `def name(...): """docstring"""` block. - -These tool signatures are injected into the system prompt using a Jinja2 template (`tool_prompt.py`) that instructs the model to wrap tool calls in `...` delimiters: - -``` - -function_name(arg_name_1=value1, arg_name_2='string_value') - -``` - -After generation, `_extract_tools` uses a regex to find `` blocks, then `extract_function_calls_from_text` parses each `name(kwargs)` call and validates it against registered tools. Valid calls become `ResponseFunctionToolCall` dicts with generated `call_id`s. - -### OpenAI API path (`ResponsesApiModelHandler`) - -Tools are passed natively as the `tools=` parameter to `client.responses.create`. The API returns structured `function_call` items directly -- no prompt engineering or regex parsing needed. Per-response `tool_choice` overrides from `response.create` are supported. - -### Common output path - -Both handlers yield `(text, language_code, tools)` tuples. `LMOutputProcessor` forwards clean text to TTS and puts `{"type": "assistant_text", "text": ..., "tools": [...]}` on the `text_output_queue`. The router's `_send_loop` translates these into: -- `response.output_audio_transcript.done` for the text -- `response.function_call_arguments.done` for each tool call - -### Tool result flow - -1. Client executes the tool and sends `conversation.item.create` with `type: "function_call_output"` and `output: ""` -2. `RealtimeService` appends the tool output to the chat context and emits `conversation.item.created`; this does not trigger generation. -3. If the tool result needs to be spoken to the user, such as camera/search/data results, the client sends `response.create` to trigger follow-up generation. -4. For fire-and-forget robot actions such as dance, emotion, head movement, stop, or idle tools, the client can stop after `conversation.item.created`; the assistant should already have spoken the natural lead-in before the tool call. - ---- - -## Interruption Handling - -Barge-in (user speaks while the assistant is playing audio) is handled cooperatively between the VAD, the `_send_loop`, and the LLM/TTS handlers via a shared `CancelScope` object (`cancel_scope.py`). - -### CancelScope design - -`CancelScope` replaces the old two-signal pattern (`cancel_response` Event + `discard_stale_output` boolean) with a single object that manages: - -- **Generation counter** (`cancel_scope.generation`): pipeline threads (LLM, TTS) capture the current generation at the start of each response and check `cancel_scope.is_stale(gen)` on every streaming token. When `cancel()` is called, the generation increments and all prior generations become stale -- no timing games required. -- **Discard flag** (`cancel_scope.discarding`): set by `cancel()`, checked by the async `_send_loop` to drop output from superseded generations that arrives between `cancel()` and `response_done()`. Cleared by `response_done(generation)` (only when the sentinel's generation matches the discarded or current one -- sentinels from unrelated older generations are ignored), by `new_response()` on an explicit `response.create`, or by `reset()` on session claim/release. - -Pipeline output is **generation-tagged**: `AudioOutput` chunks and `AssistantTextEvent`s carry a `cancel_generation` field stamped by the handler that produced them. The send loop's `_generation_is_discardable` drops an item if its generation is stale, or if `discarding` is set and the item is not from the current generation. Output from the *current* generation always passes through, so a fresh response is never swallowed by a lingering discard window (e.g. a superseded speculative turn whose TTS never emitted a `__RESPONSE_DONE__` sentinel). - -```mermaid -sequenceDiagram - participant User - participant VAD - participant SendLoop as _send_loop - participant LLM - participant TTS - participant Client - - Note over TTS,Client: Response active or pending (in_response / response_pending) - User->>VAD: speaks - VAD->>SendLoop: speech_started on text_output_queue - SendLoop->>Client: input_audio_buffer.speech_started - SendLoop->>Client: response.done (status=cancelled, reason=turn_detected) - SendLoop->>SendLoop: cancel_scope.cancel() (gen++ & discarding=True) - SendLoop->>SendLoop: flush output_queue + text_output_queue - SendLoop->>SendLoop: response_playing.clear() - LLM->>LLM: is_stale(gen) → True, aborts generation - TTS->>TTS: is_stale(gen) → True, aborts generation - TTS->>SendLoop: __RESPONSE_DONE__ (tagged with gen) - SendLoop->>SendLoop: cancel_scope.response_done(gen) (discarding=False) - Note over VAD,Client: Pipeline is now processing the new user utterance -``` - -**Step by step:** - -1. **VAD detects speech**: puts a `SpeechStartedEvent` on `text_output_queue`. -2. **`_send_loop` processes text events first** (priority over audio): translates `speech_started` into protocol events. If an active response was in progress, `RealtimeService.dispatch_pipeline_event` emits `response.output_audio.done` + `response.done` with `status="cancelled"` and `reason="turn_detected"`. -3. **Cancel + queue flush**: if a response is active (`in_response`) *or* pending (`response_pending` -- accepted `response.create`, no audio yet), and interrupts are enabled (see step 4), the send loop calls `cancel_scope.cancel()` (increments generation, enables discard), clears `response_pending`, drains `output_queue` (preserving `__RESPONSE_DONE__` sentinels) and `text_output_queue` (preserving user-side events: `speech_stopped`, partial/completed transcriptions, token usage), then clears `response_playing`. -4. **Interrupt gating**: the cancel only fires if the `SpeechStartedEvent.interrupt_response` flag is set *and* the session config allows it (`turn_detection.interrupt_response`, read via `RuntimeConfig.interrupt_response_enabled`, default true). When disabled, user speech during a response is transcribed but the response keeps playing. -5. **LLM/TTS cancellation**: handlers capture `gen = cancel_scope.generation` at the start of each response and check `cancel_scope.is_stale(gen)` on every streaming token, aborting early when stale. -6. **Discard guard**: while `cancel_scope.discarding` is True, the send loop drops audio chunks and assistant text whose `cancel_generation` is not current (see `_generation_is_discardable` above). The guard clears when a `__RESPONSE_DONE__` with a matching generation arrives (via `cancel_scope.response_done(gen)`), or when an explicit `response.create` starts a new response (`cancel_scope.new_response()`). -7. **Client-initiated cancel**: `response.cancel` calls `cancel_scope.cancel()` (only if a response was active), flushes both queues with the same preservation rules, triggers `finish_response(status="cancelled", reason="client_cancelled")`, re-enables `should_listen`, and clears `response_playing`. -8. **Spurious cancel safety**: if no response is active, `cancel_scope.cancel()` is not called, preventing the discard guard from being set without a `__RESPONSE_DONE__` to clear it. - ---- - -## Testing - -### Local LLM with Transformers - -```bash -uv run speech-to-speech \ - --mode realtime \ - --stt parakeet-tdt \ - --llm_backend transformers \ - --tts kokoro \ - --model_name "Qwen/Qwen3-4B-Instruct-2507" \ - --llm_device mps \ - --llm_torch_dtype float16 \ - --enable_live_transcription -``` - -### Local LLM with MLX-LM - -```bash -uv run speech-to-speech \ - --mode realtime \ - --stt parakeet-tdt \ - --llm_backend mlx-lm \ - --tts kokoro \ - --model_name "mlx-community/Qwen3-4B-Instruct-2507-bf16" \ - --llm_device mps \ - --llm_torch_dtype float16 \ - --enable_live_transcription -``` - -### Remote LLM with OpenAI-compatible API - -```bash -uv run speech-to-speech \ - --mode realtime \ - --stt parakeet-tdt \ - --llm_backend responses-api \ - --tts kokoro \ - --model_name "openai/gpt-oss-20b:groq" \ - --responses_api_base_url "https://router.huggingface.co/v1" \ - --responses_api_api_key "$HF_TOKEN" \ - --responses_api_stream \ - --enable_live_transcription -``` +This directory implements the OpenAI Realtime-compatible WebSocket service, +session configuration, event handlers, and pipeline routing. See the +[realtime API guide](../../../docs/speech/realtime-api.md) for architecture, +supported events, tool calling, cancellation, and startup examples.