Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
Hutch/feat calls transcription (#2346)
Will Hutchinson6ca0705ad614
diff --git a/.env-local.enc b/.env-local.encindex c379321408..fddc579f89 100644--- a/.env-local.enc+++ b/.env-local.enc@@ -124,6 +124,7 @@ STRIPE_PRICE_ID_OPUS=ENC[AES256_GCM,data:EWmSRm5ncUnZSfPX+TB6Q+Er9wfMpQFJTLtpwzcLIVEKIT_SERVER_URL=ENC[AES256_GCM,data:w4SAApcyzwRtST6WGnzJTfFdX0Dp8pthvtH6Mymz2t/nhLZbLGrIIA==,iv:HHvLpOjtoC1Iw5DgXYidN+PAgzvdVY1PACgUPKrJUzE=,tag:p2YAF/sxxfFbpCJ4xtSGSw==,type:str]LIVEKIT_API_KEY=ENC[AES256_GCM,data:qhLZaV4ww9UxE03tj91qx2Y=,iv:QJVCtekxlAe0fZLHIflnodnOmv45wpLzSBcNj5CtCOo=,tag:LlZ6f5STiC8ArQPLRMEsWw==,type:str]LIVEKIT_API_SECRET=ENC[AES256_GCM,data:GLdp8wpK4kpbGPmR5aaWzZ4ns8jzTkRuFfroG8PUeG8ChFJONtoCFx1VjlxUfQ==,iv:YcaFnOZG8lA9kMxM8C4WD+DXqHRhprburLqIzDWI7Zc=,tag:Ro55kVfVytCWdfCT/GERCA==,type:str]+LIVEKIT_TRANSCRIPTION_AGENT_NAME=ENC[AES256_GCM,data:RgXJ+WNruFiyg1Pjjzo++SDOLg==,iv:r7XZRhIJg+4qiEBBG6Pbvj+maiUh/jrO5lnwNkUXgxM=,tag:yVVoGBzz1Bl0lY1KqH4G3Q==,type:str]sops_age__list_0__map_enc=-----BEGIN AGE ENCRYPTED FILE-----\nYWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IHBpdi1wMjU2IEUzMVUyZyBBM1lmcDc3\nUENpRVorSGVGa3R2NFlrdkx1Mm43aEcyR1ZtbEswL2RnWHlqMwpVMnY4ck5makNC\nZzVZc3JrZ3NKV2x3RTY0TFovRXJtVzEyeFZOZWRheHBNCi0tLSBobjhCbHpJa25s\nZDhyQjhCaEYrOWNiWHZkRWpnRlkwTnNEbjMwYzdxcTUwCqxxxmXy3mFUAbAy29y8\n2DFYDATdVvmplHpDTvgrNyY+lAL/3Jp9vtIs5DGXW/r73Nv3AhISmuCid18qhpAY\nUqE=\n-----END AGE ENCRYPTED FILE-----\nsops_age__list_0__map_recipient=age1yubikey1qw64ag5lzvn9ekrflu5ruj4a6ucycscl6ctk39fjzf76jptsay39z442pxvsops_kms__list_0__map_arn=arn:aws:kms:us-east-1:569036502058:key/mrk-cab29bf948044eb79005a81f48d40e93@@ -134,7 +135,7 @@ sops_kms__list_1__map_arn=arn:aws:kms:us-west-1:569036502058:key/mrk-cab29bf9480sops_kms__list_1__map_aws_profile=sops_kms__list_1__map_created_at=2026-03-03T19:32:07Zsops_kms__list_1__map_enc=AQICAHjuYcSMsjB0lKJtZ3DIAvxF8N3RNRn5KZaAN74Et6122wFUqf7u/HEfCUGv7j69Mb6YAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMpcJQR1XeIAFFE7ebAgEQgDvYRYIWelwN8TuwA+6fZVaB34yKo9EQ5xPLr/3BU+ro1Mn2eBPCg3q8ie2LuE/3voim1X35P/cdtDqTZg==-sops_lastmodified=2026-04-01T17:58:53Z-sops_mac=ENC[AES256_GCM,data:bmKaEjJ+Aq8XQ7mdNqk0W6AbLOvALLHgOd/RU06GEooAoH3EHJzGW1qPsVywXkQ6+PaaZyuKMIM40HkDPf9ZcW8kbp/s7SkYH1+RDd97sevxu/JpG+fDDmWOHf/khGq7rjEUHCkD/hOXiWUdNQsStcMApafxRA/Xk6EDES/O/fA=,iv:AG+HFzzQv5Ex1TsdjQMCJ1CzZSypSmHHdnOgPKNZK2U=,tag:4B8ogEduTaJvkWaghtogWA==,type:str]+sops_lastmodified=2026-04-01T20:17:51Z+sops_mac=ENC[AES256_GCM,data:GK+wXonn+pnGyNyZQlDGzC02E2EydPTr9oN7oRXz6B4p1l/rhoAhWtymyOyXV7I120oqIYPEjrEtf941/+5IjH0uRq8n4rye2b5CF2RVUnVwkCcZLAfm1Psx/rvoMrt39Fmd1Fqicpe64ve4bGhNuGQp/omZ4+iLtgO6ZGT9Loc=,iv:VNhTK6b+kAVZrKOLs7wuX/MUnaz4ZBCj8deVo8AI2eE=,tag:uPhDbPHBcevvfnLxp9AxiA==,type:str]sops_unencrypted_suffix=_unencryptedsops_version=3.12.1diff --git a/.env-localdev.enc b/.env-localdev.encindex 45ec06a917..8ab1b06cbc 100644--- a/.env-localdev.enc+++ b/.env-localdev.enc@@ -130,6 +130,7 @@ STRIPE_PRICE_ID_OPUS=ENC[AES256_GCM,data:fgVL97kmyo7kTrG6UjvFr/2gbgAFSpV+hnpy3jkLIVEKIT_SERVER_URL=ENC[AES256_GCM,data:aBbXYtf18XRTfQX500l5Mej8FPxqDmH+Lp9W6LdGzI7NgX1kzfZSoA==,iv:IIpmcZ6BXUVl4w51XqpTa7BLvNeEooR16UPxrKW0My8=,tag:JQvnwl+ccDbQxTC1ghJ+Jw==,type:str]LIVEKIT_API_KEY=ENC[AES256_GCM,data:aKkhucWrN/FNaYmbloWdxm0=,iv:RmykULpzwZ9lftkF2wrcAzekMIk9+YWc9AZsZhKiYx0=,tag:f245xdM6FmWDioEV/Lv9Nw==,type:str]LIVEKIT_API_SECRET=ENC[AES256_GCM,data:VrLzVGpQG7ML+TZcopCsEkyj/mXiTm+9BsqWE3nGdIozRf6PIyUwHlyErGoFCQ==,iv:na9JIyCdt94SFnPLh9l+33c8lZRW+uR8WYw+Ju8zdYw=,tag:cLL0wJz4jzpAIRysbt4tSQ==,type:str]+LIVEKIT_TRANSCRIPTION_AGENT_NAME=ENC[AES256_GCM,data:kPe4llQDxy8gkYjNH6bIe3W6Sg==,iv:8j7ryXT1MTiSoGz14jifVSH/FYlHRRY1DwCqdIqwenw=,tag:3GCNvV7rL2uIKj2sPw0LxQ==,type:str]sops_age__list_0__map_enc=-----BEGIN AGE ENCRYPTED FILE-----\nYWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IHBpdi1wMjU2IEUzMVUyZyBBNDlKWUVt\nbUpscDEzSE9IZTNvdkd6VUFpWWhQM1ZWcndzL0srVXE4SW5GUQpHR2xNR3lIUnBV\nY3BqbmRadVVPMUdkeUluR0RycDJsWWt1V2Z0T1hqbG1JCi0tLSA5cVZQSGtNNmgr\nVXdyWGZsLzg2N0lyakxuVDZuNEFDUlUrNXJIMHE3UmRRClCd0JD9Q51ZLVKv73Px\nebG4SM/4o73tU3IHJu4tyQUrFM+we+JEDvsYKHBuUgTGC+2yQRPmHV+HObTqqRnu\nzGg=\n-----END AGE ENCRYPTED FILE-----\nsops_age__list_0__map_recipient=age1yubikey1qw64ag5lzvn9ekrflu5ruj4a6ucycscl6ctk39fjzf76jptsay39z442pxvsops_kms__list_0__map_arn=arn:aws:kms:us-east-1:569036502058:key/mrk-cab29bf948044eb79005a81f48d40e93@@ -140,7 +141,7 @@ sops_kms__list_1__map_arn=arn:aws:kms:us-west-1:569036502058:key/mrk-cab29bf9480sops_kms__list_1__map_aws_profile=sops_kms__list_1__map_created_at=2026-03-03T19:32:17Zsops_kms__list_1__map_enc=AQICAHjuYcSMsjB0lKJtZ3DIAvxF8N3RNRn5KZaAN74Et6122wHtcTS4UVhM79Eansn1/OmrAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMRrFwSp99ZM2mPtJzAgEQgDvsIaiNifNz0/18C9OH77AG/LQLpmDiXiJYV46yLDv9vdyPL3PaLMvkAqgL3Xb2F4RcZOIUxkTS3u92xQ==-sops_lastmodified=2026-04-01T17:58:57Z-sops_mac=ENC[AES256_GCM,data:1dqNviaaNLsw6pTZx/yCBqBKVobf5/tjkTang8lp3HyycvKxwh3cHyGVIIap/+N9QLhDfF5TzfKjlZLqGq/Qt87pD6lWbSnhxLXGTiDrIRpD8gPxmhmMkV6PdQK/PxdPnVaQgxKK7Q+DuX6UE+k4SXeuVxpg/18c1Pw+oAKyFJ8=,iv:+iz30VKRImCveqKlV7QHqJ32vsRW9UPtPr1B69+d4ZE=,tag:AqSEj7atSbCfs1cbiD47vA==,type:str]+sops_lastmodified=2026-04-01T20:17:46Z+sops_mac=ENC[AES256_GCM,data:cVMAjc/owLjIwnnPqq/8GK/ziFKL0gqAsE4a0t/JZZRhQ9z/liSn17UKMdBuw1QVdUuQb3wlolz123bnggxKuM0m1MIfLfgeqcvRfkc4py6czR5pCLu2TrOc4/UvgwRW3QGeNVjisz03EGFAorGgK7MxOra8U6B+wUWonGKcrjU=,iv:JkaUPaf35o/NSHujB+uOsQ8bg6EOvulb+mHRmynf+jA=,tag:Na004I9bo0NA3k2t9fO3yw==,type:str]sops_unencrypted_suffix=_unencryptedsops_version=3.12.1diff --git a/agents/transcription/.dockerignore b/agents/transcription/.dockerignorenew file mode 100644index 0000000000..27fb03dd6f--- /dev/null+++ b/agents/transcription/.dockerignore@@ -0,0 +1,73 @@+# Project tests+test/+tests/+eval/+evals/++# Python bytecode and artifacts+__pycache__/+*.py[cod]+*.pyo+*.pyd+*.egg-info/+dist/+build/++# Virtual environments+.venv/+venv/++# Caches and test output+.cache/+.pytest_cache/+.ruff_cache/+coverage/++# Logs and temp files+*.log+*.gz+*.tgz+.tmp+.cache++# Environment variables+.env+.env.*++# VCS, editor, OS+.git+.gitignore+.gitattributes+.github/+.idea/+.vscode/+.DS_Store++# Project docs and misc+README.md+CONTRIBUTING.md+LICENSE++# Coding agent files+.claude/+.codex/+.cursor/+.windsurf/+.gemini/+.cline/+.clinerules+.clinerules/+.aider*+.cursorrules+.cursorignore+.cursorindexingignore+.clineignore+.codeiumignore+.geminiignore+.windsurfrules+CLAUDE.md+AGENTS.md+GEMINI.md+.github/copilot-instructions.md+.github/personal-instructions.md+.github/instructions/diff --git a/agents/transcription/.gitignore b/agents/transcription/.gitignorenew file mode 100644index 0000000000..c59566dec4--- /dev/null+++ b/agents/transcription/.gitignore@@ -0,0 +1 @@+livekit.tomldiff --git a/agents/transcription/Dockerfile b/agents/transcription/Dockerfilenew file mode 100644index 0000000000..cffec2e7e6--- /dev/null+++ b/agents/transcription/Dockerfile@@ -0,0 +1,85 @@+# This is an example Dockerfile that builds a minimal container for running LK Agents+# For more information on the build process, see https://docs.livekit.io/agents/ops/deployment/builds/+# syntax=docker/dockerfile:1++# Use the official Python base image with Python 3.13+# We use the slim variant to keep the image size smaller while still having essential tools+ARG PYTHON_VERSION=3.13+FROM python:${PYTHON_VERSION}-slim AS base++# Keeps Python from buffering stdout and stderr to avoid situations where+# the application crashes without emitting any logs due to buffering.+ENV PYTHONUNBUFFERED=1++# Disable pip version check to speed up builds+ENV PIP_DISABLE_PIP_VERSION_CHECK=1++# --- Build stage ---+# Install dependencies, build native extensions, and prepare the application+FROM base AS build++# Install build dependencies required for Python packages with native extensions+# gcc: C compiler needed for building Python packages with C extensions+# g++: C++ compiler needed for building Python packages with C++ extensions+# python3-dev: Python development headers needed for compilation+# We clean up the apt cache after installation to keep the image size down+RUN apt-get update && apt-get install -y \+ gcc \+ g++ \+ python3-dev \+ && rm -rf /var/lib/apt/lists/*++# Create a new directory for our application code+# And set it as the working directory+WORKDIR /app++# Copy just the dependency files first, for more efficient layer caching+COPY requirements.txt ./++# Create a virtual environment and install Python dependencies+# The venv keeps dependencies in /app so they can be copied to the production stage+RUN python -m venv .venv+ENV PATH="/app/.venv/bin:$PATH"+RUN pip install --no-cache-dir -r requirements.txt++# Copy all remaining application files into the container+# This includes source code, configuration files, and dependency specifications+# (Excludes files specified in .dockerignore)+COPY . .++# Pre-download any ML models or files the agent needs+# This ensures the container is ready to run immediately without downloading+# dependencies at runtime, which improves startup time and reliability+RUN python "transcriber.py" download-files++# --- Production stage ---+# Build tools (gcc, g++, python3-dev) are not included in the final image+FROM base++# Create a non-privileged user that the app will run under.+# See https://docs.docker.com/build/building/best-practices/#user+ARG UID=10001+RUN adduser \+ --disabled-password \+ --gecos "" \+ --home "/app" \+ --shell "/sbin/nologin" \+ --uid "${UID}" \+ appuser++WORKDIR /app++# Copy the application and virtual environment with correct ownership in a single layer+# This avoids expensive recursive chown and excludes build tools from the final image+COPY --from=build --chown=appuser:appuser /app /app++# Activate virtual environment+ENV PATH="/app/.venv/bin:$PATH"++# Switch to the non-privileged user for all subsequent operations+# This improves security by not running as root+USER appuser++# Run the application+# The "start" command tells the worker to connect to LiveKit and begin waiting for jobs.+CMD ["python", "transcriber.py", "start"]diff --git a/agents/transcription/justfile b/agents/transcription/justfilenew file mode 100644index 0000000000..4100f68b16--- /dev/null+++ b/agents/transcription/justfile@@ -0,0 +1,20 @@+# Deploy the agent to LiveKit Cloud+deploy-dev:+ cp livekit.dev.toml livekit.toml+ lk agent deploy++# Run the agent locally in console mode+dev:+ python transcriber.py console++# Stream agent logs from LiveKit Cloud+logs:+ lk agent logs++# Check agent deployment status+status:+ lk agent status++# Install Python dependencies+install:+ pip install -r requirements.txtdiff --git a/agents/transcription/livekit.dev.toml b/agents/transcription/livekit.dev.tomlnew file mode 100644index 0000000000..aa57138d50--- /dev/null+++ b/agents/transcription/livekit.dev.toml@@ -0,0 +1,5 @@+[project]+ subdomain = "macro-dev-nx63k8cs"++[agent]+ id = "CA_F5rP586ockUG"diff --git a/agents/transcription/requirements.txt b/agents/transcription/requirements.txtnew file mode 100644index 0000000000..3179896894--- /dev/null+++ b/agents/transcription/requirements.txt@@ -0,0 +1,2 @@+python-dotenv+livekit-agents[silero]diff --git a/agents/transcription/transcriber.py b/agents/transcription/transcriber.pynew file mode 100644index 0000000000..26230c0d12--- /dev/null+++ b/agents/transcription/transcriber.py@@ -0,0 +1,140 @@+import asyncio+import logging++from dotenv import load_dotenv+from livekit import rtc+from livekit.agents import (+ Agent,+ AgentSession,+ AutoSubscribe,+ JobContext,+ JobProcess,+ RoomIO,+ StopResponse,+ cli,+ inference,+ llm,+ room_io,+ utils,+ WorkerOptions,+)+from livekit.plugins import silero++load_dotenv()++logger = logging.getLogger("macro-transcriber")+++class Transcriber(Agent):+ """STT-only agent bound to a single participant."""++ def __init__(self, *, participant_identity: str):+ super().__init__(+ instructions="Transcribe user speech.",+ stt=inference.STT("deepgram/nova-3"),+ )+ self.participant_identity = participant_identity++ async def on_user_turn_completed(+ self, chat_ctx: llm.ChatContext, new_message: llm.ChatMessage+ ):+ raise StopResponse()+++class MultiUserTranscriber:+ """Manages one AgentSession per participant so all speakers are transcribed."""++ def __init__(self, ctx: JobContext):+ self.ctx = ctx+ self._sessions: dict[str, AgentSession] = {}+ self._tasks: set[asyncio.Task] = set()++ def start(self):+ self.ctx.room.on("participant_connected", self.on_participant_connected)+ self.ctx.room.on(+ "participant_disconnected", self.on_participant_disconnected+ )++ async def aclose(self):+ await utils.aio.cancel_and_wait(*self._tasks)+ await asyncio.gather(+ *[self._close_session(s) for s in self._sessions.values()]+ )+ self.ctx.room.off("participant_connected", self.on_participant_connected)+ self.ctx.room.off(+ "participant_disconnected", self.on_participant_disconnected+ )++ def on_participant_connected(self, participant: rtc.RemoteParticipant):+ if participant.identity in self._sessions:+ return++ logger.info(f"starting transcription session for {participant.identity}")+ task = asyncio.create_task(self._start_session(participant))+ self._tasks.add(task)++ def on_done(t: asyncio.Task):+ try:+ self._sessions[participant.identity] = t.result()+ finally:+ self._tasks.discard(t)++ task.add_done_callback(on_done)++ def on_participant_disconnected(self, participant: rtc.RemoteParticipant):+ session = self._sessions.pop(participant.identity, None)+ if session is None:+ return++ logger.info(f"closing transcription session for {participant.identity}")+ task = asyncio.create_task(self._close_session(session))+ self._tasks.add(task)+ task.add_done_callback(lambda t: self._tasks.discard(t))++ async def _start_session(+ self, participant: rtc.RemoteParticipant+ ) -> AgentSession:+ session = AgentSession(vad=self.ctx.proc.userdata["vad"])++ # Create RoomIO per participant to avoid handler conflicts+ # when multiple sessions share the same room.+ rio = RoomIO(+ agent_session=session,+ room=self.ctx.room,+ participant=participant,+ options=room_io.RoomOptions(+ text_input=False,+ text_output=True,+ audio_output=False,+ ),+ )+ await rio.start()+ is_first = len(self._sessions) == 0+ await session.start(+ agent=Transcriber(participant_identity=participant.identity),+ record=is_first,+ )+ return session++ async def _close_session(self, session: AgentSession):+ await session.drain()+ await session.aclose()+++async def entrypoint(ctx: JobContext):+ transcriber = MultiUserTranscriber(ctx)+ transcriber.start()+ await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY)++ for participant in ctx.room.remote_participants.values():+ transcriber.on_participant_connected(participant)++ ctx.add_shutdown_callback(lambda: transcriber.aclose())+++def prewarm(proc: JobProcess):+ proc.userdata["vad"] = silero.VAD.load()+++if __name__ == "__main__":+ cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, prewarm_fnc=prewarm))diff --git a/infra/stacks/cloud-storage-service/Pulumi.dev.yaml b/infra/stacks/cloud-storage-service/Pulumi.dev.yamlindex f7223b5600..3dac6171d4 100644--- a/infra/stacks/cloud-storage-service/Pulumi.dev.yaml+++ b/infra/stacks/cloud-storage-service/Pulumi.dev.yaml@@ -21,3 +21,4 @@ config:cloud-storage-service:livekit_server_url: livekit-server-url-devcloud-storage-service:livekit_api_key: livekit-api-key-devcloud-storage-service:livekit_api_secret: livekit-api-secret-dev+ cloud-storage-service:livekit_transcription_agent_name: macro-transcriberdiff --git a/infra/stacks/cloud-storage-service/Pulumi.prod.yaml b/infra/stacks/cloud-storage-service/Pulumi.prod.yamlindex 6103de82f9..b4044d7d0f 100644--- a/infra/stacks/cloud-storage-service/Pulumi.prod.yaml+++ b/infra/stacks/cloud-storage-service/Pulumi.prod.yaml@@ -21,3 +21,4 @@ config:cloud-storage-service:livekit_server_url: livekit-server-url-prodcloud-storage-service:livekit_api_key: livekit-api-key-prodcloud-storage-service:livekit_api_secret: livekit-api-secret-prod+ cloud-storage-service:livekit_transcription_agent_name: macro-transcriberdiff --git a/infra/stacks/cloud-storage-service/index.ts b/infra/stacks/cloud-storage-service/index.tsindex f055e2bb7f..3fd9ee373f 100644--- a/infra/stacks/cloud-storage-service/index.ts+++ b/infra/stacks/cloud-storage-service/index.ts@@ -322,7 +322,10 @@ const cloudStorageService = new CloudStorageService(name: 'LIVEKIT_API_SECRET',value: pulumi.interpolate`${LIVEKIT_API_SECRET}`,},-+ {+ name: 'LIVEKIT_TRANSCRIPTION_AGENT_NAME',+ value: config.require('livekit_transcription_agent_name'),+ },{name: 'OPENSEARCH_URL',value: OPENSEARCH_URL,diff --git a/rust/cloud-storage/call/src/domain/ports.rs b/rust/cloud-storage/call/src/domain/ports.rsindex e6463f5091..97356e7be3 100644--- a/rust/cloud-storage/call/src/domain/ports.rs+++ b/rust/cloud-storage/call/src/domain/ports.rs@@ -154,6 +154,14 @@ pub trait CallRtcClient: Send + Sync + 'static {/// Validate a webhook signature and parse the event from the raw body.fn receive_webhook(&self, body: &str, auth_token: &str) -> Result<CallWebhookEvent, CallError>;++ /// Dispatch the transcription agent to a room (best-effort).+ ///+ /// Returns `Ok(())` if dispatch succeeded or if no agent is configured.+ fn dispatch_transcription_agent(+ &self,+ room_name: &str,+ ) -> impl Future<Output = anyhow::Result<()>> + Send;}/// Service interface for call operations.diff --git a/rust/cloud-storage/call/src/domain/service.rs b/rust/cloud-storage/call/src/domain/service.rsindex 8790641e3b..092ab9d522 100644--- a/rust/cloud-storage/call/src/domain/service.rs+++ b/rust/cloud-storage/call/src/domain/service.rs@@ -66,7 +66,16 @@ impl<R: CallRepository, C: CallRtcClient> CallService for CallServiceImpl<R, C>.map_err(|e| CallError::Internal(e.into()))?{Some(call) => {- // We are the creator — start recording if configured.+ // We are the creator — dispatch transcription agent (best-effort).+ self.rtc_client+ .dispatch_transcription_agent(&room_name)+ .await+ .inspect_err(|e| {+ tracing::error!(error=?e, "failed to dispatch transcription agent")+ })+ .ok();++ // Start recording if configured.if let Some(s3_config) = &self.egress_s3_config {match self.rtc_client@@ -134,26 +143,14 @@ impl<R: CallRepository, C: CallRtcClient> CallService for CallServiceImpl<R, C>.map_err(|e| CallError::Internal(e.into()))?.ok_or_else(|| CallError::NotFound(channel_id.to_string()))?;- // Verify user is in the call.- let is_in_call = self- .repo- .is_participant(&call.id, user_id)- .await- .map_err(|e| CallError::Internal(e.into()))?;-- if !is_in_call {- return Err(CallError::NotInCall);- }-- // Remove participant from DB.+ // Remove participant from DB (idempotent — no-op if already removed by webhook).self.repo.remove_participant(&call.id, user_id).await.map_err(|e| CallError::Internal(e.into()))?;- // Remove from RTC (best-effort).- // LiveKit will fire participant_left and eventually room_finished webhooks,- // which handle call record archival and cleanup of the ephemeral tables.+ // Kick from LiveKit. The resulting participant_left webhook+ // handles archival and room deletion.self.rtc_client.remove_participant(&call.room_name, user_id).await@@ -162,12 +159,7 @@ impl<R: CallRepository, C: CallRtcClient> CallService for CallServiceImpl<R, C>).ok();- // Check if this was the last participant.- let remaining = self- .repo- .get_participant_count(&call.id)- .await- .map_err(|e| CallError::Internal(e.into()))?;+ let remaining = self.repo.get_participant_count(&call.id).await.unwrap_or(0);Ok(LeaveCallResponse {call_ended: remaining == 0,@@ -256,18 +248,11 @@ impl<R: CallRepository, C: CallRtcClient> CallService for CallServiceImpl<R, C>return Ok(());};- // Reconcile: remove participant from DB if still present (handles crash/disconnect).- if self- .repo- .is_participant(&call.id, participant_identity)+ // Remove participant from DB (idempotent — no-op if already left).+ self.repo+ .remove_participant(&call.id, participant_identity).await- .map_err(|e| CallError::Internal(e.into()))?- {- self.repo- .remove_participant(&call.id, participant_identity)- .await- .map_err(|e| CallError::Internal(e.into()))?;- }+ .map_err(|e| CallError::Internal(e.into()))?;// If no participants remain, archive the call and delete the room.let remaining = selfdiff --git a/rust/cloud-storage/call/src/inbound/axum_router.rs b/rust/cloud-storage/call/src/inbound/axum_router.rsindex 15865fb663..9e39707fbc 100644--- a/rust/cloud-storage/call/src/inbound/axum_router.rs+++ b/rust/cloud-storage/call/src/inbound/axum_router.rs@@ -263,15 +263,15 @@ pub async fn webhook_handler<S: CallService>(pub async fn transcript_handler<S: CallService, Svc: EntityAccessService>(State(state): State<CallRouterState<S, Svc>>,access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,- user: MacroUserExtractor,+ _user: MacroUserExtractor,Json(segment): Json<TranscriptSegmentRequest>,) -> Result<StatusCode, CallError> {let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;- let user_id = user.macro_user_id.as_ref();- if segment.speaker_id != user_id {- return Err(CallError::Auth);- }+ // Note: we don't enforce speaker_id == authenticated user because the+ // LiveKit transcription agent publishes text streams attributed to the+ // original speaker, and any channel member's frontend may relay any+ // speaker's segment. The segment_id dedup constraint prevents duplicates.state.servicediff --git a/rust/cloud-storage/call/src/outbound/livekit_rtc_client.rs b/rust/cloud-storage/call/src/outbound/livekit_rtc_client.rsindex 52a16cf871..9adc354112 100644--- a/rust/cloud-storage/call/src/outbound/livekit_rtc_client.rs+++ b/rust/cloud-storage/call/src/outbound/livekit_rtc_client.rs@@ -4,10 +4,13 @@//! egress recording, and webhook validation.use livekit_api::access_token::{AccessToken, TokenVerifier, VideoGrants};+use livekit_api::services::agent_dispatch::AgentDispatchClient;use livekit_api::services::egress::{EgressClient, EgressOutput, RoomCompositeOptions};use livekit_api::services::room::{CreateRoomOptions, RoomClient};use livekit_api::webhooks::WebhookReceiver;-use livekit_protocol::{EncodedFileOutput, S3Upload, encoded_file_output};+use livekit_protocol::{+ CreateAgentDispatchRequest, EncodedFileOutput, S3Upload, encoded_file_output,+};use crate::domain::models::{CallError, CallWebhookEvent, EgressS3Config};use crate::domain::ports::CallRtcClient;@@ -16,9 +19,12 @@ use crate::domain::ports::CallRtcClient;pub struct LivekitRtcClient {room_client: RoomClient,egress_client: EgressClient,+ agent_dispatch_client: AgentDispatchClient,webhook_receiver: WebhookReceiver,api_key: String,api_secret: String,+ /// If set, the named agent is dispatched to each new room for transcription.+ transcription_agent_name: Option<String>,}impl LivekitRtcClient {@@ -28,10 +34,12 @@ impl LivekitRtcClient {/// * `server_url` - LiveKit server URL (e.g. `https://my-livekit.example.com`)/// * `api_key` - LiveKit API key/// * `api_secret` - LiveKit API secret+ /// * `transcription_agent_name` - If set, this agent is dispatched to new rooms for STTpub fn new(server_url: &str,api_key: impl Into<String>,api_secret: impl Into<String>,+ transcription_agent_name: Option<String>,) -> Self {let api_key = api_key.into();let api_secret = api_secret.into();@@ -43,14 +51,18 @@ impl LivekitRtcClient {.replace("ws://", "http://");let room_client = RoomClient::with_api_key(&http_url, &api_key, &api_secret);let egress_client = EgressClient::with_api_key(&http_url, &api_key, &api_secret);+ let agent_dispatch_client =+ AgentDispatchClient::with_api_key(&http_url, &api_key, &api_secret);let verifier = TokenVerifier::with_api_key(&api_key, &api_secret);let webhook_receiver = WebhookReceiver::new(verifier);Self {room_client,egress_client,+ agent_dispatch_client,webhook_receiver,api_key,api_secret,+ transcription_agent_name,}}}@@ -134,6 +146,24 @@ impl CallRtcClient for LivekitRtcClient {Ok(())}+ #[tracing::instrument(err, skip(self))]+ async fn dispatch_transcription_agent(&self, room_name: &str) -> anyhow::Result<()> {+ let Some(agent_name) = &self.transcription_agent_name else {+ return Ok(());+ };++ self.agent_dispatch_client+ .create_dispatch(CreateAgentDispatchRequest {+ agent_name: agent_name.clone(),+ room: room_name.to_owned(),+ ..Default::default()+ })+ .await?;++ tracing::info!(room_name, agent_name, "dispatched transcription agent");+ Ok(())+ }+fn receive_webhook(&self, body: &str, auth_token: &str) -> Result<CallWebhookEvent, CallError> {let event = self.webhook_receiverdiff --git a/rust/cloud-storage/document_storage_service/src/config.rs b/rust/cloud-storage/document_storage_service/src/config.rsindex 52c3004659..f958948ea2 100644--- a/rust/cloud-storage/document_storage_service/src/config.rs+++ b/rust/cloud-storage/document_storage_service/src/config.rs@@ -1,5 +1,5 @@pub use macro_env::Environment;-use macro_env_var::env_var;+use macro_env_var::{env_var, maybe_env_var};use secretsmanager_client::LocalOrRemoteSecret;/// The configuration parameters for the application.@@ -67,6 +67,11 @@ env_var! {}}+maybe_env_var! {+ /// Optional name of the LiveKit agent to dispatch for call transcription.+ pub struct LivekitTranscriptionAgentName;+}+env_var! { struct Port; }env_var! { struct DocumentLimit; }env_var! { struct DocumentStorageServicePresignedUrlExpirySeconds; }diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex 3e27646d2d..473d2e001e 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -353,10 +353,13 @@ async fn main() -> anyhow::Result<()> {);// Call service (LiveKit)+ let transcription_agent_name =+ config::LivekitTranscriptionAgentName::new().map(|v| v.as_ref().to_owned());let livekit_rtc_client = LivekitRtcClient::new(config.vars.livekit_server_url.as_ref(),config.vars.livekit_api_key.as_ref(),config.vars.livekit_api_secret.as_ref(),+ transcription_agent_name,);let call_repo = PgCallRepo::new(db.clone());let call_service = Arc::new(CallServiceImpl::new(