Skip to content

Self-improving AI Employees for everyone

docs: architecture pass for the speech and media-transport subsystems

trohitg9e10739c30e7
diff --git a/CLAUDE.md b/CLAUDE.md
index f37bcbf9..e3acf255 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -34,6 +34,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire
| **[Google Cloud Service](./docs-internal/gcloud_service.md)** | Google Cloud CLI integration — `gcloudAction` (auth/config/projects + set_project / Compute Engine instances list-start-stop-describe / Cloud Run deploy-list-describe / Cloud Storage ls-cp-rm / `custom` passthrough; AI tool `gcloud`) wrapping the official gcloud CLI (pinned versioned archive via pooch into `package_dir("gcloud")` — NOT npm; the Windows bundled-python zip keeps the legacy `google-cloud-sdk-` filename prefix, the `-cli-` spelling 404s, locked by test). Cloudflare login variant (CLI opens the browser itself, random loopback port — no fixed-port hazard) + the gh marker-token pattern; success gate = `gcloud auth list --filter=status:ACTIVE --format=json` non-empty (exit codes never trusted). **Config isolation divergence from gh**: every invocation pins `CLOUDSDK_CONFIG=<DATA_DIR>/gcloud/`, so terminal logins against the operator's global gcloud are deliberately NOT visible to the node. ADC note: node login mints gcloud USER creds only (CLI commands never read ADC); client-library code gets ADC via the `custom` op `auth application-default login` (lands isolated in the pinned dir). Cold install ~100 MB → login answers `pending: True` within the 22 s WS budget. Provider id `gcloud` is orthogonal to the Workspace `google` OAuth2 provider. Palette group `deployment`. |
| **[Sarvam AI Service](./docs-internal/sarvam_service.md)** | Sarvam AI (Indic-first) — `sarvamChatModel` registered as an **OpenAI-compat provider** (one `_COMPAT_PROVIDERS` entry + a JSON block; no provider subclass) plus three text REST nodes under `nodes/sarvam/` (`sarvamTranslate` / `sarvamTransliterate` / `sarvamDetectLanguage`, palette group `language`). Sarvam's speech endpoints are NOT nodes here — they are one provider inside the abstracted `textToSpeech` / `speechToText` nodes (see **[Speech Provider RFC](./docs-internal/speech_provider_rfc.md)**). **One stored key spans two auth styles** — the chat route takes `Authorization: Bearer` (what the openai SDK sends) while every other endpoint takes only `api-subscription-key`, so `SarvamCredential` declares the native header and every surface shares it. Introduces the generic **`supports_model_listing: false`** flag: Sarvam ships no `/v1/models` route, and unhandled that 404 becomes a `NodeUserError` that `AIService.fetch_models` re-raises *before* its curated fallback, breaking key validation and the model dropdown — so `OpenAIProvider.fetch_models` serves the curated list and probes with a one-token completion instead (defaults `true`; the other 12 providers are untouched, locked by test). Reasoning needs zero Python (`thinking_type: "effort"` + `reasoning_content` are already handled); `thinking_default_on` and `reasoning_models` are deliberately omitted. Also added generic **`Connection.request(files=)`** multipart support (threaded through the auth-retry rebuild), which the speech plugin still relies on. |
| **[Speech Provider RFC](./docs-internal/speech_provider_rfc.md)** | Provider-abstracted speech — two nodes (`textToSpeech`, `speechToText`) with a `provider` dropdown, backed by **two registries, one per direction** (registry membership IS the capability: a synthesis-only vendor simply never appears in the transcription enum). Everything vendor-specific lives in the plugin folder [`server/nodes/speech/`](./server/nodes/speech/) — protocol, registries, dispatch, per-vendor modules; only the generic `services/provider_registry.py` and the vendor-neutral `services/media/` are shared. v1 providers: OpenAI (both directions), ElevenLabs (TTS), Deepgram + Groq (STT), Sarvam (both). Capabilities are JSON (`server/config/speech_defaults.json`) with per-model overrides, so no shared code branches on a provider name. **Audio never travels as bytes** — nodes return an `AudioRef` (a ~400 B reference) because a 12 MB base64 result blows Temporal's 2 MiB blob limit and retries 3× re-billing the provider each time. Backing routes: `GET/POST /api/workspace/{workflow_id}/…` in [`routers/workspace.py`](./server/routers/workspace.py). |
+| **[Media Transport](./docs-internal/media_transport.md)** | How files move through the engine, and why they move as **references rather than bytes**. `services/media/` — `AudioRef` (~400 B, `extra="forbid"` so adding a bytes field is a `ValidationError` rather than a silent regression), `write_audio` / `resolve_media` / `coerce_file_param` (the one nodes should call — accepts an `AudioRef`, a bare path, or the legacy base64 envelope), `inspect_audio` (tinytag → stdlib `wave` → PCM arithmetic, **never raises**), and `limits.py`. Containment runs through `resolve_within`, which closed a live vulnerability: a node joined a user path onto the workspace root unchecked, so `audio_file="../../credentials.db"` read the encrypted credential store and uploaded it. **The id/slug asymmetry is the trap** — workspace dirs are named by the mutable `Workflow.slug` while an `AudioRef` stores the immutable `workflow_id` so refs survive rename; `workspace_root()` raises rather than guessing, and the HTTP route owns the lookup. HTTP surface in [`routers/workspace.py`](./server/routers/workspace.py): Range support comes free from Starlette's `FileResponse`, and only `audio/ image/ video/` render inline — `text/html` and `image/svg+xml` are forced to `attachment` because `shell` / `fileDownloader` / `fileModify` can write arbitrary files into a workspace. |
| **[CI/CD Pipeline](./docs-internal/ci_cd.md)** | GitHub Actions workflows, predeploy validation, release publishing, and composite setup action |
| **[Performance](./docs-internal/performance.md)** | Cold-start measurements (Application startup complete 2.90 s warm, 21.5 s cold post-`company clean` — was 71 s before the 2026-07-14 boot-delay fixes; first WS connect 8.29 s) + warm and cold per-phase timelines + optimisation history (lazy LangChain imports, lazy LLM-SDK exception refs, esbuild sidecar bundle, bytecode-at-build, PartySocket reconnect, TanStack Query auth bootstrap, `manualChunks`, Vite dep-cache preservation, off-loop Temporal build-id hash) + bottleneck inventory + reproduction commands + anti-patterns to never reintroduce (incl. eager SDK import at LLM provider registration, unconditional `.vite` wipe, synchronous `Worker()` on the event loop). Pairs with the build-time pipeline doc below. |
| **[Release Build Pipeline](./docs-internal/release_build_pipeline.md)** | npm-distribution build pipeline: `tsgo` for type-check (5× faster than tsc), Vite `manualChunks` + `target: 'es2022'`, esbuild Node.js sidecar bundle (drops `tsx` interpreter cost), bytecode pre-compile in two halves — `[tool.uv] compile-bytecode = true` (uv sync compiles `.venv/` site-packages) + `python -m compileall` for project source (plain `.pyc`, **no `-O`** — per PEP 488 the non-`-O` runtimes never load `.opt-1.pyc`; excludes `.venv/`, `tests/`). Single source of truth for the bytecode-compile path list: `cli.commands.build.COMPILEALL_SOURCE_DIRS`. |
@@ -127,6 +128,14 @@ server/services/
├── himalaya_service.py # HimalayaService CLI wrapper for IMAP/SMTP (any email provider)
├── email_service.py # EmailService orchestrator (credential resolution, provider presets)
├── todo_service.py # TodoService singleton for writeTodos tool (JSON per-session state)
+├── media/ # Media transport — vendor-neutral, kind-agnostic (see media_transport.md)
+│ ├── refs.py # AudioRef — a reference, never bytes; extra="forbid" makes that structural
+│ ├── workspace.py # write_audio / resolve_media / read_media_bytes / coerce_file_param
+│ ├── inspect.py # tinytag -> wave -> PCM arithmetic; NEVER raises
+│ └── limits.py # every size constant, each annotated with what it defends against
+├── provider_registry.py # Generic ProviderSpec + ProviderRegistry + lazy exception refs.
+│ # Shared by services/llm and nodes/speech (which owns two, one per
+│ # direction). Registration must never import a provider SDK.
├── memory/ # Native Markdown/JSONL/runtime/vector-store helpers
├── memory_store.py # In-memory conversation sessions using native Message values
├── skill_prompt.py # Skill system prompt builder (injects SKILL.md for personality skills)
@@ -200,7 +209,12 @@ server/config/
├── model_registry.json # Cached model data from OpenRouter (auto-refreshed)
├── pricing.json # LLM and API pricing config
├── google_apis.json # Google Workspace API endpoints, scopes, OAuth callback paths
-└── email_providers.json # IMAP/SMTP provider presets (Gmail, Outlook, Yahoo, iCloud, ProtonMail, Fastmail, custom)
+├── email_providers.json # IMAP/SMTP provider presets (Gmail, Outlook, Yahoo, iCloud, ProtonMail, Fastmail, custom)
+└── speech_defaults.json # Per-provider TTS/STT capabilities, per-direction, with per-model overrides
+ # ({"whisper-1": [...], "_default": [...]} resolved exact -> longest-prefix ->
+ # _default). Drives the provider dropdowns, voice/model loaders and validation.
+ # Boolean flags default PERMISSIVE so a missing declaration never silently
+ # disables a working feature. Read by nodes/speech/_config.py.
server/nodejs/ # Persistent Node.js server for JS/TS execution
├── package.json # Dependencies: express, tsx
@@ -652,6 +666,20 @@ Node groups (palette categories): agent, model, skill, tool, trigger, workflow,
- Returns immediate 200 OK response (responseNode mode planned for future)
- `GET /webhook/` - Webhook endpoint info and usage documentation
+#### Workspace Router (`server/routers/workspace.py`)
+- `GET /api/workspace/{workflow_id}/files/{path:path}` - Serve a file from a workflow's workspace.
+ Range/seeking comes free from Starlette's `FileResponse` (`206` / `Content-Range` / `If-Range` /
+ `416`) — do NOT wrap it in a `StreamingResponse`. Containment via `resolve_within`; 404 never 403
+ (a distinct status would confirm what exists outside the workspace). Only `audio/ image/ video/`
+ render inline — `text/html` and `image/svg+xml` are forced to `attachment`, because nodes can
+ write arbitrary files into a workspace and inline markup from the app origin is stored XSS.
+- `POST /api/workspace/{workflow_id}/uploads` - Streamed multipart upload (the first in the repo on
+ either side of the wire). Chunked read with a running total — `Content-Length` is never trusted —
+ 413 past `MEDIA_MAX_UPLOAD_BYTES`. Returns an `AudioRef`, which `coerce_file_param` accepts.
+- **The URL carries `workflow_id`; the directory is named by `Workflow.slug`.** The router owns that
+ lookup because it needs the database, while `services.media` stays synchronous. See
+ [Media Transport](./docs-internal/media_transport.md).
+
#### Workflow Services (`server/services/workflow.py`)
- Node execution dispatches every registered plugin via the `BaseNode` registry (one self-contained folder per node under `server/nodes/<group>/`; 131 node types today via `len(services.node_registry.NODE_METADATA)` — a bare `__init__.py` glob overcounts by also matching the group packages)
- Parameter resolution and template variable substitution
@@ -2687,4 +2715,8 @@ This function:
- **Agent progress badge — defensive status invariant** (15b8d9d): `AIAgentNode`'s "N / max" iteration badge is gated on `isExecuting && typeof iteration === 'number' && typeof maxIterations === 'number'` where `isExecuting = nodeStatus?.status === 'executing'`. The `agent_progress` handler USED to only set `data.iteration` / `data.max_iterations`, relying on a prior `node_status='executing'` broadcast to have already stamped the status. If agent_progress arrived first (race, single-step agent completion, out-of-order Temporal activity delivery), `status` stayed undefined and the badge was hidden even though the iteration data was populated. Fix: the agent_progress handler now defensively sets `status='executing'` on the slot — but preserves `'success'` / `'error'` if a later terminal broadcast already flipped the slot (terminal states win over the resurrection).
- **Temporal Worker tuner exclusivity** (Wave 16.4, 190c896): `Worker.__init__` rejects `tuner` alongside ANY of `max_concurrent_workflow_tasks` / `max_concurrent_activities` / `max_concurrent_local_activities` / `max_concurrent_nexus_tasks` — the tuner OWNS every slot supplier via its `WorkerTuner.create_composite(workflow_supplier, activity_supplier, local_activity_supplier, nexus_supplier)` and cannot coexist with the individual max-count kwargs. In `TemporalWorkerPool.start`, ALL FOUR max-count kwargs must be pulled from the base `worker_kwargs` when `tuner=` is added; the ai-heavy / browser queues use the tuner and preserve their 10-workflow-slot ceiling via `_tuner_for -> FixedSizeSlotSupplier(10)` on the workflow_supplier slot. The framework worker at `worker.py:188` does NOT use a tuner, so it keeps the plain `max_concurrent_workflow_tasks=10` + `max_concurrent_activities=self.pool_size` kwargs directly. `TEMPORAL_WORKER_POOL_ENABLED` defaulted to True in the same commit (`test_task_queue_coverage.py::TestWorkerPoolDefaultOn` locks the default via source-introspection so the flip survives a hasty revert).
- **No hardcoded port numbers in code or docs**: `.env.template` is the single place port numbers live (`.env` overrides, process env wins). Python resolves via `core.env_defaults.env_value/env_int` (raises loudly when unconfigured — never a numeric fallback literal); the Vite config and the Node executor sidecar require their env vars the same way; scripts/CI/installers parse the template. Docs reference env var names (`PYTHON_BACKEND_PORT`, `TEMPORAL_UI_PORT`, ...) instead of numerals; user-facing quickstarts may show the default app URL once. See `docs-internal/cli_services_integration.md` for the plugin-daemon recipe.
+- **Multi-vendor nodes: one node, a `provider` dropdown, two registries.** `nodes/speech/` is the reference and the first multi-credential plugin in the repo (`credentials = (A, B, C)`; `ctx.connection(id)` is a dict lookup over that tuple). Four load-bearing rules. (1) **Imperative `@Operation` only** — the declarative `routing=` path resolves `credentials[0]` (`base.py:571`), so a routed op authenticates every provider with the first key in the tuple and `test_plugin_contract.py` would not catch it. (2) **Registry membership IS the capability** — one registry per direction, the node's provider enum literally *is* `tts_providers()`, so a synthesis-only vendor cannot be selected for transcription and there is no `supports_x` flag to keep honest. (3) **Capabilities live in JSON** (`server/config/speech_defaults.json`), per-model overrides resolved exact -> longest-prefix -> `_default`, boolean flags defaulting **permissive**; no shared code branches on a vendor name. (4) **Vendor divergence stays in the vendor module** — auth scheme, query-vs-body, response shape. The v1 set diverges on all three axes and three of those divergences fail *silently* (ElevenLabs ignores a body-placed `output_format`, Deepgram ignores body options entirely, Sarvam returns a base64 array), so each has a test asserting the outgoing request rather than the parsed result. Full reference: **[Speech Provider RFC](./docs-internal/speech_provider_rfc.md)** + [plugin_system.md -> Multi-credential nodes](./docs-internal/plugin_system.md#multi-credential-nodes).
+- **Never name a Params field `model` or `api_key` on a node that also has a `provider` field.** An effect at [`ParameterRenderer.tsx:866`](./client/src/components/ParameterRenderer.tsx#L866) keys on those two literal names: with a sibling `provider` field present it overwrites `model` with the *chat-model* list and clears `api_key` — and it never validates that the provider is an LLM provider, so `provider: "elevenlabs"` still triggers it and the field is wiped the moment the user picks a vendor. Line 930 also writes options onto the literal string `'model'`, not `parameter.name`. Prefix instead (`tts_model` / `stt_model`), locked by a test in `tests/nodes/test_speech.py`. Other reserved sibling names with name-based magic in that file: `parameters`, `message_type`, `group_id`, `group_name`, `channel_jid`, `sender_number`, `sender_name`, `session_id`, `service_id`, `action`.
+- **`usable_as_tool = True` auto-hides both canvas handles.** `base.py:215` sets `hide_input_handle` / `hide_output_handle` to `True` unless the class declares them, so a dual-purpose node that must stay wirable has to declare both `False` explicitly. Symptom: the node works fine as an AI tool but cannot be connected to anything on the canvas.
+- **Media leaves a node as a reference, never as bytes.** `services/media/` + `AudioRef` (~400 B, `extra="forbid"`). A node result is persisted 3x, broadcast 2x, retained in `_status` forever, aggregated into the workflow result, copied into every downstream activity *input*, and — if `usable_as_tool` — serialized into an LLM message; a 12 MB base64 payload therefore fails the activity, **retries 3x re-billing the provider each time**, and reports a generic error. Nodes call `write_audio` (out) and `coerce_file_param` (in); both enforce containment through `resolve_within`, which closed a live traversal that let `audio_file="../../credentials.db"` read the encrypted credential store and upload it. **id/slug trap:** workspace dirs are named by the mutable `Workflow.slug` while an `AudioRef` stores the immutable `workflow_id` so refs survive rename — `workspace_root()` raises rather than composing a wrong path, and `routers/workspace.py` owns the lookup because it needs the DB. Full reference: **[Media Transport](./docs-internal/media_transport.md)**.
- never use emojis in prints
diff --git a/docs-internal/DESIGN.md b/docs-internal/DESIGN.md
index c2284176..859c0401 100644
--- a/docs-internal/DESIGN.md
+++ b/docs-internal/DESIGN.md
@@ -116,6 +116,31 @@ class WorkflowExecutor:
self.status_callback = status_callback
```
+### 4. A node result is small, because it is copied many times
+
+Node results are not stored once. One result is written to `node_outputs`
+**3x** per store, broadcast **2x** over the status WebSocket, retained in
+`StatusBroadcaster._status` for the process lifetime and replayed to every
+newly connecting client, aggregated into the workflow result, copied into
+**every downstream activity's input**, and — when the node is
+`usable_as_tool` — serialized verbatim into an LLM message.
+
+Temporal caps a blob at **2,097,152 B** for activity results *and inputs*, and
+warns at 524,288 B. `_PayloadSizeError` is not in `NON_RETRYABLE_ERROR_TYPES`,
+so exceeding the cap costs **three attempts** — re-invoking (and re-billing)
+whatever produced the payload each time — before surfacing a generic failure
+that names nothing useful.
+
+So: **large data lives on disk in the workflow workspace, and the node returns
+a reference.** `services/media/` provides that for binary media (`AudioRef`,
+`write_audio`, `coerce_file_param`), with an HTTP route for the frontend to
+fetch through. A capped inline opt-in is explicitly rejected as a design: it
+makes the tool path *sometimes* catastrophic, which is worse than
+always-broken because it passes review.
+
+See [media_transport.md](./media_transport.md) for the measurements and the
+API.
+
---
## Design Patterns
diff --git a/docs-internal/frontend_architecture.md b/docs-internal/frontend_architecture.md
index 8220a369..3a0fc382 100644
--- a/docs-internal/frontend_architecture.md
+++ b/docs-internal/frontend_architecture.md
@@ -379,6 +379,43 @@ Currently a 2152-line switch on `parameter.type` ([client/src/components/Paramet
See [ui_migration_plan.md](./ui_migration_plan.md) Phase 6.
+### Name-based magic in this file (read before naming a Params field)
+
+Several branches key on **literal parameter names**, not on types or hints. A
+backend field that happens to use one of these names inherits behaviour nobody
+declared:
+
+| Name | What happens |
+|---|---|
+| `model`, `api_key` | With a sibling `provider` field present, an effect (~line 866) overwrites `model` with the **chat-model** list and clears `api_key`. It does **not** validate that the provider is an LLM provider, so `provider: "elevenlabs"` still triggers it. Line 930 writes options onto the literal string `'model'`, not `parameter.name`. |
+| `parameters` | Android branch: fetches `/api/android/services/.../parameters` and overwrites the whole value. |
+| `message_type` | Drives the `accept=` of the `file` input and remounts it. |
+| `group_id`, `group_name`, `channel_jid`, `channel_display_name`, `sender_number`, `sender_name` | WhatsApp loaders; several read sibling names for their display label. |
+| `session_id`, `service_id`, `action` | Agent-session and Android loaders. |
+
+Prefix instead — `tts_model`, `stt_model`. The speech nodes do, and
+`tests/nodes/test_speech.py` asserts neither declares `model` or `api_key`.
+This is a known wart of the pre-Phase-6 renderer; Phase 6's tester-based
+dispatch is what removes the whole class of it.
+
+### File parameters upload; they no longer base64
+
+`case 'file'` POSTs to `/api/workspace/{workflow_id}/uploads` via
+[`lib/workspaceUpload.ts`](../client/src/lib/workspaceUpload.ts) and stores the
+returned `AudioRef` (~400 bytes). Do **not** set `Content-Type` on that fetch —
+the browser must set it so the multipart boundary is generated.
+
+The legacy base64 envelope (`{type: 'upload', data: '<base64>'}`) survives only
+as a fallback for a workflow that has never been saved and therefore has no
+workspace yet. It is a genuine hazard at media sizes: it is JSON-stringified
+onto the WebSocket, persisted in the `node_parameters` row, re-broadcast to
+every connected client, and re-`JSON.stringify`d on every render by
+`hasUnsavedChanges` — then dies at Temporal's 2 MiB payload limit. A ~1.5 MB
+clip is already ~2 MB of base64. `coerce_file_param` still accepts it
+server-side so existing saved rows keep working.
+
+See [media_transport.md](./media_transport.md).
+
## Real-time
`contexts/WebSocketContext.tsx` is the single connection + event bus. ~125 handlers (see `server/routers/websocket.py`). Handlers follow a request/response pattern via `sendRequest(type, data)` with correlation IDs. Push-only events (node status, workflow progress, token usage, android/whatsapp status) set context state directly; components subscribe via selector hooks (`useAndroidStatus`, `useNodeStatus(nodeId)`).
@@ -471,6 +508,7 @@ Defined on `INodeTypeDescription.uiHints` ([client/src/types/INodeProperties.ts]
| `hasSkills` | Agent panels | Connect the connected-skills section |
| `isConfigNode` | `InputSection`, `OutputPanel` | This node is auxiliary configuration — its panel inherits the parent's main inputs instead of showing direct upstream connections. **Auto-derived on the backend** by `_derive_auto_ui_hints` in [`server/services/plugin/base.py`](../server/services/plugin/base.py): plugins whose `group` tuple contains `memory` or `tool` get this for free. Explicit `cls.ui_hints` always wins. |
| `outputMode: "terminal"` | `output/OutputPanel` | The node's textual output is CLI/terminal text: render it in a `<pre>` painted with the per-theme `--code-*` tokens instead of ReactMarkdown (which turns `#` into headings and collapses indentation). Strings that are wholly JSON route to the JSON tree via the shared `tryParseJson` helper. Declared by the CLI-wrapper plugins (`githubAction`, `vercelAction`, `shell`). |
+| `outputMode: "audio"` | `output/OutputPanel` | The node produces audio: render an `<audio>` player for each `AudioRef` in the result instead of letting it fall into the JSON tree. Declared by `textToSpeech`. Note the panel's detection is **structural** (`kind === "audio"`), so a ref arriving from anywhere still renders — the hint is the declarative signal, not the gate. Widening this union needed no backend change: `test_ui_hints_only_carry_known_flags` checks flag *names*, not values. |
Adding new panel behaviour: add a flag to `INodeUIHints`, annotate the relevant node definitions (or extend the auto-derivation rule on the backend), read the flag in the panel. Don't add another `nodeDefinition.name === '…'` branch — six such checks for `'masterSkill'` were retired in this round in favour of `uiHints.isMasterSkillEditor`. Pytest invariant `test_ui_hints_only_carry_known_flags` in `server/tests/test_node_spec.py` locks the flag set; new flags must be added there too.
diff --git a/docs-internal/media_transport.md b/docs-internal/media_transport.md
new file mode 100644
index 00000000..95d7d50c
--- /dev/null
+++ b/docs-internal/media_transport.md
@@ -0,0 +1,267 @@
+# Media Transport — how files move through the engine
+
+**Status:** shipped.
+**Scope:** `server/services/media/`, `server/routers/workspace.py`, `nodes/filesystem/_backend.py`.
+**Companion:** [Speech Provider RFC](./speech_provider_rfc.md) — the first consumer.
+
+One rule underneath everything here:
+
+> **Media bytes do not travel through the workflow engine.** Nodes return a
+> reference; the bytes stay on disk in the workflow's workspace.
+
+This is not a style preference. It is forced by measured limits, and every API
+in this module exists to make the correct thing the easy thing.
+
+---
+
+## 1. Why — the measured constraint
+
+| Limit | Value | Where |
+|---|---|---|
+| Temporal blob **error** (activity result *and input*, workflow result) | **2,097,152 B** | server default; no custom DataConverter anywhere |
+| Temporal blob **warning** | 524,288 B → `PayloadSizeWarning`, unfiltered | |
+| Retries burned before failing | **3** — `_PayloadSizeError` is not in `NON_RETRYABLE_ERROR_TYPES` | [`_retry_policies.py`](../server/services/temporal/_retry_policies.py) |
+| `node_outputs.data` | no cap, written **3×** per store | [`activities.py`](../server/services/temporal/activities.py) |
+| WS broadcast | no size guard; payload retained in `_status` **forever** and replayed to every new client | [`status_broadcaster.py`](../server/services/status_broadcaster.py) |
+
+A node result is not stored once. It is persisted three times, broadcast twice,
+retained in the status cache, aggregated into the workflow result, copied into
+every downstream activity's *input*, and — if the node is `usable_as_tool` —
+serialized into an LLM message.
+
+So a 12 MB base64 TTS result does not merely fail. It fails the activity,
+**retries three times re-billing the provider on each attempt**, and reports a
+generic payload error that names nothing useful.
+
+A capped opt-in ("inline base64 up to N bytes") is worse than no opt-in,
+because it makes the tool path *sometimes* catastrophic — which passes review.
+
+---
+
+## 2. `AudioRef` — a reference, structurally
+
+[`services/media/refs.py`](../server/services/media/refs.py). ~400 bytes
+serialized, so thousands fit inside Temporal's *warning* threshold.
+
+```python
+class AudioRef(BaseModel):
+ kind: Literal["audio"] = "audio"
+ path: str # workspace-RELATIVE POSIX, no leading slash
+ workflow_id: Optional[str] # immutable id — survives rename
+ filename: str # display only, never used for resolution
+ mime_type: str
+ format: str
+ size_bytes: int
+ duration_seconds: Optional[float] # None when unmeasurable; never guessed
+ sample_rate: Optional[int]
+ channels: Optional[int]
+ sha256: Optional[str]
+ url: Optional[str] # path-only, no scheme or host
+
+ model_config = ConfigDict(extra="forbid")
+```
+
+Three deliberate properties:
+
+- **No bytes field, and `extra="forbid"`.** Adding one is a `ValidationError`,
+ not a silent regression. A test asserts no `data` / `bytes` / `base64` /
+ `content` field exists — the invariant is structural, not a convention
+ someone has to remember.
+- **`path` is workspace-relative.** An absolute path embeds the mutable
+ workflow slug, leaks the operator's home directory into the database, the
+ WebSocket broadcast and the LLM context, and cannot be safely turned into an
+ HTTP URL.
+- **`duration_seconds` is `None` rather than approximate** when it could not be
+ measured. A fabricated duration silently mis-bills per-second providers.
+
+### The id/slug asymmetry (read this before touching resolution)
+
+Workspace directories are named by **`Workflow.slug`**, which changes on
+rename — `WorkflowService._get_workspace_dir` creates them and
+`workflow_storage/handlers.py` moves them. An `AudioRef` stores the
+**immutable `workflow_id`** precisely so a reference keeps working across a
+rename.
+
+Converting one to the other needs a database read, so:
+
+- `services.media` is **synchronous by contract** and never does the lookup.
+- `workspace_root()` accepts an explicit `workspace_dir=` or a `ctx`, and
+ **raises** when given only a `workflow_id` rather than guessing.
+- The caller that *has* a database — the workspace HTTP route — does the
+ lookup and passes the resolved directory in.
+
+An earlier version composed `workspaces/<workflow_id>/` here. That path never
+exists. It stayed invisible for a full wave because every caller happened to
+supply a `ctx`; the HTTP route was the first that could not.
+
+`core.paths.workspace_dir`'s parameter is named `workflow_slug` for the same
+reason — it used to say `workflow_id` and misled exactly this way.
+
+---
+
+## 3. Containment
+
+Everything funnels through `resolve_within(root, key)` in
+[`nodes/filesystem/_backend.py`](../server/nodes/filesystem/_backend.py), which
+applies two layers:
+
+1. Reject `..`, leading `~`, and drive-prefixed input **before** touching the
+ filesystem.
+2. Resolve, then re-check containment with `relative_to(root)` — so a symlink
+ or Windows junction cannot redirect the result outside the root.
+
+It is module-level rather than a `WorkspaceBackend` method precisely because
+`services.media` and the HTTP route both need it.
+
+**This closed a live vulnerability.** The Sarvam speech-to-text node joined a
+user-supplied path onto the workspace root with no check at all, so
+`audio_file="../../credentials.db"` read the encrypted credential store and
+uploaded it to a third-party provider. `coerce_file_param` closes that by
+construction for every node that adopts it.
+
+---
+
+## 4. The API
+
+[`services/media/workspace.py`](../server/services/media/workspace.py)
+
+| Function | Use |
+|---|---|
+| `write_audio(payload, *, ctx, stem, ext, …) -> AudioRef` | Atomic write into `<workspace>/audio/`. Filename is `<slug>-<node8>-<rand6>.<ext>`, so retries and repeated runs never collide or overwrite. Probes the file and populates the metadata. |
+| `resolve_media(ref_or_path, *, ctx \| workspace_dir) -> Path` | Contained absolute path. Absolute inputs are tolerated for back-compat but still contained. |
+| `read_media_bytes(...) -> (filename, bytes)` | `resolve_media` + non-empty and size checks. |
+| `coerce_file_param(value, *, ctx) -> (filename, bytes)` | **The one nodes should call.** Accepts all three shapes the UI can produce. |
+| `workspace_file_url(workflow_id, rel_path)` | Path-only URL for the HTTP route. No scheme, no host. |
+
+`coerce_file_param` accepts:
+
+1. A serialized `AudioRef` — what the upload route returns.
+2. The legacy `{"type": "upload", "data": "<base64>"}` envelope the file widget
+ used to emit. **Accepted indefinitely**: saved workflow rows carry it and
+ are not migrated. Logs one warning naming the node so operators can find and
+ re-save them.
+3. A bare path string — typed, or dragged from an upstream node.
+
+### Inspection never fails a workflow
+
+[`services/media/inspect.py`](../server/services/media/inspect.py) falls back
+`tinytag` → stdlib `wave` → raw-PCM arithmetic → empty probe, and **never
+raises**. An unknown container yields an all-`None` probe and a DEBUG line.
+
+Degrading a billing estimate is acceptable; hard-failing a valid file because a
+metadata parser did not recognise a codec variant is not.
+
+`tinytag` was chosen over mutagen (GPL-2.0 against this project's MIT — a
+licensing decision, not a technical one) and over pydub / ffprobe, which both
+need an ffmpeg binary on PATH that nothing installs on Windows.
+
+### Limits
+
+[`services/media/limits.py`](../server/services/media/limits.py) is the single
+home for every size constant, each annotated with what it is defending against.
+`MEDIA_MAX_UPLOAD_BYTES` is 25 MiB — deliberately far above the Temporal limit,
+because uploaded bytes land on disk and only a reference enters a payload.
+
+---
+
+## 5. HTTP surface
+
+[`routers/workspace.py`](../server/routers/workspace.py). A thin shell over the
+above — it owns no containment logic of its own.
+
+### `GET /api/workspace/{workflow_id}/files/{path:path}`
+
+- id → slug lookup, then `resolve_within`.
+- **404, never 403** — a distinct status would confirm the existence of files
+ outside the workspace.
+- **Range/seeking is free.** Starlette's `FileResponse` already implements
+ `Accept-Ranges`, `206`, `Content-Range`, `If-Range` and `416`. Do not wrap it
+ in a `StreamingResponse`; that loses all of it and breaks `<audio>` seeking.
+- **Inline allowlist.** Only `audio/ image/ video/` render inline; everything
+ else — emphatically including `text/html` and `image/svg+xml` — gets
+ `Content-Disposition: attachment`, plus `X-Content-Type-Options: nosniff`.
+
+ This is load-bearing. `shell`, `fileDownloader` and `fileModify` can all
+ write arbitrary files into a workspace, so serving attacker-authored markup
+ inline **from the app origin** would be stored XSS with session-cookie
+ access. Both excluded types are script-bearing.
+- No immutable caching: workspace files are mutable. `AudioRef.sha256` is a
+ natural `ETag`.
+
+### `POST /api/workspace/{workflow_id}/uploads`
+
+The first multipart endpoint in the repo, on either side of the wire.
+
+- Read in bounded chunks with a running total — never `await file.read()`, and
+ never trust `Content-Length`, which is attacker-controlled. The cap is
+ enforced on bytes **actually read**, so an oversize body aborts before it has
+ all arrived.
+- Returns a serialized `AudioRef`, which `coerce_file_param` already accepts.
+
+### Auth
+
+No work needed, and **no signed-URL scheme** — tokens in URLs leak into logs,
+`Referer` headers and browser history.
+
+`AuthMiddleware`'s SPA bypass explicitly excludes `/api/` and `/ws/`, so these
+routes are gated. A same-origin `<audio src="/api/…">` sends the session cookie
+under `SameSite=Lax`.
+
+One caveat the frontend must handle: **a 401 surfaces to `<audio>` as a silent
+`error` event.** Without an explicit handler the user sees a dead player and no
+explanation — `AudioPreview.tsx` catches it and says so.
+
+---
+
+## 6. Frontend
+
+| Piece | File |
+|---|---|
+| `AudioRef` type + `isAudioRef` + player | [`components/output/AudioPreview.tsx`](../client/src/components/output/AudioPreview.tsx) |
+| Upload helper (`FormData`, cap pre-check) | [`lib/workspaceUpload.ts`](../client/src/lib/workspaceUpload.ts) |
+| Output routing | [`components/output/OutputPanel.tsx`](../client/src/components/output/OutputPanel.tsx) |
+| File parameter widget | [`components/ParameterRenderer.tsx`](../client/src/components/ParameterRenderer.tsx) `case 'file'` |
+
+Detection in the output panel is **structural** (`kind === 'audio'`) rather than
+purely hint-driven, so a ref arriving from anywhere still renders as a player
+instead of a wall of JSON metadata. `uiHints.outputMode: "audio"` exists as the
+declarative signal but is not required.
+
+Do not set `Content-Type` on the upload fetch — the browser must set it so the
+multipart boundary is generated.
+
+**Pre-existing hazard this replaces.** The file widget base64s into the
+parameters dict with *no size check anywhere*: not in the handler, not in
+`sendRequest`, not in the WS handler. `hasUnsavedChanges` also re-`JSON.stringify`s
+the whole buffer on every render. A ~1.5 MB clip becomes ~2 MB of base64 and
+dies at the Temporal threshold. The base64 path survives only as a fallback for
+a workflow that has never been saved and therefore has no workspace yet.
+
+---
+
+## 7. Extending to other media
+
+`AudioRef` is deliberately named for what it is rather than being a generic
+`MediaRef`, because the metadata that matters differs per kind (`duration` and
+`sample_rate` for audio; `width` / `height` for images). The transport layer
+underneath — containment, atomic write, the workspace routes, the limits — is
+already kind-agnostic.
+
+An `ImageRef` should be a sibling model in `refs.py` reusing the same
+`workspace.py` helpers, with `write_image` differing from `write_audio` only in
+subdirectory and probe.
+
+---
+
+## 8. Invariants (tests)
+
+| Invariant | Test |
+|---|---|
+| `AudioRef` has no bytes/base64 field; injecting one raises | `tests/media/test_audio_ref.py` |
+| Traversal, absolute-outside, and cross-workflow access all refused | `tests/media/test_audio_ref.py` |
+| `workspace_root` raises on a bare `workflow_id` rather than guessing | `tests/media/test_audio_ref.py` |
+| `inspect_audio` never raises, on any input | `tests/media/test_audio_ref.py` |
+| Route serves `text/html` and `image/svg+xml` as `attachment` | `tests/routers/test_workspace.py` |
+| Range request returns `206` with correct `Content-Range` | `tests/routers/test_workspace.py` |
+| Oversize upload is 413; traversal filename cannot escape `uploads/` | `tests/routers/test_workspace.py` |
+| A returned ref round-trips through the GET route | `tests/routers/test_workspace.py` |
diff --git a/docs-internal/native_llm_sdk.md b/docs-internal/native_llm_sdk.md
index 5bcf1b0e..346f083e 100644
--- a/docs-internal/native_llm_sdk.md
+++ b/docs-internal/native_llm_sdk.md
@@ -28,7 +28,11 @@ server/services/llm/
|-- protocol.py Message, ToolDef, ToolCall, Usage, LLMResponse, LLMProvider (Protocol)
|-- config.py ProviderConfig, PROVIDER_CONFIGS (built from llm_defaults.json)
|-- registry.py ProviderSpec + register_provider() — the live provider entry point;
-| sdk_exception_refs are lazy "module:Class" strings resolved at except time
+| sdk_exception_refs are lazy "module:Class" strings resolved at except time.
+| THIN SHIM since the speech work: the mechanism lives in
+| services/provider_registry.py (generic, shared). `_REGISTRY` survives here
+| as an alias bound to the SAME dict object the registry mutates, because
+| several tests swap provider factories in place through it.
|-- unifier.py ChatUnifier — the dispatch facade execute_chat delegates every provider to;
| translates typed SDK errors -> NodeUserError
|-- schema.py Provider-aware tool JSON-schema compilation
diff --git a/docs-internal/node-logic-flows/code_fs_process/javascriptExecutor.md b/docs-internal/node-logic-flows/code_fs_process/javascriptExecutor.md
index 115b36e9..cae426dc 100644
--- a/docs-internal/node-logic-flows/code_fs_process/javascriptExecutor.md
+++ b/docs-internal/node-logic-flows/code_fs_process/javascriptExecutor.md
@@ -4,7 +4,7 @@
|------|-------|
| **Category** | code_fs_process / code |
| **Backend handler** | [`server/nodes/code/javascript_executor/__init__.py::JavaScriptExecutorNode.execute_op`](../../../server/nodes/code/javascript_executor/__init__.py) (dispatched via `BaseNode.execute()` + `@Operation("execute")`; base in [`_base.py`](../../../server/nodes/code/_base.py)) |
-| **Node.js client** | [`server/nodes/code/_nodejs.py::get_nodejs_client`](../../../server/nodes/code/_nodejs.py) (singleton over [`server/services/nodejs_client.py::NodeJSClient`](../../../server/services/nodejs_client.py)) |
+| **Node.js client** | [`server/nodes/code/_nodejs.py::get_nodejs_client`](../../../server/nodes/code/_nodejs.py) (singleton over [`server/nodes/code/_client.py::NodeJSClient`](../../../server/nodes/code/_client.py) — plugin-owned since July 2026; `services/nodejs_client.py` no longer exists) |
| **Tests** | [`server/tests/nodes/test_code_fs_process.py`](../../../server/tests/nodes/test_code_fs_process.py) |
| **Skill (if any)** | [`server/skills/coding_agent/javascript-skill/SKILL.md`](../../../server/skills/coding_agent/javascript-skill/SKILL.md) |
| **Dual-purpose tool** | yes - tool name `javascript_code` |
diff --git a/docs-internal/node-logic-flows/code_fs_process/typescriptExecutor.md b/docs-internal/node-logic-flows/code_fs_process/typescriptExecutor.md
index bb3c77e3..e86cf947 100644
--- a/docs-internal/node-logic-flows/code_fs_process/typescriptExecutor.md
+++ b/docs-internal/node-logic-flows/code_fs_process/typescriptExecutor.md
@@ -4,7 +4,7 @@
|------|-------|
| **Category** | code_fs_process / code |
| **Backend handler** | [`server/nodes/code/typescript_executor/__init__.py::TypeScriptExecutorNode.execute_op`](../../../server/nodes/code/typescript_executor/__init__.py) (dispatched via `BaseNode.execute()` + `@Operation("execute")`; base in [`_base.py`](../../../server/nodes/code/_base.py)) |
-| **Node.js client** | [`server/nodes/code/_nodejs.py::get_nodejs_client`](../../../server/nodes/code/_nodejs.py) (singleton over [`server/services/nodejs_client.py::NodeJSClient`](../../../server/services/nodejs_client.py)) |
+| **Node.js client** | [`server/nodes/code/_nodejs.py::get_nodejs_client`](../../../server/nodes/code/_nodejs.py) (singleton over [`server/nodes/code/_client.py::NodeJSClient`](../../../server/nodes/code/_client.py) — plugin-owned since July 2026; `services/nodejs_client.py` no longer exists) |
| **Tests** | [`server/tests/nodes/test_code_fs_process.py`](../../../server/tests/nodes/test_code_fs_process.py) |
| **Skill (if any)** | - (shared with `javascript-skill`) |
| **Dual-purpose tool** | yes - tool name `typescript_code` |
diff --git a/docs-internal/node_creation.md b/docs-internal/node_creation.md
index e317aebe..adee801a 100644
--- a/docs-internal/node_creation.md
+++ b/docs-internal/node_creation.md
@@ -17,6 +17,7 @@ this file picks the right entry point based on what you're adding.
| A node that wraps a CLI tool, supervises a daemon, or receives signed webhooks | [Wave 12 event framework](./plugin_system.md#wave-12--generalized-event-framework-servicesevents) (this section is the most important one) | self-contained folder under `server/nodes/<group>/` using `services.events` base classes |
| A polling-based trigger node | [Wave 12 event framework](./plugin_system.md#wave-12--generalized-event-framework-servicesevents) — subclass `PollingEventSource` | new file or folder; framework owns the loop |
| A long-lived service plugin (bot connection, WebSocket bridge, SDK session) | [Self-contained plugin folders (Wave 11.H)](./plugin_system.md#self-contained-plugin-folders) — telegram is the reference | folder with `_credentials.py` / `_service.py` / `_handlers.py` / `_filters.py` / `_refresh.py` |
+| **A node that must speak to several interchangeable vendors** (one canvas node, a `provider` dropdown) | [Speech Provider RFC](./speech_provider_rfc.md) + [`server/nodes/speech/`](../server/nodes/speech/) — the reference; and [Multi-credential nodes](./plugin_system.md#multi-credential-nodes) for the `ctx.connection(id)` contract | folder with `_protocol.py` / `_registry.py` / `_config.py` / `_unifier.py` / `_providers/`, a JSON capability file under `server/config/`, and a `credentials = (A, B, C)` tuple |
| A plugin whose auth is owned by an external CLI (`stripe login`, `vercel login`, `gh auth login`, `gcloud auth login`) | [Stripe Service](./stripe_service.md) — the reference for "marker-token + generic catalogue invalidation" — and [plugin_system.md → CLI-managed auth pattern](./plugin_system.md#cli-managed-auth-pattern); [Vercel Service](./vercel_service.md) for the **device-flow** variant (single blocking `login` process, no two-step complete flag) | self-contained folder + `_install.py` for the auto-downloader; `_handlers.py` calls `auth_service.store_oauth_tokens(provider, "cli-managed", "cli-managed")` after the CLI login completes, then broadcasts the existing generic `credential_catalogue_updated` event |
## The four node kinds
@@ -249,6 +250,8 @@ What you **do** still write:
| Memory lifecycle (markdown parse/append/trim, vector store, session resume) | [memory_lifecycle.md](./memory_lifecycle.md) |
| Tool building pipeline (`_build_tool_from_node`, schema, per-type Temporal dispatch) | [tool_building_pipeline.md](./tool_building_pipeline.md) |
| Process supervision (used by `DaemonEventSource`) | [server/services/process_service.py](../server/services/process_service.py) — singleton API |
+| Multi-vendor node behind one `provider` dropdown (two registries, JSON capabilities, per-vendor modules) | [speech_provider_rfc.md](./speech_provider_rfc.md) |
+| Returning media from a node without blowing the payload limits (`AudioRef`, workspace routes, containment) | [media_transport.md](./media_transport.md) |
## Wave summary (current state)
diff --git a/docs-internal/performance.md b/docs-internal/performance.md
index 223e0f07..ffbaed97 100644
--- a/docs-internal/performance.md
+++ b/docs-internal/performance.md
@@ -229,7 +229,7 @@ formula bound check across 100 × MAX_ATTEMPTS draws.
These were observed and fixed; the lessons are durable.
- **Eager `from langchain_openai import ChatOpenAI` at module top.** Cost ~21 s cold on Windows because it transitively pulls openai SDK + tiktoken + httpx wrappers. With `from __future__ import annotations` already in place, all type hints become strings; no eager import was structurally required. Lazy via per-function local imports + a small `BaseMessage`-only eager hold-out.
-- **Eager SDK import at LLM provider registration, just to reference typed exception classes.** The `services/llm/providers/*` registration blocks did `import anthropic` / `import openai` / `from google.genai import errors` at module bottom solely to populate `ProviderSpec.sdk_exception_types` — re-creating the anti-pattern above through the raw SDKs (~7.6 s warm / ~45 s cold for the AIService import vs the 703 ms baseline; google.genai alone was ~4 s warm / ~15 s cold). Fixed with lazy `"module:ClassName"` refs (`ProviderSpec.sdk_exception_refs`) resolved via `pkgutil.resolve_name` at except/read time — by then the provider factory has already imported the SDK, so resolution is a `sys.modules` cache hit. Locked by [server/tests/llm/test_lazy_sdk_imports.py](../server/tests/llm/test_lazy_sdk_imports.py) (subprocess purity probe). When adding a provider: pass a string ref, never import the SDK at module level.
+- **Eager SDK import at LLM provider registration, just to reference typed exception classes.** The `services/llm/providers/*` registration blocks did `import anthropic` / `import openai` / `from google.genai import errors` at module bottom solely to populate `ProviderSpec.sdk_exception_types` — re-creating the anti-pattern above through the raw SDKs (~7.6 s warm / ~45 s cold for the AIService import vs the 703 ms baseline; google.genai alone was ~4 s warm / ~15 s cold). Fixed with lazy `"module:ClassName"` refs (`ProviderSpec.sdk_exception_refs`) resolved via `pkgutil.resolve_name` at except/read time — by then the provider factory has already imported the SDK, so resolution is a `sys.modules` cache hit. Locked by [server/tests/llm/test_lazy_sdk_imports.py](../server/tests/llm/test_lazy_sdk_imports.py) (subprocess purity probe). When adding a provider: pass a string ref, never import the SDK at module level. **The guard is per-provider-layer, and every new one needs its own copy** — the probe runs in a clean interpreter because the pytest process already has SDKs loaded by other tests, so an in-process assertion would pass vacuously. `nodes/speech/` ships its equivalent in [tests/nodes/test_speech.py](../server/tests/nodes/test_speech.py) (`TestLazySdkImports`), asserting that importing the whole speech plugin leaves `openai` / `anthropic` / `google.genai` out of `sys.modules`.
- **Unconditional `client/node_modules/.vite` wipe on every `company dev`.** Forced a full esbuild dependency re-optimization (1-2 minutes on Windows) on every first page load. Vite self-invalidates the dep cache via lockfile/config/NODE_ENV hashes in `.vite/deps/_metadata.json`; the wipe was pure waste on a stable lockfile. Replaced with `company dev --force` → `VITE_FORCE=1` → `optimizeDeps.force` (Vite's own re-bundle mechanism), plus `optimizeDeps.include` for the heavy lazily-reached deps so late discovery can't trigger the mid-session re-optimization behind the "Outdated Optimize Dep" 504 (vitejs/vite#14284).
- **Synchronous temporalio `Worker()` construction on the event loop.** The constructor derives a default build id by MD5-hashing the bytecode of every module in `sys.modules` (disk reads included) — ~3.1 s at our module count, freezing the loop and inflating concurrent boot work (`broadcaster.refresh_whatsapp` measured 4.2 s vs its ~0.4 s siblings). The value is memoized SDK-globally, so `TemporalWorkerManager.start()` pre-warms it once via `asyncio.to_thread(load_default_build_id)` before constructing the manager worker; all pool workers then construct cheaply. Any new long synchronous call in an async startup path should get the same `to_thread` treatment.
- **Recursive `setTimeout` retry chain in `useEffect` without `AbortController`.** Survived unmount, leaked timers, called `setState` on stale closures. The React docs explicitly flag this in [https://react.dev/reference/react/useEffect](https://react.dev/reference/react/useEffect). Replaced with TanStack Query's `signal`-aware `queryFn`.
diff --git a/docs-internal/plugin_system.md b/docs-internal/plugin_system.md
index cd126e6f..f5fb8f88 100644
--- a/docs-internal/plugin_system.md
+++ b/docs-internal/plugin_system.md
@@ -72,10 +72,10 @@ class SpecializedAgentBase(ActionNode, abstract=True):
| `handles` | React Flow handle topology (`input-main`, `output-main`, …). |
| `ui_hints` | Dict of panel flags (`hasCodeEditor`, `isMemoryPanel`, `isMasterSkillEditor`, `isToolPanel`, `hasSkills`, `isConfigNode`, `outputMode: "terminal"` for CLI-wrapper nodes whose textual output must render preformatted, …). See "Auto-derived uiHints" below — `isConfigNode` is set automatically for `('memory', 'tool')` group plugins. Live flag list = the `known` set in `test_node_spec.py`. |
| `annotations` | Pipedream-style: `destructive` / `readonly` / `open_world`. |
-| `credentials` | Tuple of `Credential` subclasses the node uses. |
+| `credentials` | Sequence of `Credential` subclasses the node uses. More than one is supported — see [Multi-credential nodes](#multi-credential-nodes). |
| `Params` | Pydantic `BaseModel` — user-facing parameters. Used for both UI rendering and AI tool schemas. |
| `Output` | Pydantic `BaseModel` — runtime output shape. |
-| `usable_as_tool` | `ActionNode` flag — mints a ToolNode adapter for AI invocation. Combined with `component_kind != "model"`, makes the plugin visible to `agentBuilder.add_tool` (catalogue + rebind paths). |
+| `usable_as_tool` | `ActionNode` flag — mints a ToolNode adapter for AI invocation. Combined with `component_kind != "model"`, makes the plugin visible to `agentBuilder.add_tool` (catalogue + rebind paths). **Side effect:** setting it auto-sets `hide_input_handle` / `hide_output_handle` to `True` unless the class declares them ([base.py:215](../server/services/plugin/base.py#L215)), so a dual-purpose node that must remain wirable on the canvas has to declare both `False` explicitly. |
| `needs_canvas` | `ClassVar[bool]` — when `True`, the F4.B `AgentWorkflow` tool-dispatch forwards the parent workflow's `nodes`/`edges` into the per-tool activity payload. Today only `AgentBuilderNode` opts in (walks edges to resolve its calling agent). |
| `task_queue` | Temporal worker pool. See `TaskQueue` constants. |
| `retry_policy` | `RetryPolicy` dataclass (mirrors `temporalio.common.RetryPolicy`). |
@@ -263,6 +263,43 @@ If you find yourself declaring an `api_key: str = Field(...)` on a
Params class, stop: add an `ApiKeyCredential` subclass instead and wire
it via the `credentials = (...)` tuple on the node class.
+#### Multi-credential nodes
+
+`credentials` is a *sequence*, and `ctx.connection(id)` is a lookup over it
+— so a node that talks to several vendors declares them all and selects at
+runtime from a parameter:
+
+```python
+credentials = (OpenAICredential, ElevenLabsCredential, SarvamCredential)
+
+@Operation("synthesize")
+async def synthesize(self, ctx, params):
+ async with ctx.connection(credential_id_for(params.provider)) as conn:
+ ...
+```
+
+`_make_connection_factory` ([base.py](../server/services/plugin/base.py))
+precomputes an `{id: class}` dict; an id the node never declared raises
+`RuntimeError` synchronously, before any HTTP. A declared credential with no
+stored key fails later, at `conn.credentials()`, as an annotated
+`PermissionError` — which `BaseNode.execute` turns into a credential envelope
+plus a CloudEvents broadcast, so the Credentials modal lights up the right
+provider.
+
+**A multi-credential node MUST use imperative operations.** The declarative
+`routing=` path resolves `self.credentials[0]`
+([base.py:571](../server/services/plugin/base.py#L571)), so a routed op would
+authenticate every provider with the first key in the tuple regardless of what
+the user picked. `test_plugin_contract.py` only asserts the tuple is non-empty,
+so nothing else catches it. `nodes/speech/` has a test asserting neither of its
+nodes declares `routing=`.
+
+Reference implementation: [`nodes/speech/`](../server/nodes/speech/) — the
+first multi-credential plugin in the repo. Its `_config.credential_id(provider)`
+reads the id from JSON, keeping the mapping declarative, and cross-plugin
+credential imports (`from ..model._credentials import OpenAICredential`) are
+idiomatic — `nodes/sarvam/` already does the same.
+
### Operations (`@Operation`)
A multi-op node declares multiple methods, each decorated with
diff --git a/docs-internal/speech_provider_rfc.md b/docs-internal/speech_provider_rfc.md
index 4f32aa0d..7514a338 100644
--- a/docs-internal/speech_provider_rfc.md
+++ b/docs-internal/speech_provider_rfc.md
@@ -1,6 +1,6 @@
# RFC: Multi-provider Speech (TTS / STT)
-**Status:** accepted, implementation in progress
+**Status:** implemented (commit `a29cdb7e`)
**Date:** 2026-07-25
**Supersedes:** the vendor-locked `sarvamTextToSpeech` / `sarvamSpeechToText` nodes
@@ -325,3 +325,48 @@ come back null here.
latency**, not audio duration. The claim was wrong and the billing with it.
- Sarvam's own docs contradict themselves on `speech_sample_rate` (schema `22050`, prose `24000`).
The configured default is `24000`, matching the prose and the previous implementation.
+
+---
+
+## 8. What this pattern should absorb next
+
+Speech was the first capability to get a provider abstraction, not the only one
+that needs it. The same vendor-locked shape it replaced is still present
+elsewhere, and the argument against it is identical: a second vendor means a
+second node, a third means a third, and the user has to rewire the canvas to
+switch.
+
+**Outstanding, in the same palette group:**
+
+| Node | Capability | Other vendors that serve it |
+|---|---|---|
+| `sarvamTranslate` | text translation | Google Translate, DeepL, Azure Translator, any LLM |
+| `sarvamTransliterate` | script transliteration | Google, Azure, ICU/`uroman` locally |
+| `sarvamDetectLanguage` | language identification | Google, Azure, `lingua`/`fasttext` locally, any LLM |
+
+A `nodes/translate/` plugin would be a near-mechanical port of `nodes/speech/`:
+`_protocol.py` (one `TranslateProvider` Protocol — this capability is
+unidirectional, so **one** registry, not two), `_config.py` over a
+`translate_defaults.json`, `_unifier.py`, `_providers/`, and a
+`credentials = (...)` tuple. No new framework, and none of the media transport
+applies — translation returns text, so `AudioRef` and the workspace routes are
+not involved.
+
+Two things make it *easier* than speech was:
+
+- **No binary transport.** The whole `services/media` half of this RFC is moot.
+- **Language-detection and transliteration are the same provider surface** as
+ translation for most vendors, so one `_providers/<vendor>.py` typically serves
+ all three nodes.
+
+One thing makes it *harder*: several plausible providers are LLMs rather than
+dedicated translation APIs, so the provider module would call `ChatUnifier`
+rather than raw httpx. That is a supported shape — the Protocol does not care
+what a provider does internally — but it means the `credential_id` for those
+entries points at an existing LLM credential and the billing unit is tokens,
+not characters.
+
+**Not started, and deliberately not scoped here.** Recorded so the
+inconsistency is visible rather than discovered later: `nodes/sarvam/` is now
+the only folder in the repo where a vendor name appears in a node `type` for a
+capability several vendors serve.
diff --git a/server/nodes/README.md b/server/nodes/README.md
index 21b3b8d5..733be911 100644
--- a/server/nodes/README.md
+++ b/server/nodes/README.md
@@ -132,9 +132,12 @@ vercel/ — Vercel (CLI deploy / inspect / list / custom passthrough)
github/ — GitHub (gh CLI: clone / PRs / issues / custom; palette group "vcs")
cloudflare/ — Cloudflare (cf CLI: zones / DNS / GraphQL analytics / custom; palette group "deployment")
gcloud/ — Google Cloud (gcloud CLI: projects / Compute Engine / Cloud Run / Cloud Storage / custom; palette group "deployment")
-sarvam/ — Sarvam AI text + speech REST APIs (translate / transliterate / detect_language /
- speech_to_text / text_to_speech; palette group "language"). Its chat models are a
- separate plugin at model/sarvam_chat_model/ and share one SarvamCredential.
+sarvam/ — Sarvam AI text REST APIs (translate / transliterate / detect_language; palette
+ group "language"). Its chat models are a separate plugin at model/sarvam_chat_model/
+ and share one SarvamCredential; its SPEECH endpoints are a provider inside speech/.
+speech/ — Provider-abstracted text_to_speech / speech_to_text (palette group "language").
+ One node per direction with a `provider` dropdown, not one node per vendor. Owns
+ its own protocol / registries / dispatch / per-vendor modules — see below.
```
---
@@ -260,6 +263,52 @@ server/nodes/telegram/
└── telegram_receive.py # TriggerNode
```
+### Variant: one node, many vendors
+
+Telegram owns *one* vendor's surface. The other shape is a node that must
+speak to *several* vendors interchangeably — one canvas node whose
+`provider` parameter picks the backend. **Reference:
+`server/nodes/speech/`.**
+
+```
+server/nodes/speech/
+├── __init__.py # register_output_schema + register_option_loader (zero logic)
+├── _protocol.py # vendor-neutral requests / results / errors + two Protocols
+├── _registry.py # ONE REGISTRY PER DIRECTION, over services/provider_registry
+├── _config.py # reads server/config/speech_defaults.json
+├── _unifier.py # dispatch + typed-error -> NodeUserError, one catch site
+├── _providers/ # _http.py + one module per vendor, each self-registering
+├── _credentials.py # only the vendors no other plugin already declares
+├── _base.py # shared node helpers (credential resolve, input read, billing)
+├── _option_loaders.py # provider-aware dropdown loaders
+├── text_to_speech.py # the two nodes
+└── speech_to_text.py
+```
+
+Four ideas worth stealing wholesale:
+
+1. **Registry membership is the capability.** Two registries, one per
+ direction, and the node's provider enum *is* `tts_providers()`. A
+ synthesis-only vendor never appears in the transcription dropdown, and
+ there is no `supports_x` flag to fall out of sync with reality.
+2. **Capabilities are JSON, not Python.** `speech_defaults.json` holds
+ per-provider and per-model values (`{"whisper-1": [...], "_default": [...]}`),
+ resolved exact → longest-prefix → `_default`. Boolean flags default
+ **permissive**, so forgetting to declare one never silently disables a
+ working feature. No shared code branches on a vendor name — the ban
+ `test_plugin_shape` implies is satisfied structurally.
+3. **Vendor divergence lives in the vendor module.** Auth scheme, whether
+ options ride the query string or the body, and how the response is
+ shaped are all per-vendor facts. Keep them behind the neutral request /
+ result types and central code stays vendor-blind.
+4. **Reuse credentials, don't redeclare them.** `_credentials.py` holds only
+ the vendors nothing else owns; the rest are imported
+ (`from ..model._credentials import OpenAICredential`). Two classes with
+ the same `id` collide in `CREDENTIAL_REGISTRY` at import time.
+
+See [Multi-credential nodes](../../docs-internal/plugin_system.md#multi-credential-nodes)
+for the `ctx.connection(id)` contract and the `routing=` trap that comes with it.
+
### Six generic registries to plug into
Telegram's `__init__.py` is the canonical wiring example. Adding any
@@ -373,6 +422,48 @@ Full reference: [docs-internal/plugin_system.md → "Self-contained plugin folde
Pydantic models or `Union`, the LLM-schema emission will add `$defs`
and fail the invariant. Keep tool-facing Params flat; move nested
types to `Output` instead.
+- **Never name a Params field `model` or `api_key` on a node that also has
+ a `provider` field.** An effect in
+ [`ParameterRenderer.tsx:866`](../../client/src/components/ParameterRenderer.tsx#L866)
+ keys on those two literal names: when a sibling `provider` field is
+ present it overwrites `model` with the *chat-model* list and clears
+ `api_key`. It never checks that the provider is an LLM provider, so
+ `provider: "elevenlabs"` still triggers it and the field is wiped the
+ moment the user picks a vendor. Prefix instead — `tts_model`,
+ `stt_model`. Other reserved sibling names with name-based magic in that
+ file: `parameters`, `message_type`, `group_id`, `group_name`,
+ `channel_jid`, `sender_number`, `sender_name`, `session_id`,
+ `service_id`, `action`.
+- **The parameter panel stores `""` for every cleared field, whatever the
+ declared type.** Harmless against `str`; a hard validation error against
+ `Optional[float]`, `bool` or `Dict[str, Any]` — a freshly-dropped node fails
+ on its own defaults with `Invalid parameters: Input should be a valid
+ dictionary`. Add a `@model_validator(mode="before")` that drops blank
+ strings for fields that cannot hold one, and coerce object fields from a
+ JSON string (the panel has no object widget, so a dict parameter arrives as
+ typed text). Reusable form: `coerce_blank_params` in
+ [`nodes/speech/_base.py`](./speech/_base.py); per-node precedents:
+ `AndroidServiceParams._coerce_parameters`, `WriteTodosParams._coerce_todos`.
+ Do **not** blanket-drop blanks for `str` fields — that turns a `min_length`
+ error into a confusing "field required".
+- **`usable_as_tool = True` hides both canvas handles.** It auto-sets
+ `hide_input_handle` / `hide_output_handle` unless the class declares
+ them, so a dual-purpose node meant to stay wirable must set both to
+ `False` explicitly. Symptom: the node runs fine as a tool but cannot be
+ connected to anything on the canvas.
+- **Never accept a file path and join it onto the workspace yourself.**
+ Use `services.media.coerce_file_param` / `read_media_bytes`. A node that
+ did the naive join let `audio_file="../../credentials.db"` read the
+ encrypted credential store and upload it to a third party. Those helpers
+ reject `..` / `~` / drive prefixes *and* re-check containment after
+ resolution, so a symlink or Windows junction cannot redirect the result.
+- **Never return media bytes (or base64) from a node.** Write the file into
+ the workspace with `services.media.write_audio` and return the `AudioRef`.
+ A node result is persisted 3×, broadcast twice, retained in the status
+ cache, copied into every downstream activity input, and — if the node is
+ `usable_as_tool` — serialized into an LLM message. See
+ [`services/media/limits.py`](./../services/media/limits.py) for the
+ measured Temporal thresholds this exists to stay under.
- **Return plain data, never raw backend or third-party objects.** Backend /
SDK result objects (native filesystem `ReadResult`, httpx
responses, …) must be unwrapped to plain fields before returning —