Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(calls): move transcript to agent (#2377)

Will Hutchinson0a2cc9718ddb
diff --git a/.env-local.enc b/.env-local.enc
index 869adcca01..831e606c97 100644
--- a/.env-local.enc
+++ b/.env-local.enc
@@ -127,6 +127,7 @@ LIVEKIT_SERVER_URL=ENC[AES256_GCM,data:w4SAApcyzwRtST6WGnzJTfFdX0Dp8pthvtH6Mymz2
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]
+INTERNAL_CALL_SECRET=ENC[AES256_GCM,data:66UR3BO7Ddg5bQ0xmLNeY5EGb65L4tiXcsDNpTE=,iv:ovuMlw/k257Oh1CkosXjOXDWycQ4AoA9s+hhfHpeOvs=,tag:qXXYEFhSaM0Q4ffRdGtMRg==,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-----\n
sops_age__list_0__map_recipient=age1yubikey1qw64ag5lzvn9ekrflu5ruj4a6ucycscl6ctk39fjzf76jptsay39z442pxv
sops_kms__list_0__map_arn=arn:aws:kms:us-east-1:569036502058:key/mrk-cab29bf948044eb79005a81f48d40e93
@@ -137,7 +138,7 @@ sops_kms__list_1__map_arn=arn:aws:kms:us-west-1:569036502058:key/mrk-cab29bf9480
sops_kms__list_1__map_aws_profile=
sops_kms__list_1__map_created_at=2026-03-03T19:32:07Z
sops_kms__list_1__map_enc=AQICAHjuYcSMsjB0lKJtZ3DIAvxF8N3RNRn5KZaAN74Et6122wFUqf7u/HEfCUGv7j69Mb6YAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMpcJQR1XeIAFFE7ebAgEQgDvYRYIWelwN8TuwA+6fZVaB34yKo9EQ5xPLr/3BU+ro1Mn2eBPCg3q8ie2LuE/3voim1X35P/cdtDqTZg==
-sops_lastmodified=2026-04-02T19:15:01Z
-sops_mac=ENC[AES256_GCM,data:BR0L5sUpVI+QuMc17j/CyODLo3zrgwhcSvDc8oNSicYguvowQ5u0QynuKpKkbWh6G6AvtErQk8gQOSg9iR75V81Mws3TuMnOPOqDZq9y1AhcsCMYlxPdmH9HXXRTuRHPcDg52hHUDmirL7BhDpeLYVHBov1ynBvsDMLsFGE/mL0=,iv:+sqkFTDBUd2eElda+8gwG4R9H2GHybcHnGM4kIjPzUc=,tag:tBTxQk7SGzv0qaqUzmzukw==,type:str]
+sops_lastmodified=2026-04-06T18:22:08Z
+sops_mac=ENC[AES256_GCM,data:L+DfQz4nS3vCOGqOh5Mun6Vt2oTKMIhF2FG//tmihJifBNobcd0UrwE9nRekaysT9yH3iIHYhOHq2MIp+To06v4kH48VGoHd2LarJTEh5xYATCEXR99MFU3S9BXMKPY/g3OZedf+jhc/0rDUoPtDYUXL7jaVBwj5Vw+1veWo/G0=,iv:j06rIjEB1dIzhcyBAdCBWB4Efqk/370GoPHwFMvvaUg=,tag:B+lDWzdjaNZzRbOWLFUtqg==,type:str]
sops_unencrypted_suffix=_unencrypted
sops_version=3.12.1
diff --git a/.env-localdev.enc b/.env-localdev.enc
index d968da53f5..8a2e9c66a3 100644
--- a/.env-localdev.enc
+++ b/.env-localdev.enc
@@ -133,6 +133,7 @@ LIVEKIT_SERVER_URL=ENC[AES256_GCM,data:aBbXYtf18XRTfQX500l5Mej8FPxqDmH+Lp9W6LdGz
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]
+INTERNAL_CALL_SECRET=ENC[AES256_GCM,data:ZRHFdPR0Rrq01RiNYDECflGVdG+xdHr0qrpR9xY=,iv:DNGhICcPs2zKFpxqSAdgezeT9F8L/r/JO0hT3tJN2Rg=,tag:Rg3YlrSIhtpwI70ifErOTw==,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-----\n
sops_age__list_0__map_recipient=age1yubikey1qw64ag5lzvn9ekrflu5ruj4a6ucycscl6ctk39fjzf76jptsay39z442pxv
sops_kms__list_0__map_arn=arn:aws:kms:us-east-1:569036502058:key/mrk-cab29bf948044eb79005a81f48d40e93
@@ -143,7 +144,7 @@ sops_kms__list_1__map_arn=arn:aws:kms:us-west-1:569036502058:key/mrk-cab29bf9480
sops_kms__list_1__map_aws_profile=
sops_kms__list_1__map_created_at=2026-03-03T19:32:17Z
sops_kms__list_1__map_enc=AQICAHjuYcSMsjB0lKJtZ3DIAvxF8N3RNRn5KZaAN74Et6122wHtcTS4UVhM79Eansn1/OmrAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMRrFwSp99ZM2mPtJzAgEQgDvsIaiNifNz0/18C9OH77AG/LQLpmDiXiJYV46yLDv9vdyPL3PaLMvkAqgL3Xb2F4RcZOIUxkTS3u92xQ==
-sops_lastmodified=2026-04-02T19:12:51Z
-sops_mac=ENC[AES256_GCM,data:SlztwOseufM6RaODWunmanl8k/Tj8ewV9o7j7EoLGvTuVljVD8gPEjanxQ71zNQMd+QnakppKUJuC7j1WMHoaVD2h7wHIw5J/VhSvJdXd2JE5KgjeMNVi4rsgoVAgDU1uDnPXwRj9dGztj8S4lCylSLcAmNjUqJGdVGlI4DBQnk=,iv:QctWumXv/czKrHa1GH+72nR55LQEOrLM6FzXzUhPEHM=,tag:RD4pUJ4p7EwFGBxCZe/dmQ==,type:str]
+sops_lastmodified=2026-04-06T18:21:59Z
+sops_mac=ENC[AES256_GCM,data:bVn78dLiiNDtGJSQp2V+g7Vlvpy/IEdXpK1R5lkv83BlqWCxjlTU11Dz3HfAuLU44m3NbH/h8Goa7DvLI+e5nQPKTtEhCTgDkK6yjZ8SxhyqyQEu7Y3l+sLM+xhAE4oco+mjRI2PS+0KraA2/6NHs8VX9exl1I+5nn1SaQ9cqes=,iv:44pMBXAZEPcu2MaxJTbggI86ONUIFBToZH9nHzIDTZo=,tag:hNME/wS3YRgUTt4V2mdLHg==,type:str]
sops_unencrypted_suffix=_unencrypted
sops_version=3.12.1
diff --git a/agents/transcription/requirements.txt b/agents/transcription/requirements.txt
index 3179896894..3c5d778b26 100644
--- a/agents/transcription/requirements.txt
+++ b/agents/transcription/requirements.txt
@@ -1,2 +1,3 @@
python-dotenv
livekit-agents[silero]
+httpx
diff --git a/agents/transcription/transcriber.py b/agents/transcription/transcriber.py
index 26230c0d12..8ac5c06859 100644
--- a/agents/transcription/transcriber.py
+++ b/agents/transcription/transcriber.py
@@ -1,6 +1,10 @@
import asyncio
import logging
+import os
+import uuid
+from datetime import datetime, timezone
+import httpx
from dotenv import load_dotenv
from livekit import rtc
from livekit.agents import (
@@ -24,28 +28,111 @@ load_dotenv()
logger = logging.getLogger("macro-transcriber")
+MACRO_API_URL = os.environ.get("MACRO_API_URL", "http://localhost:8080")
+INTERNAL_CALL_SECRET = os.environ.get("INTERNAL_CALL_SECRET", "")
+
class Transcriber(Agent):
"""STT-only agent bound to a single participant."""
- def __init__(self, *, participant_identity: str):
+ def __init__(
+ self,
+ *,
+ participant_identity: str,
+ channel_id: str,
+ http_client: httpx.AsyncClient,
+ ):
super().__init__(
instructions="Transcribe user speech.",
stt=inference.STT("deepgram/nova-3"),
)
self.participant_identity = participant_identity
+ self.channel_id = channel_id
+ self.http_client = http_client
async def on_user_turn_completed(
self, chat_ctx: llm.ChatContext, new_message: llm.ChatMessage
):
+ content = new_message.text_content
+ if content:
+ message_time = datetime.now(timezone.utc)
+ if new_message.created_at is not None:
+ message_time = datetime.fromtimestamp(
+ new_message.created_at, tz=timezone.utc
+ )
+ timestamp = message_time.isoformat()
+
+ extra = new_message.extra if isinstance(new_message.extra, dict) else {}
+ source_id = (
+ extra.get("provider_message_id")
+ or extra.get("providerMessageId")
+ or new_message.id
+ )
+ segment_seed = (
+ f"{self.channel_id}:{self.participant_identity}:{source_id}:{timestamp}"
+ )
+ segment_id = str(uuid.uuid5(uuid.NAMESPACE_URL, segment_seed))
+
+ segment = {
+ "segmentId": segment_id,
+ "speakerId": self.participant_identity,
+ "content": content,
+ "startedAt": timestamp,
+ "endedAt": timestamp,
+ "isFinal": True,
+ }
+ max_attempts = 3
+ delay_seconds = 0.25
+ for attempt in range(1, max_attempts + 1):
+ try:
+ resp = await self.http_client.post(
+ f"{MACRO_API_URL}/call/{self.channel_id}/transcript",
+ json=segment,
+ headers={"x-macro-internal-call": INTERNAL_CALL_SECRET},
+ )
+ resp.raise_for_status()
+ break
+ except (httpx.TimeoutException, httpx.NetworkError) as exc:
+ if attempt == max_attempts:
+ logger.exception(
+ "failed to post transcript segment segmentId=%s error=%s",
+ segment_id,
+ exc,
+ )
+ break
+ await asyncio.sleep(delay_seconds)
+ delay_seconds *= 2
+ except httpx.HTTPStatusError as exc:
+ status_code = exc.response.status_code if exc.response else None
+ is_transient = (
+ status_code is not None and 500 <= status_code < 600
+ )
+ if is_transient and attempt < max_attempts:
+ await asyncio.sleep(delay_seconds)
+ delay_seconds *= 2
+ continue
+ logger.exception(
+ "failed to post transcript segment segmentId=%s error=%s",
+ segment_id,
+ exc,
+ )
+ break
+ except Exception as exc:
+ logger.exception(
+ "failed to post transcript segment segmentId=%s error=%s",
+ segment_id,
+ exc,
+ )
+ break
raise StopResponse()
class MultiUserTranscriber:
"""Manages one AgentSession per participant so all speakers are transcribed."""
- def __init__(self, ctx: JobContext):
+ def __init__(self, ctx: JobContext, http_client: httpx.AsyncClient):
self.ctx = ctx
+ self.http_client = http_client
self._sessions: dict[str, AgentSession] = {}
self._tasks: set[asyncio.Task] = set()
@@ -96,6 +183,9 @@ class MultiUserTranscriber:
) -> AgentSession:
session = AgentSession(vad=self.ctx.proc.userdata["vad"])
+ # The room name is the channel_id.
+ channel_id = self.ctx.room.name
+
# Create RoomIO per participant to avoid handler conflicts
# when multiple sessions share the same room.
rio = RoomIO(
@@ -111,7 +201,11 @@ class MultiUserTranscriber:
await rio.start()
is_first = len(self._sessions) == 0
await session.start(
- agent=Transcriber(participant_identity=participant.identity),
+ agent=Transcriber(
+ participant_identity=participant.identity,
+ channel_id=channel_id,
+ http_client=self.http_client,
+ ),
record=is_first,
)
return session
@@ -122,14 +216,19 @@ class MultiUserTranscriber:
async def entrypoint(ctx: JobContext):
- transcriber = MultiUserTranscriber(ctx)
+ http_client = httpx.AsyncClient()
+ transcriber = MultiUserTranscriber(ctx, http_client)
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())
+ async def shutdown():
+ await transcriber.aclose()
+ await http_client.aclose()
+
+ ctx.add_shutdown_callback(shutdown)
def prewarm(proc: JobProcess):
diff --git a/infra/stacks/cloud-storage-service/Pulumi.dev.yaml b/infra/stacks/cloud-storage-service/Pulumi.dev.yaml
index 3dac6171d4..52796d05d0 100644
--- a/infra/stacks/cloud-storage-service/Pulumi.dev.yaml
+++ b/infra/stacks/cloud-storage-service/Pulumi.dev.yaml
@@ -22,3 +22,4 @@ config:
cloud-storage-service:livekit_api_key: livekit-api-key-dev
cloud-storage-service:livekit_api_secret: livekit-api-secret-dev
cloud-storage-service:livekit_transcription_agent_name: macro-transcriber
+ cloud-storage-service:call_internal_secret: call-internal-secret-dev
diff --git a/infra/stacks/cloud-storage-service/Pulumi.prod.yaml b/infra/stacks/cloud-storage-service/Pulumi.prod.yaml
index b4044d7d0f..c58975e6c5 100644
--- a/infra/stacks/cloud-storage-service/Pulumi.prod.yaml
+++ b/infra/stacks/cloud-storage-service/Pulumi.prod.yaml
@@ -22,3 +22,4 @@ config:
cloud-storage-service:livekit_api_key: livekit-api-key-prod
cloud-storage-service:livekit_api_secret: livekit-api-secret-prod
cloud-storage-service:livekit_transcription_agent_name: macro-transcriber
+ cloud-storage-service:call_internal_secret: call-internal-secret-prod
diff --git a/infra/stacks/cloud-storage-service/index.ts b/infra/stacks/cloud-storage-service/index.ts
index 3fd9ee373f..a8441f22d7 100644
--- a/infra/stacks/cloud-storage-service/index.ts
+++ b/infra/stacks/cloud-storage-service/index.ts
@@ -277,6 +277,10 @@ const LIVEKIT_API_SECRET = aws.secretsmanager
.getSecretVersionOutput({ secretId: config.require('livekit_api_secret') })
.apply((secret) => secret.secretString);
+const INTERNAL_CALL_SECRET = aws.secretsmanager
+ .getSecretVersionOutput({ secretId: config.require('call_internal_secret') })
+ .apply((secret) => secret.secretString);
+
const cloudStorageService = new CloudStorageService(
`cloud-storage-service-${stack}`,
{
@@ -310,6 +314,10 @@ const cloudStorageService = new CloudStorageService(
githubSyncAppPemArn,
],
containerEnvVars: [
+ {
+ name: 'INTERNAL_CALL_SECRET',
+ value: pulumi.interpolate`${INTERNAL_CALL_SECRET}`,
+ },
{
name: 'LIVEKIT_SERVER_URL',
value: pulumi.interpolate`${LIVEKIT_SERVER_URL}`,
diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.ts
index e191135ac4..2ddd2a7084 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -850,8 +850,9 @@ export const leaveOrEndCallResponse = zod
.describe('Response for the leave/end call operation.');
/**
- * Receives transcript segments from the frontend.
-Requires channel membership. Duplicate segments (same `segment_id`) are ignored.
+ * Receives transcript segments from the transcription agent.
+Authenticated via the `x-macro-internal-call` shared secret.
+Duplicate segments (same `segment_id`) are ignored.
* @summary Handler for `POST /call/{channel_id}/transcript`.
*/
export const ingestTranscriptParams = zod.object({
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index f8102df7f8..ffb9cbf74a 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -735,7 +735,7 @@
"post": {
"tags": ["call::inbound::axum_router"],
"summary": "Handler for `POST /call/{channel_id}/transcript`.",
- "description": "Receives transcript segments from the frontend.\nRequires channel membership. Duplicate segments (same `segment_id`) are ignored.",
+ "description": "Receives transcript segments from the transcription agent.\nAuthenticated via the `x-macro-internal-call` shared secret.\nDuplicate segments (same `segment_id`) are ignored.",
"operationId": "ingest_transcript",
"parameters": [
{
diff --git a/rust/cloud-storage/call/src/domain/ports.rs b/rust/cloud-storage/call/src/domain/ports.rs
index 97356e7be3..b5942181e0 100644
--- a/rust/cloud-storage/call/src/domain/ports.rs
+++ b/rust/cloud-storage/call/src/domain/ports.rs
@@ -166,6 +166,9 @@ pub trait CallRtcClient: Send + Sync + 'static {
/// Service interface for call operations.
pub trait CallService: Send + Sync + 'static {
+ /// Validate an internal call token (e.g. from the `x-macro-internal-call` header).
+ fn validate_internal_call(&self, token: &str) -> bool;
+
/// Get or create a call in a channel. If a call already exists, joins it;
/// otherwise creates a new one. Always returns a join token.
fn get_or_create_call(
diff --git a/rust/cloud-storage/call/src/domain/service.rs b/rust/cloud-storage/call/src/domain/service.rs
index 092ab9d522..7dd11929b8 100644
--- a/rust/cloud-storage/call/src/domain/service.rs
+++ b/rust/cloud-storage/call/src/domain/service.rs
@@ -13,6 +13,7 @@ pub struct CallServiceImpl<R: CallRepository, C: CallRtcClient> {
rtc_client: C,
server_url: String,
egress_s3_config: Option<EgressS3Config>,
+ internal_call_secret: Option<String>,
}
impl<R: CallRepository, C: CallRtcClient> CallServiceImpl<R, C> {
@@ -23,6 +24,7 @@ impl<R: CallRepository, C: CallRtcClient> CallServiceImpl<R, C> {
rtc_client,
server_url: server_url.into(),
egress_s3_config: None,
+ internal_call_secret: None,
}
}
@@ -31,9 +33,21 @@ impl<R: CallRepository, C: CallRtcClient> CallServiceImpl<R, C> {
self.egress_s3_config = Some(s3_config);
self
}
+
+ /// Set the shared secret used to validate internal call requests.
+ pub fn with_internal_call_secret(mut self, secret: String) -> Self {
+ self.internal_call_secret = Some(secret);
+ self
+ }
}
impl<R: CallRepository, C: CallRtcClient> CallService for CallServiceImpl<R, C> {
+ fn validate_internal_call(&self, token: &str) -> bool {
+ self.internal_call_secret
+ .as_deref()
+ .is_some_and(|secret| secret == token)
+ }
+
#[tracing::instrument(err, skip(self))]
async fn get_or_create_call(
&self,
diff --git a/rust/cloud-storage/call/src/inbound/axum_router.rs b/rust/cloud-storage/call/src/inbound/axum_router.rs
index fb24579f05..62909ba5d4 100644
--- a/rust/cloud-storage/call/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/call/src/inbound/axum_router.rs
@@ -7,12 +7,13 @@
//! - [`webhook_router`] — RTC provider webhook ingestion.
//! Does **not** require auth middleware (LiveKit signs requests itself).
+use std::borrow::Cow;
use std::sync::Arc;
use axum::{
Json, Router,
- extract::{FromRef, State},
- http::StatusCode,
+ extract::{FromRef, FromRequestParts, State},
+ http::{StatusCode, request::Parts},
response::IntoResponse,
routing::{get, post},
};
@@ -72,7 +73,6 @@ impl<S, Svc> FromRef<CallRouterState<S, Svc>> for Arc<Svc> {
/// Routes:
/// - `GET /{channel_id}` — get or create a call (join existing or start new)
/// - `DELETE /{channel_id}` — leave or end a call
-/// - `POST /{channel_id}/transcript` — ingest a transcript segment (from authenticated frontend)
pub fn call_router<S, Svc, T>(state: CallRouterState<S, Svc>) -> Router<T>
where
S: CallService,
@@ -84,10 +84,6 @@ where
"/{channel_id}",
get(get_or_create_call_handler::<S, Svc>).delete(leave_or_end_call_handler::<S, Svc>),
)
- .route(
- "/{channel_id}/transcript",
- post(transcript_handler::<S, Svc>),
- )
.with_state(state)
}
@@ -129,6 +125,87 @@ where
.with_state(state)
}
+// ---------------------------------------------------------------------------
+// Internal call router (agent-authenticated via shared secret)
+// ---------------------------------------------------------------------------
+
+/// Router state for the internal transcript endpoint.
+pub struct InternalCallRouterState<S> {
+ service: Arc<S>,
+}
+
+impl<S> Clone for InternalCallRouterState<S> {
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ }
+ }
+}
+
+impl<S: CallService> InternalCallRouterState<S> {
+ /// Create a new internal call router state wrapping the call service.
+ pub fn new(service: Arc<S>) -> Self {
+ Self { service }
+ }
+}
+
+impl<S> FromRef<InternalCallRouterState<S>> for Arc<S> {
+ fn from_ref(state: &InternalCallRouterState<S>) -> Self {
+ state.service.clone()
+ }
+}
+
+/// Internal call router for agent-submitted transcript segments.
+///
+/// Routes:
+/// - `POST /{channel_id}/transcript` — ingest a transcript segment (from internal agent)
+pub fn internal_call_router<S, T>(state: InternalCallRouterState<S>) -> Router<T>
+where
+ S: CallService,
+ T: Send + Sync,
+{
+ Router::new()
+ .route("/{channel_id}/transcript", post(transcript_handler::<S>))
+ .with_state(state)
+}
+
+// ---------------------------------------------------------------------------
+// Internal call access extractor
+// ---------------------------------------------------------------------------
+
+static INTERNAL_CALL_HEADER: &str = "x-macro-internal-call";
+
+/// Axum extractor that validates the `x-macro-internal-call` header against
+/// the shared secret stored in the [`CallService`].
+pub struct InternalCallAccessExtractor(());
+
+impl<S> FromRequestParts<InternalCallRouterState<S>> for InternalCallAccessExtractor
+where
+ S: CallService,
+{
+ type Rejection = (StatusCode, Cow<'static, str>);
+
+ async fn from_request_parts(
+ parts: &mut Parts,
+ state: &InternalCallRouterState<S>,
+ ) -> Result<Self, Self::Rejection> {
+ let token = parts
+ .headers
+ .get(INTERNAL_CALL_HEADER)
+ .and_then(|v| v.to_str().ok())
+ .ok_or((
+ StatusCode::BAD_REQUEST,
+ Cow::Borrowed("missing x-macro-internal-call header"),
+ ))?;
+
+ if state.service.validate_internal_call(token) {
+ Ok(InternalCallAccessExtractor(()))
+ } else {
+ Err((StatusCode::UNAUTHORIZED, Cow::Borrowed("unauthorized")))
+ }
+ }
+}
+
// ---------------------------------------------------------------------------
// Handlers
// ---------------------------------------------------------------------------
@@ -236,8 +313,9 @@ pub async fn webhook_handler<S: CallService>(
/// Handler for `POST /call/{channel_id}/transcript`.
///
-/// Receives transcript segments from the frontend.
-/// Requires channel membership. Duplicate segments (same `segment_id`) are ignored.
+/// Receives transcript segments from the transcription agent.
+/// Authenticated via the `x-macro-internal-call` shared secret.
+/// Duplicate segments (same `segment_id`) are ignored.
#[utoipa::path(
post,
operation_id = "ingest_transcript",
@@ -254,19 +332,12 @@ pub async fn webhook_handler<S: CallService>(
)
)]
#[tracing::instrument(err, skip_all)]
-pub async fn transcript_handler<S: CallService, Svc: EntityAccessService>(
- State(state): State<CallRouterState<S, Svc>>,
- access: CallWithChannelIdAccessLevelExtractor<MemberParticipantRole, Svc>,
- _user: MacroUserExtractor,
+pub async fn transcript_handler<S: CallService>(
+ State(state): State<InternalCallRouterState<S>>,
+ _access: InternalCallAccessExtractor,
+ axum::extract::Path(channel_id): axum::extract::Path<Uuid>,
Json(segment): Json<TranscriptSegmentRequest>,
) -> Result<StatusCode, CallError> {
- let channel_id = access.channel_id;
-
- // 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
.service
.ingest_transcript_segment(&channel_id, segment)
diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rs
index 25fc14f4bd..5c404cab11 100644
--- a/rust/cloud-storage/document_storage_service/src/api/context.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs
@@ -2,7 +2,7 @@ use crate::{config::Config, service::s3::S3};
use axum::extract::FromRef;
use call::{
domain::service::CallServiceImpl,
- inbound::axum_router::{CallRouterState, WebhookRouterState},
+ inbound::axum_router::{CallRouterState, InternalCallRouterState, WebhookRouterState},
outbound::{livekit_rtc_client::LivekitRtcClient, pg_call_repo::PgCallRepo},
};
use channels::{
@@ -167,6 +167,9 @@ pub(crate) type DssCallState = CallRouterState<DssCallService, EntityAccessServi
/// Type alias for the call webhook router state.
pub(crate) type DssCallWebhookState = WebhookRouterState<DssCallService>;
+/// Type alias for the internal call router state.
+pub(crate) type DssCallInternalState = InternalCallRouterState<DssCallService>;
+
/// Type alias for the github sync service.
pub(crate) type GithubSyncServiceType =
GithubSyncServiceImpl<DocumentService, PgGithubSyncRepo, GithubSyncClientImpl>;
@@ -200,6 +203,7 @@ pub(crate) struct ApiContext {
pub channels_state: DssChannelsState,
pub call_state: DssCallState,
pub call_webhook_state: DssCallWebhookState,
+ pub call_internal_state: DssCallInternalState,
}
env_var! {
diff --git a/rust/cloud-storage/document_storage_service/src/api/mod.rs b/rust/cloud-storage/document_storage_service/src/api/mod.rs
index 1065eb5f1a..81335247b5 100644
--- a/rust/cloud-storage/document_storage_service/src/api/mod.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/mod.rs
@@ -99,6 +99,12 @@ fn api_router(state: ApiContext) -> Router {
call::inbound::axum_router::webhook_router(state.call_webhook_state.clone()),
);
+ // Internal call router — agent-authenticated via x-macro-internal-call header.
+ let internal_call_router = Router::new().nest(
+ "/call",
+ call::inbound::axum_router::internal_call_router(state.call_internal_state.clone()),
+ );
+
let internal_router = Router::new()
.nest(
"/github",
@@ -254,4 +260,5 @@ fn api_router(state: ApiContext) -> Router {
.nest("/{version}", internal_router.clone())
.merge(internal_router)
.merge(webhook_router)
+ .merge(internal_call_router)
}
diff --git a/rust/cloud-storage/document_storage_service/src/config.rs b/rust/cloud-storage/document_storage_service/src/config.rs
index f958948ea2..dbae5381c8 100644
--- a/rust/cloud-storage/document_storage_service/src/config.rs
+++ b/rust/cloud-storage/document_storage_service/src/config.rs
@@ -72,6 +72,11 @@ maybe_env_var! {
pub struct LivekitTranscriptionAgentName;
}
+maybe_env_var! {
+ /// Shared secret for internal call endpoints (e.g. transcript ingestion from the agent).
+ pub struct InternalCallSecret;
+}
+
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.rs
index 2fede74f93..af1b93fa0b 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -10,7 +10,7 @@ use crate::{
use anyhow::Context;
use call::{
domain::service::CallServiceImpl,
- inbound::axum_router::{CallRouterState, WebhookRouterState},
+ inbound::axum_router::{CallRouterState, InternalCallRouterState, WebhookRouterState},
outbound::{livekit_rtc_client::LivekitRtcClient, pg_call_repo::PgCallRepo},
};
use channels::{
@@ -353,6 +353,12 @@ async fn main() -> anyhow::Result<()> {
// Call service (LiveKit)
let transcription_agent_name =
config::LivekitTranscriptionAgentName::new().map(|v| v.as_ref().to_owned());
+ let internal_call_secret = config::InternalCallSecret::new().map(|v| v.as_ref().to_owned());
+ anyhow::ensure!(
+ transcription_agent_name.is_none() || internal_call_secret.is_some(),
+ "LIVEKIT_TRANSCRIPTION_AGENT_NAME is set but INTERNAL_CALL_SECRET is missing — \
+ the transcription agent will not be able to submit transcripts"
+ );
let livekit_rtc_client = LivekitRtcClient::new(
config.vars.livekit_server_url.as_ref(),
config.vars.livekit_api_key.as_ref(),
@@ -360,13 +366,18 @@ async fn main() -> anyhow::Result<()> {
transcription_agent_name,
);
let call_repo = PgCallRepo::new(db.clone());
- let call_service = Arc::new(CallServiceImpl::new(
+ let mut call_service_builder = CallServiceImpl::new(
call_repo,
livekit_rtc_client,
config.vars.livekit_server_url.as_ref(),
- ));
+ );
+ if let Some(secret) = internal_call_secret {
+ call_service_builder = call_service_builder.with_internal_call_secret(secret);
+ }
+ let call_service = Arc::new(call_service_builder);
let call_state = CallRouterState::new(call_service.clone(), entity_access_service.clone());
let call_webhook_state = WebhookRouterState::new(call_service.clone());
+ let call_internal_state = InternalCallRouterState::new(call_service.clone());
// Create the SQS worker for delete document processing before config is moved
let delete_document_worker = sqs_worker::SQSWorker::new(
@@ -418,6 +429,7 @@ async fn main() -> anyhow::Result<()> {
),
call_state,
call_webhook_state,
+ call_internal_state,
};
// Spawn the delete document worker