Skip to content

Build and run agents you can see, understand and trust.

feat(app): support realtime voice conversation in agent service (#2570)

DavdGaoc3c1d7fad423
diff --git a/README.md b/README.md
index dc3cf1855..1da8a7865 100644
--- a/README.md
+++ b/README.md
@@ -73,6 +73,7 @@ rather than constraining them with strict prompts and opinionated orchestrations
## News
<!-- BEGIN NEWS -->
+- **[2026-10] `FEAT` `Experimental`:** Agent service supports realtime voice conversations over WebRTC, with text and voice sharing the same session history.
- **[2026-09] `FEAT` `Experimental`:** SOP supported — run multi-step tasks as standard operating procedures, in both the framework and agent service. [Docs](https://docs.agentscope.io/latest/en/building-blocks/sop) | [Service](https://docs.agentscope.io/latest/en/deploy/sop)
- **[2026-09] `FEAT`:** `TeamPipeline` supported — a leader agent delegates tasks to member agents. [Docs](https://docs.agentscope.io/latest/en/building-blocks/pipeline/team)
- **[2026-09] `INTE`:** MiniMax chat models supported via `MiniMaxChatModel` (MiniMax-M3 by default).
@@ -82,7 +83,6 @@ rather than constraining them with strict prompts and opinionated orchestrations
- **[2026-09] `INTE`:** Support DashScope, OpenAI, Gemini and xAI realtime APIs in `RealtimeAgent`. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/realtime) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/realtime/speech-to-speech)
- **[2026-09] `FEAT` `Experimental`:** Realtime voice agent supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/realtime) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/realtime/overview)
- **[2026-09] `FEAT`:** A2A protocol supported — chat with any remote A2A agent via `A2AAgent`. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/a2a) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/a2a)
-- **[2026-08] `FEAT`:** Pipeline supported — run multiple agents by a fixed logic behind one event stream. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/pipeline) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/pipeline/overview)
<!-- END NEWS -->
[More news →](./docs/NEWS.md)
diff --git a/README_zh.md b/README_zh.md
index 4f1cbef76..ae1d24953 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -72,6 +72,7 @@ AgentScope 的目标是充分发挥大模型的推理与工具调用能力,
## 新闻
<!-- BEGIN NEWS -->
+- **[2026-10] `功能` `实验性`:** 智能体服务支持基于 WebRTC 的实时语音对话,文本与语音模式共享同一会话历史。
- **[2026-09] `功能` `实验性`:** 支持 SOP(标准作业流程)—— 将多步骤任务按标准流程执行,框架与智能体服务均已支持。[文档](https://docs.agentscope.io/latest/zh/building-blocks/sop) | [服务](https://docs.agentscope.io/latest/zh/deploy/sop)
- **[2026-09] `功能`:** 支持 `TeamPipeline` —— 由 leader 智能体向成员智能体分派任务。[文档](https://docs.agentscope.io/latest/zh/building-blocks/pipeline/team)
- **[2026-09] `集成`:** 通过 `MiniMaxChatModel` 支持 MiniMax 聊天模型(默认 MiniMax-M3)。
@@ -81,7 +82,6 @@ AgentScope 的目标是充分发挥大模型的推理与工具调用能力,
- **[2026-09] `集成`:** `RealtimeAgent` 支持 DashScope、OpenAI、Gemini 与 xAI 的实时语音 API。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/realtime) | [文档](https://docs.agentscope.io/latest/zh/building-blocks/realtime/speech-to-speech)
- **[2026-09] `功能` `实验性`:** 支持实时语音智能体。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/realtime) | [文档](https://docs.agentscope.io/latest/zh/building-blocks/realtime/overview)
- **[2026-09] `功能`:** 支持 A2A 协议 —— 通过 `A2AAgent` 与任意远端 A2A 智能体对话。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/a2a) | [文档](https://docs.agentscope.io/latest/zh/building-blocks/a2a)
-- **[2026-08] `功能`:** 支持流水线 —— 按照固化逻辑运行多智能体,并向外提供统一接口。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/pipeline) | [文档](https://docs.agentscope.io/latest/zh/building-blocks/pipeline/overview)
<!-- END NEWS -->
[更多新闻 →](./docs/NEWS_zh.md)
diff --git a/docs/NEWS.md b/docs/NEWS.md
index 32c97574b..13ccf52fe 100644
--- a/docs/NEWS.md
+++ b/docs/NEWS.md
@@ -2,6 +2,7 @@
<!-- The first 10 items are automatically synced to README.md and README_zh.md via GitHub Actions. -->
<!-- To update news in READMEs, modify this file and push to trigger the workflow. -->
+- **[2026-10] `FEAT` `Experimental`:** Agent service supports realtime voice conversations over WebRTC, with text and voice sharing the same session history.
- **[2026-09] `FEAT` `Experimental`:** SOP supported — run multi-step tasks as standard operating procedures, in both the framework and agent service. [Docs](https://docs.agentscope.io/latest/en/building-blocks/sop) | [Service](https://docs.agentscope.io/latest/en/deploy/sop)
- **[2026-09] `FEAT`:** `TeamPipeline` supported — a leader agent delegates tasks to member agents. [Docs](https://docs.agentscope.io/latest/en/building-blocks/pipeline/team)
- **[2026-09] `INTE`:** MiniMax chat models supported via `MiniMaxChatModel` (MiniMax-M3 by default).
@@ -26,4 +27,4 @@
- **[2026-06] `FEAT`:** RAG supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/rag) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/rag)
- **[2026-06] `INTE`:** Mem0 supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory) | [Docs](https://docs.agentscope.io/latest/en)
- **[2026-06] `FEAT`:** Agent Team supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [Docs](https://docs.agentscope.io/latest/en/deploy/agent-team)
-- **[2026-05] `RELS`:** AgentScope 2.0 released! [Docs](https://docs.agentscope.io/)
\ No newline at end of file
+- **[2026-05] `RELS`:** AgentScope 2.0 released! [Docs](https://docs.agentscope.io/)
diff --git a/docs/NEWS_zh.md b/docs/NEWS_zh.md
index 5312fbfde..067f61c90 100644
--- a/docs/NEWS_zh.md
+++ b/docs/NEWS_zh.md
@@ -2,6 +2,7 @@
<!-- The first 10 items are automatically synced to README.md and README_zh.md via GitHub Actions. -->
<!-- To update news in READMEs, modify this file and push to trigger the workflow. -->
+- **[2026-10] `功能` `实验性`:** 智能体服务支持基于 WebRTC 的实时语音对话,文本与语音模式共享同一会话历史。
- **[2026-09] `功能` `实验性`:** 支持 SOP(标准作业流程)—— 将多步骤任务按标准流程执行,框架与智能体服务均已支持。[文档](https://docs.agentscope.io/latest/zh/building-blocks/sop) | [服务](https://docs.agentscope.io/latest/zh/deploy/sop)
- **[2026-09] `功能`:** 支持 `TeamPipeline` —— 由 leader 智能体向成员智能体分派任务。[文档](https://docs.agentscope.io/latest/zh/building-blocks/pipeline/team)
- **[2026-09] `集成`:** 通过 `MiniMaxChatModel` 支持 MiniMax 聊天模型(默认 MiniMax-M3)。
@@ -26,4 +27,4 @@
- **[2026-06] `功能`:** 支持多模态 RAG。 [样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/rag) | [文档](https://docs.agentscope.io/latest/zh/building-blocks/rag)
- **[2026-06] `集成`:** 集成 Mem0 长期记忆。 [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory) | [Docs](https://docs.agentscope.io/latest/zh)
- **[2026-06] `功能`:** 支持 Agent Team。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [文档](https://docs.agentscope.io/latest/zh/deploy/agent-team)
-- **[2026-05] `发布`:** AgentScope 2.0 已发布![文档](https://docs.agentscope.io/)
\ No newline at end of file
+- **[2026-05] `发布`:** AgentScope 2.0 已发布![文档](https://docs.agentscope.io/)
diff --git a/examples/realtime/README.md b/examples/realtime/README.md
index 1f8076081..9aacf3a99 100644
--- a/examples/realtime/README.md
+++ b/examples/realtime/README.md
@@ -24,7 +24,7 @@ audio itself never reaches the view; the transport plays it.
- AgentScope with the realtime and TUI extras:
```bash
- pip install "agentscope[realtime,tui]"
+ pip install "agentscope[realtime,realtime-local,tui]"
```
`sounddevice` needs PortAudio: it is bundled on macOS and Windows; on
diff --git a/examples/web_ui/frontend/src/api/client.ts b/examples/web_ui/frontend/src/api/client.ts
index a7bc0c956..66a1c0b8e 100644
--- a/examples/web_ui/frontend/src/api/client.ts
+++ b/examples/web_ui/frontend/src/api/client.ts
@@ -131,8 +131,8 @@ export const client = {
path: string,
body?: unknown,
params?: Record<string, string>,
- options?: { silent?: boolean },
- ) => request<T>(path, { method: 'POST', body, params, silent: options?.silent }),
+ options?: { silent?: boolean; signal?: AbortSignal; timeoutMs?: number },
+ ) => request<T>(path, { method: 'POST', body, params, ...options }),
patch: <T>(
path: string,
body?: unknown,
diff --git a/examples/web_ui/frontend/src/api/index.ts b/examples/web_ui/frontend/src/api/index.ts
index 3054bda2c..cfb666349 100644
--- a/examples/web_ui/frontend/src/api/index.ts
+++ b/examples/web_ui/frontend/src/api/index.ts
@@ -8,7 +8,8 @@ export { hubApi } from './hub';
export { mcpApi } from './mcp';
export { skillApi } from './skill';
export { scheduleApi } from './schedule';
-export { embeddingModelApi, modelApi, ttsModelApi } from './model';
+export { embeddingModelApi, modelApi, realtimeModelApi, ttsModelApi } from './model';
+export { realtimeApi } from './realtime';
export { knowledgeBaseApi } from './knowledgeBase';
export { channelApi } from './channel';
export { healthApi } from './health';
diff --git a/examples/web_ui/frontend/src/api/model.ts b/examples/web_ui/frontend/src/api/model.ts
index d23d68d47..8c1bf1fbb 100644
--- a/examples/web_ui/frontend/src/api/model.ts
+++ b/examples/web_ui/frontend/src/api/model.ts
@@ -1,5 +1,10 @@
import { client } from './client';
-import type { ListEmbeddingModelResponse, ListModelResponse, ListTTSModelResponse } from './types';
+import type {
+ ListEmbeddingModelResponse,
+ ListModelResponse,
+ ListRealtimeModelResponse,
+ ListTTSModelResponse,
+} from './types';
export const modelApi = {
list: (provider: string) => client.get<ListModelResponse>('/model/', { provider }),
@@ -9,6 +14,11 @@ export const ttsModelApi = {
list: (provider: string) => client.get<ListTTSModelResponse>('/tts-model/', { provider }),
};
+export const realtimeModelApi = {
+ list: (provider: string) =>
+ client.get<ListRealtimeModelResponse>('/realtime/models', { provider }),
+};
+
export const embeddingModelApi = {
list: (provider: string) =>
client.get<ListEmbeddingModelResponse>('/embedding-model/', { provider }),
diff --git a/examples/web_ui/frontend/src/api/realtime.ts b/examples/web_ui/frontend/src/api/realtime.ts
new file mode 100644
index 000000000..9003518b5
--- /dev/null
+++ b/examples/web_ui/frontend/src/api/realtime.ts
@@ -0,0 +1,16 @@
+import { client } from './client';
+import type { RealtimeConfigResponse, RealtimeOfferRequest, RealtimeOfferResponse } from './types';
+
+export const realtimeApi = {
+ config: () =>
+ client.get<RealtimeConfigResponse>('/realtime/config', undefined, {
+ timeoutMs: 10_000,
+ }),
+ offer: (sessionId: string, body: RealtimeOfferRequest) =>
+ client.post<RealtimeOfferResponse>(
+ `/realtime/sessions/${sessionId}/offer`,
+ body,
+ undefined,
+ { timeoutMs: 20_000 },
+ ),
+};
diff --git a/examples/web_ui/frontend/src/api/session.ts b/examples/web_ui/frontend/src/api/session.ts
index eaee9222c..4bde161cf 100644
--- a/examples/web_ui/frontend/src/api/session.ts
+++ b/examples/web_ui/frontend/src/api/session.ts
@@ -12,6 +12,7 @@ import type {
export interface MessagesResponse {
messages: Msg[];
+ event_cursor: string | null;
is_running: boolean;
has_more: boolean;
}
@@ -104,16 +105,21 @@ export const sessionApi = {
* @param sessionId - The session to subscribe to.
* @param agentId - The agent that owns the session.
* @param signal - Optional abort signal to close the connection.
+ * @param after - Optional persisted-event cursor to resume after.
* @returns An async generator yielding ``AgentEvent`` objects.
*/
streamEvents: async function* (
sessionId: string,
agentId: string,
signal?: AbortSignal,
+ after?: string | null,
): AsyncGenerator<AgentEvent> {
const res = await client.stream(`/sessions/${sessionId}/stream`, {
method: 'GET',
- params: { agent_id: agentId },
+ params: {
+ agent_id: agentId,
+ ...(after != null && { after }),
+ },
signal,
});
diff --git a/examples/web_ui/frontend/src/api/types.ts b/examples/web_ui/frontend/src/api/types.ts
index b3be4719f..aba7c2729 100644
--- a/examples/web_ui/frontend/src/api/types.ts
+++ b/examples/web_ui/frontend/src/api/types.ts
@@ -20,6 +20,13 @@ export interface TTSModelConfig {
parameters: Record<string, unknown>;
}
+export interface RealtimeModelConfig {
+ type: string;
+ credential_id: string;
+ model: string;
+ parameters: Record<string, unknown>;
+}
+
export interface ContextConfig {
trigger_ratio?: number;
reserve_ratio?: number;
@@ -40,13 +47,21 @@ export interface InviteConfig {
// ─── Agent ────────────────────────────────────────────────────────────────────
+/** Settings that apply when the agent talks in text. */
+export interface ChatConfig {
+ context_config: ContextConfig;
+ react_config: ReActConfig;
+ invite_config: InviteConfig;
+}
+
+/** Partial text-mode settings accepted by create and update requests. */
+export type ChatConfigInput = Partial<ChatConfig>;
+
export interface AgentData {
id: string;
name: string;
system_prompt: string;
- context_config: ContextConfig;
- react_config: ReActConfig;
- invite_config: InviteConfig;
+ chat_config: ChatConfig;
}
export interface AgentView extends RecordBase {
@@ -62,8 +77,12 @@ export interface AgentView extends RecordBase {
export interface CreateAgentRequest {
name: string;
system_prompt?: string;
+ chat_config?: ChatConfigInput;
+ /** @deprecated Use `chat_config.context_config`. */
context_config?: ContextConfig;
+ /** @deprecated Use `chat_config.react_config`. */
react_config?: ReActConfig;
+ /** @deprecated Use `chat_config.invite_config`. */
invite_config?: InviteConfig;
}
@@ -74,8 +93,12 @@ export interface CreateAgentResponse {
export interface UpdateAgentRequest {
name?: string;
system_prompt?: string;
+ chat_config?: ChatConfigInput;
+ /** @deprecated Use `chat_config.context_config`. */
context_config?: ContextConfig;
+ /** @deprecated Use `chat_config.react_config`. */
react_config?: ReActConfig;
+ /** @deprecated Use `chat_config.invite_config`. */
invite_config?: InviteConfig;
}
@@ -99,11 +122,10 @@ export interface AgentSchemaResponse {
/**
* Response of `GET /agent/schema/v2`. `schema` is the full `AgentData`
* JSON Schema (with `$ref`s inlined, `id` filtered out, and
- * `context_config.summary_schema` filtered out). The frontend derives
- * its section grouping directly from `schema.properties`:
+ * `chat_config.context_config.summary_schema` filtered out). The
+ * frontend derives its section grouping directly from `schema`:
* - top-level scalar/textarea/boolean properties → "identity" section
- * - top-level `object`-typed properties (currently `context_config`,
- * `react_config`, and `invite_config`) → one section each
+ * - each object under a mode block (`chat_config`) → one section
*/
export interface AgentSchemaV2Response {
schema: JSONSchema;
@@ -135,6 +157,8 @@ export interface SessionConfig {
fallback_chat_model_config: ChatModelConfig | null;
/** TTS model configuration. null means TTS is not enabled. */
tts_model_config: TTSModelConfig | null;
+ /** Realtime voice model configuration. null disables voice mode. */
+ realtime_model_config: RealtimeModelConfig | null;
/** Knowledge bases attached to this session + KB middleware parameters. */
knowledge_config: SessionKnowledgeConfig | null;
workspace_id: string;
@@ -172,6 +196,8 @@ export interface CreateSessionRequest {
fallback_chat_model_config?: ChatModelConfig | null;
/** Optional TTS model. Omit (or pass null) for no TTS. */
tts_model_config?: TTSModelConfig | null;
+ /** Optional realtime voice model. Omit (or pass null) for none. */
+ realtime_model_config?: RealtimeModelConfig | null;
/** Optional knowledge base attachment. Omit (or null) for none. */
knowledge_config?: SessionKnowledgeConfig | null;
}
@@ -201,6 +227,8 @@ export interface UpdateSessionRequest {
* - set to a value → replace the existing TTS config
*/
tts_model_config?: TTSModelConfig | null;
+ /** New realtime voice model, or null to disable voice mode. */
+ realtime_model_config?: RealtimeModelConfig | null;
/**
* New knowledge base attachment. PATCH semantics:
* - omit the field → leave unchanged
@@ -811,6 +839,53 @@ export interface ListModelResponse {
total: number;
}
+export interface RealtimeModelCard {
+ type: 'realtime_model';
+ model_type: string;
+ name: string;
+ label: string;
+ status: 'active' | 'deprecated' | 'sunset';
+ deprecated_at: string | null;
+ input_types: string[];
+ output_types: string[];
+ input_sample_rate: number;
+ output_sample_rate: number;
+ supports_tools: boolean;
+ max_context_tokens: number | null;
+ max_audio_turns: number | null;
+ max_audio_duration_s: number | null;
+ max_session_duration_s: number | null;
+ parameter_schema: Record<string, unknown>;
+ parameter_overrides: Record<string, Record<string, unknown>>;
+}
+
+export interface ListRealtimeModelResponse {
+ models: RealtimeModelCard[];
+ total: number;
+}
+
+export interface RealtimeIceServer {
+ urls: string | string[];
+ username?: string;
+ credential?: string;
+ credentialType?: 'password' | 'oauth';
+}
+
+export interface RealtimeConfigResponse {
+ ice_servers: RealtimeIceServer[];
+}
+
+export interface RealtimeOfferRequest {
+ agent_id: string;
+ sdp: string;
+ type: 'offer';
+}
+
+export interface RealtimeOfferResponse {
+ sdp: string;
+ type: 'answer';
+}
+
// ─── Embedding ────────────────────────────────────────────────────────────────
export interface EmbeddingModelConfig {
diff --git a/examples/web_ui/frontend/src/components/chat/ChatContent.tsx b/examples/web_ui/frontend/src/components/chat/ChatContent.tsx
index 4c0cb3859..cdc61294b 100644
--- a/examples/web_ui/frontend/src/components/chat/ChatContent.tsx
+++ b/examples/web_ui/frontend/src/components/chat/ChatContent.tsx
@@ -30,6 +30,7 @@ import {
import { Spinner } from '@/components/ui/spinner';
import type { ReplyPhase } from '@/hooks/useMessages';
import { useTranslation } from '@/i18n/useI18n';
+import type { RealtimeConnectionState } from '@/lib/browserWebRTCTransport';
import { cn } from '@/lib/utils';
/** How long a load may run before it is worth showing a spinner. */
@@ -69,7 +70,7 @@ interface ChatContentProps {
loading?: boolean;
/**
* Reply lifecycle phase from ``useMessages`` — forwarded to
- * ``TextInput`` so the single send / stop button can pick its
+ * ``TextInput`` so the shared voice / send / stop button can pick its
* icon, tooltip, disabled state and click handler from one source.
*/
phase: ReplyPhase;
@@ -85,6 +86,9 @@ interface ChatContentProps {
className?: string;
/** Called when the user clicks the stop button. */
onInterrupt?: () => void;
+ voiceState?: RealtimeConnectionState;
+ onVoiceToggle?: () => void;
+ voiceDisabled?: boolean;
/**
* Optional content pinned at the bottom of the chat — between the
* message scroll area and the text input (e.g. pending subagent HITL
@@ -121,6 +125,9 @@ const ChatContentComponent: React.FC<ChatContentProps> = ({
autoComplete,
className,
onInterrupt,
+ voiceState,
+ onVoiceToggle,
+ voiceDisabled,
footerSlot,
allowedInputTypes,
fileProcessor,
@@ -295,6 +302,9 @@ const ChatContentComponent: React.FC<ChatContentProps> = ({
fileProcessor={fileProcessor}
phase={phase}
onInterrupt={onInterrupt}
+ voiceState={voiceState}
+ onVoiceToggle={onVoiceToggle}
+ voiceDisabled={voiceDisabled}
headerSlot={
<div className="flex w-full items-center justify-between px-2 py-1 text-sm text-muted-foreground">
<WorkingDirectoryDialog
diff --git a/examples/web_ui/frontend/src/components/chat/TextInput.tsx b/examples/web_ui/frontend/src/components/chat/TextInput.tsx
index 4678892da..33c9871a5 100644
--- a/examples/web_ui/frontend/src/components/chat/TextInput.tsx
+++ b/examples/web_ui/frontend/src/components/chat/TextInput.tsx
@@ -1,5 +1,6 @@
import type { ContentBlock, TextBlock } from '@agentscope-ai/agentscope/message';
import {
+ AudioLines,
Paperclip,
Loader2,
Square,
@@ -34,6 +35,7 @@ import {
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import type { ReplyPhase } from '@/hooks/useMessages';
import { useTranslation } from '@/i18n/useI18n.ts';
+import type { RealtimeConnectionState } from '@/lib/browserWebRTCTransport';
import { cn } from '@/lib/utils';
/**
@@ -77,13 +79,19 @@ interface TextInputProps {
fileProcessor: (file: File) => Promise<ContentBlock | null>;
/**
* The current reply lifecycle phase from ``useMessages``. Drives the
- * send / stop button in one shot:
+ * primary action button when realtime voice is inactive:
* - ``idle`` — Send (enabled when there is content to send)
* - ``streaming`` — Stop (click to interrupt)
* - ``interrupting`` — Stop (disabled while the interrupt is in flight)
*/
phase?: ReplyPhase;
onInterrupt?: () => void;
+ /** Current browser realtime voice connection state. */
+ voiceState?: RealtimeConnectionState;
+ /** Starts or stops the browser realtime voice connection. */
+ onVoiceToggle?: () => void;
+ /** Prevents voice start when no realtime model is configured. */
+ voiceDisabled?: boolean;
/**
* Content rendered directly above the input pill, inside the outer
* wrapper that {@link className} styles (e.g. the working directory
@@ -139,6 +147,9 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(
fileProcessor,
phase = 'idle',
onInterrupt,
+ voiceState = 'idle',
+ onVoiceToggle,
+ voiceDisabled = false,
headerSlot,
},
ref,
@@ -249,20 +260,40 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(
};
/**
- * Send / stop button configuration derived from the current reply
- * phase. One struct = one branch of rendering, so the JSX stays flat.
+ * Primary action configuration derived from realtime voice, reply,
+ * and text input state. One struct keeps the JSX branch-free.
*/
- const sendButton: {
+ const actionButton: {
icon: LucideIcon;
tooltip: string;
disabled: boolean;
+ variant: 'default' | 'ghost';
onClick: (() => void) | undefined;
} = (() => {
+ if (voiceState === 'connecting') {
+ return {
+ icon: Loader2,
+ tooltip: t('realtime.stop'),
+ disabled: false,
+ variant: 'default',
+ onClick: onVoiceToggle,
+ };
+ }
+ if (voiceState === 'active') {
+ return {
+ icon: Square,
+ tooltip: t('realtime.stop'),
+ disabled: false,
+ variant: 'default',
+ onClick: onVoiceToggle,
+ };
+ }
if (phase === 'streaming') {
return {
icon: Square,
tooltip: t('textInput.stop'),
disabled: false,
+ variant: 'default',
onClick: onInterrupt,
};
}
@@ -271,14 +302,25 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(
icon: Square,
tooltip: t('textInput.stopping'),
disabled: true,
+ variant: 'default',
onClick: onInterrupt,
};
}
+ if (value.trim()) {
+ return {
+ icon: ArrowUp,
+ tooltip: t('textInput.send'),
+ disabled: disabled || hasProcessing,
+ variant: 'default',
+ onClick: handleSend,
+ };
+ }
return {
- icon: ArrowUp,
- tooltip: t('textInput.send'),
- disabled: disabled || !value.trim() || hasProcessing,
- onClick: handleSend,
+ icon: AudioLines,
+ tooltip: voiceDisabled ? t('realtime.selectFirst') : t('realtime.start'),
+ disabled: voiceDisabled,
+ variant: 'ghost',
+ onClick: onVoiceToggle,
};
})();
@@ -502,20 +544,30 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(
</TooltipContent>
</Tooltip>
- {/* Send / Stop button — driven by ``sendButton`` config */}
+ {/* Voice / Send / Stop — driven by ``actionButton`` config */}
<Tooltip>
<TooltipTrigger asChild>
<Button
type="button"
- onClick={sendButton.onClick}
- disabled={sendButton.disabled}
+ variant={actionButton.variant}
+ onClick={actionButton.onClick}
+ disabled={actionButton.disabled}
size="icon-lg"
- className="shrink-0 rounded-full"
+ className={cn(
+ 'relative shrink-0 rounded-full transition-colors',
+ voiceState === 'active' &&
+ 'before:absolute before:inset-[-4px] before:rounded-full before:border before:border-primary/30 before:animate-pulse',
+ )}
>
- <sendButton.icon className="h-4 w-4" />
+ <actionButton.icon
+ className={cn(
+ 'h-4 w-4',
+ voiceState === 'connecting' && 'animate-spin',
+ )}
+ />
</Button>
</TooltipTrigger>
- <TooltipContent>{sendButton.tooltip}</TooltipContent>
+ <TooltipContent>{actionButton.tooltip}</TooltipContent>
</Tooltip>
{/* Hidden file input */}
diff --git a/examples/web_ui/frontend/src/components/dialog/AgentDialog.tsx b/examples/web_ui/frontend/src/components/dialog/AgentDialog.tsx
index df611bced..301a5ef4c 100644
--- a/examples/web_ui/frontend/src/components/dialog/AgentDialog.tsx
+++ b/examples/web_ui/frontend/src/components/dialog/AgentDialog.tsx
@@ -67,9 +67,11 @@ export function AgentDialog({ onCreated, children }: Props) {
{
name,
system_prompt: values.identity.system_prompt as string | undefined,
- context_config: values.context_config as unknown as ContextConfig,
- react_config: values.react_config as unknown as ReActConfig,
- invite_config: values.invite_config as unknown as InviteConfig,
+ chat_config: {
+ context_config: values.context_config as unknown as ContextConfig,
+ react_config: values.react_config as unknown as ReActConfig,
+ invite_config: values.invite_config as unknown as InviteConfig,
+ },
},
{ silent: true },
);
diff --git a/examples/web_ui/frontend/src/components/dialog/EditAgentDialog.tsx b/examples/web_ui/frontend/src/components/dialog/EditAgentDialog.tsx
index 859e9c126..dc6ae6622 100644
--- a/examples/web_ui/frontend/src/components/dialog/EditAgentDialog.tsx
+++ b/examples/web_ui/frontend/src/components/dialog/EditAgentDialog.tsx
@@ -57,9 +57,9 @@ export function EditAgentDialog({ open, onOpenChange, agent, onUpdated }: Props)
name: d.name,
system_prompt: d.system_prompt,
},
- context_config: { ...base.context_config, ...(d.context_config ?? {}) },
- react_config: { ...base.react_config, ...(d.react_config ?? {}) },
- invite_config: { ...base.invite_config, ...(d.invite_config ?? {}) },
+ context_config: { ...base.context_config, ...d.chat_config.context_config },
+ react_config: { ...base.react_config, ...d.chat_config.react_config },
+ invite_config: { ...base.invite_config, ...d.chat_config.invite_config },
});
setErrorMsg('');
}, [open, schema, agent]);
@@ -83,9 +83,11 @@ export function EditAgentDialog({ open, onOpenChange, agent, onUpdated }: Props)
{
name,
system_prompt: values.identity.system_prompt as string | undefined,
- context_config: values.context_config as unknown as ContextConfig,
- react_config: values.react_config as unknown as ReActConfig,
- invite_config: values.invite_config as unknown as InviteConfig,
+ chat_config: {
+ context_config: values.context_config as unknown as ContextConfig,
+ react_config: values.react_config as unknown as ReActConfig,
+ invite_config: values.invite_config as unknown as InviteConfig,
+ },
},
{ silent: true },
);
diff --git a/examples/web_ui/frontend/src/components/form/AgentFormFields.tsx b/examples/web_ui/frontend/src/components/form/AgentFormFields.tsx
index 030a8e339..ee700083e 100644
--- a/examples/web_ui/frontend/src/components/form/AgentFormFields.tsx
+++ b/examples/web_ui/frontend/src/components/form/AgentFormFields.tsx
@@ -23,11 +23,12 @@ interface Props {
}
/**
- * Section derivation from the flat `AgentData` schema. Ordered — controls
- * the visual order of the fieldsets. "identity" carries every top-level
- * property that is NOT one of the nested-object sections below, so any
- * newly added scalar / boolean / textarea field on `AgentData` shows up
- * in the identity fieldset automatically.
+ * Section derivation from the `AgentData` schema. Ordered — controls the
+ * visual order of the fieldsets. "identity" carries every top-level
+ * property that is not a mode block, so any newly added scalar / boolean
+ * / textarea field on `AgentData` shows up in the identity fieldset
+ * automatically; the sections below live one level down, inside the
+ * `chat_config` mode block.
*/
const NESTED_SECTIONS: Array<{ key: Exclude<AgentSection, 'identity'>; i18n: string }> = [
{ key: 'context_config', i18n: 'context-config' },
@@ -35,19 +36,25 @@ const NESTED_SECTIONS: Array<{ key: Exclude<AgentSection, 'identity'>; i18n: str
{ key: 'invite_config', i18n: 'invite-config' },
];
+/** Top-level `AgentData` properties that group one mode's settings. */
+const MODE_BLOCKS = ['chat_config'];
+
const IDENTITY_I18N = 'identity';
const toKebab = (s: string) => s.replace(/_/g, '-');
-/** Split the flat `AgentData` schema into the sections the form renders
+/** Split the `AgentData` schema into the sections the form renders
* (currently four: `identity` + one per `NESTED_SECTIONS` entry). */
function sliceSchema(root: JSONSchema): Record<AgentSection, JSONSchema> {
const props = root.properties ?? {};
- const nestedKeys = new Set(NESTED_SECTIONS.map((s) => s.key));
+ const chatProps = ((props.chat_config as JSONSchema)?.properties ?? {}) as Record<
+ string,
+ JSONSchemaProperty
+ >;
const identityProps: Record<string, JSONSchemaProperty> = {};
for (const [k, prop] of Object.entries(props)) {
- if (nestedKeys.has(k as Exclude<AgentSection, 'identity'>)) continue;
+ if (MODE_BLOCKS.includes(k)) continue;
identityProps[k] = prop;
}
@@ -55,22 +62,20 @@ function sliceSchema(root: JSONSchema): Record<AgentSection, JSONSchema> {
type: 'object',
title: 'Identity',
properties: identityProps,
- required: (root.required ?? []).filter(
- (r) => !nestedKeys.has(r as Exclude<AgentSection, 'identity'>),
- ),
+ required: (root.required ?? []).filter((r) => !MODE_BLOCKS.includes(r)),
};
return {
identity,
- context_config: (props.context_config as JSONSchema) ?? {
+ context_config: (chatProps.context_config as JSONSchema) ?? {
type: 'object',
properties: {},
},
- react_config: (props.react_config as JSONSchema) ?? {
+ react_config: (chatProps.react_config as JSONSchema) ?? {
type: 'object',
properties: {},
},
- invite_config: (props.invite_config as JSONSchema) ?? {
+ invite_config: (chatProps.invite_config as JSONSchema) ?? {
type: 'object',
properties: {},
},
diff --git a/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx b/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx
index 7c5fabe49..7b849c7a5 100644
--- a/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx
+++ b/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx
@@ -5,6 +5,8 @@ import type {
ChatModelConfig,
CredentialView,
ModelCard,
+ RealtimeModelCard,
+ RealtimeModelConfig,
TTSModelCard,
TTSModelConfig,
} from '@/api';
@@ -78,7 +80,7 @@ function resolveType(prop: ParameterProperty): ResolvedType {
return { type: 'string', enumValues: null };
}
-/** Extract default values from a TTS model card's parameter schema. */
+/** Extract default values from a model card's parameter schema. */
function extractDefaults(schema: ParameterSchema | undefined): Record<string, unknown> {
const defaults: Record<string, unknown> = {};
if (schema?.properties) {
@@ -117,8 +119,18 @@ function BooleanField({ id, label, prop, value, onChange }: FieldProps) {
);
}
-function EnumField({ id, label, required, prop, value, onChange }: FieldProps) {
- const enumValues = resolveType(prop).enumValues ?? [];
+function EnumField({
+ id,
+ label,
+ required,
+ prop,
+ value,
+ onChange,
+ excludedValues = [],
+}: FieldProps & { excludedValues?: unknown[] }) {
+ const enumValues = (resolveType(prop).enumValues ?? []).filter(
+ (option) => !excludedValues.includes(option),
+ );
// TODO: experiment with using prop.description as placeholder text
const displayValue = value !== undefined && value !== null ? String(value) : '';
@@ -218,9 +230,9 @@ function StringField({ id, label, required, prop, value, onChange }: FieldProps)
interface Props {
/** Currently selected primary model — used to read the parameter schema. */
- selectedModel: ChatModelConfig | null;
+ selectedModel: ChatModelConfig | RealtimeModelConfig | null;
/** Model card describing the primary model's parameter schema. */
- modelCard: ModelCard | null;
+ modelCard: ModelCard | RealtimeModelCard | null;
/** Called when the user edits the primary model's parameters. */
onChange: (parameters: Record<string, unknown>) => void;
/** Currently selected fallback model. `null` means no fallback configured. `undefined` hides the section. */
@@ -237,6 +249,14 @@ interface Props {
* whenever no primary model is selected.
*/
disabled?: boolean;
+ /** Prefix field ids when more than one parameter editor is rendered. */
+ idPrefix?: string;
+ /** Accessible label for the icon-only trigger. */
+ triggerLabel?: string;
+ /** Enum values unavailable in the current transport or UI. */
+ excludedEnumValues?: Record<string, unknown[]>;
+ /** Hide array fields when the caller has no array editor. */
+ hideArrayParameters?: boolean;
}
/**
@@ -257,6 +277,10 @@ export function ModelParametersPopover({
selectedTTSModel,
onTTSChange,
disabled: locked = false,
+ idPrefix = 'model',
+ triggerLabel,
+ excludedEnumValues,
+ hideArrayParameters = false,
}: Props) {
const [values, setValues] = useState<Record<string, unknown>>({});
const { t } = useTranslation();
@@ -266,11 +290,13 @@ export function ModelParametersPopover({
const schema = modelCard?.parameter_schema as ParameterSchema | undefined;
const properties = schema?.properties ?? {};
const required = schema?.required ?? [];
- const entries = Object.entries(properties);
+ const entries = Object.entries(properties).filter(
+ ([, prop]) => !hideArrayParameters || resolveType(prop).type !== 'array',
+ );
useEffect(() => {
setValues(selectedModel?.parameters ?? {});
- }, [selectedModel?.model]);
+ }, [selectedModel]);
const handleChange = useCallback(
(key: string, value: unknown) => {
@@ -307,7 +333,13 @@ export function ModelParametersPopover({
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
- <Button variant="ghost" size="icon-sm" disabled={disabled}>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ disabled={disabled}
+ aria-label={triggerLabel}
+ title={triggerLabel}
+ >
<SlidersHorizontal />
</Button>
</DropdownMenuTrigger>
@@ -427,68 +459,76 @@ export function ModelParametersPopover({
<DropdownMenuSubTrigger>
{t('model-parameters.parametersLabel')}
</DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="w-80 max-h-96 overflow-y-auto p-3">
- <div className="mb-3">
- <p className="text-sm font-medium">{t('model-parameters.title')}</p>
- <p className="text-muted-foreground text-xs">
- {t('model-parameters.description')}
- </p>
- </div>
- {entries.length === 0 ? (
- <p className="text-muted-foreground text-xs">
- {t('model-parameters.empty')}
- </p>
- ) : (
- <div
- className="grid grid-cols-[auto_1fr] items-center gap-x-3 gap-y-3"
- onPointerDown={(e) => e.stopPropagation()}
- onKeyDown={(e) => e.stopPropagation()}
- >
- {entries.map(([key, prop]) => {
- const { type: effectiveType, enumValues } = resolveType(prop);
- const label = prop.title ?? key;
- const isRequired = required.includes(key);
- const fieldProps: FieldProps = {
- id: `param-${key}`,
- label,
- required: isRequired,
- prop,
- value: values[key],
- onChange: (v) => handleChange(key, v),
- };
-
- let field: React.ReactNode;
- if (effectiveType === 'boolean') {
- field = <BooleanField {...fieldProps} />;
- } else if (enumValues) {
- field = <EnumField {...fieldProps} />;
- } else if (
- effectiveType === 'number' ||
- effectiveType === 'integer'
- ) {
- field = <NumberField {...fieldProps} />;
- } else {
- field = <StringField {...fieldProps} />;
- }
-
- return (
- <Tooltip key={key}>
- <TooltipTrigger asChild>
- <div className="col-span-2 grid grid-cols-subgrid items-center">
- {field}
- </div>
- </TooltipTrigger>
- {prop.description && (
- <TooltipContent side="left">
- {prop.description}
- </TooltipContent>
- )}
- </Tooltip>
- );
- })}
+ <DropdownMenuPortal>
+ <DropdownMenuSubContent className="w-80 max-h-(--radix-dropdown-menu-content-available-height) overflow-x-hidden overflow-y-auto p-3">
+ <div className="mb-3">
+ <p className="text-sm font-medium">{t('model-parameters.title')}</p>
+ <p className="text-muted-foreground text-xs">
+ {t('model-parameters.description')}
+ </p>
</div>
- )}
- </DropdownMenuSubContent>
+ {entries.length === 0 ? (
+ <p className="text-muted-foreground text-xs">
+ {t('model-parameters.empty')}
+ </p>
+ ) : (
+ <div
+ className="grid grid-cols-[auto_1fr] items-center gap-x-3 gap-y-3"
+ onPointerDown={(e) => e.stopPropagation()}
+ onKeyDown={(e) => e.stopPropagation()}
+ >
+ {entries.map(([key, prop]) => {
+ const { type: effectiveType, enumValues } =
+ resolveType(prop);
+ const label = prop.title ?? key;
+ const isRequired = required.includes(key);
+ const fieldProps: FieldProps = {
+ id: `param-${idPrefix}-${key}`,
+ label,
+ required: isRequired,
+ prop,
+ value: values[key],
+ onChange: (v) => handleChange(key, v),
+ };
+
+ let field: React.ReactNode;
+ if (effectiveType === 'boolean') {
+ field = <BooleanField {...fieldProps} />;
+ } else if (enumValues) {
+ field = (
+ <EnumField
+ {...fieldProps}
+ excludedValues={excludedEnumValues?.[key]}
+ />
+ );
+ } else if (
+ effectiveType === 'number' ||
+ effectiveType === 'integer'
+ ) {
+ field = <NumberField {...fieldProps} />;
+ } else {
+ field = <StringField {...fieldProps} />;
+ }
+
+ return (
+ <Tooltip key={key}>
+ <TooltipTrigger asChild>
+ <div className="col-span-2 grid grid-cols-subgrid items-center">
+ {field}
+ </div>
+ </TooltipTrigger>
+ {prop.description && (
+ <TooltipContent side="left">
+ {prop.description}
+ </TooltipContent>
+ )}
+ </Tooltip>
+ );
+ })}
+ </div>
+ )}
+ </DropdownMenuSubContent>
+ </DropdownMenuPortal>
</DropdownMenuSub>
{/* ----- TTS ----- */}
diff --git a/examples/web_ui/frontend/src/components/select/LlmSelect.tsx b/examples/web_ui/frontend/src/components/select/LlmSelect.tsx
index 4ff680f3c..97815064a 100644
--- a/examples/web_ui/frontend/src/components/select/LlmSelect.tsx
+++ b/examples/web_ui/frontend/src/components/select/LlmSelect.tsx
@@ -1,5 +1,4 @@
import { ChevronDown, PlusCircle, Ban } from 'lucide-react';
-import { useEffect } from 'react';
import type { ChatModelConfig } from '@/api';
import { Button } from '@/components/ui/button';
@@ -29,7 +28,6 @@ interface Props extends Omit<React.ComponentPropsWithoutRef<typeof Button>, 'onC
*/
onChange?: (value: ChatModelConfig | null) => void;
onAddCredential?: () => void;
- refetchTrigger?: number;
/** Override the trigger label shown when no model is selected. */
placeholder?: string;
/**
@@ -45,14 +43,13 @@ export function LlmSelect({
value,
onChange,
onAddCredential,
- refetchTrigger,
placeholder,
allowClear = false,
clearLabel,
className,
...props
}: Props) {
- const { groups, loading, refetch } = useAvailableModels();
+ const { groups, loading } = useAvailableModels();
const { t } = useTranslation();
// Credentials whose model list failed to load come back with an empty
// `models` array; drop them so they don't render empty submenus
@@ -61,10 +58,6 @@ export function LlmSelect({
.filter(([, usable]) => usable.length > 0);
const hasOptions = groupEntries.length > 0;
- useEffect(() => {
- if (refetchTrigger !== undefined && refetchTrigger > 0) refetch();
- }, [refetchTrigger, refetch]);
-
const handleSelect = (type: string, credentialId: string, model: string) => {
onChange?.({ type, credential_id: credentialId, model, parameters: {} });
};
diff --git a/examples/web_ui/frontend/src/components/select/RealtimeModelSelect.tsx b/examples/web_ui/frontend/src/components/select/RealtimeModelSelect.tsx
new file mode 100644
index 000000000..407f54310
--- /dev/null
+++ b/examples/web_ui/frontend/src/components/select/RealtimeModelSelect.tsx
@@ -0,0 +1,135 @@
+import { AudioLines, Ban, ChevronDown, PlusCircle } from 'lucide-react';
+
+import type { RealtimeModelCard, RealtimeModelConfig } from '@/api';
+import { Button } from '@/components/ui/button';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuPortal,
+ DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { useAvailableRealtimeModels } from '@/hooks/useAvailableRealtimeModels';
+import { useTranslation } from '@/i18n/useI18n';
+import { cn } from '@/lib/utils';
+import { credentialLabel } from '@/utils/common';
+
+interface Props extends Omit<React.ComponentPropsWithoutRef<typeof Button>, 'onChange' | 'value'> {
+ value?: RealtimeModelConfig | null;
+ onChange?: (value: RealtimeModelConfig | null) => void;
+ onAddCredential?: () => void;
+}
+
+function parameterDefaults(model: RealtimeModelCard): Record<string, unknown> {
+ const schema = model.parameter_schema as {
+ properties?: Record<string, { default?: unknown }>;
+ };
+ return Object.fromEntries(
+ Object.entries(schema.properties ?? {})
+ .filter(([, property]) => property.default !== undefined)
+ .map(([name, property]) => [name, property.default]),
+ );
+}
+
+export function RealtimeModelSelect({
+ value,
+ onChange,
+ onAddCredential,
+ className,
+ ...props
+}: Props) {
+ const { groups, loading } = useAvailableRealtimeModels();
+ const { t } = useTranslation();
+ const entries = Object.entries(groups);
+
+ const handleSelect = (credentialId: string, model: RealtimeModelCard) => {
+ onChange?.({
+ type: model.model_type,
+ credential_id: credentialId,
+ model: model.name,
+ parameters: parameterDefaults(model),
+ });
+ };
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="ghost"
+ size="sm"
+ className={cn('max-w-52 justify-between gap-1 font-mono', className)}
+ {...props}
+ >
+ <AudioLines className="size-4 shrink-0" />
+ <span className="hidden max-w-32 truncate lg:inline">
+ {value?.model ?? t('realtime.selectModel')}
+ </span>
+ <ChevronDown className="size-3.5 shrink-0 text-muted-foreground" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="min-w-56 max-h-72 overflow-y-auto">
+ {!loading && entries.length === 0 ? (
+ <div className="px-3 py-4 text-center text-sm text-muted-foreground">
+ {t('realtime.noModels')}
+ </div>
+ ) : (
+ entries.map(([provider, items], index) => (
+ <DropdownMenuGroup key={provider}>
+ {index > 0 && <DropdownMenuSeparator />}
+ <DropdownMenuLabel>
+ {provider.replace(/_credential$/, '')}
+ </DropdownMenuLabel>
+ {items.length === 1
+ ? items[0].models.map((model) => (
+ <DropdownMenuItem
+ key={`${model.model_type}:${model.name}`}
+ onSelect={() =>
+ handleSelect(items[0].credential.id, model)
+ }
+ >
+ {model.label}
+ </DropdownMenuItem>
+ ))
+ : items.map(({ credential, models }) => (
+ <DropdownMenuSub key={credential.id}>
+ <DropdownMenuSubTrigger>
+ {credentialLabel(credential)}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuSubContent>
+ {models.map((model) => (
+ <DropdownMenuItem
+ key={`${model.model_type}:${model.name}`}
+ onSelect={() =>
+ handleSelect(credential.id, model)
+ }
+ >
+ {model.label}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuPortal>
+ </DropdownMenuSub>
+ ))}
+ </DropdownMenuGroup>
+ ))
+ )}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onSelect={() => onChange?.(null)} disabled={!value}>
+ <Ban className="size-4" />
+ {t('realtime.disable')}
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={onAddCredential}>
+ <PlusCircle className="size-4" />
+ {t('llm-select.addCredential')}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/examples/web_ui/frontend/src/hooks/useAvailableModels.ts b/examples/web_ui/frontend/src/hooks/useAvailableModels.ts
index e649a63d7..ccfd029ad 100644
--- a/examples/web_ui/frontend/src/hooks/useAvailableModels.ts
+++ b/examples/web_ui/frontend/src/hooks/useAvailableModels.ts
@@ -15,8 +15,7 @@ export interface CredentialWithModels {
*
* One credential list plus one model list per provider — the most expensive
* fan-out on the page, and every model picker in the app mounts it. Cached
- * under the shared default window and re-fetched on demand through
- * `refetch`, which is what the "credential just added" trigger calls.
+ * under a shared query key that credential mutations invalidate.
*/
async function fetchGroups(): Promise<Record<string, CredentialWithModels[]>> {
const { credentials } = await credentialApi.list();
@@ -54,7 +53,7 @@ async function fetchGroups(): Promise<Record<string, CredentialWithModels[]>> {
export const AVAILABLE_MODELS_KEY = ['available-models'];
export function useAvailableModels() {
- const { data, isPending, error, refetch } = useQuery({
+ const { data, isPending, error } = useQuery({
queryKey: AVAILABLE_MODELS_KEY,
queryFn: fetchGroups,
});
@@ -63,6 +62,5 @@ export function useAvailableModels() {
groups: data ?? {},
loading: isPending,
error: error as Error | null,
- refetch: () => void refetch(),
};
}
diff --git a/examples/web_ui/frontend/src/hooks/useAvailableRealtimeModels.ts b/examples/web_ui/frontend/src/hooks/useAvailableRealtimeModels.ts
new file mode 100644
index 000000000..4853592fa
--- /dev/null
+++ b/examples/web_ui/frontend/src/hooks/useAvailableRealtimeModels.ts
@@ -0,0 +1,54 @@
+import { useQuery } from '@tanstack/react-query';
+
+import { credentialApi, realtimeModelApi } from '@/api';
+import type { CredentialView, RealtimeModelCard } from '@/api';
+
+interface CredentialWithRealtimeModels {
+ credential: CredentialView;
+ models: RealtimeModelCard[];
+}
+
+async function fetchGroups(): Promise<Record<string, CredentialWithRealtimeModels[]>> {
+ const { credentials } = await credentialApi.list();
+ const result: Record<string, CredentialWithRealtimeModels[]> = {};
+ const credentialsByProvider: Record<string, CredentialView[]> = {};
+
+ for (const credential of credentials) {
+ const provider = credential.data.type as string | undefined;
+ if (!provider) continue;
+ (credentialsByProvider[provider] ??= []).push(credential);
+ }
+
+ await Promise.all(
+ Object.entries(credentialsByProvider).map(async ([provider, providerCredentials]) => {
+ try {
+ const { models } = await realtimeModelApi.list(provider);
+ if (models.length === 0) return;
+ const sortedModels = [...models].sort((a, b) =>
+ b.name.localeCompare(a.name, undefined, { numeric: true }),
+ );
+ result[provider] = providerCredentials.map((credential) => ({
+ credential,
+ models: sortedModels,
+ }));
+ } catch {
+ // A credential without realtime support is not an error for this picker.
+ }
+ }),
+ );
+
+ return result;
+}
+
+export const AVAILABLE_REALTIME_MODELS_KEY = ['available-realtime-models'];
+
+export function useAvailableRealtimeModels() {
+ const { data, isPending } = useQuery({
+ queryKey: AVAILABLE_REALTIME_MODELS_KEY,
+ queryFn: fetchGroups,
+ });
+ return {
+ groups: data ?? {},
+ loading: isPending,
+ };
+}
diff --git a/examples/web_ui/frontend/src/hooks/useCredentials.ts b/examples/web_ui/frontend/src/hooks/useCredentials.ts
index c015d4768..ee2c50d76 100644
--- a/examples/web_ui/frontend/src/hooks/useCredentials.ts
+++ b/examples/web_ui/frontend/src/hooks/useCredentials.ts
@@ -4,6 +4,7 @@ import { useState, useEffect, useCallback } from 'react';
import { credentialApi } from '../api';
import type { CredentialView, CreateCredentialRequest, UpdateCredentialRequest } from '../api';
import { AVAILABLE_MODELS_KEY } from './useAvailableModels';
+import { AVAILABLE_REALTIME_MODELS_KEY } from './useAvailableRealtimeModels';
/**
* Manages API key credentials with CRUD operations.
@@ -32,13 +33,14 @@ export function useCredentials() {
refetch();
}, [refetch]);
- // Every model picker reads its options from the cached
- // `available-models` query, which is derived from the credentials —
- // so a credential that just changed has to drop that cache too,
- // rather than leaving the pickers to time out of it.
+ // Every model picker derives its options from the credentials, so a
+ // credential change must invalidate both cached model catalogues.
const refresh = useCallback(async () => {
await refetch();
- await queryClient.invalidateQueries({ queryKey: AVAILABLE_MODELS_KEY });
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: AVAILABLE_MODELS_KEY }),
+ queryClient.invalidateQueries({ queryKey: AVAILABLE_REALTIME_MODELS_KEY }),
+ ]);
}, [refetch, queryClient]);
/** Stores a new credential and refreshes the list. */
diff --git a/examples/web_ui/frontend/src/hooks/useMessages.ts b/examples/web_ui/frontend/src/hooks/useMessages.ts
index 3d93538be..86e47a1c1 100644
--- a/examples/web_ui/frontend/src/hooks/useMessages.ts
+++ b/examples/web_ui/frontend/src/hooks/useMessages.ts
@@ -88,9 +88,10 @@ const INTERRUPT_TIMEOUT_MS = 10_000;
* background retrigger, team member message, …).
*
* The hook opens the SSE connection immediately after fetching
- * history. User input and human-in-the-loop confirmations are sent
- * via ``POST /chat/`` (fire-and-forget); the resulting events arrive
- * through the already-open SSE connection.
+ * history. User input is sent via ``POST /chat/``. Human-in-the-loop
+ * confirmations use the active realtime control channel during voice
+ * mode and ``POST /chat/`` otherwise. Resulting events arrive through
+ * the already-open SSE connection.
*
* ``phase`` is driven by event content, not HTTP lifecycle: it moves
* to ``streaming`` on ``ReplyStartEvent`` and back to ``idle`` on
@@ -131,6 +132,10 @@ export function useMessages(
* the session list to pick the new one up.
*/
onSessionUpdated?: () => void;
+ /** True when a dedicated realtime transport already plays PCM audio. */
+ isRealtimeAudioActive?: () => boolean;
+ /** Send a tool confirmation over the active realtime transport. */
+ sendRealtimeUserConfirm?: (event: UserConfirmResultEvent) => Promise<void>;
},
) {
const [msgs, setMsgs] = useState<Msg[]>([]);
@@ -218,15 +223,25 @@ export function useMessages(
currentReplyRef.current = existing;
} else {
audioManager?.stopAllPlayback();
- const msg = AssistantMsg({ id: e.reply_id, name: e.name, content: [] });
+ const msg =
+ e.role === 'user'
+ ? UserMsg({ id: e.reply_id, name: e.name, content: [] })
+ : AssistantMsg({ id: e.reply_id, name: e.name, content: [] });
msgsRef.current = [...msgsRef.current, msg];
currentReplyRef.current = msg;
}
clearInterruptTimer();
setPhase('streaming');
} else {
- if (currentReplyRef.current) {
- const reply = currentReplyRef.current;
+ // Realtime providers may start the assistant response before the
+ // user's final transcription arrives. Route every identified event
+ // to its own reply instead of assuming event streams never overlap.
+ const reply = event.reply_id
+ ? currentReplyRef.current?.id === event.reply_id
+ ? currentReplyRef.current
+ : (msgsRef.current.find((message) => message.id === event.reply_id) ?? null)
+ : currentReplyRef.current;
+ if (reply) {
appendEvent(reply, event);
// ``appendEvent`` mutates in place, which would leave
// every Msg identical across renders and force the whole
@@ -238,9 +253,16 @@ export function useMessages(
// everything else looks the reply up by id.
const updated = { ...reply, content: [...reply.content] };
msgsRef.current = msgsRef.current.map((m) => (m === reply ? updated : m));
- currentReplyRef.current = updated;
+ if (currentReplyRef.current?.id === reply.id) {
+ currentReplyRef.current = updated;
+ }
}
- if (event.type === EventType.REPLY_END) {
+ if (
+ event.type === EventType.REPLY_END &&
+ (!event.reply_id ||
+ currentReplyRef.current === null ||
+ currentReplyRef.current.id === event.reply_id)
+ ) {
clearInterruptTimer();
setPhase('idle');
currentReplyRef.current = null;
@@ -294,14 +316,19 @@ export function useMessages(
let cancelled = false;
(async () => {
+ let eventCursor: string | null = null;
// 1. Fetch persisted history — unless this tab just created the
// session, in which case there is provably none.
if (takeFreshlyCreated(sessionId)) {
if (!cancelled) setLoadedKey(`${agentId}:${sessionId}`);
} else {
try {
- const { messages, is_running } = await sessionApi.messages(sessionId, agentId);
+ const { messages, is_running, event_cursor } = await sessionApi.messages(
+ sessionId,
+ agentId,
+ );
if (cancelled) return;
+ eventCursor = event_cursor;
msgsRef.current = messages;
// If a reply is in flight (running on a worker) OR the
// tail msg is parked on a pending tool_call (awaiting
@@ -346,6 +373,7 @@ export function useMessages(
sessionId,
agentId,
controller.signal,
+ eventCursor,
)) {
if (cancelled) break;
processEvent(event);
@@ -394,9 +422,10 @@ export function useMessages(
);
/**
- * Confirm or deny a tool call (human-in-the-loop). Fires a
- * ``POST /chat/`` with a ``UserConfirmResultEvent``; events
- * arrive via SSE.
+ * Confirm or deny a tool call (human-in-the-loop). Sends a
+ * ``UserConfirmResultEvent`` through realtime control while voice mode
+ * is active, or through ``POST /chat/`` otherwise. Events arrive via
+ * SSE in both cases.
*
* @param toolCall - The tool call block to confirm/deny.
* @param confirm - Whether the user confirmed.
@@ -427,11 +456,18 @@ export function useMessages(
};
try {
- await chatApi.trigger({
- agent_id: agentId,
- session_id: sessionId,
- input: event,
- });
+ if (
+ optionsRef.current?.isRealtimeAudioActive?.() &&
+ optionsRef.current.sendRealtimeUserConfirm
+ ) {
+ await optionsRef.current.sendRealtimeUserConfirm(event);
+ } else {
+ await chatApi.trigger({
+ agent_id: agentId,
+ session_id: sessionId,
+ input: event,
+ });
+ }
} catch (e) {
setError(e as Error);
throw e;
diff --git a/examples/web_ui/frontend/src/hooks/useRealtimeVoice.ts b/examples/web_ui/frontend/src/hooks/useRealtimeVoice.ts
new file mode 100644
index 000000000..da08717c2
--- /dev/null
+++ b/examples/web_ui/frontend/src/hooks/useRealtimeVoice.ts
@@ -0,0 +1,69 @@
+import type { UserConfirmResultEvent } from '@agentscope-ai/agentscope/event';
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { toast } from 'sonner';
+
+import { BrowserWebRTCTransport, type RealtimeConnectionState } from '@/lib/browserWebRTCTransport';
+
+export function useRealtimeVoice(agentId: string | null, sessionId: string | null) {
+ const [state, setState] = useState<RealtimeConnectionState>('idle');
+ const transportRef = useRef<BrowserWebRTCTransport | null>(null);
+
+ const stop = useCallback(async () => {
+ const transport = transportRef.current;
+ transportRef.current = null;
+ if (transport) await transport.stop();
+ setState('idle');
+ }, []);
+
+ useEffect(() => {
+ setState('idle');
+ return () => {
+ const transport = transportRef.current;
+ if (transport) {
+ transportRef.current = null;
+ void transport.stop();
+ }
+ };
+ }, [agentId, sessionId]);
+
+ const start = useCallback(async () => {
+ if (!agentId || !sessionId || transportRef.current) return;
+ const transport = new BrowserWebRTCTransport({
+ agentId,
+ sessionId,
+ onStateChange: (nextState) => {
+ if (transportRef.current === transport) setState(nextState);
+ },
+ onError: (error) => {
+ if (transportRef.current !== transport) return;
+ transportRef.current = null;
+ setState('error');
+ toast.error(error.message);
+ },
+ });
+ transportRef.current = transport;
+ try {
+ await transport.start();
+ } catch (error) {
+ await transport.stop();
+ if (transportRef.current === transport) {
+ transportRef.current = null;
+ setState('error');
+ toast.error(error instanceof Error ? error.message : 'Voice mode failed to start.');
+ }
+ }
+ }, [agentId, sessionId]);
+
+ const toggle = useCallback(async () => {
+ if (state === 'active' || state === 'connecting') await stop();
+ else await start();
+ }, [start, state, stop]);
+
+ const userConfirm = useCallback(async (event: UserConfirmResultEvent) => {
+ const transport = transportRef.current;
+ if (!transport) throw new Error('Realtime voice mode is not active.');
+ transport.userConfirm(event);
+ }, []);
+
+ return { state, toggle, userConfirm };
+}
diff --git a/examples/web_ui/frontend/src/i18n/locales/en.json b/examples/web_ui/frontend/src/i18n/locales/en.json
index a887957df..aa3afff06 100644
--- a/examples/web_ui/frontend/src/i18n/locales/en.json
+++ b/examples/web_ui/frontend/src/i18n/locales/en.json
@@ -444,6 +444,15 @@
"clear": "Clear selection",
"noFallback": "No fallback"
},
+ "realtime": {
+ "selectModel": "Voice model",
+ "parameters": "Realtime voice parameters",
+ "noModels": "No realtime voice models are available.",
+ "disable": "Disable voice model",
+ "selectFirst": "Select a voice model first",
+ "start": "Start voice conversation",
+ "stop": "End voice conversation"
+ },
"embedding-select": {
"placeholder": "Select an embedding model",
"loading": "Loading…",
diff --git a/examples/web_ui/frontend/src/i18n/locales/zh.json b/examples/web_ui/frontend/src/i18n/locales/zh.json
index 6249ac4a4..f79787048 100644
--- a/examples/web_ui/frontend/src/i18n/locales/zh.json
+++ b/examples/web_ui/frontend/src/i18n/locales/zh.json
@@ -444,6 +444,15 @@
"clear": "清除选择",
"noFallback": "无兜底模型"
},
+ "realtime": {
+ "selectModel": "语音模型",
+ "parameters": "实时语音参数",
+ "noModels": "暂无可用的实时语音模型。",
+ "disable": "停用语音模型",
+ "selectFirst": "请先选择语音模型",
+ "start": "开始语音对话",
+ "stop": "结束语音对话"
+ },
"embedding-select": {
"placeholder": "选择 Embedding 模型",
"loading": "加载中…",
diff --git a/examples/web_ui/frontend/src/lib/browserWebRTCTransport.ts b/examples/web_ui/frontend/src/lib/browserWebRTCTransport.ts
new file mode 100644
index 000000000..eb66ffc0b
--- /dev/null
+++ b/examples/web_ui/frontend/src/lib/browserWebRTCTransport.ts
@@ -0,0 +1,367 @@
+import type { UserConfirmResultEvent } from '@agentscope-ai/agentscope/event';
+
+import { realtimeApi } from '@/api';
+
+export type RealtimeConnectionState = 'idle' | 'connecting' | 'active' | 'error';
+
+interface BrowserWebRTCTransportOptions {
+ agentId: string;
+ sessionId: string;
+ onStateChange: (state: RealtimeConnectionState) => void;
+ onError: (error: Error) => void;
+}
+
+interface AudioStartFrame {
+ type: 'audio_start';
+ item_id: string;
+ track_time_ms: number;
+}
+
+interface AudioDurationFrame {
+ type: 'audio_duration';
+ item_id: string;
+ duration_ms: number;
+}
+
+interface ClearAudioFrame {
+ type: 'clear_audio';
+ request_id: string;
+ resume_track_time_ms: number;
+}
+
+interface ErrorFrame {
+ type: 'error';
+ detail: string;
+}
+
+type ServerFrame = AudioStartFrame | AudioDurationFrame | ClearAudioFrame | ErrorFrame;
+
+const ICE_GATHERING_TIMEOUT_MS = 10_000;
+const CONNECTION_TIMEOUT_MS = 20_000;
+const PLAYOUT_FENCE_POLL_MS = 20;
+const PLAYOUT_FENCE_POLL_TIMEOUT_MS = 5_000;
+
+/** WebRTC microphone, model audio, and DataChannel control transport. */
+export class BrowserWebRTCTransport {
+ private readonly options: BrowserWebRTCTransportOptions;
+ private peerConnection: RTCPeerConnection | null = null;
+ private controlChannel: RTCDataChannel | null = null;
+ private localStream: MediaStream | null = null;
+ private remoteStream: MediaStream | null = null;
+ private audioElement: HTMLAudioElement | null = null;
+ private progressTimer: number | null = null;
+ private playoutFenceTimer: number | null = null;
+ private playoutFenceAudio: HTMLAudioElement | null = null;
+ private playoutFenceListener: (() => void) | null = null;
+ private readonly itemStarts: AudioStartFrame[] = [];
+ private readonly durationsMs = new Map<string, number>();
+ private intentionalClose = false;
+ private failed = false;
+ private active = false;
+ private failureError: Error | null = null;
+
+ constructor(options: BrowserWebRTCTransportOptions) {
+ this.options = options;
+ }
+
+ async start(): Promise<void> {
+ this.intentionalClose = false;
+ this.failed = false;
+ this.active = false;
+ this.failureError = null;
+ this.options.onStateChange('connecting');
+ if (!navigator.mediaDevices?.getUserMedia || !window.RTCPeerConnection) {
+ throw new Error('WebRTC microphone capture is not available in this browser.');
+ }
+
+ const { ice_servers: iceServers } = await realtimeApi.config();
+ this.throwIfStopped();
+ const localStream = await navigator.mediaDevices.getUserMedia({
+ audio: {
+ channelCount: 1,
+ echoCancellation: true,
+ noiseSuppression: true,
+ autoGainControl: true,
+ },
+ });
+ this.localStream = localStream;
+ this.throwIfStopped();
+
+ const peerConnection = new RTCPeerConnection({ iceServers });
+ this.peerConnection = peerConnection;
+ const controlChannel = peerConnection.createDataChannel('control', {
+ ordered: true,
+ });
+ this.controlChannel = controlChannel;
+ controlChannel.onmessage = (event) => this.handleMessage(event.data);
+ controlChannel.onclose = () => {
+ if (!this.intentionalClose) {
+ this.fail(new Error('The realtime control channel was closed.'));
+ }
+ };
+
+ peerConnection.ontrack = (event) => this.attachRemoteTrack(event.track);
+ peerConnection.onconnectionstatechange = () => {
+ if (
+ !this.intentionalClose &&
+ (peerConnection.connectionState === 'failed' ||
+ peerConnection.connectionState === 'closed')
+ ) {
+ this.fail(new Error('The realtime media connection was lost.'));
+ }
+ };
+ for (const track of localStream.getTracks()) {
+ peerConnection.addTrack(track, localStream);
+ }
+
+ const channelReady = this.waitForControlChannel(controlChannel);
+ void channelReady.catch(() => undefined);
+ const offer = await peerConnection.createOffer();
+ this.throwIfStopped();
+ await peerConnection.setLocalDescription(offer);
+ await this.waitForIceGathering(peerConnection);
+ this.throwIfStopped();
+ const localDescription = peerConnection.localDescription;
+ if (!localDescription || localDescription.type !== 'offer') {
+ throw new Error('The browser did not produce a WebRTC offer.');
+ }
+
+ const answer = await realtimeApi.offer(this.options.sessionId, {
+ agent_id: this.options.agentId,
+ sdp: localDescription.sdp,
+ type: 'offer',
+ });
+ this.throwIfStopped();
+ await peerConnection.setRemoteDescription({
+ sdp: answer.sdp,
+ type: answer.type,
+ });
+ await channelReady;
+ this.throwIfStopped();
+
+ this.progressTimer = window.setInterval(() => this.reportPlayout(), 100);
+ this.active = true;
+ this.options.onStateChange('active');
+ }
+
+ async stop(): Promise<void> {
+ this.intentionalClose = true;
+ if (this.progressTimer !== null) {
+ window.clearInterval(this.progressTimer);
+ this.progressTimer = null;
+ }
+ this.clearPlayoutFence();
+ this.sendJson({ type: 'close' });
+ this.controlChannel?.close();
+ this.peerConnection?.close();
+ this.localStream?.getTracks().forEach((track) => track.stop());
+ this.remoteStream?.getTracks().forEach((track) => track.stop());
+ if (this.audioElement) {
+ this.audioElement.pause();
+ this.audioElement.srcObject = null;
+ }
+ this.controlChannel = null;
+ this.peerConnection = null;
+ this.localStream = null;
+ this.remoteStream = null;
+ this.audioElement = null;
+ this.itemStarts.length = 0;
+ this.durationsMs.clear();
+ this.active = false;
+ this.options.onStateChange('idle');
+ }
+
+ userConfirm(event: UserConfirmResultEvent): void {
+ if (this.controlChannel?.readyState !== 'open') {
+ throw new Error('The realtime control channel is not open.');
+ }
+ this.controlChannel.send(
+ JSON.stringify({ type: 'control', control: 'user_confirm', data: event }),
+ );
+ }
+
+ private attachRemoteTrack(track: MediaStreamTrack): void {
+ if (track.kind !== 'audio') return;
+ this.clearPlayoutFence();
+ this.remoteStream = new MediaStream([track]);
+ const audio = new Audio();
+ audio.autoplay = true;
+ audio.srcObject = this.remoteStream;
+ this.audioElement = audio;
+ void audio.play().catch(() => {
+ this.fail(new Error('The browser blocked realtime audio playback.'));
+ });
+ }
+
+ private handleMessage(raw: unknown): void {
+ if (typeof raw !== 'string') return;
+ let frame: ServerFrame;
+ try {
+ frame = JSON.parse(raw) as ServerFrame;
+ } catch {
+ this.fail(new Error('The server sent an invalid realtime control frame.'));
+ return;
+ }
+
+ if (frame.type === 'audio_start') {
+ this.itemStarts.push(frame);
+ this.itemStarts.sort((left, right) => left.track_time_ms - right.track_time_ms);
+ } else if (frame.type === 'audio_duration') {
+ this.durationsMs.set(frame.item_id, frame.duration_ms);
+ } else if (frame.type === 'clear_audio') {
+ this.acknowledgeClear(frame);
+ } else if (frame.type === 'error') {
+ this.fail(new Error(frame.detail));
+ }
+ }
+
+ private acknowledgeClear(frame: ClearAudioFrame): void {
+ const position = this.currentPosition();
+ this.muteUntilTrackTime(frame.resume_track_time_ms);
+ this.sendJson({
+ type: 'playout_cleared',
+ request_id: frame.request_id,
+ ...position,
+ });
+ this.itemStarts.length = 0;
+ this.durationsMs.clear();
+ }
+
+ private muteUntilTrackTime(trackTimeMs: number): void {
+ const audio = this.audioElement;
+ if (!audio || !Number.isFinite(trackTimeMs)) return;
+ this.clearPlayoutFence();
+ audio.muted = true;
+ const deadline = performance.now() + PLAYOUT_FENCE_POLL_TIMEOUT_MS;
+ const releaseIfCaughtUp = () => {
+ if (this.audioElement !== audio) {
+ this.clearPlayoutFence();
+ return true;
+ }
+ if (audio.currentTime * 1000 < trackTimeMs) return false;
+ audio.muted = false;
+ this.clearPlayoutFence();
+ return true;
+ };
+ const release = () => {
+ if (releaseIfCaughtUp()) return;
+ if (performance.now() >= deadline) {
+ this.playoutFenceTimer = null;
+ this.playoutFenceAudio = audio;
+ this.playoutFenceListener = () => {
+ releaseIfCaughtUp();
+ };
+ audio.addEventListener('playing', this.playoutFenceListener);
+ audio.addEventListener('timeupdate', this.playoutFenceListener);
+ return;
+ }
+ this.playoutFenceTimer = window.setTimeout(release, PLAYOUT_FENCE_POLL_MS);
+ };
+ release();
+ }
+
+ private clearPlayoutFence(): void {
+ if (this.playoutFenceTimer !== null) {
+ window.clearTimeout(this.playoutFenceTimer);
+ this.playoutFenceTimer = null;
+ }
+ if (this.playoutFenceAudio && this.playoutFenceListener) {
+ this.playoutFenceAudio.removeEventListener('playing', this.playoutFenceListener);
+ this.playoutFenceAudio.removeEventListener('timeupdate', this.playoutFenceListener);
+ }
+ this.playoutFenceAudio = null;
+ this.playoutFenceListener = null;
+ }
+
+ private currentPosition(): { item_id: string; played_ms: number } {
+ const currentTimeMs = (this.audioElement?.currentTime ?? 0) * 1000;
+ if (!Number.isFinite(currentTimeMs)) {
+ return { item_id: '', played_ms: 0 };
+ }
+
+ let currentIndex = -1;
+ for (let index = 0; index < this.itemStarts.length; index += 1) {
+ if (this.itemStarts[index].track_time_ms > currentTimeMs) break;
+ currentIndex = index;
+ }
+ if (currentIndex < 0) return { item_id: '', played_ms: 0 };
+
+ const current = this.itemStarts[currentIndex];
+ for (const completed of this.itemStarts.splice(0, currentIndex)) {
+ this.durationsMs.delete(completed.item_id);
+ }
+ const elapsed = Math.max(0, currentTimeMs - current.track_time_ms);
+ const duration = this.durationsMs.get(current.item_id) ?? 0;
+ return {
+ item_id: current.item_id,
+ played_ms: Math.round(Math.min(elapsed, duration)),
+ };
+ }
+
+ private reportPlayout(): void {
+ const position = this.currentPosition();
+ if (position.item_id) this.sendJson({ type: 'playout', ...position });
+ }
+
+ private sendJson(payload: Record<string, unknown>): void {
+ if (this.controlChannel?.readyState === 'open') {
+ this.controlChannel.send(JSON.stringify(payload));
+ }
+ }
+
+ private throwIfStopped(): void {
+ if (this.intentionalClose) {
+ throw this.failureError ?? new Error('The realtime connection was stopped.');
+ }
+ }
+
+ private waitForIceGathering(peerConnection: RTCPeerConnection): Promise<void> {
+ if (peerConnection.iceGatheringState === 'complete') return Promise.resolve();
+ return new Promise((resolve, reject) => {
+ const timeout = window.setTimeout(() => {
+ peerConnection.removeEventListener('icegatheringstatechange', onChange);
+ reject(new Error('Timed out while gathering WebRTC network candidates.'));
+ }, ICE_GATHERING_TIMEOUT_MS);
+ const onChange = () => {
+ if (peerConnection.iceGatheringState !== 'complete') return;
+ window.clearTimeout(timeout);
+ peerConnection.removeEventListener('icegatheringstatechange', onChange);
+ resolve();
+ };
+ peerConnection.addEventListener('icegatheringstatechange', onChange);
+ });
+ }
+
+ private waitForControlChannel(channel: RTCDataChannel): Promise<void> {
+ if (channel.readyState === 'open') return Promise.resolve();
+ return new Promise((resolve, reject) => {
+ const cleanup = () => {
+ window.clearTimeout(timeout);
+ channel.removeEventListener('open', onOpen);
+ channel.removeEventListener('close', onClose);
+ };
+ const timeout = window.setTimeout(() => {
+ cleanup();
+ reject(new Error('Timed out while opening the realtime connection.'));
+ }, CONNECTION_TIMEOUT_MS);
+ const onOpen = () => {
+ cleanup();
+ resolve();
+ };
+ const onClose = () => {
+ cleanup();
+ reject(this.failureError ?? new Error('The realtime connection was closed.'));
+ };
+ channel.addEventListener('open', onOpen);
+ channel.addEventListener('close', onClose);
+ });
+ }
+
+ private fail(error: Error): void {
+ if (this.failed || this.intentionalClose) return;
+ this.failed = true;
+ this.failureError = error;
+ if (this.active) this.options.onError(error);
+ void this.stop().finally(() => this.options.onStateChange('error'));
+ }
+}
diff --git a/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx
index 988a4fa74..6314a991b 100644
--- a/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx
+++ b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx
@@ -14,6 +14,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import type {
ChatModelConfig,
PermissionMode,
+ RealtimeModelConfig,
SessionKnowledgeConfig,
TTSModelConfig,
UpdateSessionRequest,
@@ -34,6 +35,7 @@ import { KnowledgeBaseParametersPopover } from '@/components/popover/KnowledgeBa
import { ModelParametersPopover } from '@/components/popover/ModelParametersPopover';
import { LlmSelect } from '@/components/select/LlmSelect';
import { PermissionModeSelect } from '@/components/select/PermissionModeSelect.tsx';
+import { RealtimeModelSelect } from '@/components/select/RealtimeModelSelect';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
@@ -49,14 +51,20 @@ import {
} from '@/components/ui/resizable.tsx';
import { SidebarTrigger } from '@/components/ui/sidebar';
import { useAvailableModels } from '@/hooks/useAvailableModels';
+import { useAvailableRealtimeModels } from '@/hooks/useAvailableRealtimeModels';
import { useKnowledgeBaseMiddlewareSchema } from '@/hooks/useKnowledgeBaseMiddlewareSchema';
import { useKnowledgeBases } from '@/hooks/useKnowledgeBases';
import { useMessages } from '@/hooks/useMessages';
+import { useRealtimeVoice } from '@/hooks/useRealtimeVoice';
import { useSessions } from '@/hooks/useSessions';
import { useWorkspace } from '@/hooks/useWorkspace.ts';
import { useWorkspaceStatus } from '@/hooks/useWorkspaceStatus';
import { useTranslation } from '@/i18n/useI18n';
+const REALTIME_EXCLUDED_ENUM_VALUES: Record<string, unknown[]> = {
+ turn_detection: ['none'],
+};
+
interface ChatViewportProps {
/**
* The agent that owns the session being viewed. May be the
@@ -172,17 +180,20 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
const { t } = useTranslation();
const { sessions, refetch: refetchSessions } = useSessions(agentId);
const { groups } = useAvailableModels();
+ const { groups: realtimeGroups } = useAvailableRealtimeModels();
const [selectedModel, setSelectedModel] = useState<ChatModelConfig | null>(null);
const [selectedFallbackModel, setSelectedFallbackModel] = useState<ChatModelConfig | null>(
null,
);
const [selectedTTSModel, setSelectedTTSModel] = useState<TTSModelConfig | null>(null);
+ const [selectedRealtimeModel, setSelectedRealtimeModel] = useState<RealtimeModelConfig | null>(
+ null,
+ );
const [selectedKnowledgeConfig, setSelectedKnowledgeConfig] =
useState<SessionKnowledgeConfig | null>(null);
const [selectedPermissionMode, setSelectedPermissionMode] = useState<string>('default');
const [credentialOpen, setCredentialOpen] = useState(false);
- const [credentialRefetchTrigger, setCredentialRefetchTrigger] = useState(0);
const [tasksContext, setTasksContext] = useState<TaskContext | null>(null);
const [permissionContext, setPermissionContext] = useState<PermissionContext | null>(null);
const [configPending, setConfigPending] = useState(false);
@@ -247,6 +258,8 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
[sessionId],
);
+ const realtimeVoice = useRealtimeVoice(agentId, sessionId);
+ const voiceBusy = realtimeVoice.state === 'active' || realtimeVoice.state === 'connecting';
const {
msgs,
loading: messagesLoading,
@@ -260,6 +273,8 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
onTeamUpdated: handleTeamUpdated,
onStateUpdated: handleStateUpdated,
onSessionUpdated: handleSessionUpdated,
+ isRealtimeAudioActive: () => voiceBusy,
+ sendRealtimeUserConfirm: realtimeVoice.userConfirm,
});
const {
mcps,
@@ -511,6 +526,7 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
setSelectedModel(null);
setSelectedFallbackModel(null);
setSelectedTTSModel(null);
+ setSelectedRealtimeModel(null);
setSelectedKnowledgeConfig(null);
}, [sessionId]);
@@ -525,6 +541,22 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
return null;
}, [groups, selectedModel?.type, selectedModel?.model]);
+ const selectedRealtimeModelCard = useMemo(() => {
+ if (!selectedRealtimeModel) return null;
+ for (const items of Object.values(realtimeGroups)) {
+ for (const { credential, models } of items) {
+ if (credential.id !== selectedRealtimeModel.credential_id) continue;
+ const card = models.find(
+ (model) =>
+ model.model_type === selectedRealtimeModel.type &&
+ model.name === selectedRealtimeModel.model,
+ );
+ if (card) return card;
+ }
+ }
+ return null;
+ }, [realtimeGroups, selectedRealtimeModel]);
+
/**
* Pick the first model the available-models endpoint surfaces, used
* as a sensible default when the current session has no model
@@ -618,6 +650,7 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
setSelectedFallbackModel(view.session.config.fallback_chat_model_config ?? null);
setSelectedTTSModel(view.session.config.tts_model_config ?? null);
+ setSelectedRealtimeModel(view.session.config.realtime_model_config ?? null);
setSelectedKnowledgeConfig(view.session.config.knowledge_config ?? null);
}, [view, groups, sessionId, agentId]);
@@ -674,6 +707,22 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
await patchConfig({ tts_model_config: config }, () => setSelectedTTSModel(config));
};
+ /** Persist the model used by browser realtime voice mode. */
+ const handleRealtimeModelChange = async (config: RealtimeModelConfig | null) => {
+ await patchConfig({ realtime_model_config: config }, () =>
+ setSelectedRealtimeModel(config),
+ );
+ };
+
+ /** Persist parameters for the browser realtime voice model. */
+ const handleRealtimeParametersChange = async (parameters: Record<string, unknown>) => {
+ if (!selectedRealtimeModel) return;
+ const updated = { ...selectedRealtimeModel, parameters };
+ await patchConfig({ realtime_model_config: updated }, () =>
+ setSelectedRealtimeModel(updated),
+ );
+ };
+
/**
* Persist a permission-mode change.
*
@@ -745,6 +794,23 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
{/* Never squeezed by a long session name: the
name truncates instead. */}
<div className="flex shrink-0 flex-row gap-x-1">
+ <RealtimeModelSelect
+ value={selectedRealtimeModel}
+ onChange={handleRealtimeModelChange}
+ onAddCredential={() => setCredentialOpen(true)}
+ disabled={configPending || voiceBusy}
+ className="text-muted-foreground hover:text-foreground"
+ />
+ <ModelParametersPopover
+ selectedModel={selectedRealtimeModel}
+ modelCard={selectedRealtimeModelCard}
+ onChange={handleRealtimeParametersChange}
+ idPrefix="realtime"
+ triggerLabel={t('realtime.parameters')}
+ disabled={configPending || voiceBusy}
+ hideArrayParameters
+ excludedEnumValues={REALTIME_EXCLUDED_ENUM_VALUES}
+ />
<LlmSelect
id="tour-llm-select"
variant="ghost"
@@ -752,7 +818,6 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
value={selectedModel}
onChange={handleLlmChange}
onAddCredential={() => setCredentialOpen(true)}
- refetchTrigger={credentialRefetchTrigger}
disabled={configPending}
/>
<ModelParametersPopover
@@ -849,10 +914,13 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
git={workspaceStatus?.git ?? null}
onRefreshGit={refetchWorkspaceStatus}
phase={phase}
- disabled={selectedModel === null}
+ disabled={selectedModel === null || voiceBusy}
onSend={send}
onUserConfirm={onUserConfirm}
onInterrupt={interrupt}
+ voiceState={realtimeVoice.state}
+ onVoiceToggle={() => void realtimeVoice.toggle()}
+ voiceDisabled={!selectedRealtimeModel || !agentId || !sessionId}
// cwd={
// {cwd: view?.session.config.cwd, git: {
// branch: 'main',
@@ -940,11 +1008,7 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
<PanelDock layout={panelLayout} panels={panels} onClosePanel={closePanel} />
</ResizablePanelGroup>
</main>
- <CreateCredentialDialog
- open={credentialOpen}
- onOpenChange={setCredentialOpen}
- onCreated={() => setCredentialRefetchTrigger((n) => n + 1)}
- />
+ <CreateCredentialDialog open={credentialOpen} onOpenChange={setCredentialOpen} />
</>
);
}
diff --git a/examples/web_ui/frontend/src/pages/chat/index.tsx b/examples/web_ui/frontend/src/pages/chat/index.tsx
index 045fc22e7..5346f5452 100644
--- a/examples/web_ui/frontend/src/pages/chat/index.tsx
+++ b/examples/web_ui/frontend/src/pages/chat/index.tsx
@@ -197,6 +197,9 @@ const ChatPageInner = () => {
...(seedConfig?.fallback_chat_model_config
? { fallback_chat_model_config: seedConfig.fallback_chat_model_config }
: {}),
+ ...(seedConfig?.realtime_model_config
+ ? { realtime_model_config: seedConfig.realtime_model_config }
+ : {}),
});
navigate(`/chat/${urlAgentId}/${res.session_id}`);
};
diff --git a/pyproject.toml b/pyproject.toml
index 2f5ac931d..3aa83dbcf 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -67,6 +67,7 @@ service = [
"uvicorn",
"apscheduler",
"ag-ui-protocol>=0.1.10",
+ "aiortc>=1.14",
]
# ------------ Storage backends ------------
storage-redis = ["redis"]
@@ -111,8 +112,8 @@ tools = [
# ------------ Realtime voice ------------
realtime = [
"websockets>=13",
- "sounddevice",
]
+realtime-local = ["sounddevice"]
# ------------ Terminal UI ------------
tui = [
"textual>=8.2,<9",
@@ -174,6 +175,7 @@ full = [
"agentscope[models]",
"agentscope[classifiers]",
"agentscope[service]",
+ "agentscope[realtime]",
"agentscope[storage-redis]",
"agentscope[storage-sql]",
"agentscope[storage-s3]",
diff --git a/src/agentscope/agent/_realtime/_agent.py b/src/agentscope/agent/_realtime/_agent.py
index 34c8ce2c9..65b19d6d8 100644
--- a/src/agentscope/agent/_realtime/_agent.py
+++ b/src/agentscope/agent/_realtime/_agent.py
@@ -45,8 +45,10 @@ from ...event import (
)
from ...message import (
Msg,
+ SystemMsg,
TextBlock,
ToolCallBlock,
+ ToolCallState,
ToolResultBlock,
ToolResultState,
Usage,
@@ -59,50 +61,32 @@ from ...types import ReplyFinishedReason
# Audio buffered while the model is being reconnected: 10 s at 100 ms chunks.
_BACKLOG_FRAMES = 100
+_HISTORY_MAX_MESSAGES = 100
+_HISTORY_MAX_TEXT_CHARS = 32_000
@dataclass
class _Reply:
- """One in-flight assistant turn, plus the text/audio alignment needed
- to work out what the user actually heard."""
+ """One in-flight model response."""
item_id: str
- """The provider's response item; what playout and truncation refer to."""
+ """The provider's response item identifier."""
reply_id: str
"""The agent's reply this response belongs to, as seen in events and
context. A reply spans every response up to the next user turn, so
one that calls tools has several responses."""
text_block_id: str = field(default_factory=lambda: uuid.uuid4().hex)
audio_block_id: str = field(default_factory=lambda: uuid.uuid4().hex)
- text: str = ""
- final_text: str | None = None
- """Set on a barge-in: the text block is truncated to this."""
- audio_ms: float = 0.0
text_started: bool = False
audio_started: bool = False
- marks: list[tuple[float, int]] = field(default_factory=list)
- def on_audio(self, pcm: bytes, sample_rate: int) -> None:
- """Account for one chunk of generated audio."""
- self.audio_ms += len(pcm) / (sample_rate * 2) * 1000
- def on_text(self, delta: str) -> None:
- """Record a transcript delta against the audio generated so far."""
- self.text += delta
- self.marks.append((self.audio_ms, len(self.text)))
-
- def spoken_prefix(self, played_ms: int) -> str:
- """The transcript prefix matching *played_ms* of playback.
+@dataclass
+class _QueuedEvent:
+ """One outward event and its state at a persistence boundary."""
- Transcript deltas usually run slightly ahead of the audio they
- describe, so this errs towards keeping one word too many.
- """
- length = 0
- for at_ms, text_len in self.marks:
- if at_ms > played_ms:
- break
- length = text_len
- return self.text[:length]
+ event: AgentEvent
+ checkpoint: AgentState | None = None
class RealtimeAgent:
@@ -190,8 +174,10 @@ class RealtimeAgent:
self._engine = PermissionEngine(self.state.permission_context)
self._transport: TransportBase | None = None
- self._out: asyncio.Queue = asyncio.Queue()
+ self._out: asyncio.Queue[_QueuedEvent] = asyncio.Queue()
+ self._yielded_checkpoint: tuple[str, AgentState] | None = None
self._reply: _Reply | None = None
+ self._audio_pending = False
self._finished_item = ""
# The agent's open reply, and whether the next response continues
# it (after tool results) rather than starting a new one.
@@ -210,6 +196,7 @@ class RealtimeAgent:
# any transport, and reconnect bookkeeping.
self._connected = False
self._connected_event = asyncio.Event()
+ self._connection_generation = 0
self._downlink: asyncio.Task | None = None
self._backlog: list[bytes] = []
self._retry_at = 0.0
@@ -234,6 +221,13 @@ class RealtimeAgent:
if self._connected:
return
+ if self._connection_generation:
+ async with self._barge_lock:
+ self._end_user_turn()
+ self._user_turn = ""
+ self._finish_reply(ReplyFinishedReason.ERROR)
+ self._connection_generation += 1
+
instructions = self.system_prompt
tools = None
if self.toolkit is not None:
@@ -245,9 +239,9 @@ class RealtimeAgent:
tools = await self.toolkit.get_tool_schemas(groups)
# TODO(realtime): tools and instructions are sent once, here.
- # Activating a tool group or installing a skill mid-session —
- # ResetTools, the meta tool — therefore has no effect until the
- # next connect, even though the model is told it can do it.
+ # Activating a tool group or installing a skill mid-session —
+ # ResetTools, the meta tool — therefore has no effect until the
+ # next connect, even though the model is told it can do it.
#
# Fix: a `RealtimeModelBase.update_session(instructions, tools)`
# re-sent whenever `state.tool_context.activated_groups` changes.
@@ -257,23 +251,60 @@ class RealtimeAgent:
# context. No provider documents whether the update applies
# retroactively, so treat it as affecting future turns only. Do
# not let it change `voice`: OpenAI locks it after first audio.
- # Providers differ in whether prior turns can be seeded, so the
- # transcript so far rides along in the instructions, which every
- # provider takes. Only matters on reconnect; first connect is empty.
- history = "\n".join(
- f"{m.name}: {text}"
- for m in self.state.context
- if (text := m.get_text_content())
- )
- if history:
- instructions = (
- f"{instructions}\n\n## Conversation so far\n{history}"
+ history = [
+ message
+ for message in self.state.context
+ if message.id != self._reply_id
+ and (
+ message.role != "assistant"
+ or message.finished_reason is not ReplyFinishedReason.ERROR
)
- await self.model.connect(
- instructions=instructions,
- tools=tools,
- turn_detection_disabled=self.vad is not None,
- )
+ ][-_HISTORY_MAX_MESSAGES:]
+ summary = self.state.summary
+ if isinstance(summary, str):
+ summary_text = summary
+ else:
+ summary_text = "\n".join(
+ block.text for block in summary if isinstance(block, TextBlock)
+ )
+ if summary_text.strip():
+ history.insert(
+ 0,
+ SystemMsg(name="summary", content=summary_text),
+ )
+ if history and not self.model.supports_history_replay:
+ lines = [
+ f"{message.name}: {text}"
+ for message in history
+ if (text := message.get_text_content())
+ ]
+ kept: list[str] = []
+ kept_chars = 0
+ for line in reversed(lines):
+ separator_chars = 1 if kept else 0
+ if (
+ kept_chars + separator_chars + len(line)
+ > _HISTORY_MAX_TEXT_CHARS
+ ):
+ break
+ kept.append(line)
+ kept_chars += separator_chars + len(line)
+ fallback = "\n".join(reversed(kept))
+ if fallback:
+ instructions = (
+ f"{instructions}\n\n## Conversation so far\n{fallback}"
+ )
+ try:
+ await self.model.connect(
+ instructions=instructions,
+ tools=tools,
+ turn_detection_disabled=self.vad is not None,
+ )
+ if history and self.model.supports_history_replay:
+ await self.model.replay_history(history)
+ except Exception:
+ await self.model.close()
+ raise
if self.vad is not None:
self.vad.reset()
self.aggregator.reset()
@@ -404,7 +435,16 @@ class RealtimeAgent:
return_when=asyncio.FIRST_COMPLETED,
)
if getter in done:
- yield getter.result()
+ queued = getter.result()
+ self._yielded_checkpoint = (
+ (queued.event.id, queued.checkpoint)
+ if queued.checkpoint is not None
+ else None
+ )
+ try:
+ yield queued.event
+ finally:
+ self._yielded_checkpoint = None
else:
getter.cancel()
# The transport is gone: cut off any reply still in flight so
@@ -413,7 +453,16 @@ class RealtimeAgent:
# stream ends rather than leaking them into the next run.
await self._barge_in()
while not self._out.empty():
- yield self._out.get_nowait()
+ queued = self._out.get_nowait()
+ self._yielded_checkpoint = (
+ (queued.event.id, queued.checkpoint)
+ if queued.checkpoint is not None
+ else None
+ )
+ try:
+ yield queued.event
+ finally:
+ self._yielded_checkpoint = None
# A transport failure must not look like a clean disconnect.
if not uplink.cancelled() and uplink.exception() is not None:
raise uplink.exception() # type: ignore[misc]
@@ -539,7 +588,8 @@ class RealtimeAgent:
self._start_user_turn()
await self._barge_in()
elif speech is SpeechTransition.ENDED:
- self._end_user_turn()
+ if not self.model.input_transcription_enabled:
+ self._end_user_turn()
now = time.monotonic()
self._metrics.user_speech_end_at = now
await self.model.commit_turn()
@@ -568,7 +618,7 @@ class RealtimeAgent:
# ------------------------------------------------------------------
async def _barge_in(self) -> None:
- """Cut the reply short and correct both contexts to what was heard.
+ """Stop playback and any response that is still being generated.
Whether a given overlap counts as an interruption is decided
before this is called — by the provider when it owns turn
@@ -583,59 +633,16 @@ class RealtimeAgent:
async def _barge_in_locked(self) -> None:
"""Body of :meth:`_barge_in`, run under the lock."""
- reply = self._reply
- if reply is None:
- # Nothing playing, but a reply may be waiting on its tools.
- self._finish_reply(ReplyFinishedReason.INTERRUPTED)
- return
+ active_reply = self._reply
+ if self._transport is not None and self._audio_pending:
+ await self._transport.clear_audio()
+ self._audio_pending = False
- spoken, played_ms = (
- "",
- 0,
- ) # nothing reaches the ear without a transport
- if self._transport is not None:
- position = await self._transport.clear_audio()
- if position.item_id and position.item_id != reply.item_id:
- logger.warning(
- "RealtimeAgent: playout reports %s but %s is open; "
- "not truncating.",
- position.item_id,
- reply.item_id,
- )
- return
- played_ms = position.played_ms
- spoken = reply.spoken_prefix(played_ms)
-
- self._truncate_reply(spoken)
- reply.final_text = spoken
- if self._connected:
- await self.model.truncate(reply.item_id, played_ms, spoken)
+ if active_reply is not None and self._connected:
await self.model.cancel_response()
- self._finish_reply(ReplyFinishedReason.INTERRUPTED)
- def _truncate_reply(self, spoken: str) -> None:
- """Rewrite the current reply in context to the part heard.
-
- Non-text blocks stay: a tool call that already ran belongs in the
- record even though the sentence around it was never heard.
- """
- if not self.state.context:
- return
- tail = self.state.context[-1]
- if tail.role != "assistant" or tail.name != self.name:
- return
-
- others = (
- []
- if isinstance(tail.content, str)
- else [_ for _ in tail.content if not isinstance(_, TextBlock)]
- )
- if spoken.strip():
- tail.content = [TextBlock(text=spoken), *others]
- elif others:
- tail.content = others
- else:
- self.state.context.pop()
+ if self._reply_id:
+ self._finish_reply(ReplyFinishedReason.INTERRUPTED)
# ------------------------------------------------------------------
# Downlink: model -> transport + events (lives with the agent)
@@ -650,10 +657,16 @@ class RealtimeAgent:
"""
while True:
await self._connected_event.wait()
+ generation = self._connection_generation
async for event in self.model.events():
await self._on_model_event(event)
- self._mark_disconnected()
- self._finish_reply(ReplyFinishedReason.ERROR)
+ async with self._barge_lock:
+ if generation != self._connection_generation:
+ continue
+ self._mark_disconnected()
+ self._end_user_turn()
+ self._user_turn = ""
+ self._finish_reply(ReplyFinishedReason.ERROR)
logger.info(
"RealtimeAgent: model session ended; keep talking and it "
"reconnects on the next audio.",
@@ -668,7 +681,8 @@ class RealtimeAgent:
await self._barge_in()
case me.SpeechEndedEvent():
- self._end_user_turn()
+ if not self.model.input_transcription_enabled:
+ self._end_user_turn()
# With provider turn detection this is also its commit.
now = time.monotonic()
self._metrics.user_speech_end_at = now
@@ -678,6 +692,10 @@ class RealtimeAgent:
case me.InputTranscriptionEvent():
self._on_transcription(event)
+ case me.InputTranscriptionFailedEvent():
+ self._end_user_turn()
+ self._user_turn = ""
+
case me.ResponseCreatedEvent():
self._start_reply(event.item_id)
@@ -688,8 +706,8 @@ class RealtimeAgent:
reply = self._start_reply(event.item_id)
if reply is None:
return
- reply.on_audio(event.pcm, rate)
await self._transport.send_audio(event.pcm, reply.item_id)
+ self._audio_pending = True
self._emit_audio(reply, event.pcm, rate)
self._metrics.backend_first_audio_at = (
self._metrics.backend_first_audio_at or time.monotonic()
@@ -699,7 +717,6 @@ class RealtimeAgent:
reply = self._start_reply(event.item_id)
if reply is None:
return
- reply.on_text(event.delta)
self._emit_text(reply, event.delta)
case me.ToolCallEvent():
@@ -708,24 +725,31 @@ class RealtimeAgent:
self.state.append_context(self.name, [event.tool_call])
case me.ResponseDoneEvent():
- self._metrics.input_tokens = event.input_tokens
- self._metrics.output_tokens = event.output_tokens
- tail = self.state.context[-1] if self.state.context else None
- if tail is not None and tail.id == self._reply_id:
- tail.append_usage(
- Usage(
- input_tokens=event.input_tokens,
- output_tokens=event.output_tokens,
- ),
+ async with self._barge_lock:
+ reply = self._reply
+ if reply is None or reply.item_id != event.item_id:
+ return
+ self._metrics.input_tokens = event.input_tokens
+ self._metrics.output_tokens = event.output_tokens
+ tail = (
+ self.state.context[-1] if self.state.context else None
)
- if self._pending_tools and self.toolkit is not None:
- # The reply goes on: tools run, then the next response
- # answers with their results.
- self._finish_response()
- self._continuing = True
- self._schedule_tools()
- else:
- self._finish_reply(ReplyFinishedReason.COMPLETED)
+ if tail is not None and tail.id == self._reply_id:
+ tail.append_usage(
+ Usage(
+ input_tokens=event.input_tokens,
+ output_tokens=event.output_tokens,
+ ),
+ )
+ if self._pending_tools and self.toolkit is not None:
+ # The reply goes on: tools run, then the next
+ # response answers with their results.
+ reply_id = reply.reply_id
+ self._finish_response()
+ self._continuing = True
+ self._schedule_tools(reply_id)
+ else:
+ self._finish_reply(ReplyFinishedReason.COMPLETED)
case me.ModelErrorEvent():
logger.error(
@@ -733,7 +757,10 @@ class RealtimeAgent:
event.code,
event.message,
)
- self._finish_reply(ReplyFinishedReason.ERROR)
+ async with self._barge_lock:
+ self._end_user_turn()
+ self._user_turn = ""
+ self._finish_reply(ReplyFinishedReason.ERROR)
case me.SessionEndedEvent():
# The events() iterator ends right after this.
@@ -759,7 +786,7 @@ class RealtimeAgent:
)
def _end_user_turn(self) -> None:
- """Close the user's turn; the transcript may still be on its way."""
+ """Close the user reply once no transcript remains pending."""
if not self._user_turn_open:
return
self._user_turn_open = False
@@ -777,6 +804,8 @@ class RealtimeAgent:
turn = self.aggregator.take(event.text)
if turn is None:
logger.debug("RealtimeAgent: dropping %r", event.text)
+ self._end_user_turn()
+ self._user_turn = ""
return
# A transcript with no detected speech, e.g. after a reconnect,
@@ -793,8 +822,6 @@ class RealtimeAgent:
),
)
self._emit(TextBlockEndEvent(reply_id=reply_id, block_id=block_id))
- self._end_user_turn()
- self._user_turn = ""
if not (
self.aggregator.merges_with_previous() and self._merge_user(turn)
@@ -802,6 +829,8 @@ class RealtimeAgent:
self.state.context.append(
UserMsg(name="user", content=turn, id=reply_id),
)
+ self._end_user_turn()
+ self._user_turn = ""
def _merge_user(self, text: str) -> bool:
"""Append *text* to the previous user turn that endpointing split.
@@ -868,6 +897,7 @@ class RealtimeAgent:
reply = self._reply
if reply is None:
return
+ position = None
if self._transport is not None:
position = self._transport.playout()
if position.item_id == reply.item_id:
@@ -877,7 +907,6 @@ class RealtimeAgent:
TextBlockEndEvent(
reply_id=reply.reply_id,
block_id=reply.text_block_id,
- text=reply.final_text,
),
)
if reply.audio_started:
@@ -900,15 +929,19 @@ class RealtimeAgent:
def _finish_reply(self, reason: ReplyFinishedReason) -> None:
"""Close the open reply, if any, response included."""
self._finish_response()
+ self._pending_tools.clear()
if not self._reply_id:
return
- self._emit(
- ReplyEndEvent(
- session_id=self.state.session_id,
- reply_id=self._reply_id,
- finished_reason=reason,
- ),
+ event = ReplyEndEvent(
+ session_id=self.state.session_id,
+ reply_id=self._reply_id,
+ finished_reason=reason,
)
+ for message in reversed(self.state.context):
+ if message.id == self._reply_id:
+ message.append_event(event)
+ break
+ self._emit(event)
self._reply_id = ""
self._continuing = False
@@ -937,7 +970,10 @@ class RealtimeAgent:
):
blocks[-1].text += delta
else:
- self.state.append_context(self.name, [TextBlock(text=delta)])
+ self.state.append_context(
+ self.name,
+ [TextBlock(id=reply.text_block_id, text=delta)],
+ )
self._emit(
TextBlockDeltaEvent(
reply_id=reply.reply_id,
@@ -969,35 +1005,63 @@ class RealtimeAgent:
def _emit(self, event: AgentEvent) -> None:
"""Queue one event for :meth:`reply_stream`."""
- self._out.put_nowait(event)
+ checkpoint = None
+ if isinstance(
+ event,
+ (
+ ReplyEndEvent,
+ RequireUserConfirmEvent,
+ ToolResultEndEvent,
+ ),
+ ):
+ checkpoint = self.state.model_copy(deep=True)
+ self._out.put_nowait(_QueuedEvent(event, checkpoint))
+
+ def checkpoint_snapshot(self, event: AgentEvent) -> AgentState | None:
+ """Return the immutable state paired with the yielded event."""
+ checkpoint = self._yielded_checkpoint
+ if checkpoint is None or checkpoint[0] != event.id:
+ return None
+ return checkpoint[1]
# ------------------------------------------------------------------
# Tools
# ------------------------------------------------------------------
- def _schedule_tools(self) -> None:
+ def _schedule_tools(self, reply_id: str) -> None:
"""Run the tool calls of the finished reply, then ask for more."""
- if not self._pending_tools or self.toolkit is None:
+ if not reply_id or not self._pending_tools or self.toolkit is None:
return
calls = list(self._pending_tools.values())
self._pending_tools.clear()
- task = asyncio.create_task(self._run_tools(calls), name="rt-tools")
+ task = asyncio.create_task(
+ self._run_tools(reply_id, calls),
+ name="rt-tools",
+ )
self._tasks.add(task)
task.add_done_callback(self._tasks.discard)
- async def _run_tools(self, calls: list[ToolCallBlock]) -> None:
+ async def _run_tools(
+ self,
+ reply_id: str,
+ calls: list[ToolCallBlock],
+ ) -> None:
"""Execute *calls* in order, then trigger the follow-up response."""
- reply_id = self._reply_id
try:
for call in calls:
+ async with self._barge_lock:
+ if self._reply_id != reply_id:
+ return
await self._run_tool(reply_id, call)
# Unless the user cut the reply short while the tools ran.
- if self._reply_id == reply_id:
- await self.model.request_response()
+ async with self._barge_lock:
+ if self._reply_id == reply_id:
+ await self.model.request_response()
except Exception: # noqa: BLE001
logger.exception("RealtimeAgent: tool execution failed")
- if self._reply_id == reply_id:
- self._finish_reply(ReplyFinishedReason.ERROR)
+ async with self._barge_lock:
+ if self._reply_id == reply_id:
+ self._finish_reply(ReplyFinishedReason.ERROR)
async def _run_tool(self, reply_id: str, call: ToolCallBlock) -> None:
"""Check permission for one call, run it, and report the result."""
@@ -1052,6 +1116,8 @@ class RealtimeAgent:
state=ToolResultState.DENIED,
)
return
+ else:
+ call.state = ToolCallState.ALLOWED
self._emit(
ToolResultStartEvent(
@@ -1113,6 +1179,7 @@ class RealtimeAgent:
) -> bool:
"""Ask the user to confirm *call* and wait for the answer."""
call.suggested_rules = decision.suggested_rules or []
+ call.state = ToolCallState.ASKING
self._emit(
RequireUserConfirmEvent(reply_id=reply_id, tool_calls=[call]),
)
@@ -1129,6 +1196,11 @@ class RealtimeAgent:
for rule in result.rules or []:
self._engine.add_rule(rule)
+ call.state = (
+ ToolCallState.ALLOWED
+ if result.confirmed
+ else ToolCallState.FINISHED
+ )
return result.confirmed
async def _report_tool(
@@ -1140,6 +1212,7 @@ class RealtimeAgent:
started: bool = False,
) -> None:
"""Close the tool result lifecycle and send the output back."""
+ call.state = ToolCallState.FINISHED
if not started:
self._emit(
ToolResultStartEvent(
@@ -1155,13 +1228,6 @@ class RealtimeAgent:
delta=output,
),
)
- self._emit(
- ToolResultEndEvent(
- reply_id=reply_id,
- tool_call_id=call.id,
- state=state,
- ),
- )
block = ToolResultBlock(
id=call.id,
name=call.name,
@@ -1176,4 +1242,11 @@ class RealtimeAgent:
break
else:
self.state.append_context(self.name, [block])
+ self._emit(
+ ToolResultEndEvent(
+ reply_id=reply_id,
+ tool_call_id=call.id,
+ state=state,
+ ),
+ )
await self.model.push_tool_result(block)
diff --git a/src/agentscope/app/_app.py b/src/agentscope/app/_app.py
index 6cd0ae7a3..8ed7f6037 100644
--- a/src/agentscope/app/_app.py
+++ b/src/agentscope/app/_app.py
@@ -1,8 +1,13 @@
# -*- coding: utf-8 -*-
"""AgentScope app factory."""
+import json
+import os
import secrets
+from weakref import WeakValueDictionary
from typing import Type, TYPE_CHECKING, Any
+from pydantic import TypeAdapter
+
from ._lifespan import lifespan
from .access import DenyAllResourceAccessPolicy, ResourceAccessPolicyBase
from .hub import HubBase, HubError, MCPHubBase, SkillHubBase
@@ -20,6 +25,7 @@ from ._router import (
embedding_model_router,
mcp_router,
model_router,
+ realtime_router,
tts_model_router,
schedule_router,
session_router,
@@ -27,7 +33,12 @@ from ._router import (
sop_router,
workspace_router,
)
-from ._types import AgentMiddlewareFactory, AgentToolFactory, SubAgentTemplate
+from ._types import (
+ AgentMiddlewareFactory,
+ AgentToolFactory,
+ RealtimeIceServer,
+ SubAgentTemplate,
+)
from .channel import ChannelBase, ChannelTypeRegistry
from .message_bus import MessageBus
from .storage import StorageBase
@@ -76,6 +87,29 @@ def _index_hubs(hubs: list | None, kind: str) -> dict:
return indexed
+def _load_realtime_ice_servers(
+ configured: list[dict[str, Any]] | None,
+) -> list[dict[str, Any]]:
+ """Load and validate browser-compatible ICE server dictionaries."""
+ servers: Any = configured
+ if servers is None:
+ raw = os.getenv("AGENTSCOPE_REALTIME_ICE_SERVERS")
+ if not raw:
+ return []
+ try:
+ servers = json.loads(raw)
+ except json.JSONDecodeError as exc:
+ raise ValueError(
+ "AGENTSCOPE_REALTIME_ICE_SERVERS must be valid JSON.",
+ ) from exc
+
+ validated = TypeAdapter(list[RealtimeIceServer]).validate_python(servers)
+ return [
+ server.model_dump(mode="json", by_alias=True, exclude_none=True)
+ for server in validated
+ ]
+
+
def create_app(
storage: StorageBase,
message_bus: MessageBus,
@@ -99,6 +133,7 @@ def create_app(
resource_access_policy: ResourceAccessPolicyBase | None = None,
channels: list[Type[ChannelBase]] | None = None,
download_secret: str | None = None,
+ realtime_ice_servers: list[dict[str, Any]] | None = None,
title: str = "AgentScope",
version: str = __version__,
**kwargs: Any,
@@ -274,6 +309,12 @@ def create_app(
be set explicitly behind a load balancer** — otherwise a
token minted by one replica is rejected by the next, and
downloads fail at random.
+ realtime_ice_servers (`list[dict[str, Any]] | None`, optional):
+ STUN and TURN servers exposed to browser WebRTC clients. When
+ omitted, the JSON array in
+ ``AGENTSCOPE_REALTIME_ICE_SERVERS`` is used. The default is an
+ empty list, which permits host candidates without silently
+ sending network metadata to a public STUN service.
title (`str`, defaults to ``"AgentScope"``):
OpenAPI title shown in the docs UI.
version (`str`, defaults to the package version):
@@ -312,6 +353,11 @@ def create_app(
app.state.mcp_hubs = _index_hubs(mcp_hubs, "MCP")
app.state.skill_hubs = _index_hubs(skill_hubs, "skill")
app.state.download_secret = download_secret or secrets.token_urlsafe(32)
+ app.state.realtime_ice_servers = _load_realtime_ice_servers(
+ realtime_ice_servers,
+ )
+ app.state.realtime_connections = {}
+ app.state.realtime_offer_locks = WeakValueDictionary()
# Parser / chunker / blob-store defaults only make sense when the
# KB feature is actually enabled. When ``knowledge_base_manager`` is
@@ -400,6 +446,7 @@ def create_app(
sop_router,
workspace_router,
model_router,
+ realtime_router,
tts_model_router,
embedding_model_router,
channel_router,
diff --git a/src/agentscope/app/_lifespan.py b/src/agentscope/app/_lifespan.py
index 3b9e2e866..4bc7592c3 100644
--- a/src/agentscope/app/_lifespan.py
+++ b/src/agentscope/app/_lifespan.py
@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
"""The lifespan of the agent service."""
+import asyncio
import socket
import uuid
from contextlib import AsyncExitStack, asynccontextmanager
@@ -20,6 +21,7 @@ from ._service import (
IndexTaskConsumer,
IndexWorker,
KnowledgeBaseService,
+ RealtimeService,
ResourceAccessService,
SessionService,
SOPService,
@@ -178,6 +180,18 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
)
app.state.chat_service = chat_service
+ app.state.realtime_service = RealtimeService(
+ storage=storage,
+ workspace_manager=workspace_manager,
+ scheduler_manager=scheduler,
+ background_task_manager=bg_manager,
+ message_bus=message_bus,
+ resource_access_service=resource_access_service,
+ extra_agent_tools=app.state.extra_agent_tools,
+ custom_subagent_templates=app.state.custom_subagent_templates,
+ channel_clients=channel_clients,
+ )
+
app.state.session_service = SessionService(
storage=storage,
message_bus=message_bus,
@@ -280,6 +294,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
message_bus=message_bus,
registry=chat_run_registry,
bg_manager=bg_manager,
+ realtime_connections=app.state.realtime_connections,
),
)
@@ -289,4 +304,15 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
if channel_dispatcher is not None:
await stack.enter_async_context(channel_dispatcher.lifespan())
+ async def _close_realtime_connections() -> None:
+ connections = list(app.state.realtime_connections.values())
+ app.state.realtime_connections.clear()
+ if connections:
+ await asyncio.gather(
+ *(connection.close() for connection in connections),
+ return_exceptions=True,
+ )
+
+ stack.push_async_callback(_close_realtime_connections)
+
yield
diff --git a/src/agentscope/app/_manager/_cancel_dispatcher.py b/src/agentscope/app/_manager/_cancel_dispatcher.py
index c5364f700..3ba69ce71 100644
--- a/src/agentscope/app/_manager/_cancel_dispatcher.py
+++ b/src/agentscope/app/_manager/_cancel_dispatcher.py
@@ -3,8 +3,9 @@
Subscribes to two bus channels:
-1. **Session cancel** — cancel all local work for a session (chat run
- + all BG tasks). Triggered by session deletion or explicit abort.
+1. **Session cancel** — cancel all local work for a session (chat run,
+ realtime run, and all BG tasks). Triggered by session deletion or
+ explicit abort.
2. **Task cancel** — cancel a single BG task by task_id. Triggered by
the :class:`ToolStop` agent tool when the target task lives on a
different worker.
@@ -14,6 +15,7 @@ or task simply do no work — the publisher does not need to know which
worker holds what; it broadcasts and lets each holder self-select.
"""
import asyncio
+from collections.abc import Mapping
from typing import TYPE_CHECKING, Self
from ..._logging import logger
@@ -21,6 +23,7 @@ from ..message_bus import MessageBusKeys
if TYPE_CHECKING:
from ..message_bus import MessageBus
+ from .._service._webrtc_session import WebRTCSession
from ._background_task_manager import BackgroundTaskManager
from ._chat_run_registry import ChatRunRegistry
@@ -37,6 +40,10 @@ class CancelDispatcher:
cancelled.
bg_manager (`BackgroundTaskManager`):
The per-process background task manager.
+ realtime_connections (`Mapping`, optional):
+ The per-process browser realtime sessions. The shared cancel
+ broadcast closes matching runners on whichever process owns
+ them.
"""
def __init__(
@@ -44,6 +51,11 @@ class CancelDispatcher:
message_bus: "MessageBus",
registry: "ChatRunRegistry",
bg_manager: "BackgroundTaskManager",
+ realtime_connections: Mapping[
+ tuple[str, str],
+ "WebRTCSession",
+ ]
+ | None = None,
) -> None:
"""Bind dependencies.
@@ -54,10 +66,15 @@ class CancelDispatcher:
The per-process chat-run registry.
bg_manager (`BackgroundTaskManager`):
The per-process background task manager.
+ realtime_connections (`Mapping`, optional):
+ The per-process browser realtime sessions.
"""
self._bus = message_bus
self._registry = registry
self._bg_manager = bg_manager
+ self._realtime_connections = (
+ realtime_connections if realtime_connections is not None else {}
+ )
self._session_task: asyncio.Task | None = None
self._task_cancel_task: asyncio.Task | None = None
self._interrupt_task: asyncio.Task | None = None
@@ -162,6 +179,21 @@ class CancelDispatcher:
session_id,
)
+ realtime_cancelled = 0
+ for (_, candidate_session_id), runner in list(
+ self._realtime_connections.items(),
+ ):
+ if candidate_session_id == session_id:
+ runner.request_close()
+ realtime_cancelled += 1
+ if realtime_cancelled:
+ logger.info(
+ "CancelDispatcher: closing %d local realtime run(s) for "
+ "session %s",
+ realtime_cancelled,
+ session_id,
+ )
+
# ------------------------------------------------------------------
# Task-level cancel loop
# ------------------------------------------------------------------
diff --git a/src/agentscope/app/_router/__init__.py b/src/agentscope/app/_router/__init__.py
index ca07e67b7..1b237afe5 100644
--- a/src/agentscope/app/_router/__init__.py
+++ b/src/agentscope/app/_router/__init__.py
@@ -14,6 +14,7 @@ from ._session import session_router
from ._skill import skill_router
from ._sop import sop_router
from ._model import model_router
+from ._realtime import realtime_router
from ._tts_model import tts_model_router
from ._workspace import workspace_router
@@ -21,6 +22,7 @@ __all__ = [
"agent_router",
"channel_router",
"model_router",
+ "realtime_router",
"embedding_model_router",
"tts_model_router",
"chat_router",
diff --git a/src/agentscope/app/_router/_agent.py b/src/agentscope/app/_router/_agent.py
index e7b622abc..c78a7e16f 100644
--- a/src/agentscope/app/_router/_agent.py
+++ b/src/agentscope/app/_router/_agent.py
@@ -103,21 +103,21 @@ async def get_agent_schema_v2() -> AgentSchemaV2Response:
- ``id``: server-assigned, marked :class:`SkipJsonSchema` on
:attr:`AgentData.id`.
- - ``context_config.summary_schema``: internal structured-output
- spec for the compression model, dropped below since it is not
- user-editable and there is no equivalent hook on the Pydantic
- side.
+ - ``chat_config.context_config.summary_schema``: internal
+ structured-output spec for the compression model, dropped below
+ since it is not user-editable and there is no equivalent hook on
+ the Pydantic side.
``$ref`` inlining is delegated to
:func:`~agentscope._utils._common._flatten_json_schema` so the
frontend can render every property from the response body alone.
- The frontend derives its section grouping (identity / context /
- react / invite) directly from this schema — top-level scalar
- properties are the "identity" section, and top-level nested-object
- properties each become their own section. Adding a new
- user-editable field to :class:`AgentData` is thus enough to have it
- appear in the create / edit form without a router change.
+ The frontend derives its section grouping directly from this
+ schema — top-level scalar properties are the "identity" section,
+ and every nested object below a mode block (``chat_config``)
+ becomes its own section. Adding a new user-editable field to
+ :class:`AgentData` is thus enough to have it appear in the create /
+ edit form without a router change.
Returns:
`AgentSchemaV2Response`:
@@ -127,7 +127,11 @@ async def get_agent_schema_v2() -> AgentSchemaV2Response:
# ``summary_schema`` is Pydantic's structured-output spec fed to the
# compression model — internal, not user-editable. No pydantic-side
# hook covers this deep nested field, so drop it after inlining.
- context_config = schema.get("properties", {}).get("context_config", {})
+ chat_config = schema.get("properties", {}).get("chat_config", {})
+ context_config = chat_config.get("properties", {}).get(
+ "context_config",
+ {},
+ )
context_config.get("properties", {}).pop("summary_schema", None)
return AgentSchemaV2Response(schema=schema)
@@ -191,18 +195,12 @@ async def create_agent(
`HTTPException`: 422 if the request body passes
:class:`CreateAgentRequest` validation but the resulting
:class:`AgentData` fails its cross-field invariants (e.g.
- ``invite_config.invitable=True`` without a non-empty
- ``invite_description``). Symmetrical with
+ ``chat_config.invite_config.invitable=True`` without a
+ non-empty ``invite_description``). Symmetrical with
:func:`update_agent`.
"""
try:
- data = AgentData(
- name=body.name,
- system_prompt=body.system_prompt,
- context_config=body.context_config,
- react_config=body.react_config,
- invite_config=body.invite_config,
- )
+ data = AgentData.model_validate(body.model_dump(exclude_none=True))
except ValidationError as exc:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
@@ -250,15 +248,25 @@ async def update_agent(
agent_id,
)
- updates = body.model_dump(exclude_none=True)
+ updates = body.model_dump(exclude_none=True, exclude_unset=True)
+ current_data = existing.data.model_dump()
+ chat_updates = updates.pop("chat_config", None)
+ if chat_updates is not None:
+ updates["chat_config"] = {
+ **current_data["chat_config"],
+ **chat_updates,
+ }
# ``model_copy(update=...)`` skips validators; re-run
# ``AgentData.model_validate`` on the merged shape so the
# ``invite_config`` sub-model's ``invitable ⇒ non-empty description``
# invariant enforced by ``@model_validator(mode="after")`` produces
- # an HTTP 422 instead of a stored-but-invalid record.
+ # an HTTP 422 instead of a stored-but-invalid record. Nested updates
+ # replace only the supplied sub-configs. A body still using the
+ # pre-``chat_config`` field names is folded in there too, on top of
+ # the stored block rather than over it.
try:
updated_data = AgentData.model_validate(
- {**existing.data.model_dump(), **updates},
+ {**current_data, **updates},
)
except ValidationError as exc:
raise HTTPException(
diff --git a/src/agentscope/app/_router/_realtime.py b/src/agentscope/app/_router/_realtime.py
new file mode 100644
index 000000000..69bba8ac2
--- /dev/null
+++ b/src/agentscope/app/_router/_realtime.py
@@ -0,0 +1,297 @@
+# -*- coding: utf-8 -*-
+"""Realtime voice model discovery and WebRTC negotiation endpoints."""
+
+import asyncio
+from typing import Any
+from weakref import WeakValueDictionary
+
+from fastapi import APIRouter, Depends, HTTPException, Request, status
+
+from ...agent import RealtimeAgent
+from ...credential import CredentialFactory
+from ..deps import (
+ get_current_user_id,
+ get_message_bus,
+ get_resource_access_service,
+ get_realtime_service,
+ get_storage,
+)
+from ..message_bus import MessageBus, MessageBusKeys
+from ..storage import StorageBase
+from .._service import (
+ RealtimeService,
+ ResourceAccessService,
+ get_realtime_model,
+)
+from ._schema import (
+ ListRealtimeModelsRequest,
+ ListRealtimeModelsResponse,
+ RealtimeConfigResponse,
+ RealtimeOfferRequest,
+ RealtimeOfferResponse,
+)
+
+
+realtime_router = APIRouter(
+ prefix="/realtime",
+ tags=["realtime"],
+ responses={404: {"description": "Not found"}},
+)
+
+_SESSION_LOCK_ACQUIRE_TIMEOUT_SECONDS = 1.0
+
+
+@realtime_router.get(
+ "/models",
+ response_model=ListRealtimeModelsResponse,
+ summary="List realtime models for a credential provider",
+)
+async def list_realtime_models(
+ body: ListRealtimeModelsRequest = Depends(),
+) -> ListRealtimeModelsResponse:
+ """Return realtime model cards supported by a credential provider."""
+ credential_cls = CredentialFactory.get_credential_class(body.provider)
+ if credential_cls is None:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"Provider {body.provider!r} not found.",
+ )
+
+ models = credential_cls.list_realtime_models()
+ return ListRealtimeModelsResponse(models=models, total=len(models))
+
+
+@realtime_router.get(
+ "/config",
+ response_model=RealtimeConfigResponse,
+ summary="Get browser WebRTC configuration",
+)
+async def get_realtime_config(
+ request: Request,
+ _: str = Depends(get_current_user_id),
+) -> RealtimeConfigResponse:
+ """Return deployment-provided ICE servers for browser negotiation."""
+ return RealtimeConfigResponse(
+ ice_servers=request.app.state.realtime_ice_servers,
+ )
+
+
+@realtime_router.post(
+ "/sessions/{session_id}/offer",
+ response_model=RealtimeOfferResponse,
+ summary="Start a realtime session from a WebRTC offer",
+)
+async def create_realtime_offer(
+ session_id: str,
+ body: RealtimeOfferRequest,
+ request: Request,
+ user_id: str = Depends(get_current_user_id),
+ storage: StorageBase = Depends(get_storage),
+ message_bus: MessageBus = Depends(get_message_bus),
+ access: ResourceAccessService = Depends(get_resource_access_service),
+ realtime_service: RealtimeService = Depends(get_realtime_service),
+) -> RealtimeOfferResponse:
+ """Negotiate one browser peer connection for a persisted session."""
+ connection_key = (user_id, session_id)
+ offer_locks: WeakValueDictionary[
+ tuple[str, str],
+ asyncio.Lock,
+ ] = request.app.state.realtime_offer_locks
+ offer_lock = offer_locks.setdefault(connection_key, asyncio.Lock())
+ async with offer_lock:
+ return await _create_realtime_offer(
+ session_id=session_id,
+ body=body,
+ request=request,
+ user_id=user_id,
+ storage=storage,
+ message_bus=message_bus,
+ access=access,
+ realtime_service=realtime_service,
+ )
+
+
+async def _create_realtime_offer(
+ *,
+ session_id: str,
+ body: RealtimeOfferRequest,
+ request: Request,
+ user_id: str,
+ storage: StorageBase,
+ message_bus: MessageBus,
+ access: ResourceAccessService,
+ realtime_service: RealtimeService,
+) -> RealtimeOfferResponse:
+ """Create one offer while this process serializes session starts."""
+ await access.resolve_agent(user_id, body.agent_id)
+ session = await storage.get_session(
+ user_id,
+ body.agent_id,
+ session_id,
+ )
+ if session is None:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"Session {session_id!r} not found.",
+ )
+ connection_key = (user_id, session_id)
+ connections: dict[
+ tuple[str, str],
+ Any,
+ ] = request.app.state.realtime_connections
+ previous = connections.get(connection_key)
+ if previous is not None:
+ await previous.close()
+ # The old runner persists during close, so reload after it is gone.
+ session = await storage.get_session(
+ user_id,
+ body.agent_id,
+ session_id,
+ )
+ if session is None:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"Session {session_id!r} not found.",
+ )
+ config = session.config.realtime_model_config
+ if config is None:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail="Configure a realtime model before starting voice mode.",
+ )
+ if config.parameters.get("turn_detection") == "none":
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail=(
+ "Browser voice mode does not support "
+ "turn_detection='none'. Select provider turn detection."
+ ),
+ )
+
+ try:
+ model = await get_realtime_model(user_id, config, access)
+ except ValueError as exc:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=str(exc),
+ ) from exc
+
+ lock_key = MessageBusKeys.session_lock(session_id)
+ if await message_bus.is_locked(lock_key):
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail=f"Session {session_id!r} is already running.",
+ )
+
+ try:
+ from aiortc import (
+ RTCConfiguration,
+ RTCIceServer,
+ RTCPeerConnection,
+ RTCSessionDescription,
+ )
+
+ from .._service._webrtc_audio_transport import (
+ WebRTCAudioTransport,
+ )
+ from .._service._webrtc_session import WebRTCSession
+ except ImportError as exc:
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail=(
+ "WebRTC support is not installed. Install "
+ "agentscope[realtime]."
+ ),
+ ) from exc
+
+ ice_servers = [
+ RTCIceServer(**server)
+ for server in request.app.state.realtime_ice_servers
+ ]
+ peer_connection = RTCPeerConnection(
+ configuration=RTCConfiguration(iceServers=ice_servers),
+ )
+ transport = WebRTCAudioTransport(
+ input_sample_rate=model.input_sample_rate,
+ output_sample_rate=model.output_sample_rate,
+ )
+ runner: WebRTCSession | None = None
+
+ @peer_connection.on("track")
+ def _on_track(track: Any) -> None:
+ if track.kind == "audio":
+ transport.set_input_track(track)
+
+ @peer_connection.on("datachannel")
+ def _on_datachannel(channel: Any) -> None:
+ if channel.label == "control":
+ transport.set_data_channel(channel)
+
+ @peer_connection.on("connectionstatechange")
+ def _on_connection_state_change() -> None:
+ if runner is not None and peer_connection.connectionState in {
+ "failed",
+ "closed",
+ }:
+ runner.request_close()
+
+ try:
+ await peer_connection.setRemoteDescription(
+ RTCSessionDescription(sdp=body.sdp, type=body.type),
+ )
+ peer_connection.addTrack(transport.output_track)
+ answer = await peer_connection.createAnswer()
+ await peer_connection.setLocalDescription(answer)
+ local_description = peer_connection.localDescription
+ if local_description is None:
+ raise RuntimeError("WebRTC negotiation produced no answer.")
+
+ async def _create_agent() -> RealtimeAgent:
+ return await realtime_service.create_agent(
+ user_id=user_id,
+ agent_id=body.agent_id,
+ session_id=session_id,
+ model=model,
+ )
+
+ def _remove_closed(closed: WebRTCSession) -> None:
+ if connections.get(connection_key) is closed:
+ connections.pop(connection_key, None)
+
+ runner = WebRTCSession(
+ peer_connection=peer_connection,
+ transport=transport,
+ agent_factory=_create_agent,
+ storage=storage,
+ message_bus=message_bus,
+ user_id=user_id,
+ agent_id=body.agent_id,
+ session_id=session_id,
+ on_closed=_remove_closed,
+ )
+ transport.on_disconnect = runner.request_close
+ connections[connection_key] = runner
+ runner.start()
+ if not await runner.wait_until_lock_acquired(
+ _SESSION_LOCK_ACQUIRE_TIMEOUT_SECONDS,
+ ):
+ await runner.close()
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail=f"Session {session_id!r} is already running.",
+ )
+ return RealtimeOfferResponse(
+ sdp=local_description.sdp,
+ type="answer",
+ )
+ except HTTPException:
+ await transport.close()
+ await peer_connection.close()
+ raise
+ except Exception as exc:
+ await transport.close()
+ await peer_connection.close()
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=f"WebRTC negotiation failed: {exc}",
+ ) from exc
diff --git a/src/agentscope/app/_router/_schema/__init__.py b/src/agentscope/app/_router/_schema/__init__.py
index 7f5232bf4..084f150a1 100644
--- a/src/agentscope/app/_router/_schema/__init__.py
+++ b/src/agentscope/app/_router/_schema/__init__.py
@@ -32,6 +32,13 @@ from ._embedding_model import (
ListEmbeddingModelsRequest,
)
from ._model import ListModelsResponse, ListModelsRequest
+from ._realtime import (
+ ListRealtimeModelsRequest,
+ ListRealtimeModelsResponse,
+ RealtimeConfigResponse,
+ RealtimeOfferRequest,
+ RealtimeOfferResponse,
+)
from ._tts_model import ListTTSModelsResponse, ListTTSModelsRequest
from ._schedule import (
CreateScheduleRequest,
@@ -177,6 +184,11 @@ __all__ = [
"ListEmbeddingModelsResponse",
"ListModelsRequest",
"ListModelsResponse",
+ "ListRealtimeModelsRequest",
+ "ListRealtimeModelsResponse",
+ "RealtimeConfigResponse",
+ "RealtimeOfferRequest",
+ "RealtimeOfferResponse",
# TTS Model
"ListTTSModelsRequest",
"ListTTSModelsResponse",
diff --git a/src/agentscope/app/_router/_schema/_agent.py b/src/agentscope/app/_router/_schema/_agent.py
index 750db6938..91baaecde 100644
--- a/src/agentscope/app/_router/_schema/_agent.py
+++ b/src/agentscope/app/_router/_schema/_agent.py
@@ -5,33 +5,42 @@ import warnings
from pydantic import BaseModel, Field
from ....agent import ContextConfig, ReActConfig
-from ...storage import InviteConfig
+from ...storage import AgentChatConfig, InviteConfig
from ..._service import AgentView
class CreateAgentRequest(BaseModel):
- """Request body for creating a new agent."""
+ """Request body for creating a new agent.
+
+ Mirrors :class:`AgentData`, so the shape a client reads back is the
+ shape it writes. The three pre-``chat_config`` fields below are
+ still accepted and are folded into it by
+ :class:`AgentData`; sending both puts the flat one on top.
+ """
name: str = Field(description="Display name of the agent.")
system_prompt: str = Field(
default="You're a helpful assistant.",
description="Base system prompt fed to the agent.",
)
- context_config: ContextConfig = Field(
- default_factory=ContextConfig,
- description="Context-window management configuration.",
+ chat_config: AgentChatConfig = Field(
+ default_factory=AgentChatConfig,
+ description="Settings for the agent's text conversations.",
)
- react_config: ReActConfig = Field(
- default_factory=ReActConfig,
- description="ReAct loop configuration.",
+ context_config: ContextConfig | None = Field(
+ default=None,
+ description="**Deprecated.** Use ``chat_config.context_config``.",
+ deprecated=True,
)
- invite_config: InviteConfig = Field(
- default_factory=InviteConfig,
- description=(
- "Invite-pool settings for this agent. See "
- ":class:`InviteConfig` — enforces the "
- "``invitable ⇒ non-empty description`` invariant."
- ),
+ react_config: ReActConfig | None = Field(
+ default=None,
+ description="**Deprecated.** Use ``chat_config.react_config``.",
+ deprecated=True,
+ )
+ invite_config: InviteConfig | None = Field(
+ default=None,
+ description="**Deprecated.** Use ``chat_config.invite_config``.",
+ deprecated=True,
)
@@ -52,21 +61,30 @@ class UpdateAgentRequest(BaseModel):
default=None,
description="New system prompt.",
)
+ chat_config: AgentChatConfig | None = Field(
+ default=None,
+ description=(
+ "New text-conversation settings. Only supplied sub-configs "
+ "are replaced; omitted sub-configs keep their current values."
+ ),
+ )
context_config: ContextConfig | None = Field(
default=None,
- description="New context configuration.",
+ description=(
+ "**Deprecated.** Use ``chat_config``. Still honoured, and "
+ "narrower: it replaces only this sub-config."
+ ),
+ deprecated=True,
)
react_config: ReActConfig | None = Field(
default=None,
- description="New ReAct loop configuration.",
+ description="**Deprecated.** Use ``chat_config``.",
+ deprecated=True,
)
invite_config: InviteConfig | None = Field(
default=None,
- description=(
- "New invite-pool settings. Pass the full :class:`InviteConfig` "
- "object to update; omit to leave both invitable-related "
- "fields unchanged."
- ),
+ description="**Deprecated.** Use ``chat_config``.",
+ deprecated=True,
)
diff --git a/src/agentscope/app/_router/_schema/_realtime.py b/src/agentscope/app/_router/_schema/_realtime.py
new file mode 100644
index 000000000..6510753e8
--- /dev/null
+++ b/src/agentscope/app/_router/_schema/_realtime.py
@@ -0,0 +1,49 @@
+# -*- coding: utf-8 -*-
+"""Realtime model and WebRTC negotiation schemas."""
+
+from typing import Literal
+
+from pydantic import BaseModel, Field
+
+from ....realtime import RealtimeModelCard
+from ..._types import RealtimeIceServer
+
+
+class ListRealtimeModelsRequest(BaseModel):
+ """List realtime models for one credential provider."""
+
+ provider: str = Field(
+ description="The credential provider type.",
+ )
+
+
+class ListRealtimeModelsResponse(BaseModel):
+ """Realtime model candidates exposed by a credential provider."""
+
+ models: list[RealtimeModelCard] = Field(
+ description="The candidate realtime models.",
+ )
+ total: int = Field(description="The total number of candidates.")
+
+
+class RealtimeConfigResponse(BaseModel):
+ """Browser-facing WebRTC configuration."""
+
+ ice_servers: list[RealtimeIceServer] = Field(
+ description="RTCIceServer-compatible dictionaries.",
+ )
+
+
+class RealtimeOfferRequest(BaseModel):
+ """A browser WebRTC offer for a persisted session."""
+
+ agent_id: str = Field(description="The agent that owns the session.")
+ sdp: str = Field(description="The browser's SDP offer.")
+ type: Literal["offer"] = "offer"
+
+
+class RealtimeOfferResponse(BaseModel):
+ """The server WebRTC answer."""
+
+ sdp: str = Field(description="The server's SDP answer.")
+ type: Literal["answer"] = "answer"
diff --git a/src/agentscope/app/_router/_schema/_session.py b/src/agentscope/app/_router/_schema/_session.py
index ca393b6e3..4f54cc63f 100644
--- a/src/agentscope/app/_router/_schema/_session.py
+++ b/src/agentscope/app/_router/_schema/_session.py
@@ -5,6 +5,7 @@ from pydantic import BaseModel, Field
from ....permission import PermissionMode
from ...storage import (
ChatModelConfig,
+ RealtimeModelConfig,
SessionKnowledgeConfig,
TTSModelConfig,
SessionRecord,
@@ -86,6 +87,12 @@ class CreateSessionRequest(BaseModel):
default=None,
description="TTS model configuration. Can be set later via PATCH.",
)
+ realtime_model_config: RealtimeModelConfig | None = Field(
+ default=None,
+ description=(
+ "Realtime voice model configuration. Can be set later via PATCH."
+ ),
+ )
knowledge_config: SessionKnowledgeConfig | None = Field(
default=None,
description=(
@@ -128,6 +135,11 @@ class UpdateSessionRequest(BaseModel):
description="New TTS model configuration. "
"Pass null to clear; omit to leave unchanged.",
)
+ realtime_model_config: RealtimeModelConfig | None = Field(
+ default=None,
+ description="New realtime voice model configuration. "
+ "Pass null to clear; omit to leave unchanged.",
+ )
knowledge_config: SessionKnowledgeConfig | None = Field(
default=None,
description=(
@@ -217,6 +229,12 @@ class ListMessagesResponse(BaseModel):
"""Response body for listing messages in a session."""
messages: list = Field(description="Messages in chronological order.")
+ event_cursor: str | None = Field(
+ default=None,
+ description=(
+ "Latest replay event already included in these messages."
+ ),
+ )
is_running: bool = Field(
description="Whether the session is currently running.",
)
diff --git a/src/agentscope/app/_router/_session.py b/src/agentscope/app/_router/_session.py
index 34b620c9e..7082782c1 100644
--- a/src/agentscope/app/_router/_session.py
+++ b/src/agentscope/app/_router/_session.py
@@ -42,6 +42,7 @@ from .._service import (
)
from ..storage import (
ChatModelConfig,
+ RealtimeModelConfig,
SessionKnowledgeConfig,
TTSModelConfig,
SessionConfig,
@@ -130,7 +131,7 @@ session_router = APIRouter(
async def _ensure_credential_exists(
access: ResourceAccessService,
user_id: str,
- config: ChatModelConfig | TTSModelConfig | None,
+ config: ChatModelConfig | RealtimeModelConfig | TTSModelConfig | None,
) -> None:
"""Validate that the credential referenced by ``config`` is visible to
the given user (own or shared). No-op when ``config`` is ``None``.
@@ -138,8 +139,8 @@ async def _ensure_credential_exists(
Args:
access (`ResourceAccessService`): Injected access service.
user_id (`str`): The authenticated user ID.
- config (`ChatModelConfig | TTSModelConfig | None`): Model config to
- validate. Pass ``None`` to skip the check.
+ config (`ChatModelConfig | RealtimeModelConfig | TTSModelConfig | \
+ None`): Model config to validate. Pass ``None`` to skip the check.
Raises:
`HTTPException`: 404 if the credential does not exist or is not
@@ -330,6 +331,11 @@ async def create_session(
body.fallback_chat_model_config,
)
await _ensure_credential_exists(access, user_id, body.tts_model_config)
+ await _ensure_credential_exists(
+ access,
+ user_id,
+ body.realtime_model_config,
+ )
await _ensure_knowledge_bases_exist(
access,
user_id,
@@ -356,6 +362,7 @@ async def create_session(
chat_model_config=body.chat_model_config,
fallback_chat_model_config=body.fallback_chat_model_config,
tts_model_config=body.tts_model_config,
+ realtime_model_config=body.realtime_model_config,
knowledge_config=body.knowledge_config,
# A caller that named the session owns that name; anything
# else starts on the creation timestamp and is the server's
@@ -514,6 +521,11 @@ async def update_session(
body.fallback_chat_model_config,
)
await _ensure_credential_exists(access, user_id, body.tts_model_config)
+ await _ensure_credential_exists(
+ access,
+ user_id,
+ body.realtime_model_config,
+ )
await _ensure_knowledge_bases_exist(
access,
user_id,
@@ -619,7 +631,8 @@ async def list_messages(
message_bus: Injected message bus.
Returns:
- Messages, running status, and whether more pages exist.
+ Messages, their replay cursor, running status, and whether more
+ pages exist.
"""
existing = await storage.get_session(user_id, agent_id, session_id)
if existing is None:
@@ -633,15 +646,35 @@ async def list_messages(
if offset is not None:
extra["offset"] = offset
- messages, has_more = await storage.list_messages(
- user_id,
- session_id,
- limit=limit,
- before=before,
- **extra,
- )
+ event_cursor = None
+ if before is not None or offset is not None:
+ messages, has_more = await storage.list_messages(
+ user_id,
+ session_id,
+ limit=limit,
+ before=before,
+ **extra,
+ )
+ else:
+ checkpoint_key = MessageBusKeys.session_event_checkpoint(session_id)
+ async with message_bus.acquire_lock(
+ MessageBusKeys.session_event_checkpoint_lock(session_id),
+ ttl_secs=(MessageBusKeys.SESSION_EVENT_CHECKPOINT_LOCK_TTL_SECS),
+ ):
+ event_cursor = await message_bus.registry_get(
+ checkpoint_key,
+ MessageBusKeys.SESSION_EVENT_CURSOR_FIELD,
+ )
+ messages, has_more = await storage.list_messages(
+ user_id,
+ session_id,
+ limit=limit,
+ before=before,
+ **extra,
+ )
return ListMessagesResponse(
messages=messages,
+ event_cursor=event_cursor,
is_running=await message_bus.is_locked(
MessageBusKeys.session_lock(session_id),
),
@@ -715,6 +748,7 @@ async def get_session_status(
# ----------------------------------------------------------------------
_HEARTBEAT_INTERVAL_SECS = 30
+_SUBSCRIBE_TIMEOUT_SECS = 5.0
# Interval between SSE heartbeat comment frames (``:\\n\\n``).
@@ -781,6 +815,11 @@ async def _worker_still_asking(
async def stream_session_events(
session_id: str,
agent_id: str = Query(description="Agent the session belongs to."),
+ after: str
+ | None = Query(
+ None,
+ description=("Replay only events after this checkpoint cursor."),
+ ),
user_id: str = Depends(get_current_user_id),
storage: StorageBase = Depends(get_storage),
message_bus: MessageBus = Depends(get_message_bus),
@@ -803,6 +842,8 @@ async def stream_session_events(
agent_id (`str`):
The agent that owns the session (used for ownership
validation).
+ after (`str | None`):
+ Persisted replay cursor returned by the messages endpoint.
user_id (`str`):
Injected authenticated user id.
storage (`StorageBase`):
@@ -822,62 +863,8 @@ async def stream_session_events(
)
async def _sse_generator() -> AsyncGenerator[str, None]:
- # 1. Replay buffered events from the current run (if any).
- for _entry_id, event in await message_bus.log_read(
- MessageBusKeys.session_events(session_id),
- max_count=MessageBusKeys.SESSION_REPLAY_MAX_LEN,
- ):
- yield f"data: {json.dumps(event, ensure_ascii=False)}\n\n"
-
- # 1b. Inject pending subagent HITL cards projected onto this
- # session as a team leader (design §3.5). These live in a
- # durable Redis hash — NOT in the replay log (trimmed per
- # run) nor in the leader's own Msg history — so a fresh
- # reconnect after the worker parked still surfaces them.
- #
- # Reconcile-on-read: the worker session's own context is the
- # SSOT. Inject only when the worker is still ASKING; drop and
- # delete ghosts (worker resolved/cancelled without clearing).
- projection = SessionProjection(message_bus)
- for payload in await projection.list(
- session_id,
- SubagentHitlProjector.KIND,
- ):
- if not await _worker_still_asking(
- storage,
- user_id,
- payload["worker_agent_id"],
- payload["worker_session_id"],
- payload["reply_id"],
- ):
- await projection.delete(
- session_id,
- SubagentHitlProjector.KIND,
- SubagentHitlProjector.entry_id(
- payload["worker_session_id"],
- payload["reply_id"],
- ),
- )
- continue
- custom = CustomEvent(
- name=SubagentHitlProjector.EVT_REQUIRE,
- value=payload,
- )
- data = json.dumps(
- custom.model_dump(mode="json"),
- ensure_ascii=False,
- )
-
- yield f"data: {data}\n\n"
-
- # 2. Live subscribe via a background feeder task that pushes
- # events into a queue. The main loop reads from the queue
- # with a timeout so we can interleave heartbeat frames.
- #
- # We avoid calling ``wait_for(__anext__())`` on the async
- # generator directly because cancelling a suspended
- # ``__anext__`` leaves the generator in a "running" state
- # that prevents ``aclose()`` from working.
+ events_key = MessageBusKeys.session_events(session_id)
+ ready = asyncio.Event()
queue: asyncio.Queue[dict | None] = asyncio.Queue()
async def _feeder() -> None:
@@ -888,11 +875,10 @@ async def stream_session_events(
"""
try:
async for evt in message_bus.subscribe(
- MessageBusKeys.session_events(session_id),
+ events_key,
+ on_ready=ready.set,
):
- await queue.put(
- {k: v for k, v in evt.items() if k != "_entry_id"},
- )
+ await queue.put(evt)
except asyncio.CancelledError:
pass
finally:
@@ -904,6 +890,55 @@ async def stream_session_events(
)
try:
+ # Subscribe first, then replay. Events arriving across that
+ # seam are present in both paths and deduplicated by entry id.
+ await asyncio.wait_for(
+ ready.wait(),
+ timeout=_SUBSCRIBE_TIMEOUT_SECS,
+ )
+ seen_entry_ids: set[str] = set()
+ for entry_id, event in await message_bus.log_read(
+ events_key,
+ since=after,
+ max_count=MessageBusKeys.SESSION_REPLAY_MAX_LEN,
+ ):
+ seen_entry_ids.add(str(entry_id))
+ yield f"data: {json.dumps(event, ensure_ascii=False)}\n\n"
+
+ # Inject pending subagent HITL cards projected onto this
+ # session as a team leader. These live in a durable registry,
+ # outside the replay log.
+ projection = SessionProjection(message_bus)
+ for payload in await projection.list(
+ session_id,
+ SubagentHitlProjector.KIND,
+ ):
+ if not await _worker_still_asking(
+ storage,
+ user_id,
+ payload["worker_agent_id"],
+ payload["worker_session_id"],
+ payload["reply_id"],
+ ):
+ await projection.delete(
+ session_id,
+ SubagentHitlProjector.KIND,
+ SubagentHitlProjector.entry_id(
+ payload["worker_session_id"],
+ payload["reply_id"],
+ ),
+ )
+ continue
+ custom = CustomEvent(
+ name=SubagentHitlProjector.EVT_REQUIRE,
+ value=payload,
+ )
+ data = json.dumps(
+ custom.model_dump(mode="json"),
+ ensure_ascii=False,
+ )
+ yield f"data: {data}\n\n"
+
while True:
try:
item = await asyncio.wait_for(
@@ -912,7 +947,18 @@ async def stream_session_events(
)
if item is None:
break
- yield f"data: {json.dumps(item, ensure_ascii=False)}\n\n"
+ entry_id = item.get("_entry_id")
+ if entry_id is not None:
+ entry_id = str(entry_id)
+ if entry_id in seen_entry_ids:
+ continue
+ payload = {
+ key: value
+ for key, value in item.items()
+ if key != "_entry_id"
+ }
+ data = json.dumps(payload, ensure_ascii=False)
+ yield f"data: {data}\n\n"
except asyncio.TimeoutError:
yield ":\n\n"
finally:
diff --git a/src/agentscope/app/_service/__init__.py b/src/agentscope/app/_service/__init__.py
index 200a6faea..8c89d99a8 100644
--- a/src/agentscope/app/_service/__init__.py
+++ b/src/agentscope/app/_service/__init__.py
@@ -19,11 +19,12 @@ from ._index_task_consumer import IndexTaskConsumer
from ._index_worker import IndexWorker
from ._knowledge_base import KnowledgeBaseService
from ._mcp_render import MCPRenderError, render_mcp
-from ._model import get_model
+from ._model import get_model, get_realtime_model
from ._tts_model import get_tts_model
from ._session import SessionService, SessionStatus
from ._session_projection import SessionProjection
from ._projectors import SubagentHitlProjector
+from ._realtime import RealtimeService
from ._sop import SessionSOPStep, SOPService
from ._toolkit import get_toolkit
from ._download_token import sign_download_token, verify_download_token
@@ -45,6 +46,7 @@ __all__ = [
"KnowledgeBaseView",
"MCPRenderError",
"ResourceAccessService",
+ "RealtimeService",
"SessionSOPStep",
"SOPService",
"SessionService",
@@ -57,6 +59,7 @@ __all__ = [
"WorkspaceStatus",
"get_embedding_model",
"get_model",
+ "get_realtime_model",
"get_tts_model",
"get_toolkit",
"render_mcp",
diff --git a/src/agentscope/app/_service/_access.py b/src/agentscope/app/_service/_access.py
index 4f4fce042..966891e7f 100644
--- a/src/agentscope/app/_service/_access.py
+++ b/src/agentscope/app/_service/_access.py
@@ -3,10 +3,15 @@
from __future__ import annotations
from datetime import datetime
-from typing import Any, Literal, TypeVar, overload
+from typing import Any, Literal, TypeVar, cast, overload
from fastapi import HTTPException, status
-from pydantic import AliasChoices, BaseModel, Field, model_validator
+from pydantic import (
+ AliasChoices,
+ BaseModel,
+ Field,
+ model_validator,
+)
from ..access import (
ResourceAccessPolicyBase,
@@ -32,9 +37,8 @@ from ..storage import (
class AgentView(AgentRecord):
"""Agent record + viewer-relative ``editable``.
- Subclasses :class:`AgentRecord` so the wire format is a strict
- superset of the historical response (one extra top-level field);
- old clients ignore ``editable`` transparently.
+ Subclasses :class:`AgentRecord` so the stored agent data keeps its
+ declared response schema, with one extra top-level field.
"""
editable: bool = Field(
@@ -182,6 +186,13 @@ class KnowledgeBaseView(BaseModel):
return merged
+ResourceKindValue = Literal["credential", "agent", "knowledge_base"]
+ResourceView = CredentialView | AgentView | KnowledgeBaseView
+ResourceViewList = (
+ list[CredentialView] | list[AgentView] | list[KnowledgeBaseView]
+)
+
+
# ---------------------------------------------------------------------
# Service
# ---------------------------------------------------------------------
@@ -221,7 +232,7 @@ class ResourceAccessService:
async def list_resource(
self,
viewer_id: str,
- kind: Literal[ResourceKind.CREDENTIAL],
+ kind: Literal["credential"],
) -> list[CredentialView]:
...
@@ -229,7 +240,7 @@ class ResourceAccessService:
async def list_resource(
self,
viewer_id: str,
- kind: Literal[ResourceKind.AGENT],
+ kind: Literal["agent"],
) -> list[AgentView]:
...
@@ -237,15 +248,23 @@ class ResourceAccessService:
async def list_resource(
self,
viewer_id: str,
- kind: Literal[ResourceKind.KNOWLEDGE_BASE],
+ kind: Literal["knowledge_base"],
) -> list[KnowledgeBaseView]:
...
+ @overload
async def list_resource(
self,
viewer_id: str,
kind: ResourceKind,
- ) -> list[BaseModel]:
+ ) -> ResourceViewList:
+ ...
+
+ async def list_resource(
+ self,
+ viewer_id: str,
+ kind: ResourceKind | ResourceKindValue,
+ ) -> ResourceViewList:
"""List resources of ``kind`` visible to ``viewer_id``.
The result merges the viewer's own records (always ``editable``)
@@ -255,9 +274,10 @@ class ResourceAccessService:
:meth:`resolve_credential` should be used when the raw payload
is required for runtime provider calls.
"""
- if kind is ResourceKind.CREDENTIAL:
+ resource_kind = ResourceKind(kind)
+ if resource_kind is ResourceKind.CREDENTIAL:
own = await self._storage.list_credentials(viewer_id)
- elif kind is ResourceKind.AGENT:
+ elif resource_kind is ResourceKind.AGENT:
own = [
record
for record in await self._storage.list_agents(viewer_id)
@@ -266,17 +286,17 @@ class ResourceAccessService:
else:
own = await self._storage.list_knowledge_bases(viewer_id)
- views: list[BaseModel] = [
+ views: list[ResourceView] = [
self._build_view(record, viewer_id, True) for record in own
]
seen = {(record.user_id, record.id) for record in own}
- for ref in await self._list_refs(viewer_id, kind):
+ for ref in await self._list_refs(viewer_id, resource_kind):
key = (ref.owner_id, ref.resource_id)
if key in seen:
continue
record = await self._get_owned(
- kind,
+ resource_kind,
ref.owner_id,
ref.resource_id,
)
@@ -294,7 +314,7 @@ class ResourceAccessService:
),
)
seen.add(key)
- return views
+ return cast(ResourceViewList, views)
# ------------------------------------------------------------------
# get_resource
@@ -304,7 +324,7 @@ class ResourceAccessService:
async def get_resource(
self,
viewer_id: str,
- kind: Literal[ResourceKind.CREDENTIAL],
+ kind: Literal["credential"],
resource_id: str,
) -> CredentialView:
...
@@ -313,7 +333,7 @@ class ResourceAccessService:
async def get_resource(
self,
viewer_id: str,
- kind: Literal[ResourceKind.AGENT],
+ kind: Literal["agent"],
resource_id: str,
) -> AgentView:
...
@@ -322,17 +342,26 @@ class ResourceAccessService:
async def get_resource(
self,
viewer_id: str,
- kind: Literal[ResourceKind.KNOWLEDGE_BASE],
+ kind: Literal["knowledge_base"],
resource_id: str,
) -> KnowledgeBaseView:
...
+ @overload
async def get_resource(
self,
viewer_id: str,
kind: ResourceKind,
resource_id: str,
- ) -> BaseModel:
+ ) -> ResourceView:
+ ...
+
+ async def get_resource(
+ self,
+ viewer_id: str,
+ kind: ResourceKind | ResourceKindValue,
+ resource_id: str,
+ ) -> ResourceView:
"""Get a visible resource by id or raise ``404``.
Returns the viewer-relative view so the caller does not have to
@@ -343,18 +372,23 @@ class ResourceAccessService:
is masked for shared entries — use :meth:`resolve_credential`
for runtime provider calls.
"""
- own = await self._get_owned(kind, viewer_id, resource_id)
+ resource_kind = ResourceKind(kind)
+ own = await self._get_owned(
+ resource_kind,
+ viewer_id,
+ resource_id,
+ )
if own is not None:
# Owner-side reads bypass the ``team`` filter on purpose:
# runtime paths legitimately load the owner's ``source ==
# "team"`` agents, and we want a single call site.
return self._build_view(own, viewer_id, True)
- for ref in await self._list_refs(viewer_id, kind):
+ for ref in await self._list_refs(viewer_id, resource_kind):
if ref.resource_id != resource_id:
continue
record = await self._get_owned(
- kind,
+ resource_kind,
ref.owner_id,
ref.resource_id,
)
@@ -367,7 +401,7 @@ class ResourceAccessService:
viewer_id,
ref.permission == ResourcePermission.EDIT,
)
- raise self._not_found(kind, resource_id)
+ raise self._not_found(resource_kind, resource_id)
# ------------------------------------------------------------------
# Runtime-only helpers
@@ -550,7 +584,7 @@ class ResourceAccessService:
record: Any,
viewer_id: str,
editable: bool,
- ) -> BaseModel:
+ ) -> ResourceView:
"""Project a raw storage record onto a viewer-relative view.
Credential ``data`` is masked when the viewer is not the owner
diff --git a/src/agentscope/app/_service/_chat.py b/src/agentscope/app/_service/_chat.py
index a66c2edc6..a8f374cb7 100644
--- a/src/agentscope/app/_service/_chat.py
+++ b/src/agentscope/app/_service/_chat.py
@@ -88,6 +88,11 @@ if TYPE_CHECKING:
from ..channel import ChannelClients
+_CHECKPOINT_LOCK_TTL_SECS = (
+ MessageBusKeys.SESSION_EVENT_CHECKPOINT_LOCK_TTL_SECS
+)
+
+
@dataclass(frozen=True)
class _LeaderContext:
"""This session leads its team."""
@@ -436,7 +441,7 @@ class ChatService:
session_id: str,
reply_msg: Msg,
error: Exception,
- ) -> None:
+ ) -> str | None:
"""Close a reply that died mid-stream, and say why.
The stream never emitted its terminating ``ReplyEndEvent``, so
@@ -463,7 +468,7 @@ class ChatService:
"completed.",
session_id,
)
- return
+ return None
end_event = ReplyEndEvent(
session_id=session_id,
@@ -472,7 +477,7 @@ class ChatService:
error=_classify_error(error),
)
reply_msg.append_event(end_event)
- await publish_session_event(
+ entry_id = await publish_session_event(
self._message_bus,
session_id,
end_event.model_dump(mode="json"),
@@ -482,6 +487,7 @@ class ChatService:
session_id,
end_event.error.type if end_event.error else "error",
)
+ return entry_id
async def _notify_leader_of_failure(
self,
@@ -633,18 +639,28 @@ class ChatService:
name=agent_id,
content=[],
)
+ checkpoint_cursor = ""
for event in (start_event, end_event):
reply_msg.append_event(event)
- await publish_session_event(
+ checkpoint_cursor = await publish_session_event(
self._message_bus,
session_id,
event.model_dump(mode="json"),
)
- await self._storage.upsert_message(
- user_id,
- session_id,
- reply_msg,
- )
+ async with self._message_bus.acquire_lock(
+ MessageBusKeys.session_event_checkpoint_lock(session_id),
+ ttl_secs=_CHECKPOINT_LOCK_TTL_SECS,
+ ):
+ await self._storage.upsert_message(
+ user_id,
+ session_id,
+ reply_msg,
+ )
+ await self._message_bus.registry_set(
+ MessageBusKeys.session_event_checkpoint(session_id),
+ MessageBusKeys.SESSION_EVENT_CURSOR_FIELD,
+ checkpoint_cursor,
+ )
except Exception:
logger.exception(
"Failed to report a failure for session %r; the original "
@@ -1159,14 +1175,15 @@ class ChatService:
agent_state = session_record.state
agent_state.session_id = session_id
+ chat_config = agent_record.data.chat_config
agent = self._agent_cls(
name=agent_record.data.name,
system_prompt=system_prompt,
model=model,
toolkit=toolkit,
model_config=ModelConfig(fallback_model=fallback_model),
- context_config=agent_record.data.context_config,
- react_config=agent_record.data.react_config,
+ context_config=chat_config.context_config,
+ react_config=chat_config.react_config,
state=agent_state,
middlewares=middlewares,
offloader=workspace,
@@ -1192,7 +1209,6 @@ class ChatService:
# ----------------------------------------------------------------
# 7. Run the agent (still under the session lock)
# -----------------------------------------------------------------
- events_key = MessageBusKeys.session_events(session_id)
# Channel-bound run: start streaming the reply back to the
# platform chat. Delivery is plain REST, so this node does it
# rather than handing the run to whichever one holds the
@@ -1210,6 +1226,7 @@ class ChatService:
)
reply_msg: Msg | None = None
reply_msgs: list[Msg] = []
+ checkpoint_cursor: str | None = None
released = False
# Text of the user turn that opened this run, captured
@@ -1262,10 +1279,12 @@ class ChatService:
elif reply_msg is not None:
reply_msg.append_event(event)
try:
- await publish_session_event(
- self._message_bus,
- session_id,
- event.model_dump(mode="json"),
+ checkpoint_cursor = (
+ await publish_session_event(
+ self._message_bus,
+ session_id,
+ event.model_dump(mode="json"),
+ )
)
await self._project_event(
user_id,
@@ -1316,10 +1335,12 @@ class ChatService:
ExternalExecutionResultEvent,
),
):
- await publish_session_event(
- self._message_bus,
- session_id,
- input_msg.model_dump(mode="json"),
+ checkpoint_cursor = (
+ await publish_session_event(
+ self._message_bus,
+ session_id,
+ input_msg.model_dump(mode="json"),
+ )
)
# Emit a synthetic REPLY_START so SSE subscribers
@@ -1337,7 +1358,7 @@ class ChatService:
reply_id=agent.state.reply_id,
name=agent_record.data.name,
)
- await publish_session_event(
+ checkpoint_cursor = await publish_session_event(
self._message_bus,
session_id,
continuation_start.model_dump(mode="json"),
@@ -1352,10 +1373,12 @@ class ChatService:
if reply_msg is not None:
reply_msg.append_event(event)
try:
- await publish_session_event(
- self._message_bus,
- session_id,
- event.model_dump(mode="json"),
+ checkpoint_cursor = (
+ await publish_session_event(
+ self._message_bus,
+ session_id,
+ event.model_dump(mode="json"),
+ )
)
await self._project_event(
user_id,
@@ -1387,11 +1410,13 @@ class ChatService:
worker_name,
)
else:
- await self._close_failed_reply(
+ failure_cursor = await self._close_failed_reply(
session_id,
reply_msg,
e,
)
+ if failure_cursor is not None:
+ checkpoint_cursor = failure_cursor
# A failed turn stops the run; whatever is still
# queued is handed to a fresh one by the
@@ -1455,19 +1480,36 @@ class ChatService:
# before this write lands.
async def _persist() -> None:
try:
- for msg in reply_msgs:
- await self._storage.upsert_message(
- user_id,
+ async with self._message_bus.acquire_lock(
+ MessageBusKeys.session_event_checkpoint_lock(
session_id,
- msg,
+ ),
+ ttl_secs=_CHECKPOINT_LOCK_TTL_SECS,
+ ):
+ for msg in reply_msgs:
+ await self._storage.upsert_message(
+ user_id,
+ session_id,
+ msg,
+ )
+ await self._storage.update_session_state(
+ user_id=user_id,
+ agent_id=agent_id,
+ session_id=session_id,
+ state=agent.state,
)
- await self._storage.update_session_state(
- user_id=user_id,
- agent_id=agent_id,
- session_id=session_id,
- state=agent.state,
- )
- await self._message_bus.log_trim(events_key)
+ if checkpoint_cursor is not None:
+ await self._message_bus.registry_set(
+ MessageBusKeys.session_event_checkpoint(
+ session_id,
+ ),
+ MessageBusKeys.SESSION_EVENT_CURSOR_FIELD,
+ checkpoint_cursor,
+ )
+ await self._message_bus.log_trim(
+ MessageBusKeys.session_events(session_id),
+ before_id=checkpoint_cursor,
+ )
finally:
# A worker whose turn died never reached
# ``TeamSay``. Sent from inside the shielded
diff --git a/src/agentscope/app/_service/_model.py b/src/agentscope/app/_service/_model.py
index 739391f0d..1f5fc6b12 100644
--- a/src/agentscope/app/_service/_model.py
+++ b/src/agentscope/app/_service/_model.py
@@ -1,9 +1,10 @@
# -*- coding: utf-8 -*-
"""Model service: builds a ChatModelBase from stored credential + config."""
from ._access import ResourceAccessService
-from ..storage import ChatModelConfig
+from ..storage import ChatModelConfig, RealtimeModelConfig
from ...credential import CredentialFactory
from ...model import ChatModelBase
+from ...realtime import RealtimeModelBase
from ..._logging import logger
@@ -73,3 +74,59 @@ async def get_model(
)
return model
+
+
+async def get_realtime_model(
+ user_id: str,
+ config: RealtimeModelConfig,
+ access: ResourceAccessService,
+) -> RealtimeModelBase:
+ """Build a realtime model from a stored credential and config.
+
+ Args:
+ user_id (`str`): The viewer's user id.
+ config (`RealtimeModelConfig`): The realtime model configuration.
+ access (`ResourceAccessService`): Injected access service.
+
+ Returns:
+ `RealtimeModelBase`: The matching realtime model instance.
+
+ Raises:
+ `ValueError`: If the credential does not expose the configured
+ realtime adapter or model.
+ """
+ credential_record = await access.resolve_credential(
+ user_id,
+ config.credential_id,
+ )
+ credential = CredentialFactory.from_dict(credential_record.data)
+
+ for model_cls in credential.get_realtime_model_classes():
+ if model_cls.type != config.type:
+ continue
+ card = next(
+ (
+ candidate
+ for candidate in model_cls.list_models()
+ if candidate.name == config.model
+ ),
+ None,
+ )
+ if card is None:
+ continue
+ parameters = (
+ model_cls.Parameters(**config.parameters)
+ if config.parameters
+ else None
+ )
+ return model_cls(
+ credential=credential,
+ model=config.model,
+ parameters=parameters,
+ model_card=card,
+ )
+
+ raise ValueError(
+ f"Realtime model {config.model!r} with type {config.type!r} "
+ f"is not available for credential {config.credential_id!r}.",
+ )
diff --git a/src/agentscope/app/_service/_realtime.py b/src/agentscope/app/_service/_realtime.py
new file mode 100644
index 000000000..153e32838
--- /dev/null
+++ b/src/agentscope/app/_service/_realtime.py
@@ -0,0 +1,188 @@
+# -*- coding: utf-8 -*-
+"""Runtime assembly for browser realtime agents."""
+
+from typing import Literal
+
+from ..._logging import logger
+from ...agent import RealtimeAgent
+from ...permission import AdditionalWorkingDirectory
+from ...realtime import RealtimeModelBase
+from .._manager import BackgroundTaskManager, SchedulerManager
+from .._types import AgentToolFactory, SubAgentTemplate
+from ...tool import ToolBase
+from ..channel import ChannelBase, ChannelClients, ChatKind
+from ..message_bus import MessageBus
+from ..storage import ChannelOrigin, SessionRecord, StorageBase
+from ..workspace_manager import WorkspaceManagerBase
+from ._access import ResourceAccessService
+from ._toolkit import get_toolkit
+
+
+class RealtimeService:
+ """Assemble a persisted session as a toolkit-enabled realtime agent."""
+
+ def __init__(
+ self,
+ *,
+ storage: StorageBase,
+ workspace_manager: WorkspaceManagerBase,
+ scheduler_manager: SchedulerManager,
+ background_task_manager: BackgroundTaskManager,
+ message_bus: MessageBus,
+ resource_access_service: ResourceAccessService,
+ extra_agent_tools: AgentToolFactory | None = None,
+ custom_subagent_templates: dict[str, SubAgentTemplate] | None = None,
+ channel_clients: ChannelClients | None = None,
+ ) -> None:
+ self._storage = storage
+ self._workspace_manager = workspace_manager
+ self._scheduler_manager = scheduler_manager
+ self._background_task_manager = background_task_manager
+ self._message_bus = message_bus
+ self._access = resource_access_service
+ self._extra_agent_tools = extra_agent_tools
+ self._subagent_templates = custom_subagent_templates or {}
+ self._channel_clients = channel_clients
+
+ async def create_agent(
+ self,
+ *,
+ user_id: str,
+ agent_id: str,
+ session_id: str,
+ model: RealtimeModelBase,
+ ) -> RealtimeAgent:
+ """Load the locked session and assemble its realtime runtime."""
+ agent_record = await self._access.resolve_agent(user_id, agent_id)
+ session = await self._storage.get_session(
+ user_id,
+ agent_id,
+ session_id,
+ )
+ if session is None:
+ raise RuntimeError(f"Session {session_id!r} no longer exists.")
+
+ workspace = await self._workspace_manager.get_workspace(
+ user_id,
+ agent_id,
+ session_id,
+ session.config.workspace_id,
+ )
+ working_dirs = session.state.permission_context.working_directories
+ if workspace.workdir not in working_dirs:
+ working_dirs[workspace.workdir] = AdditionalWorkingDirectory(
+ path=workspace.workdir,
+ source="session",
+ )
+
+ team_role = await self._resolve_team_role(user_id, session)
+ channel_origin = (
+ session.origin
+ if isinstance(session.origin, ChannelOrigin)
+ else None
+ )
+ channel = (
+ await self._channel_clients.get(channel_origin.channel_id)
+ if channel_origin is not None and self._channel_clients is not None
+ else None
+ )
+ chat_kind = (
+ await channel.chat_kind(channel_origin.chat_id)
+ if channel is not None and channel_origin is not None
+ else None
+ )
+ channel_tools = (
+ await channel.list_tools(
+ workspace,
+ channel_origin.channel_user_id
+ if chat_kind is ChatKind.PRIVATE
+ else None,
+ )
+ if channel is not None and channel_origin is not None
+ else []
+ )
+ toolkit = await get_toolkit(
+ storage=self._storage,
+ workspace=workspace,
+ workspace_manager=self._workspace_manager,
+ scheduler_manager=self._scheduler_manager,
+ background_task_manager=self._background_task_manager,
+ message_bus=self._message_bus,
+ middlewares=[],
+ user_id=user_id,
+ agent_record=agent_record,
+ session_record=session,
+ resource_access_service=self._access,
+ extra_factory=self._extra_agent_tools,
+ sub_agent_templates=self._subagent_templates,
+ team_role=team_role,
+ channel_tools=channel_tools,
+ )
+
+ session.state.session_id = session_id
+ system_prompt = await self._build_system_prompt(
+ agent_record.data.system_prompt,
+ session,
+ channel,
+ channel_tools,
+ chat_kind,
+ )
+ return RealtimeAgent(
+ name=agent_record.data.name,
+ system_prompt=system_prompt,
+ model=model,
+ toolkit=toolkit,
+ state=session.state,
+ )
+
+ async def _resolve_team_role(
+ self,
+ user_id: str,
+ session: SessionRecord,
+ ) -> Literal["leader", "worker"] | None:
+ """Resolve the toolkit's team role from the current team record."""
+ if session.team_id is None:
+ return None
+ team = await self._storage.get_team(user_id, session.team_id)
+ if team is None:
+ logger.warning(
+ "Session %r points at missing team %r; assembling realtime "
+ "tools without a team role.",
+ session.id,
+ session.team_id,
+ )
+ return None
+ return "leader" if team.session_id == session.id else "worker"
+
+ @staticmethod
+ async def _build_system_prompt(
+ base_prompt: str,
+ session: SessionRecord,
+ channel: ChannelBase | None,
+ channel_tools: list[ToolBase],
+ chat_kind: ChatKind | None,
+ ) -> str:
+ """Attach the session and optional channel identity to the prompt."""
+ attachment = f"You're within a session (id={session.id})."
+ if channel is not None and isinstance(session.origin, ChannelOrigin):
+ tools = ", ".join(tool.name for tool in channel_tools)
+ chat_id = session.origin.chat_id
+ name = session.origin.chat_name or await channel.chat_name(chat_id)
+ where = f' named "{name}"' if name else ""
+ attachment += (
+ f" This session is bound to a chat{where} (id "
+ f"{chat_id!r}) on the {channel.display_name} platform."
+ )
+ if chat_kind is ChatKind.GROUP:
+ attachment += " It is a group chat with multiple people."
+ elif chat_kind is ChatKind.PRIVATE:
+ attachment += " It is a one-to-one private chat."
+ if tools:
+ attachment += (
+ f" These {channel.display_name} tools are available: "
+ f"{tools}. Use this chat's id as their target."
+ )
+ return (
+ f"{base_prompt}\n\n"
+ f"<system-notification>{attachment}</system-notification>"
+ )
diff --git a/src/agentscope/app/_service/_session.py b/src/agentscope/app/_service/_session.py
index 2037489f0..b157c33d8 100644
--- a/src/agentscope/app/_service/_session.py
+++ b/src/agentscope/app/_service/_session.py
@@ -266,22 +266,22 @@ class SessionService:
unconditionally. Every process's
:class:`~agentscope.app._manager.CancelDispatcher` reacts to the
broadcast by cancelling whatever it locally holds for the
- session — the chat-run asyncio task **and** any background
- tasks owned by that session. The publisher does not need to
- know which worker holds which piece.
+ session — the chat or realtime run **and** any background tasks
+ owned by that session. The publisher does not need to know
+ which worker holds which piece.
After publishing, polls
:meth:`MessageBus.session_is_running` until the distributed
- chat-run lock clears. Only the chat run holds a distributed
- lock; BG tasks do not, so this poll only waits for the chat
- run. Returns immediately when no chat run was active.
+ session-run lock clears. Chat and realtime runs use that lock;
+ BG tasks do not, so this poll waits only for the active agent
+ run. Returns immediately when no run was active.
Idempotent: calling on an idle session just sends a no-op
broadcast and observes a clear lock.
Args:
session_id (`str`):
- The session whose chat run + BG tasks should be
+ The session whose agent run and BG tasks should be
cancelled.
timeout (`float`, defaults to ``10.0``):
Maximum seconds to wait for the chat-run lock to
@@ -291,7 +291,7 @@ class SessionService:
Returns:
`bool`:
- ``True`` if the chat-run lock was confirmed released
+ ``True`` if the session-run lock was confirmed released
within ``timeout`` seconds (or was never held).
``False`` if the lock was still held when the timeout
expired.
@@ -664,6 +664,9 @@ class SessionService:
await self._bus.registry_drop(
MessageBusKeys.bg_tasks(session_id),
)
+ await self._bus.registry_drop(
+ MessageBusKeys.session_event_checkpoint(session_id),
+ )
async def _purge_subagent_hitl(
self,
diff --git a/src/agentscope/app/_service/_toolkit.py b/src/agentscope/app/_service/_toolkit.py
index 5d20760db..f17ed4b5c 100644
--- a/src/agentscope/app/_service/_toolkit.py
+++ b/src/agentscope/app/_service/_toolkit.py
@@ -214,8 +214,10 @@ time or interval"
invitable_pool = [
view
for view in visible_agents
- if view.data.invite_config.invitable
- and (view.data.invite_config.invite_description or "").strip()
+ if view.data.chat_config.invite_config.invitable
+ and (
+ view.data.chat_config.invite_config.invite_description or ""
+ ).strip()
]
if invitable_pool:
tools.append(
diff --git a/src/agentscope/app/_service/_webrtc_audio_transport.py b/src/agentscope/app/_service/_webrtc_audio_transport.py
new file mode 100644
index 000000000..a3bf7c71d
--- /dev/null
+++ b/src/agentscope/app/_service/_webrtc_audio_transport.py
@@ -0,0 +1,417 @@
+# -*- coding: utf-8 -*-
+"""WebRTC media and control transport for browser voice sessions."""
+
+import asyncio
+import json
+import time
+import uuid
+from collections import deque
+from fractions import Fraction
+from typing import AsyncIterator, Callable
+
+import numpy as np
+from aiortc import MediaStreamTrack, RTCDataChannel
+from aiortc.mediastreams import MediaStreamError
+from av import AudioFrame as AVAudioFrame
+from av import AudioResampler
+
+from ...realtime import (
+ AudioFrame,
+ ControlFrame,
+ ControlFrameType,
+ PlayoutPosition,
+ TransportBase,
+ TransportFrame,
+)
+
+
+_END = object()
+_CLEAR_TIMEOUT_SECONDS = 2.0
+_WEBRTC_SAMPLE_RATE = 48_000
+_FRAME_DURATION_MS = 20
+_FRAME_SAMPLES = _WEBRTC_SAMPLE_RATE * _FRAME_DURATION_MS // 1_000
+_FRAME_BYTES = _FRAME_SAMPLES * 2
+_MAX_INCOMING_AUDIO_MS = 10_000
+
+
+class WebRTCAudioTrack(MediaStreamTrack):
+ """A continuous mono audio track fed by model PCM chunks."""
+
+ kind = "audio"
+
+ def __init__(
+ self,
+ source_sample_rate: int,
+ on_item_started: Callable[[str, int], None],
+ ) -> None:
+ super().__init__()
+ self._source_sample_rate = source_sample_rate
+ self._on_item_started = on_item_started
+ self._resampler = AudioResampler(
+ format="s16",
+ layout="mono",
+ rate=_WEBRTC_SAMPLE_RATE,
+ )
+ self._chunks: deque[tuple[str, bytearray]] = deque()
+ self._started_item_id = ""
+ self._pts = 0
+ self._started_at: float | None = None
+
+ def push(self, pcm: bytes, item_id: str) -> None:
+ """Resample and queue one model PCM16 chunk."""
+ if not pcm:
+ return
+ samples = np.frombuffer(pcm, dtype="<i2").reshape(1, -1)
+ frame = AVAudioFrame.from_ndarray(
+ samples,
+ format="s16",
+ layout="mono",
+ )
+ frame.sample_rate = self._source_sample_rate
+ for converted in self._resampler.resample(frame):
+ data = converted.to_ndarray().astype("<i2", copy=False).tobytes()
+ if data:
+ self._chunks.append((item_id, bytearray(data)))
+
+ def clear(self) -> int:
+ """Discard queued audio and return the next silent track time."""
+ self._chunks.clear()
+ self._resampler = AudioResampler(
+ format="s16",
+ layout="mono",
+ rate=_WEBRTC_SAMPLE_RATE,
+ )
+ return self._pts * 1_000 // _WEBRTC_SAMPLE_RATE
+
+ async def recv(self) -> AVAudioFrame:
+ """Return one paced 20 ms frame, using silence while idle."""
+ if self._started_at is None:
+ self._started_at = time.monotonic()
+ target = self._started_at + self._pts / _WEBRTC_SAMPLE_RATE
+ delay = target - time.monotonic()
+ if delay > 0:
+ await asyncio.sleep(delay)
+
+ payload = bytearray()
+ frame_item = ""
+ while self._chunks and len(payload) < _FRAME_BYTES:
+ item_id, chunk = self._chunks[0]
+ if frame_item and item_id != frame_item:
+ break
+ frame_item = item_id
+ remaining = _FRAME_BYTES - len(payload)
+ payload.extend(chunk[:remaining])
+ del chunk[:remaining]
+ if not chunk:
+ self._chunks.popleft()
+
+ if frame_item and frame_item != self._started_item_id:
+ self._started_item_id = frame_item
+ self._on_item_started(
+ frame_item,
+ self._pts * 1_000 // _WEBRTC_SAMPLE_RATE,
+ )
+
+ if len(payload) < _FRAME_BYTES:
+ payload.extend(b"\x00" * (_FRAME_BYTES - len(payload)))
+ samples = np.frombuffer(payload, dtype="<i2").reshape(1, -1)
+ frame = AVAudioFrame.from_ndarray(
+ samples,
+ format="s16",
+ layout="mono",
+ )
+ frame.sample_rate = _WEBRTC_SAMPLE_RATE
+ frame.pts = self._pts
+ frame.time_base = Fraction(1, _WEBRTC_SAMPLE_RATE)
+ self._pts += _FRAME_SAMPLES
+ return frame
+
+
+class WebRTCAudioTransport(TransportBase):
+ """Bridge WebRTC audio tracks and a control DataChannel to an agent."""
+
+ def __init__(
+ self,
+ input_sample_rate: int,
+ output_sample_rate: int,
+ ) -> None:
+ self.input_sample_rate = input_sample_rate
+ self.output_sample_rate = output_sample_rate
+ self.output_track = WebRTCAudioTrack(
+ source_sample_rate=output_sample_rate,
+ on_item_started=self._on_item_started,
+ )
+ self._incoming: deque[TransportFrame | object] = deque()
+ self._incoming_ready = asyncio.Event()
+ self._queued_audio_frames = 0
+ self._max_queued_audio_frames = max(
+ 1,
+ _MAX_INCOMING_AUDIO_MS // _FRAME_DURATION_MS,
+ )
+ self._input_task: asyncio.Task | None = None
+ self._channel: RTCDataChannel | None = None
+ self._position = PlayoutPosition(item_id="")
+ self._audio_bytes: dict[str, int] = {}
+ self._latest_item_id = ""
+ self._blocked_item_id = ""
+ self._clear_waiters: dict[
+ str,
+ asyncio.Future[PlayoutPosition],
+ ] = {}
+ self._closed = False
+ self.on_disconnect: Callable[[], None] | None = None
+
+ async def start(self) -> None:
+ """Mark the transport ready; WebRTC resources are attached later."""
+
+ async def close(self) -> None:
+ """Stop media work and unblock the agent's incoming iterator."""
+ if self._closed:
+ return
+ self._closed = True
+ if self._input_task is not None:
+ self._input_task.cancel()
+ await asyncio.gather(self._input_task, return_exceptions=True)
+ self._input_task = None
+ self.output_track.stop()
+ for waiter in self._clear_waiters.values():
+ if not waiter.done():
+ waiter.set_result(self.playout())
+ self._clear_waiters.clear()
+ self._incoming.append(_END)
+ self._incoming_ready.set()
+
+ def set_input_track(self, track: MediaStreamTrack) -> None:
+ """Attach the browser microphone track."""
+ if self._input_task is not None:
+ self._input_task.cancel()
+ self._input_task = asyncio.create_task(
+ self._read_input(track),
+ name="webrtc-audio-input",
+ )
+
+ def set_data_channel(self, channel: RTCDataChannel) -> None:
+ """Attach the browser-created control DataChannel."""
+ self._channel = channel
+
+ @channel.on("message")
+ def _on_message(message: str | bytes) -> None:
+ if isinstance(message, str):
+ self._handle_json(message)
+
+ @channel.on("close")
+ def _on_close() -> None:
+ self._notify_disconnect()
+
+ async def incoming(self) -> AsyncIterator[TransportFrame]:
+ """Yield decoded microphone PCM and control frames."""
+ while True:
+ while not self._incoming:
+ self._incoming_ready.clear()
+ await self._incoming_ready.wait()
+ frame = self._incoming.popleft()
+ if isinstance(frame, AudioFrame):
+ self._queued_audio_frames -= 1
+ if frame is _END:
+ return
+ yield frame # type: ignore[misc]
+
+ async def send_audio(self, pcm: bytes, item_id: str) -> None:
+ """Queue assistant PCM on the outgoing WebRTC audio track."""
+ if item_id == self._blocked_item_id:
+ return
+ if item_id != self._latest_item_id:
+ self._audio_bytes.pop(self._latest_item_id, None)
+ self._latest_item_id = item_id
+ self.output_track.push(pcm, item_id)
+ self._audio_bytes[item_id] = self._audio_bytes.get(item_id, 0) + len(
+ pcm,
+ )
+ duration_ms = round(
+ self._audio_bytes[item_id] / (self.output_sample_rate * 2) * 1_000,
+ )
+ self._send_json(
+ {
+ "type": "audio_duration",
+ "item_id": item_id,
+ "duration_ms": duration_ms,
+ },
+ )
+
+ async def clear_audio(self) -> PlayoutPosition:
+ """Stop queued media and ask the browser what was audible."""
+ self._blocked_item_id = self._latest_item_id
+ self._audio_bytes.pop(self._blocked_item_id, None)
+ resume_track_time_ms = self.output_track.clear()
+ if self._channel is None or self._channel.readyState != "open":
+ return self._take_playout()
+ request_id = uuid.uuid4().hex
+ waiter = asyncio.get_running_loop().create_future()
+ self._clear_waiters[request_id] = waiter
+ self._send_json(
+ {
+ "type": "clear_audio",
+ "request_id": request_id,
+ "resume_track_time_ms": resume_track_time_ms,
+ },
+ )
+ try:
+ return await asyncio.wait_for(
+ waiter,
+ timeout=_CLEAR_TIMEOUT_SECONDS,
+ )
+ except asyncio.TimeoutError:
+ return self._take_playout()
+ finally:
+ self._clear_waiters.pop(request_id, None)
+
+ def playout(self) -> PlayoutPosition:
+ """Return the browser's latest playback report."""
+ return self._position.model_copy()
+
+ def send_error(self, detail: str) -> None:
+ """Send a protocol error over the control channel."""
+ self._send_json({"type": "error", "detail": detail})
+
+ def _on_item_started(self, item_id: str, track_time_ms: int) -> None:
+ """Tell the browser where an item begins on the media timeline."""
+ self._position = PlayoutPosition(item_id=item_id)
+ self._send_json(
+ {
+ "type": "audio_start",
+ "item_id": item_id,
+ "track_time_ms": track_time_ms,
+ },
+ )
+
+ def _send_json(self, payload: dict) -> None:
+ """Send a control message when the DataChannel is open."""
+ if self._channel is not None and self._channel.readyState == "open":
+ self._channel.send(json.dumps(payload))
+
+ async def _read_input(self, track: MediaStreamTrack) -> None:
+ """Decode and resample the browser microphone into model PCM."""
+ resampler = AudioResampler(
+ format="s16",
+ layout="mono",
+ rate=self.input_sample_rate,
+ )
+ cancelled = False
+ try:
+ while True:
+ frame = await track.recv()
+ for converted in resampler.resample(frame):
+ pcm = (
+ converted.to_ndarray()
+ .astype("<i2", copy=False)
+ .tobytes()
+ )
+ if pcm:
+ self._enqueue_incoming(AudioFrame(pcm=pcm))
+ except asyncio.CancelledError:
+ cancelled = True
+ except MediaStreamError:
+ pass
+ finally:
+ if not cancelled and not self._closed:
+ self._notify_disconnect()
+
+ def _enqueue_incoming(self, frame: TransportFrame) -> None:
+ """Queue one frame, dropping only stale audio when audio is full."""
+ if self._closed:
+ return
+ if isinstance(frame, AudioFrame):
+ if self._queued_audio_frames >= self._max_queued_audio_frames:
+ for index, queued in enumerate(self._incoming):
+ if isinstance(queued, AudioFrame):
+ del self._incoming[index]
+ self._queued_audio_frames -= 1
+ break
+ self._queued_audio_frames += 1
+ self._incoming.append(frame)
+ self._incoming_ready.set()
+
+ def _handle_json(self, raw: str) -> None:
+ """Handle one DataChannel control or playback report."""
+ try:
+ payload = json.loads(raw)
+ except json.JSONDecodeError:
+ self.send_error("DataChannel messages must be JSON.")
+ return
+ if not isinstance(payload, dict):
+ self.send_error("DataChannel JSON messages must be objects.")
+ return
+
+ frame_type = payload.get("type")
+ if frame_type == "control":
+ control_value = payload.get("control")
+ if not isinstance(control_value, str):
+ self.send_error("Unknown realtime control frame.")
+ return
+ try:
+ control = ControlFrameType(control_value)
+ except ValueError:
+ self.send_error("Unknown realtime control frame.")
+ return
+ data = payload.get("data", {})
+ if not isinstance(data, dict):
+ self.send_error("Control frame data must be an object.")
+ return
+ self._enqueue_incoming(ControlFrame(type=control, data=data))
+ return
+
+ if frame_type == "playout":
+ self._update_playout(payload)
+ return
+
+ if frame_type == "playout_cleared":
+ request_id = payload.get("request_id")
+ waiter = (
+ self._clear_waiters.get(request_id)
+ if isinstance(request_id, str)
+ else None
+ )
+ if waiter is None or waiter.done():
+ return
+ self._update_playout(payload)
+ waiter.set_result(self._take_playout())
+ return
+
+ if frame_type == "close":
+ self._notify_disconnect()
+ return
+
+ self.send_error("Unknown realtime frame type.")
+
+ def _notify_disconnect(self) -> None:
+ """Notify the session owner that its peer is gone."""
+ callback = self.on_disconnect
+ if callback is not None:
+ callback()
+
+ def _update_playout(self, payload: dict) -> None:
+ """Record the browser's item-aware playback position."""
+ item_id = payload.get("item_id")
+ played_ms = payload.get("played_ms")
+ if not isinstance(item_id, str) or not isinstance(played_ms, int):
+ return
+ if played_ms < 0:
+ return
+ if not item_id and played_ms > 0 and self._position.item_id:
+ item_id = self._position.item_id
+ first_played_at = self._position.first_played_at
+ if item_id != self._position.item_id:
+ first_played_at = None
+ if played_ms > 0 and first_played_at is None:
+ first_played_at = time.monotonic()
+ self._position = PlayoutPosition(
+ item_id=item_id,
+ played_ms=played_ms,
+ first_played_at=first_played_at,
+ )
+
+ def _take_playout(self) -> PlayoutPosition:
+ """Return the current position and begin a fresh playback epoch."""
+ position = self.playout()
+ self._position = PlayoutPosition(item_id="")
+ return position
diff --git a/src/agentscope/app/_service/_webrtc_session.py b/src/agentscope/app/_service/_webrtc_session.py
new file mode 100644
index 000000000..e23c06495
--- /dev/null
+++ b/src/agentscope/app/_service/_webrtc_session.py
@@ -0,0 +1,292 @@
+# -*- coding: utf-8 -*-
+"""Lifecycle owner for one browser WebRTC realtime session."""
+
+import asyncio
+from collections.abc import Awaitable, Callable
+
+from aiortc import RTCPeerConnection
+
+from ..._logging import logger
+from ...agent import RealtimeAgent
+from ...event import (
+ DataBlockDeltaEvent,
+ DataBlockEndEvent,
+ DataBlockStartEvent,
+ ReplyEndEvent,
+ ReplyStartEvent,
+)
+from ...state import AgentState
+from .._bus_ops import publish_session_event
+from ..message_bus import MessageBus, MessageBusKeys
+from ..storage import StorageBase
+from ._webrtc_audio_transport import WebRTCAudioTransport
+
+_CHECKPOINT_LOCK_TTL_SECS = (
+ MessageBusKeys.SESSION_EVENT_CHECKPOINT_LOCK_TTL_SECS
+)
+
+
+class WebRTCSession:
+ """Run and persist one realtime agent over a peer connection."""
+
+ def __init__(
+ self,
+ *,
+ peer_connection: RTCPeerConnection,
+ transport: WebRTCAudioTransport,
+ agent_factory: Callable[[], Awaitable[RealtimeAgent]],
+ storage: StorageBase,
+ message_bus: MessageBus,
+ user_id: str,
+ agent_id: str,
+ session_id: str,
+ on_closed: Callable[["WebRTCSession"], None],
+ ) -> None:
+ self.peer_connection = peer_connection
+ self.transport = transport
+ self._agent_factory = agent_factory
+ self.agent: RealtimeAgent | None = None
+ self.storage = storage
+ self.message_bus = message_bus
+ self.user_id = user_id
+ self.agent_id = agent_id
+ self.session_id = session_id
+ self._on_closed = on_closed
+ self._task: asyncio.Task[None] | None = None
+ self._close_task: asyncio.Task[None] | None = None
+ self._close_lock = asyncio.Lock()
+ self._closing = False
+ self._lock_acquired = asyncio.Event()
+ self._persisted_messages: dict[str, str] = {}
+ self._open_user_replies: set[str] = set()
+ self._pcm_block_ids: set[str] = set()
+ self._last_entry_id: str | None = None
+ self._checkpoint_entry_id: str | None = None
+
+ def start(self) -> None:
+ """Start the agent pump after WebRTC negotiation succeeds."""
+ if self._task is not None:
+ raise RuntimeError("The WebRTC session is already running.")
+ self._task = asyncio.create_task(
+ self._run(),
+ name=f"webrtc-session-{self.session_id}",
+ )
+
+ def request_close(self) -> None:
+ """Schedule one owned close task from a synchronous callback."""
+ if self._closing or self._close_task is not None:
+ return
+ self._close_task = asyncio.create_task(
+ self.close(),
+ name=f"webrtc-session-close-{self.session_id}",
+ )
+ self._close_task.add_done_callback(self._on_close_done)
+
+ def _on_close_done(self, task: asyncio.Task[None]) -> None:
+ """Retrieve an asynchronous close error instead of losing it."""
+ if task.cancelled():
+ return
+ error = task.exception()
+ if error is not None:
+ logger.error(
+ "Failed to close WebRTC session %r: %s",
+ self.session_id,
+ error,
+ )
+
+ async def close(self) -> None:
+ """End the transport and wait for persistence to finish."""
+ async with self._close_lock:
+ if not self._closing:
+ self._closing = True
+ await self.transport.close()
+
+ task = self._task
+ if task is not None and task is not asyncio.current_task():
+ if not self._lock_acquired.is_set():
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+ elif task is None:
+ await self.peer_connection.close()
+ self._on_closed(self)
+
+ async def wait_until_lock_acquired(self, timeout: float) -> bool:
+ """Wait until this runner owns the distributed session lock."""
+ try:
+ await asyncio.wait_for(
+ self._lock_acquired.wait(),
+ timeout=timeout,
+ )
+ except asyncio.TimeoutError:
+ return False
+ return True
+
+ async def _run(self) -> None:
+ """Hold the session lock while forwarding events to the SSE log."""
+ try:
+ async with self.message_bus.acquire_lock(
+ MessageBusKeys.session_lock(self.session_id),
+ ttl_secs=MessageBusKeys.SESSION_RUN_TTL_SECS,
+ ):
+ self._lock_acquired.set()
+ try:
+ self.agent = await self._agent_factory()
+ self._persisted_messages = {
+ message.id: message.model_dump_json()
+ for message in self.agent.state.context
+ }
+ async with self.transport:
+ async with self.agent:
+ async for event in self.agent.reply_stream(
+ self.transport,
+ ):
+ if isinstance(event, DataBlockStartEvent) and (
+ event.media_type.startswith("audio/pcm")
+ ):
+ self._pcm_block_ids.add(event.block_id)
+ continue
+ if isinstance(
+ event,
+ DataBlockDeltaEvent,
+ ) and event.media_type.startswith("audio/pcm"):
+ self._pcm_block_ids.add(event.block_id)
+ continue
+ if (
+ isinstance(event, DataBlockEndEvent)
+ and event.block_id in self._pcm_block_ids
+ ):
+ self._pcm_block_ids.discard(event.block_id)
+ continue
+ checkpoint = self.agent.checkpoint_snapshot(
+ event,
+ )
+ payload = event.model_dump(mode="json")
+ entry_id = await publish_session_event(
+ self.message_bus,
+ self.session_id,
+ payload,
+ )
+ self._last_entry_id = entry_id
+ if (
+ isinstance(event, ReplyStartEvent)
+ and event.role == "user"
+ ):
+ self._open_user_replies.add(
+ event.reply_id,
+ )
+ elif isinstance(event, ReplyEndEvent):
+ self._open_user_replies.discard(
+ event.reply_id,
+ )
+ if (
+ checkpoint is not None
+ and not self._open_user_replies
+ ):
+ try:
+ await self._checkpoint_state(
+ entry_id,
+ checkpoint,
+ )
+ except Exception as exc:
+ logger.warning(
+ "Failed to checkpoint WebRTC "
+ "session %r: %s",
+ self.session_id,
+ exc,
+ )
+ finally:
+ try:
+ async with self.message_bus.acquire_lock(
+ MessageBusKeys.session_event_checkpoint_lock(
+ self.session_id,
+ ),
+ ttl_secs=_CHECKPOINT_LOCK_TTL_SECS,
+ ):
+ await self._persist_state()
+ if (
+ self._last_entry_id is not None
+ and self._last_entry_id
+ != self._checkpoint_entry_id
+ ):
+ await self._set_checkpoint_cursor(
+ self._last_entry_id,
+ )
+ except Exception as exc:
+ logger.exception(
+ "Failed to persist WebRTC session %r: %s",
+ self.session_id,
+ exc,
+ )
+ except Exception as exc:
+ logger.exception(
+ "WebRTC session %r failed: %s",
+ self.session_id,
+ exc,
+ )
+ self.transport.send_error(str(exc))
+ finally:
+ async with self._close_lock:
+ self._closing = True
+ await self.transport.close()
+ await self.peer_connection.close()
+ self._on_closed(self)
+
+ async def _checkpoint_state(
+ self,
+ entry_id: str | None,
+ state: AgentState,
+ ) -> None:
+ """Persist state and bind it to the replay entry it includes."""
+ async with self.message_bus.acquire_lock(
+ MessageBusKeys.session_event_checkpoint_lock(self.session_id),
+ ttl_secs=_CHECKPOINT_LOCK_TTL_SECS,
+ ):
+ await self._persist_state(state)
+ if entry_id is not None:
+ await self._set_checkpoint_cursor(entry_id)
+
+ async def _set_checkpoint_cursor(self, entry_id: str) -> None:
+ """Record the last event included in the persisted state."""
+ await self.message_bus.registry_set(
+ MessageBusKeys.session_event_checkpoint(self.session_id),
+ MessageBusKeys.SESSION_EVENT_CURSOR_FIELD,
+ entry_id,
+ )
+ self._checkpoint_entry_id = entry_id
+ await self.message_bus.log_trim(
+ MessageBusKeys.session_events(self.session_id),
+ before_id=entry_id,
+ )
+
+ async def _persist_state(self, state: AgentState | None = None) -> None:
+ """Persist the latest complete messages and agent state."""
+ if self.agent is None:
+ return
+ state = state or self.agent.state
+ current_messages = {
+ message.id: message.model_dump_json() for message in state.context
+ }
+ for message in state.context:
+ serialized = current_messages[message.id]
+ if self._persisted_messages.get(message.id) == serialized:
+ continue
+ await self.storage.upsert_message(
+ self.user_id,
+ self.session_id,
+ message,
+ )
+ self._persisted_messages[message.id] = serialized
+ await self.storage.update_session_state(
+ user_id=self.user_id,
+ agent_id=self.agent_id,
+ session_id=self.session_id,
+ state=state,
+ )
+ removed_ids = self._persisted_messages.keys() - current_messages.keys()
+ for message_id in sorted(removed_ids):
+ await self.storage.delete_message(
+ self.user_id,
+ self.session_id,
+ message_id,
+ )
+ self._persisted_messages.pop(message_id, None)
diff --git a/src/agentscope/app/_tool/_agent_create.py b/src/agentscope/app/_tool/_agent_create.py
index 9a25bfc7f..0f8ee4a1b 100644
--- a/src/agentscope/app/_tool/_agent_create.py
+++ b/src/agentscope/app/_tool/_agent_create.py
@@ -14,6 +14,7 @@ from .._bus_ops import deliver_to_inbox
from ..storage import (
AgentData,
AgentRecord,
+ AgentChatConfig,
SessionConfig,
TeamMember,
TeamOrigin,
@@ -409,12 +410,10 @@ optional):
data=AgentData(
name=name,
system_prompt=system_prompt,
- context_config=template.context_config.model_copy(
- deep=True,
- ),
- react_config=template.react_config.model_copy(
- deep=True,
- ),
+ chat_config=AgentChatConfig(
+ context_config=template.context_config,
+ react_config=template.react_config,
+ ).model_copy(deep=True),
),
)
await self._storage.upsert_agent(self._user_id, worker_agent)
diff --git a/src/agentscope/app/_tool/_agent_invite.py b/src/agentscope/app/_tool/_agent_invite.py
index ba461de32..7395df170 100644
--- a/src/agentscope/app/_tool/_agent_invite.py
+++ b/src/agentscope/app/_tool/_agent_invite.py
@@ -217,7 +217,7 @@ class AgentInvite(_TeamToolBase):
]
target_lines = [
f"- ``{_display_name(a.data.name, a.id)!r}`` — "
- f"{a.data.invite_config.invite_description}"
+ f"{a.data.chat_config.invite_config.invite_description}"
for a in invitable_pool
]
self.description = (
@@ -295,9 +295,10 @@ class AgentInvite(_TeamToolBase):
fresh = None
if (
fresh is None
- or not fresh.data.invite_config.invitable
+ or not fresh.data.chat_config.invite_config.invitable
or not (
- fresh.data.invite_config.invite_description or ""
+ fresh.data.chat_config.invite_config.invite_description
+ or ""
).strip()
):
return _error(
diff --git a/src/agentscope/app/_types.py b/src/agentscope/app/_types.py
index abee28e47..e115c6f30 100644
--- a/src/agentscope/app/_types.py
+++ b/src/agentscope/app/_types.py
@@ -1,9 +1,9 @@
# -*- coding: utf-8 -*-
"""Shared type aliases for the agentscope app layer."""
from collections.abc import Awaitable, Callable
-from typing import TYPE_CHECKING, Protocol
+from typing import Literal, TYPE_CHECKING, Protocol
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, ConfigDict, Field, field_validator
from ..agent import ContextConfig, ReActConfig
from ..event import AgentEvent
@@ -18,6 +18,31 @@ if TYPE_CHECKING:
from .storage import AgentRecord, SessionRecord
+class RealtimeIceServer(BaseModel):
+ """Browser-compatible WebRTC ICE server configuration."""
+
+ model_config = ConfigDict(extra="forbid", populate_by_name=True)
+
+ urls: str | list[str]
+ username: str | None = None
+ credential: str | None = None
+ credential_type: Literal["password", "oauth"] | None = Field(
+ default=None,
+ alias="credentialType",
+ )
+
+ @field_validator("urls")
+ @classmethod
+ def _validate_urls(cls, value: str | list[str]) -> str | list[str]:
+ """Require at least one non-empty ICE server URL."""
+ if isinstance(value, str):
+ if value:
+ return value
+ elif value and all(url for url in value):
+ return value
+ raise ValueError("urls must contain at least one non-empty URL")
+
+
AgentMiddlewareFactory = (
Callable[[str, str, str], Awaitable[list[MiddlewareBase]]]
| Callable[
diff --git a/src/agentscope/app/channel/_clients.py b/src/agentscope/app/channel/_clients.py
index e5c84b4b9..894fb3da3 100644
--- a/src/agentscope/app/channel/_clients.py
+++ b/src/agentscope/app/channel/_clients.py
@@ -197,8 +197,8 @@ class ChannelClients:
)
# Subscribe before returning: the caller is about to run the
- # agent, and the run drops its event log when it persists, so a
- # subscription opened any later could miss the whole reply.
+ # agent, and this lets the stream distinguish the retained prior
+ # run from events that belong to the new reply.
try:
events = await open_reply_stream(self._bus, session_id)
except Exception: # pylint: disable=broad-except
diff --git a/src/agentscope/app/channel/_stream.py b/src/agentscope/app/channel/_stream.py
index ca7e264b7..dbd9f2e05 100644
--- a/src/agentscope/app/channel/_stream.py
+++ b/src/agentscope/app/channel/_stream.py
@@ -34,10 +34,9 @@ async def open_reply_stream(
) -> AsyncGenerator[dict, None]:
"""Subscribe to a run's events and return a gap-free reader.
- The subscription is live by the time this returns, which is what the
- caller needs: a run drops its whole event log when it persists, so a
- reader that only subscribes afterwards would find nothing to replay
- and then wait on a feed that has already gone quiet.
+ The subscription is live by the time this returns. Replay starts after
+ the persisted checkpoint so retained events from an earlier run are not
+ delivered as the current reply.
Args:
bus (`MessageBus`): The application message bus.
@@ -62,10 +61,14 @@ async def open_reply_stream(
feeder_task = asyncio.create_task(feeder())
try:
await asyncio.wait_for(ready.wait(), timeout=_SUBSCRIBE_TIMEOUT_SECS)
+ cursor = await bus.registry_get(
+ MessageBusKeys.session_event_checkpoint(session_id),
+ MessageBusKeys.SESSION_EVENT_CURSOR_FIELD,
+ )
except BaseException:
feeder_task.cancel()
raise
- return _read(bus, event_key, queue, feeder_task)
+ return _read(bus, event_key, queue, feeder_task, cursor)
async def _read(
@@ -73,6 +76,7 @@ async def _read(
event_key: str,
queue: "asyncio.Queue[dict]",
feeder_task: "asyncio.Task",
+ after: str | None,
) -> AsyncGenerator[dict, None]:
"""Replay the log, then go live, stopping at the terminal event.
@@ -84,6 +88,7 @@ async def _read(
event_key (`str`): The session's event log / channel key.
queue (`asyncio.Queue[dict]`): Live events buffered so far.
feeder_task (`asyncio.Task`): The subscription, cancelled on close.
+ after (`str | None`): Persisted checkpoint cursor to replay after.
Yields:
`dict`: Each session event, up to and including the terminal one.
@@ -92,6 +97,7 @@ async def _read(
try:
for entry_id, evt in await bus.log_read(
event_key,
+ since=after,
max_count=MessageBusKeys.SESSION_REPLAY_MAX_LEN,
):
seen.add(str(entry_id))
diff --git a/src/agentscope/app/deps.py b/src/agentscope/app/deps.py
index 55b6d40ab..eec2c5157 100644
--- a/src/agentscope/app/deps.py
+++ b/src/agentscope/app/deps.py
@@ -18,6 +18,7 @@ from ._service import (
ChatService,
SOPService,
KnowledgeBaseService,
+ RealtimeService,
ResourceAccessService,
SessionService,
WorkspaceService,
@@ -92,6 +93,11 @@ async def get_chat_service(request: Request) -> ChatService:
return request.app.state.chat_service
+async def get_realtime_service(request: Request) -> RealtimeService:
+ """Return the application-wide realtime agent assembly service."""
+ return request.app.state.realtime_service
+
+
async def get_resource_access_service(
request: Request,
) -> ResourceAccessService:
diff --git a/src/agentscope/app/message_bus/_keys.py b/src/agentscope/app/message_bus/_keys.py
index 3ce31cec8..3f1cc6053 100644
--- a/src/agentscope/app/message_bus/_keys.py
+++ b/src/agentscope/app/message_bus/_keys.py
@@ -126,11 +126,28 @@ class MessageBusKeys: # pylint: disable=too-many-public-methods
SESSION_REPLAY_MAX_LEN = 1000
"""Replay log length cap; older events are trimmed on append."""
+ _SESSION_EVENT_CHECKPOINT = "agentscope:session:event_checkpoint:{sid}"
+ _SESSION_EVENT_CHECKPOINT_LOCK = (
+ "agentscope:session:event_checkpoint:lock:{sid}"
+ )
+ SESSION_EVENT_CURSOR_FIELD: Final = "cursor"
+ SESSION_EVENT_CHECKPOINT_LOCK_TTL_SECS = 30
+
@classmethod
def session_events(cls, session_id: str) -> str:
"""Replay log + live pub/sub channel key for a session."""
return cls._SESSION_EVENTS.format(sid=session_id)
+ @classmethod
+ def session_event_checkpoint(cls, session_id: str) -> str:
+ """Registry namespace for the persisted replay cursor."""
+ return cls._SESSION_EVENT_CHECKPOINT.format(sid=session_id)
+
+ @classmethod
+ def session_event_checkpoint_lock(cls, session_id: str) -> str:
+ """Lock pairing a persisted message snapshot with its cursor."""
+ return cls._SESSION_EVENT_CHECKPOINT_LOCK.format(sid=session_id)
+
# ------------------------------------------------------------------
# Session run lock
# ------------------------------------------------------------------
diff --git a/src/agentscope/app/storage/__init__.py b/src/agentscope/app/storage/__init__.py
index aece10a45..f681cb8fa 100644
--- a/src/agentscope/app/storage/__init__.py
+++ b/src/agentscope/app/storage/__init__.py
@@ -45,12 +45,14 @@ from ._model import (
SOPWorkspaceGrain,
SkillRecord,
ChatModelConfig,
+ RealtimeModelConfig,
TTSModelConfig,
EmbeddingModelConfig,
TeamData,
TeamRecord,
UserRecord,
TeamMember,
+ AgentChatConfig,
InviteConfig,
)
@@ -86,6 +88,7 @@ __all__ = [
"RedisStorage",
"AsyncSQLAlchemyStorage",
# The ORM models
+ "AgentChatConfig",
"InviteConfig",
"AgentData",
"AgentRecord",
@@ -124,6 +127,7 @@ __all__ = [
"SOPWorkspaceGrain",
"SkillRecord",
"ChatModelConfig",
+ "RealtimeModelConfig",
"TTSModelConfig",
"EmbeddingModelConfig",
"TeamMember",
diff --git a/src/agentscope/app/storage/_base.py b/src/agentscope/app/storage/_base.py
index 7fb1fda84..2dbc2ba43 100644
--- a/src/agentscope/app/storage/_base.py
+++ b/src/agentscope/app/storage/_base.py
@@ -743,9 +743,8 @@ class StorageBase(ABC):
) -> None:
"""Persist a message to the session's message list.
- If the last message in the list has the same ``id`` as *msg*, it is
- replaced (merge/overwrite for the same reply_id across continuation
- calls). Otherwise, *msg* is appended as a new entry.
+ If a message in the list has the same ``id`` as *msg*, it is replaced
+ in place. Otherwise, *msg* is appended as a new entry.
Args:
user_id (`str`): The owner user id.
@@ -753,6 +752,24 @@ class StorageBase(ABC):
msg (`Msg`): The message to persist.
"""
+ @abstractmethod
+ async def delete_message(
+ self,
+ user_id: str,
+ session_id: str,
+ message_id: str,
+ ) -> bool:
+ """Delete one message from a session.
+
+ Args:
+ user_id (`str`): The owner user id.
+ session_id (`str`): The session id.
+ message_id (`str`): The message id to delete.
+
+ Returns:
+ `bool`: Whether a matching message was deleted.
+ """
+
@abstractmethod
async def get_message(
self,
diff --git a/src/agentscope/app/storage/_model/__init__.py b/src/agentscope/app/storage/_model/__init__.py
index 51c959085..6b9b074ca 100644
--- a/src/agentscope/app/storage/_model/__init__.py
+++ b/src/agentscope/app/storage/_model/__init__.py
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
"""Storage models for persisted resources."""
-from ._agent import AgentRecord, AgentData, InviteConfig
+from ._agent import AgentChatConfig, AgentData, AgentRecord, InviteConfig
from ._channel import (
ChannelBinding,
ChannelRecord,
@@ -28,6 +28,7 @@ from ._session import (
SessionNaming,
SessionKnowledgeConfig,
ChatModelConfig,
+ RealtimeModelConfig,
TTSModelConfig,
EmbeddingModelConfig,
SessionOrigin,
@@ -94,11 +95,13 @@ __all__ = [
"SOPVerifier",
"SOPWorkspaceGrain",
"ChatModelConfig",
+ "RealtimeModelConfig",
"TTSModelConfig",
"EmbeddingModelConfig",
"TeamData",
"TeamRecord",
"TeamMember",
"UserRecord",
+ "AgentChatConfig",
"InviteConfig",
]
diff --git a/src/agentscope/app/storage/_model/_agent.py b/src/agentscope/app/storage/_model/_agent.py
index 412c046d0..2e35fe405 100644
--- a/src/agentscope/app/storage/_model/_agent.py
+++ b/src/agentscope/app/storage/_model/_agent.py
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
"""The agent storage class."""
-from typing import Literal, Self
+import warnings
+from typing import Any, Literal, Self
from pydantic import Field, BaseModel, model_validator
from pydantic.json_schema import SkipJsonSchema
@@ -62,6 +63,34 @@ class InviteConfig(BaseModel):
return self
+class AgentChatConfig(BaseModel):
+ """The settings that apply when the agent talks in text.
+
+ Grouped in their own sub-model so a second interaction mode — a
+ realtime voice one, whose context management and parameters differ
+ from the text loop's — adds a block beside this one instead of
+ widening :class:`AgentData` with fields that only apply to one mode.
+ """
+
+ context_config: ContextConfig = Field(
+ default_factory=ContextConfig,
+ description="The context config for the agent.",
+ title="Context Config",
+ )
+
+ react_config: ReActConfig = Field(
+ default_factory=ReActConfig,
+ description="The react config for the agent.",
+ title="React Config",
+ )
+
+ invite_config: InviteConfig = Field(
+ default_factory=InviteConfig,
+ description="The invite config for the agent.",
+ title="Invite Config",
+ )
+
+
class AgentData(BaseModel):
"""The agent data model."""
@@ -92,21 +121,65 @@ class AgentData(BaseModel):
json_schema_extra={"format": "textarea"},
)
- context_config: ContextConfig = Field(
- description="The context config for the agent.",
- title="Context Config",
- )
-
- react_config: ReActConfig = Field(
- description="The react config for the agent.",
- title="React Config",
+ chat_config: AgentChatConfig = Field(
+ default_factory=AgentChatConfig,
+ description="The settings for the agent's text conversations.",
+ title="Chat Config",
)
- invite_config: InviteConfig = Field(
- default_factory=InviteConfig,
- description="The invite config for the agent.",
- title="Invite Config",
- )
+ @property
+ def context_config(self) -> ContextConfig:
+ """Return the deprecated flat context configuration."""
+ warnings.warn(
+ "AgentData.context_config is deprecated; use "
+ "AgentData.chat_config.context_config instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return self.chat_config.context_config
+
+ @property
+ def react_config(self) -> ReActConfig:
+ """Return the deprecated flat ReAct configuration."""
+ warnings.warn(
+ "AgentData.react_config is deprecated; use "
+ "AgentData.chat_config.react_config instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return self.chat_config.react_config
+
+ @property
+ def invite_config(self) -> InviteConfig:
+ """Return the deprecated flat invite configuration."""
+ warnings.warn(
+ "AgentData.invite_config is deprecated; use "
+ "AgentData.chat_config.invite_config instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return self.chat_config.invite_config
+
+ @model_validator(mode="before")
+ @classmethod
+ def _fold_legacy_configs(cls, data: Any) -> Any:
+ """Fold deprecated flat configs into ``chat_config``."""
+ if not isinstance(data, dict):
+ return data
+ legacy = {
+ key: data[key]
+ for key in ("context_config", "react_config", "invite_config")
+ if key in data
+ }
+ if not legacy:
+ return data
+
+ chat_config = data.get("chat_config") or {}
+ if not isinstance(chat_config, dict):
+ chat_config = chat_config.model_dump()
+ data = {k: v for k, v in data.items() if k not in legacy}
+ data["chat_config"] = {**chat_config, **legacy}
+ return data
class AgentRecord(_RecordBase):
diff --git a/src/agentscope/app/storage/_model/_session.py b/src/agentscope/app/storage/_model/_session.py
index c7cf207ea..29b502469 100644
--- a/src/agentscope/app/storage/_model/_session.py
+++ b/src/agentscope/app/storage/_model/_session.py
@@ -140,6 +140,22 @@ class TTSModelConfig(BaseModel):
"""TTS parameters (voice, language, etc.)."""
+class RealtimeModelConfig(BaseModel):
+ """The realtime voice model configuration class."""
+
+ type: str
+ """The realtime adapter type."""
+
+ credential_id: str
+ """The credential id."""
+
+ model: str
+ """The realtime model name."""
+
+ parameters: dict
+ """Realtime model parameters (voice, turn detection, etc.)."""
+
+
class EmbeddingModelConfig(BaseModel):
"""Configuration for constructing an embedding model from a credential.
@@ -287,6 +303,9 @@ class SessionConfig(BaseModel):
tts_model_config: TTSModelConfig | None = None
"""The TTS model config. None means TTS is not enabled."""
+ realtime_model_config: RealtimeModelConfig | None = None
+ """The realtime voice model config. None disables voice mode."""
+
knowledge_config: SessionKnowledgeConfig | None = None
"""Knowledge bases attached to this session and the corresponding
:class:`~agentscope.middleware.RAGMiddleware` parameters.
diff --git a/src/agentscope/app/storage/_redis_storage.py b/src/agentscope/app/storage/_redis_storage.py
index 3f7607820..d42a80697 100644
--- a/src/agentscope/app/storage/_redis_storage.py
+++ b/src/agentscope/app/storage/_redis_storage.py
@@ -97,6 +97,9 @@ class RedisStorage(StorageBase):
messages: str = (
"agentscope:user:{user_id}:session:{session_id}:messages"
)
+ message_index: str = (
+ "agentscope:user:{user_id}:session:{session_id}:message_ids"
+ )
schedule: str = "agentscope:user:{user_id}:schedule:{schedule_id}"
schedule_index: str = "agentscope:user:{user_id}:schedules"
@@ -1112,9 +1115,14 @@ class RedisStorage(StorageBase):
user_id=user_id,
session_id=session_id,
)
+ msg_index_key = self._key(
+ self.key_config.message_index,
+ user_id=user_id,
+ session_id=session_id,
+ )
await self._client.delete(key)
await self._client.srem(index_key, session_id)
- await self._client.delete(msg_key)
+ await self._client.delete(msg_key, msg_index_key)
if isinstance(record.origin, ScheduleOrigin):
schedule_session_key = self._key(
@@ -1441,6 +1449,14 @@ class RedisStorage(StorageBase):
session_id=session_id,
)
+ def _message_index_key(self, user_id: str, session_id: str) -> str:
+ """Return the Redis Set key for a session's message IDs."""
+ return self._key(
+ self.key_config.message_index,
+ user_id=user_id,
+ session_id=session_id,
+ )
+
async def upsert_message(
self,
user_id: str,
@@ -1449,15 +1465,66 @@ class RedisStorage(StorageBase):
) -> None:
"""Persist a message to the session's message list."""
key = self._message_key(user_id, session_id)
- last_raw = await self._client.lindex(key, -1)
- if last_raw:
- last_msg = Msg.model_validate_json(last_raw)
- if last_msg.id == msg.id:
- await self._client.lset(key, -1, msg.model_dump_json())
- await self._refresh_key_ttl(key)
+ index_key = self._message_index_key(user_id, session_id)
+
+ async with self._client.pipeline(transaction=False) as pipe:
+ pipe.exists(index_key)
+ pipe.sismember(index_key, msg.id)
+ index_exists, message_exists = await pipe.execute()
+ message_exists = bool(message_exists)
+ if not index_exists:
+ raw_messages = await self._client.lrange(key, 0, -1)
+ message_ids = {
+ Msg.model_validate_json(raw).id for raw in raw_messages
+ }
+ message_exists = msg.id in message_ids
+ if message_ids:
+ await self._client.sadd(index_key, *message_ids)
+
+ payload = msg.model_dump_json()
+ if message_exists:
+ index = await self._find_message_index(key, msg.id)
+ if index is not None:
+ async with self._client.pipeline(transaction=True) as pipe:
+ pipe.lset(key, index, payload)
+ if self.key_ttl is not None:
+ pipe.expire(key, self.key_ttl)
+ pipe.expire(index_key, self.key_ttl)
+ await pipe.execute()
return
- await self._client.rpush(key, msg.model_dump_json())
- await self._refresh_key_ttl(key)
+
+ async with self._client.pipeline(transaction=True) as pipe:
+ pipe.rpush(key, payload)
+ pipe.sadd(index_key, msg.id)
+ if self.key_ttl is not None:
+ pipe.expire(key, self.key_ttl)
+ pipe.expire(index_key, self.key_ttl)
+ await pipe.execute()
+
+ async def delete_message(
+ self,
+ user_id: str,
+ session_id: str,
+ message_id: str,
+ ) -> bool:
+ """Delete the stored message matching ``message_id``."""
+ key = self._message_key(user_id, session_id)
+ index_key = self._message_index_key(user_id, session_id)
+ index = await self._find_message_index(key, message_id)
+ if index is None:
+ return False
+ raw = await self._client.lindex(key, index)
+ if raw is None:
+ return False
+ async with self._client.pipeline(transaction=True) as pipe:
+ pipe.lrem(key, 0, raw)
+ pipe.srem(index_key, message_id)
+ if self.key_ttl is not None:
+ pipe.expire(key, self.key_ttl)
+ pipe.expire(index_key, self.key_ttl)
+ results = await pipe.execute()
+ deleted = bool(results[0])
+ return deleted
async def get_message(
self,
diff --git a/src/agentscope/app/storage/_sql/_storage.py b/src/agentscope/app/storage/_sql/_storage.py
index 8d0eaa962..d1e26ca23 100644
--- a/src/agentscope/app/storage/_sql/_storage.py
+++ b/src/agentscope/app/storage/_sql/_storage.py
@@ -1678,14 +1678,7 @@ class AsyncSQLAlchemyStorage(StorageBase):
session_id: str,
msg: Msg,
) -> None:
- """Insert-or-update by ``(session_id, msg_id)``.
-
- Semantics mirror :meth:`RedisStorage.upsert_message` closely
- enough for every caller in the codebase — the Redis version
- only replaces when the *tail* message matches; ours replaces
- on any matching id. The looser rule is safe because callers
- never reuse a message id across turns.
- """
+ """Insert-or-update by ``(session_id, msg_id)``."""
_ = user_id # scoping enforced by caller
now = _utcnow()
payload = msg.model_dump(mode="json")
@@ -1710,6 +1703,26 @@ class AsyncSQLAlchemyStorage(StorageBase):
)
await sess.commit()
+ async def delete_message(
+ self,
+ user_id: str,
+ session_id: str,
+ message_id: str,
+ ) -> bool:
+ """Delete one message by ``(session_id, message_id)``."""
+ _ = user_id
+ from sqlalchemy import delete
+
+ async with self._session() as sess:
+ result = await sess.execute(
+ delete(MessageRow).where(
+ MessageRow.session_id == session_id,
+ MessageRow.msg_id == message_id,
+ ),
+ )
+ await sess.commit()
+ return bool(result.rowcount)
+
async def get_message(
self,
user_id: str,
diff --git a/src/agentscope/realtime/__init__.py b/src/agentscope/realtime/__init__.py
index d24365f62..6b910e840 100644
--- a/src/agentscope/realtime/__init__.py
+++ b/src/agentscope/realtime/__init__.py
@@ -5,7 +5,7 @@ The model side of a voice session: realtime models, their cards and
events, transports and VAD. The agent that ties them together is
:class:`agentscope.agent.RealtimeAgent`.
"""
-from ._base import ModelDisconnectedError, RealtimeModelBase, TruncationSupport
+from ._base import ModelDisconnectedError, RealtimeModelBase
from ._dashscope import (
DashScopeAudioRealtimeModel,
DashScopeRealtimeModel,
@@ -13,6 +13,7 @@ from ._dashscope import (
from ._events import (
AudioDeltaEvent,
InputTranscriptionEvent,
+ InputTranscriptionFailedEvent,
ModelErrorEvent,
ModelEvent,
ResponseCreatedEvent,
@@ -47,7 +48,6 @@ __all__ = [
"OpenAIRealtimeModel",
"XAIRealtimeModel",
"RealtimeModelCard",
- "TruncationSupport",
"ModelDisconnectedError",
# Transport
"TransportBase",
@@ -66,6 +66,7 @@ __all__ = [
"SpeechStartedEvent",
"SpeechEndedEvent",
"InputTranscriptionEvent",
+ "InputTranscriptionFailedEvent",
"ResponseCreatedEvent",
"AudioDeltaEvent",
"TranscriptDeltaEvent",
diff --git a/src/agentscope/realtime/_base.py b/src/agentscope/realtime/_base.py
index 6f3a10833..58a2bd37a 100644
--- a/src/agentscope/realtime/_base.py
+++ b/src/agentscope/realtime/_base.py
@@ -2,34 +2,21 @@
"""The realtime model base class."""
import inspect
from abc import ABC, abstractmethod
-from enum import StrEnum
from pathlib import Path
-from typing import Any, AsyncIterator
+from typing import Any, AsyncIterator, Sequence
from pydantic import BaseModel
from ._events import ModelEvent
from ._model_card import RealtimeModelCard
from ..credential import CredentialBase
-from ..message import ToolResultBlock
+from ..message import Msg, ToolResultBlock
class ModelDisconnectedError(ConnectionError):
"""The provider closed the session; the next user audio reconnects."""
-class TruncationSupport(StrEnum):
- """How the provider lets an interrupted turn be corrected. A protocol
- property, constant across the models of one API."""
-
- NONE = "none"
- SERVER = "server"
- """The provider corrects itself; ``truncate`` is a no-op."""
-
- EXPLICIT = "explicit"
- """The provider accepts an explicit truncate frame."""
-
-
class RealtimeModelBase(ABC):
"""A bidirectional realtime model: audio in, audio and tool calls out.
@@ -50,12 +37,12 @@ class RealtimeModelBase(ABC):
"""Identifies the adapter; stamped onto every card it lists so a stored
config can be mapped back to this class."""
- truncation: TruncationSupport = TruncationSupport.NONE
- """Whether and how an interrupted turn can be corrected."""
-
supports_text_input: bool = False
"""Whether a text turn can be injected mid-session."""
+ supports_history_replay: bool = False
+ """Whether completed messages can seed a newly opened session."""
+
def __init__(
self,
model: str,
@@ -83,8 +70,21 @@ class RealtimeModelBase(ABC):
"""
self.model = model
self.credential = credential
- self.parameters = parameters or self.Parameters()
self.card = model_card or self._find_card(model)
+ card_defaults = {
+ name: override["default"]
+ for name, override in self.card.parameter_overrides.items()
+ if "default" in override
+ }
+ if parameters is None:
+ self.parameters = self.Parameters(**card_defaults)
+ else:
+ defaults = {
+ name: value
+ for name, value in card_defaults.items()
+ if name not in parameters.model_fields_set
+ }
+ self.parameters = parameters.model_copy(update=defaults)
@classmethod
def _find_card(cls, model: str) -> RealtimeModelCard:
@@ -138,6 +138,11 @@ class RealtimeModelBase(ABC):
"""The PCM rate of the audio in :class:`AudioDelta`, in Hz."""
return self.card.output_sample_rate
+ @property
+ def input_transcription_enabled(self) -> bool:
+ """Whether a settled user transcript is expected after speech."""
+ return False
+
# ------------------------------------------------------------------
# Lifecycle
# ------------------------------------------------------------------
@@ -190,6 +195,26 @@ class RealtimeModelBase(ABC):
``False``.
"""
+ async def replay_history(self, messages: Sequence[Msg]) -> None:
+ """Seed a newly opened session without requesting a response.
+
+ Providers that implement this method must preserve message roles and
+ must not trigger model inference. The caller invokes it after
+ :meth:`connect` and before forwarding new user input.
+
+ Args:
+ messages (`Sequence[Msg]`):
+ Completed conversation messages in chronological order.
+
+ Raises:
+ `NotImplementedError`: If the adapter does not support structured
+ history replay.
+ """
+ if messages:
+ raise NotImplementedError(
+ f"{type(self).__name__} cannot replay conversation history.",
+ )
+
@abstractmethod
async def push_tool_result(self, block: ToolResultBlock) -> None:
"""Feed the result of a tool the caller executed."""
@@ -210,22 +235,3 @@ class RealtimeModelBase(ABC):
@abstractmethod
async def cancel_response(self) -> None:
"""Stop the active reply without closing the session."""
-
- @abstractmethod
- async def truncate(
- self,
- item_id: str,
- played_ms: int,
- played_text: str,
- ) -> None:
- """Rewrite an assistant turn to what the user actually heard. A
- no-op unless :attr:`truncation` is ``EXPLICIT``.
-
- Args:
- item_id (`str`):
- The interrupted assistant item.
- played_ms (`int`):
- Milliseconds of its audio that reached the speaker.
- played_text (`str`):
- The corresponding prefix of its spoken text.
- """
diff --git a/src/agentscope/realtime/_dashscope/_audio_model.py b/src/agentscope/realtime/_dashscope/_audio_model.py
index bf868908b..903be67c6 100644
--- a/src/agentscope/realtime/_dashscope/_audio_model.py
+++ b/src/agentscope/realtime/_dashscope/_audio_model.py
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
"""The DashScope Qwen-Audio realtime model."""
from pathlib import Path
-from typing import Any, Literal
+from typing import Any, Literal, Sequence
from pydantic import Field
@@ -10,10 +10,11 @@ from .. import _events as me
from .._base import RealtimeModelBase
from .._model_card import RealtimeModelCard
from ..._logging import logger
+from ...message import Msg, TextBlock, ToolCallBlock, ToolResultBlock
class DashScopeAudioRealtimeModel(DashScopeRealtimeModel):
- """The Qwen-Audio-3.0-Realtime API over WebSocket.
+ """The Qwen-Audio-Realtime API over WebSocket.
Same endpoint and framing as Qwen-Omni, but it accepts text turns,
spells both PCM formats as ``"pcm"``, and offers ``smart_turn``
@@ -40,9 +41,15 @@ class DashScopeAudioRealtimeModel(DashScopeRealtimeModel):
type = "dashscope_audio_realtime"
supports_text_input = True
+ supports_history_replay = True
parameters: "DashScopeAudioRealtimeModel.Parameters"
+ @property
+ def input_transcription_enabled(self) -> bool:
+ """Qwen Audio does not emit settled input transcription."""
+ return False
+
@classmethod
def list_models(
cls,
@@ -67,6 +74,112 @@ class DashScopeAudioRealtimeModel(DashScopeRealtimeModel):
)
await self.request_response()
+ async def replay_history(self, messages: Sequence[Msg]) -> None:
+ """Insert completed history without asking the model to respond."""
+ call_ids = {
+ block.id
+ for message in messages
+ for block in message.content
+ if isinstance(block, ToolCallBlock)
+ }
+ result_ids = {
+ block.id
+ for message in messages
+ for block in message.content
+ if isinstance(block, ToolResultBlock) and block.state != "running"
+ }
+ paired_ids = call_ids & result_ids
+
+ for message in messages:
+ text_parts: list[str] = []
+
+ for block in message.content:
+ if isinstance(block, TextBlock):
+ if block.text:
+ text_parts.append(block.text)
+ continue
+
+ if text_parts:
+ content_type = (
+ "output_text"
+ if message.role == "assistant"
+ else "input_text"
+ )
+ await self._send(
+ {
+ "type": "conversation.item.create",
+ "item": {
+ "type": "message",
+ "role": message.role,
+ "content": [
+ {
+ "type": content_type,
+ "text": "\n".join(text_parts),
+ },
+ ],
+ },
+ },
+ )
+ text_parts.clear()
+ if isinstance(block, ToolCallBlock):
+ if block.id not in paired_ids:
+ continue
+ await self._send(
+ {
+ "type": "conversation.item.create",
+ "item": {
+ "type": "function_call",
+ "call_id": block.id,
+ "name": block.name,
+ "arguments": block.input,
+ },
+ },
+ )
+ elif isinstance(block, ToolResultBlock):
+ if block.id not in paired_ids:
+ continue
+ output = (
+ block.output
+ if isinstance(block.output, str)
+ else "".join(
+ part.text
+ for part in block.output
+ if isinstance(part, TextBlock)
+ )
+ )
+ await self._send(
+ {
+ "type": "conversation.item.create",
+ "item": {
+ "type": "function_call_output",
+ "call_id": block.id,
+ "output": output,
+ },
+ },
+ )
+
+ if text_parts:
+ content_type = (
+ "output_text"
+ if message.role == "assistant"
+ else "input_text"
+ )
+ await self._send(
+ {
+ "type": "conversation.item.create",
+ "item": {
+ "type": "message",
+ "role": message.role,
+ "content": [
+ {
+ "type": content_type,
+ "text": "\n".join(text_parts),
+ },
+ ],
+ },
+ },
+ )
+
def _session_update(
self,
instructions: str,
diff --git a/src/agentscope/realtime/_dashscope/_audio_models/qwen-audio-3.1-realtime-plus.yaml b/src/agentscope/realtime/_dashscope/_audio_models/qwen-audio-3.1-realtime-plus.yaml
new file mode 100644
index 000000000..87b2d357d
--- /dev/null
+++ b/src/agentscope/realtime/_dashscope/_audio_models/qwen-audio-3.1-realtime-plus.yaml
@@ -0,0 +1,38 @@
+type: realtime_model
+name: qwen-audio-3.1-realtime-plus
+label: Qwen-Audio-3.1-Realtime-Plus
+status: active
+
+input_types:
+ - audio/pcm
+ - text/plain
+output_types:
+ - audio/pcm
+ - text/plain
+
+input_sample_rate: 16000
+output_sample_rate: 24000
+
+supports_tools: true
+
+max_context_tokens: 262144
+max_audio_turns: 50
+max_audio_duration_s: 300
+
+parameter_overrides:
+ voice:
+ default: "longanqian_v3.1"
+ enum:
+ - "longanqian"
+ - "longanlingxin"
+ - "longanlingxi"
+ - "longanxiaoxin"
+ - "longanlufeng"
+ - "longanqian_v3.1"
+ - "longanhuan_v3.1"
+ - "longanlingxin_v3.1"
+ - "longanfengyue_v3.1"
+ - "xunanchuan_v3.1"
+ - "beth_v3.1"
+ - "betty_v3.1"
+ - "cally_v3.1"
diff --git a/src/agentscope/realtime/_dashscope/_model.py b/src/agentscope/realtime/_dashscope/_model.py
index 800965bd8..e57836c5b 100644
--- a/src/agentscope/realtime/_dashscope/_model.py
+++ b/src/agentscope/realtime/_dashscope/_model.py
@@ -4,21 +4,28 @@ import asyncio
import base64
import json
from typing import Any, AsyncIterator, Literal
+from urllib.parse import urlsplit
from pydantic import Field
from .. import _events as me
-from .._base import (
- ModelDisconnectedError,
- RealtimeModelBase,
- TruncationSupport,
-)
+from .._base import ModelDisconnectedError, RealtimeModelBase
from .._model_card import RealtimeModelCard
from ..._logging import logger
from ...credential import DashScopeCredential
from ...message import TextBlock, ToolCallBlock, ToolResultBlock
-_REALTIME_URL = "wss://dashscope.aliyuncs.com/api-ws/v1/realtime"
+_SESSION_READY_TIMEOUT_S = 15.0
+_REALTIME_PATH = "/api-ws/v1/realtime"
+
+
+def _realtime_url(base_url: str, model: str) -> str:
+ """Build the DashScope realtime endpoint from a credential URL."""
+ parsed = urlsplit(base_url)
+ if parsed.scheme not in {"http", "https"} or not parsed.netloc:
+ raise ValueError(f"Invalid DashScope base_url: {base_url!r}.")
+ scheme = "wss" if parsed.scheme == "https" else "ws"
+ return f"{scheme}://{parsed.netloc}{_REALTIME_PATH}?model={model}"
class DashScopeRealtimeModel(RealtimeModelBase):
@@ -48,9 +55,13 @@ class DashScopeRealtimeModel(RealtimeModelBase):
)
type = "dashscope_omni_realtime"
- truncation = TruncationSupport.NONE
supports_text_input = False
+ @property
+ def input_transcription_enabled(self) -> bool:
+ """Whether DashScope input transcription is enabled."""
+ return self.parameters.input_audio_transcription
+
def __init__(
self,
model: str,
@@ -75,6 +86,8 @@ class DashScopeRealtimeModel(RealtimeModelBase):
self._ws: Any = None
self._reader: asyncio.Task | None = None
self._queue: asyncio.Queue[me.ModelEvent | None] = asyncio.Queue()
+ self._session_ready = asyncio.Event()
+ self._session_setup_error: Exception | None = None
self._item_id = ""
self._tool_args: dict[str, str] = {}
self._tool_names: dict[str, str] = {}
@@ -92,42 +105,74 @@ class DashScopeRealtimeModel(RealtimeModelBase):
"""Open the WebSocket and send the session config."""
import websockets
- # Stop the previous session and drop its terminal events.
+ # Stop the previous session. Replacing the queue below isolates the
+ # new event stream from its terminal events.
await self.close()
- while not self._queue.empty():
- self._queue.get_nowait()
if kwargs.get("turn_detection_disabled"):
self.parameters = self.parameters.model_copy(
update={"turn_detection": "none"},
)
+ self._queue = asyncio.Queue()
+ self._session_ready.clear()
+ self._session_setup_error = None
+
credential: DashScopeCredential = self.credential # type: ignore
self._ws = await websockets.connect(
- f"{_REALTIME_URL}?model={self.model}",
+ _realtime_url(credential.base_url, self.model),
additional_headers={
"Authorization": f"Bearer "
f"{credential.api_key.get_secret_value()}",
"X-DashScope-DataInspection": "disable",
},
)
- self._reader = asyncio.create_task(self._read(), name="dashscope-rt")
+ queue = self._queue
+ websocket = self._ws
+ self._reader = asyncio.create_task(
+ self._read(websocket, queue),
+ name="dashscope-rt",
+ )
await self._send(self._session_update(instructions, tools))
+ try:
+ await asyncio.wait_for(
+ self._session_ready.wait(),
+ timeout=_SESSION_READY_TIMEOUT_S,
+ )
+ except asyncio.TimeoutError as exc:
+ await self._stop_connection()
+ raise ModelDisconnectedError(
+ "Timed out waiting for DashScope session setup.",
+ ) from exc
+ if self._session_setup_error is not None:
+ error = self._session_setup_error
+ await self._stop_connection()
+ raise error
async def close(self) -> None:
"""Stop reading and close the WebSocket."""
- if self._reader is not None:
- self._reader.cancel()
- await asyncio.gather(self._reader, return_exceptions=True)
- self._reader = None
- if self._ws is not None:
- await self._ws.close()
- self._ws = None
+ self._fail_session_setup("Session closed before setup completed.")
+ await self._stop_connection()
+
+ async def _stop_connection(self) -> None:
+ """Stop the current reader and socket without reusing its queue."""
+ websocket = self._ws
+ self._ws = None
+
+ reader = self._reader
+ self._reader = None
+ if reader is not None:
+ reader.cancel()
+ await asyncio.gather(reader, return_exceptions=True)
+
+ if websocket is not None:
+ await websocket.close()
async def events(self) -> AsyncIterator[me.ModelEvent]:
"""Yield events until the session ends."""
+ queue = self._queue
while True:
- event = await self._queue.get()
+ event = await queue.get()
if event is None:
return
yield event
@@ -195,14 +240,6 @@ class DashScopeRealtimeModel(RealtimeModelBase):
if self._item_id:
await self._send({"type": "response.cancel"})
- async def truncate(
- self,
- item_id: str,
- played_ms: int,
- played_text: str,
- ) -> None:
- """No-op: the protocol has no truncate frame."""
-
# ------------------------------------------------------------------
# Wire
# ------------------------------------------------------------------
@@ -253,10 +290,14 @@ class DashScopeRealtimeModel(RealtimeModelBase):
self._ws = None
raise ModelDisconnectedError(str(exc.rcvd or exc)) from exc
- async def _read(self) -> None:
+ async def _read(
+ self,
+ websocket: Any,
+ queue: asyncio.Queue[me.ModelEvent | None],
+ ) -> None:
"""Drain the WebSocket into the event queue until it closes."""
try:
- async for raw in self._ws:
+ async for raw in websocket:
if isinstance(raw, bytes):
raw = raw.decode("utf-8")
try:
@@ -265,12 +306,24 @@ class DashScopeRealtimeModel(RealtimeModelBase):
logger.exception("DashScopeRealtimeModel: bad frame")
continue
if event is not None:
- self._queue.put_nowait(event)
+ queue.put_nowait(event)
except Exception as exc: # noqa: BLE001
logger.error("DashScopeRealtimeModel: connection lost: %s", exc)
finally:
- self._queue.put_nowait(me.SessionEndedEvent(reason="closed"))
- self._queue.put_nowait(None)
+ if self._ws is websocket:
+ self._ws = None
+ self._fail_session_setup(
+ "Connection closed before session setup completed.",
+ )
+ queue.put_nowait(me.SessionEndedEvent(reason="closed"))
+ queue.put_nowait(None)
+
+ def _fail_session_setup(self, message: str) -> None:
+ """Release setup waiters with a provider connection error."""
+ if self._session_ready.is_set():
+ return
+ self._session_setup_error = ModelDisconnectedError(message)
+ self._session_ready.set()
# pylint: disable=too-many-return-statements
def _parse(self, data: dict) -> me.ModelEvent | None:
@@ -279,6 +332,10 @@ class DashScopeRealtimeModel(RealtimeModelBase):
item_id = data.get("item_id", "")
match kind:
+ case "session.updated":
+ self._session_ready.set()
+ return None
+
case "response.created":
self._item_id = data.get("response", {}).get("id", "")
return me.ResponseCreatedEvent(item_id=self._item_id)
@@ -319,6 +376,9 @@ class DashScopeRealtimeModel(RealtimeModelBase):
text=data.get("transcript", ""),
)
+ case "conversation.item.input_audio_transcription.failed":
+ return me.InputTranscriptionFailedEvent(item_id=item_id)
+
case "input_audio_buffer.speech_started":
return me.SpeechStartedEvent(
item_id=item_id,
@@ -370,9 +430,15 @@ class DashScopeRealtimeModel(RealtimeModelBase):
case "error":
err = data.get("error", {})
+ message = err.get("message", "")
+ if not self._session_ready.is_set():
+ self._session_setup_error = ModelDisconnectedError(
+ f"DashScope session setup failed: {message}",
+ )
+ self._session_ready.set()
return me.ModelErrorEvent(
code=err.get("code", ""),
- message=err.get("message", ""),
+ message=message,
)
case _:
diff --git a/src/agentscope/realtime/_dashscope/_models/qwen-omni-turbo-realtime.yaml b/src/agentscope/realtime/_dashscope/_models/qwen-omni-turbo-realtime.yaml
index f77c8be5b..5721e873d 100644
--- a/src/agentscope/realtime/_dashscope/_models/qwen-omni-turbo-realtime.yaml
+++ b/src/agentscope/realtime/_dashscope/_models/qwen-omni-turbo-realtime.yaml
@@ -23,4 +23,5 @@ max_session_duration_s: 7200
parameter_overrides:
voice:
+ default: "Chelsie"
enum: ["Cherry", "Serena", "Ethan", "Chelsie"]
diff --git a/src/agentscope/realtime/_dashscope/_models/qwen3-omni-flash-realtime.yaml b/src/agentscope/realtime/_dashscope/_models/qwen3-omni-flash-realtime.yaml
index 0ad882b73..722ed0773 100644
--- a/src/agentscope/realtime/_dashscope/_models/qwen3-omni-flash-realtime.yaml
+++ b/src/agentscope/realtime/_dashscope/_models/qwen3-omni-flash-realtime.yaml
@@ -23,4 +23,5 @@ max_session_duration_s: 7200
parameter_overrides:
voice:
+ default: "Cherry"
enum: ["Cherry", "Serena", "Ethan", "Chelsie"]
diff --git a/src/agentscope/realtime/_dashscope/_models/qwen3.5-omni-flash-realtime.yaml b/src/agentscope/realtime/_dashscope/_models/qwen3.5-omni-flash-realtime.yaml
index df48a83c5..c5f9a8509 100644
--- a/src/agentscope/realtime/_dashscope/_models/qwen3.5-omni-flash-realtime.yaml
+++ b/src/agentscope/realtime/_dashscope/_models/qwen3.5-omni-flash-realtime.yaml
@@ -24,4 +24,4 @@ max_session_duration_s: 7200
parameter_overrides:
voice:
default: "Tina"
- enum: ["Cherry", "Serena", "Ethan", "Chelsie", "Tina"]
+ enum: ["Tina", "Serena", "Ethan"]
diff --git a/src/agentscope/realtime/_dashscope/_models/qwen3.5-omni-plus-realtime.yaml b/src/agentscope/realtime/_dashscope/_models/qwen3.5-omni-plus-realtime.yaml
index e54af5d75..81b070b3c 100644
--- a/src/agentscope/realtime/_dashscope/_models/qwen3.5-omni-plus-realtime.yaml
+++ b/src/agentscope/realtime/_dashscope/_models/qwen3.5-omni-plus-realtime.yaml
@@ -24,4 +24,4 @@ max_session_duration_s: 7200
parameter_overrides:
voice:
default: "Tina"
- enum: ["Cherry", "Serena", "Ethan", "Chelsie", "Tina"]
+ enum: ["Tina", "Serena", "Ethan"]
diff --git a/src/agentscope/realtime/_events.py b/src/agentscope/realtime/_events.py
index dd22e2862..ebfb4ad60 100644
--- a/src/agentscope/realtime/_events.py
+++ b/src/agentscope/realtime/_events.py
@@ -41,6 +41,12 @@ class InputTranscriptionEvent(ModelEvent):
text: str
+class InputTranscriptionFailedEvent(ModelEvent):
+ """The provider could not transcribe one committed user turn."""
+
+ item_id: str = ""
+
+
class ResponseCreatedEvent(ModelEvent):
"""The provider started producing a reply."""
diff --git a/src/agentscope/realtime/_gemini/_model.py b/src/agentscope/realtime/_gemini/_model.py
index ceb4a7bf1..3ea563492 100644
--- a/src/agentscope/realtime/_gemini/_model.py
+++ b/src/agentscope/realtime/_gemini/_model.py
@@ -9,11 +9,7 @@ from typing import Any, AsyncIterator, Literal
from pydantic import Field
from .. import _events as me
-from .._base import (
- ModelDisconnectedError,
- RealtimeModelBase,
- TruncationSupport,
-)
+from .._base import ModelDisconnectedError, RealtimeModelBase
from .._model_card import RealtimeModelCard
from ..._logging import logger
from ..._utils._common import _flatten_json_schema
@@ -39,7 +35,7 @@ class GeminiRealtimeModel(RealtimeModelBase):
starts the reply, so :meth:`request_response` sends nothing.
- Interruption is the server's job — it reports
``serverContent.interrupted`` and drops the rest of the reply
- itself — so :meth:`truncate` and :meth:`cancel_response` are no-ops.
+ itself — so :meth:`cancel_response` is a no-op.
With caller-owned turns the caller silences the reply locally
instead, and the server is told not to interrupt on its own.
"""
@@ -70,9 +66,13 @@ class GeminiRealtimeModel(RealtimeModelBase):
)
type = "gemini_realtime"
- truncation = TruncationSupport.SERVER
supports_text_input = True
+ @property
+ def input_transcription_enabled(self) -> bool:
+ """Whether Gemini input transcription is enabled."""
+ return self.parameters.input_audio_transcription
+
def __init__(
self,
model: str,
@@ -241,14 +241,6 @@ class GeminiRealtimeModel(RealtimeModelBase):
async def cancel_response(self) -> None:
"""No-op: the protocol has no cancel frame."""
- async def truncate(
- self,
- item_id: str,
- played_ms: int,
- played_text: str,
- ) -> None:
- """No-op: the server drops the interrupted reply itself."""
-
# ------------------------------------------------------------------
# Wire
# ------------------------------------------------------------------
diff --git a/src/agentscope/realtime/_openai/_model.py b/src/agentscope/realtime/_openai/_model.py
index 8b88f8239..0a22922b3 100644
--- a/src/agentscope/realtime/_openai/_model.py
+++ b/src/agentscope/realtime/_openai/_model.py
@@ -8,11 +8,7 @@ from typing import Any, AsyncIterator, Literal
from pydantic import Field
from .. import _events as me
-from .._base import (
- ModelDisconnectedError,
- RealtimeModelBase,
- TruncationSupport,
-)
+from .._base import ModelDisconnectedError, RealtimeModelBase
from .._model_card import RealtimeModelCard
from ..._logging import logger
from ...credential import OpenAICredential
@@ -65,9 +61,13 @@ class OpenAIRealtimeModel(RealtimeModelBase):
)
type = "openai_realtime"
- truncation = TruncationSupport.EXPLICIT
supports_text_input = True
+ @property
+ def input_transcription_enabled(self) -> bool:
+ """Whether the configured input transcription model is enabled."""
+ return bool(self.parameters.input_audio_transcription)
+
def __init__(
self,
model: str,
@@ -219,24 +219,6 @@ class OpenAIRealtimeModel(RealtimeModelBase):
if self._response_id:
await self._send({"type": "response.cancel"})
- async def truncate(
- self,
- item_id: str,
- played_ms: int,
- played_text: str,
- ) -> None:
- """Cut the assistant item back to the audio the user heard. The
- server drops the transcript tail itself, so *played_text* is
- unused."""
- await self._send(
- {
- "type": "conversation.item.truncate",
- "item_id": item_id,
- "content_index": 0,
- "audio_end_ms": played_ms,
- },
- )
-
# ------------------------------------------------------------------
# Wire
# ------------------------------------------------------------------
@@ -417,6 +399,11 @@ class OpenAIRealtimeModel(RealtimeModelBase):
text=data.get("transcript", ""),
)
+ case "conversation.item.input_audio_transcription.failed":
+ return me.InputTranscriptionFailedEvent(
+ item_id=data.get("item_id", ""),
+ )
+
case "input_audio_buffer.speech_started":
return me.SpeechStartedEvent(
item_id=data.get("item_id", ""),
diff --git a/src/agentscope/realtime/_transport/_base.py b/src/agentscope/realtime/_transport/_base.py
index 8aba5f698..425159a39 100644
--- a/src/agentscope/realtime/_transport/_base.py
+++ b/src/agentscope/realtime/_transport/_base.py
@@ -98,18 +98,11 @@ class TransportBase(ABC):
@abstractmethod
async def clear_audio(self) -> PlayoutPosition:
- """Cut playback short and report how much was actually heard.
-
- Fades out briefly to avoid an audible click, then discards queued
- and in-flight audio.
-
- Clearing and reporting are one call on purpose: the returned
- position is what the caller must feed to
- :meth:`VoiceBackendBase.truncate`, so the two cannot drift apart
- and the truncation cannot be forgotten.
+ """Clear audio playback and return its position before the cut.
Returns:
- `PlayoutPosition`: What the user heard before the cut.
+ `PlayoutPosition`: The playback position before audio was
+ cleared.
"""
@abstractmethod
diff --git a/src/agentscope/realtime/_xai/_model.py b/src/agentscope/realtime/_xai/_model.py
index 3e1e889eb..0d6dec61e 100644
--- a/src/agentscope/realtime/_xai/_model.py
+++ b/src/agentscope/realtime/_xai/_model.py
@@ -8,11 +8,7 @@ from typing import Any, AsyncIterator, Literal
from pydantic import Field
from .. import _events as me
-from .._base import (
- ModelDisconnectedError,
- RealtimeModelBase,
- TruncationSupport,
-)
+from .._base import ModelDisconnectedError, RealtimeModelBase
from .._model_card import RealtimeModelCard
from ..._logging import logger
from ...credential import XAICredential
@@ -57,9 +53,13 @@ class XAIRealtimeModel(RealtimeModelBase):
)
type = "xai_realtime"
- truncation = TruncationSupport.NONE
supports_text_input = True
+ @property
+ def input_transcription_enabled(self) -> bool:
+ """xAI always reports settled input transcription events."""
+ return True
+
def __init__(
self,
model: str,
@@ -205,14 +205,6 @@ class XAIRealtimeModel(RealtimeModelBase):
if self._response_id:
await self._send({"type": "response.cancel"})
- async def truncate(
- self,
- item_id: str,
- played_ms: int,
- played_text: str,
- ) -> None:
- """No-op: the protocol documents no truncate frame."""
-
# ------------------------------------------------------------------
# Wire
# ------------------------------------------------------------------
@@ -338,6 +330,9 @@ class XAIRealtimeModel(RealtimeModelBase):
text=data.get("transcript", ""),
)
+ case "conversation.item.input_audio_transcription.failed":
+ return me.InputTranscriptionFailedEvent(item_id=item_id)
+
case "input_audio_buffer.speech_started":
return me.SpeechStartedEvent(
item_id=item_id,
diff --git a/tests/agent_basic_test.py b/tests/agent_basic_test.py
index 4cd35f313..f144861d9 100644
--- a/tests/agent_basic_test.py
+++ b/tests/agent_basic_test.py
@@ -334,7 +334,6 @@ class AgentBasicTest(IsolatedAsyncioTestCase):
},
],
"finished_at": AnyString(),
- "finished_reason": None,
"structured_output": None,
"error": None,
},
@@ -976,6 +975,7 @@ class AgentBasicTest(IsolatedAsyncioTestCase):
},
],
"finished_at": AnyString(),
+ "finished_reason": None,
},
{
**msg_base,
diff --git a/tests/agent_config_grouping_test.py b/tests/agent_config_grouping_test.py
new file mode 100644
index 000000000..f0699cbd0
--- /dev/null
+++ b/tests/agent_config_grouping_test.py
@@ -0,0 +1,351 @@
+# -*- coding: utf-8 -*-
+"""``AgentData.chat_config`` grouping test case.
+
+The text-mode settings moved from the top level of ``AgentData`` into a
+``chat_config`` block, so a realtime voice mode can add its own block
+beside them. Nothing migrates the stored rows and nothing rewrites the
+request bodies clients already send, so both the old and the new shape
+have to land in the same place — that is what these cases pin down.
+"""
+import json
+from typing import Any
+from unittest import IsolatedAsyncioTestCase
+
+import fakeredis.aioredis
+from fastapi.testclient import TestClient
+
+from agentscope.app import create_app
+from agentscope.app.message_bus import RedisMessageBus
+from agentscope.app.storage import AgentData, AgentRecord, RedisStorage
+from agentscope.app.workspace_manager import LocalWorkspaceManager
+
+HEADERS = {"X-User-ID": "alice"}
+
+
+class AgentConfigGroupingTest(IsolatedAsyncioTestCase):
+ """Reading, creating and updating agents across both shapes."""
+
+ async def asyncSetUp(self) -> None:
+ """Start an app backed by fakeredis."""
+ redis = fakeredis.aioredis.FakeRedis(decode_responses=True)
+ self.redis = redis
+
+ class _Storage(RedisStorage):
+ async def __aenter__(self) -> Any:
+ self._client = redis
+ return self
+
+ async def aclose(self) -> None:
+ self._client = None
+
+ class _Bus(RedisMessageBus):
+ async def __aenter__(self) -> Any:
+ self._client = redis
+ return self
+
+ async def aclose(self) -> None:
+ self._client = None
+
+ app = create_app(
+ storage=_Storage(),
+ message_bus=_Bus(),
+ workspace_manager=LocalWorkspaceManager("/tmp"),
+ enable_index_worker=False,
+ )
+ # pylint: disable=consider-using-with
+ self.client = self.enterContext(TestClient(app))
+ self.storage = app.state.storage
+
+ def test_legacy_record_folds_into_chat_config(self) -> None:
+ """An agent written before the grouping reads back grouped."""
+ data = AgentData.model_validate(
+ {
+ "id": "a1",
+ "name": "ann",
+ "system_prompt": "You are ann.",
+ "context_config": {"max_image_num": 3},
+ "react_config": {"max_iters": 7},
+ "invite_config": {
+ "invitable": True,
+ "invite_description": "an old agent",
+ },
+ },
+ )
+
+ self.assertDictEqual(
+ data.model_dump(mode="json", exclude_defaults=True),
+ {
+ "id": "a1",
+ "name": "ann",
+ "system_prompt": "You are ann.",
+ "chat_config": {
+ "context_config": {"max_image_num": 3},
+ "react_config": {"max_iters": 7},
+ "invite_config": {
+ "invitable": True,
+ "invite_description": "an old agent",
+ },
+ },
+ },
+ )
+ with self.assertWarns(DeprecationWarning):
+ context_config = data.context_config
+ with self.assertWarns(DeprecationWarning):
+ react_config = data.react_config
+ with self.assertWarns(DeprecationWarning):
+ invite_config = data.invite_config
+ self.assertEqual(
+ {
+ "context_config": context_config,
+ "react_config": react_config,
+ "invite_config": invite_config,
+ },
+ {
+ "context_config": data.chat_config.context_config,
+ "react_config": data.chat_config.react_config,
+ "invite_config": data.chat_config.invite_config,
+ },
+ )
+
+ def test_create_accepts_both_shapes(self) -> None:
+ """POST bodies in either shape store the same grouped record."""
+ nested = self.client.post(
+ "/agent/",
+ headers=HEADERS,
+ json={
+ "name": "nested",
+ "chat_config": {"react_config": {"max_iters": 5}},
+ },
+ )
+ legacy = self.client.post(
+ "/agent/",
+ headers=HEADERS,
+ json={"name": "legacy", "react_config": {"max_iters": 5}},
+ )
+ self.assertEqual(nested.status_code, 201)
+ self.assertEqual(legacy.status_code, 201)
+
+ agents = self.client.get("/agent/", headers=HEADERS).json()["agents"]
+ by_name = {a["data"]["name"]: a["data"] for a in agents}
+ self.assertEqual(
+ by_name["nested"]["chat_config"],
+ by_name["legacy"]["chat_config"],
+ )
+ self.assertEqual(
+ by_name["nested"]["chat_config"],
+ AgentData.model_validate(
+ {
+ "name": "expected",
+ "chat_config": {
+ "react_config": {"max_iters": 5},
+ },
+ },
+ ).chat_config.model_dump(mode="json"),
+ )
+ self.assertListEqual(
+ sorted(by_name["legacy"]),
+ [
+ "chat_config",
+ "id",
+ "name",
+ "system_prompt",
+ ],
+ )
+
+ def test_update_keeps_untouched_sub_configs(self) -> None:
+ """A legacy PATCH replaces its own sub-config and nothing else."""
+ agent_id = self.client.post(
+ "/agent/",
+ headers=HEADERS,
+ json={
+ "name": "ann",
+ "chat_config": {
+ "react_config": {"max_iters": 5},
+ "invite_config": {
+ "invitable": True,
+ "invite_description": "keep me",
+ },
+ },
+ },
+ ).json()["agent_id"]
+
+ updated = self.client.patch(
+ f"/agent/{agent_id}",
+ headers=HEADERS,
+ json={"context_config": {"max_image_num": 9}},
+ )
+
+ self.assertEqual(updated.status_code, 200)
+ self.assertEqual(
+ updated.json()["data"]["chat_config"],
+ AgentData.model_validate(
+ {
+ "name": "expected",
+ "chat_config": {
+ "context_config": {"max_image_num": 9},
+ "react_config": {"max_iters": 5},
+ "invite_config": {
+ "invitable": True,
+ "invite_description": "keep me",
+ },
+ },
+ },
+ ).chat_config.model_dump(mode="json"),
+ )
+
+ def test_nested_update_keeps_untouched_sub_configs(self) -> None:
+ """A nested PATCH replaces only the supplied sub-config."""
+ agent_id = self.client.post(
+ "/agent/",
+ headers=HEADERS,
+ json={
+ "name": "ann",
+ "chat_config": {
+ "context_config": {"max_image_num": 9},
+ "react_config": {
+ "max_iters": 5,
+ "stop_on_reject": True,
+ },
+ "invite_config": {
+ "invitable": True,
+ "invite_description": "keep me",
+ },
+ },
+ },
+ ).json()["agent_id"]
+
+ updated = self.client.patch(
+ f"/agent/{agent_id}",
+ headers=HEADERS,
+ json={"chat_config": {"react_config": {"max_iters": 7}}},
+ )
+
+ self.assertEqual(updated.status_code, 200)
+ self.assertEqual(
+ updated.json()["data"]["chat_config"],
+ AgentData.model_validate(
+ {
+ "name": "expected",
+ "chat_config": {
+ "context_config": {"max_image_num": 9},
+ "react_config": {"max_iters": 7},
+ "invite_config": {
+ "invitable": True,
+ "invite_description": "keep me",
+ },
+ },
+ },
+ ).chat_config.model_dump(mode="json"),
+ )
+
+ def test_legacy_update_overrides_nested_update(self) -> None:
+ """Flat compatibility fields win over the nested equivalent."""
+ agent_id = self.client.post(
+ "/agent/",
+ headers=HEADERS,
+ json={"name": "ann"},
+ ).json()["agent_id"]
+
+ updated = self.client.patch(
+ f"/agent/{agent_id}",
+ headers=HEADERS,
+ json={
+ "chat_config": {
+ "context_config": {"max_image_num": 7},
+ "react_config": {"max_iters": 11},
+ },
+ "context_config": {"max_image_num": 3},
+ },
+ )
+
+ self.assertEqual(updated.status_code, 200)
+ self.assertEqual(
+ updated.json()["data"]["chat_config"],
+ AgentData.model_validate(
+ {
+ "name": "expected",
+ "chat_config": {
+ "context_config": {"max_image_num": 3},
+ "react_config": {"max_iters": 11},
+ },
+ },
+ ).chat_config.model_dump(mode="json"),
+ )
+
+ def test_schema_exposes_the_grouped_sections(self) -> None:
+ """The form schema carries the sections inside ``chat_config``."""
+ schema = self.client.get("/agent/schema/v2").json()["schema"]
+
+ self.assertListEqual(
+ sorted(schema["properties"]),
+ ["chat_config", "name", "system_prompt"],
+ )
+ chat_config = schema["properties"]["chat_config"]
+ self.assertListEqual(
+ sorted(chat_config["properties"]),
+ ["context_config", "invite_config", "react_config"],
+ )
+ self.assertNotIn(
+ "summary_schema",
+ chat_config["properties"]["context_config"]["properties"],
+ )
+ openapi = self.client.get("/openapi.json").json()
+ agent_view = openapi["components"]["schemas"]["AgentView"]
+ self.assertIn("data", agent_view["properties"])
+ self.assertNotEqual(agent_view.get("additionalProperties"), True)
+
+ async def test_stored_agent_survives_a_round_trip(self) -> None:
+ """A raw legacy Redis record is read and rewritten grouped."""
+ record_id = "record-1"
+ raw_record = {
+ "id": record_id,
+ "created_at": "2026-09-01T01:02:03",
+ "updated_at": "2026-09-02T04:05:06",
+ "user_id": "alice",
+ "source": "user",
+ "data": {
+ "id": "agent-1",
+ "name": "ann",
+ "system_prompt": "You are ann.",
+ "context_config": {"max_image_num": 3},
+ "react_config": {"max_iters": 7},
+ "invite_config": {
+ "invitable": True,
+ "invite_description": "an old agent",
+ },
+ },
+ }
+ key = self.storage.key_config.agent.format(
+ user_id="alice",
+ agent_id=record_id,
+ )
+ await self.redis.set(key, json.dumps(raw_record))
+
+ stored = await self.storage.get_agent("alice", record_id)
+ expected = AgentRecord.model_validate(
+ {
+ **raw_record,
+ "data": {
+ "id": "agent-1",
+ "name": "ann",
+ "system_prompt": "You are ann.",
+ "chat_config": {
+ "context_config": {"max_image_num": 3},
+ "react_config": {"max_iters": 7},
+ "invite_config": {
+ "invitable": True,
+ "invite_description": "an old agent",
+ },
+ },
+ },
+ },
+ )
+
+ self.assertEqual(stored.model_dump(), expected.model_dump())
+
+ await self.storage.upsert_agent("alice", stored)
+ rewritten = json.loads(await self.redis.get(key))
+ self.assertEqual(
+ rewritten["data"],
+ expected.data.model_dump(mode="json"),
+ )
diff --git a/tests/channel_stream_test.py b/tests/channel_stream_test.py
index 690f49089..16d5ebd38 100644
--- a/tests/channel_stream_test.py
+++ b/tests/channel_stream_test.py
@@ -14,7 +14,7 @@ from unittest import IsolatedAsyncioTestCase
from agentscope.app._bus_ops import publish_session_event
from agentscope.app.channel._stream import open_reply_stream
-from agentscope.app.message_bus import InMemoryMessageBus
+from agentscope.app.message_bus import InMemoryMessageBus, MessageBusKeys
from agentscope.event import (
ReplyEndEvent,
ReplyStartEvent,
@@ -119,6 +119,26 @@ class EventStreamTest(IsolatedAsyncioTestCase):
["REPLY_START", "REPLY_END"],
)
+ async def test_replay_starts_after_persisted_checkpoint(self) -> None:
+ """Retained events from the prior run are not redelivered."""
+ bus = InMemoryMessageBus()
+ await _publish(bus, "s-1", _start())
+ await _publish(bus, "s-1", _end())
+ entries = await bus.log_read(MessageBusKeys.session_events("s-1"))
+ await bus.registry_set(
+ MessageBusKeys.session_event_checkpoint("s-1"),
+ MessageBusKeys.SESSION_EVENT_CURSOR_FIELD,
+ entries[-1][0],
+ )
+
+ async def _run() -> None:
+ await asyncio.sleep(0.01)
+ await _publish(bus, "s-1", _start())
+ await _publish(bus, "s-1", _end())
+
+ drained, _ = await asyncio.gather(_drain(bus, "s-1"), _run())
+ self.assertListEqual(drained, ["REPLY_START", "REPLY_END"])
+
async def test_delivers_events_published_while_streaming(self) -> None:
"""The common case: delivery starts first, events arrive after."""
bus = InMemoryMessageBus()
diff --git a/tests/realtime_agent_test.py b/tests/realtime_agent_test.py
index aec8813e4..209d6d1e5 100644
--- a/tests/realtime_agent_test.py
+++ b/tests/realtime_agent_test.py
@@ -3,18 +3,26 @@
transport — no network, no sound card."""
# pylint: disable=protected-access, unused-argument
import asyncio
-from typing import Any, AsyncIterator
+from typing import Any, AsyncIterator, Sequence
from unittest.async_case import IsolatedAsyncioTestCase
-from utils import AnyString
+from utils import AnyString, MockModel
-from agentscope.agent import RealtimeAgent, TurnAggregator
+from agentscope.agent import (
+ Agent,
+ InjectionConfig,
+ RealtimeAgent,
+ TurnAggregator,
+)
from agentscope.credential import DashScopeCredential
from agentscope.event import (
+ DataBlockDeltaEvent,
ReplyEndEvent,
ReplyStartEvent,
TextBlockDeltaEvent,
+ TextBlockEndEvent,
)
-from agentscope.message import Msg
+from agentscope.message import AssistantMsg, Msg, UserMsg
+from agentscope.model import ChatResponse
from agentscope.realtime import (
AudioFrame,
ControlFrame,
@@ -25,7 +33,6 @@ from agentscope.realtime import (
RealtimeModelCard,
SpeechTransition,
TransportBase,
- TruncationSupport,
VADBase,
)
from agentscope.event import (
@@ -44,26 +51,59 @@ from agentscope.permission import (
PermissionContext,
PermissionDecision,
)
+from agentscope.state import AgentState
from agentscope.tool import ToolBase, ToolChunk, ToolResponse, Toolkit
from agentscope.realtime import _events as me
+from agentscope.types import ReplyFinishedReason
PCM_100MS = b"\x01\x00" * 2400
+
+def _message_summary(message: Msg) -> dict[str, Any]:
+ """Keep only state-machine fields relevant to realtime assertions."""
+ payload = message.model_dump(mode="json")
+ content = []
+ for block in payload["content"]:
+ summary = {
+ key: block[key]
+ for key in ("type", "text", "name", "input", "output", "state")
+ if key in block
+ }
+ if block["type"] in {"tool_call", "tool_result"}:
+ summary["id"] = block["id"]
+ content.append(summary)
+ return {
+ "role": payload["role"],
+ "id": payload["id"],
+ "content": content,
+ "usage": payload["usage"],
+ "finished_reason": payload["finished_reason"],
+ }
+
+
REPLY_R1 = [
me.SpeechEndedEvent(item_id="u1"),
- me.InputTranscriptionEvent(item_id="u1", text="讲个故事"),
+ me.InputTranscriptionEvent(item_id="u1", text="Tell me a story"),
me.ResponseCreatedEvent(item_id="r1"),
]
-for _word in ["从前", "有座山", "山里", "有座庙", "庙里", "有个", "老和尚"]:
+for _word in [
+ "Once ",
+ "upon ",
+ "a time, ",
+ "there ",
+ "was ",
+ "an old ",
+ "monk.",
+]:
REPLY_R1 += [
me.TranscriptDeltaEvent(item_id="r1", delta=_word),
me.AudioDeltaEvent(item_id="r1", pcm=PCM_100MS, sample_rate=24000),
]
REPLY_R2 = [
- me.InputTranscriptionEvent(item_id="u3", text="你好"),
+ me.InputTranscriptionEvent(item_id="u3", text="Hello"),
me.ResponseCreatedEvent(item_id="r2"),
- me.TranscriptDeltaEvent(item_id="r2", delta="你好呀"),
+ me.TranscriptDeltaEvent(item_id="r2", delta="Hi there."),
me.AudioDeltaEvent(item_id="r2", pcm=PCM_100MS, sample_rate=24000),
me.ResponseDoneEvent(item_id="r2", input_tokens=10, output_tokens=3),
]
@@ -72,10 +112,23 @@ REPLY_R2 = [
class ScriptedModel(RealtimeModelBase):
"""Plays one event script per session and records every call."""
- truncation = TruncationSupport.NONE
+ class Parameters(RealtimeModelBase.Parameters):
+ """Test-only switch for delayed input transcription."""
+
+ input_audio_transcription: bool = False
+
type = "scripted"
- def __init__(self, scripts: list[list[Any]]) -> None:
+ @property
+ def input_transcription_enabled(self) -> bool:
+ """Whether the scripted model delays user turn completion."""
+ return self.parameters.input_audio_transcription
+
+ def __init__(
+ self,
+ scripts: list[list[Any]],
+ input_audio_transcription: bool = False,
+ ) -> None:
card = RealtimeModelCard(
name="scripted",
label="scripted",
@@ -85,12 +138,16 @@ class ScriptedModel(RealtimeModelBase):
super().__init__(
"scripted",
DashScopeCredential(api_key="sk-x"),
+ parameters=self.Parameters(
+ input_audio_transcription=input_audio_transcription,
+ ),
model_card=card,
)
self.scripts = scripts
self.calls: list[str] = []
self.sessions = 0
self.instructions = ""
+ self.supports_text_input = False
self.connect_error: Exception | None = None
self.push_text_error: Exception | None = None
self._open = asyncio.Event()
@@ -159,18 +216,61 @@ class ScriptedModel(RealtimeModelBase):
"""Record the cancel."""
self.calls.append("cancel")
- async def truncate(
+
+class HistoryScriptedModel(ScriptedModel):
+ """Records structured history supplied for each new model session."""
+
+ supports_history_replay = True
+
+ def __init__(self, scripts: list[list[Any]]) -> None:
+ super().__init__(scripts)
+ self.replayed: list[list[Msg]] = []
+
+ async def replay_history(self, messages: Sequence[Msg]) -> None:
+ """Keep a deep copy so later context changes cannot affect it."""
+ replay = [message.model_copy(deep=True) for message in messages]
+ self.replayed.append(replay)
+ self.calls.append("replay_history")
+
+
+class QueueSessionModel(ScriptedModel):
+ """Keeps each session's event iterator alive on its own queue."""
+
+ def __init__(self) -> None:
+ super().__init__([])
+ self.event_queues: list[asyncio.Queue[me.ModelEvent | None]] = []
+ self.iterator_started: list[asyncio.Event] = []
+ self.iterator_finished: list[asyncio.Event] = []
+
+ async def connect(
self,
- item_id: str,
- played_ms: int,
- played_text: str,
+ instructions: str,
+ tools: list[dict] | None = None,
+ **kwargs: Any,
) -> None:
- """Record what the agent thinks the user heard."""
- self.calls.append(f"truncate({item_id},{played_ms}ms,{played_text!r})")
+ """Open a session with a distinct event queue."""
+ await super().connect(instructions, tools, **kwargs)
+ self.event_queues.append(asyncio.Queue())
+ self.iterator_started.append(asyncio.Event())
+ self.iterator_finished.append(asyncio.Event())
+
+ async def events(self) -> AsyncIterator[me.ModelEvent]:
+ """Yield only events belonging to the current session."""
+ index = self.sessions - 1
+ queue = self.event_queues[index]
+ self.iterator_started[index].set()
+ try:
+ while True:
+ event = await queue.get()
+ if event is None:
+ return
+ yield event
+ finally:
+ self.iterator_finished[index].set()
class FakeTransport(TransportBase):
- """Emits ``frames`` chunks of silence, reports 320 ms played."""
+ """Emit ``frames`` chunks of silence and record transport calls."""
input_sample_rate = 16000
output_sample_rate = 24000
@@ -206,10 +306,9 @@ class FakeTransport(TransportBase):
return self.playout()
def playout(self) -> PlayoutPosition:
- """Always 320 ms into the current item."""
+ """Report a fixed position in the current item."""
return PlayoutPosition(
item_id=self.item,
- played_ms=320,
first_played_at=1.0,
)
@@ -230,6 +329,92 @@ class GatedTransport(FakeTransport):
yield frame
+class BlockingClearTransport(GatedTransport):
+ """Hold ``clear_audio`` open while a response completion arrives."""
+
+ def __init__(self) -> None:
+ super().__init__([])
+ self.audio_sent = asyncio.Event()
+ self.clear_started = asyncio.Event()
+ self.clear_release = asyncio.Event()
+
+ async def send_audio(self, pcm: bytes, item_id: str) -> None:
+ """Record the item and signal that interruption can begin."""
+ await super().send_audio(pcm, item_id)
+ self.audio_sent.set()
+
+ async def clear_audio(self) -> PlayoutPosition:
+ """Wait until the test permits the browser acknowledgment."""
+ self.cleared += 1
+ self.clear_started.set()
+ await self.clear_release.wait()
+ return self.playout()
+
+
+async def _run_terminal_event_during_barge_in(
+ agent: RealtimeAgent,
+ model: QueueSessionModel,
+ terminal_event: me.ModelEvent,
+ tool_call: ToolCallBlock | None = None,
+) -> tuple[list[Any], dict[str, Any]]:
+ """Deliver a terminal event while browser playout clearing is blocked."""
+ transport = BlockingClearTransport()
+ events = []
+
+ async def _collect() -> None:
+ async for event in agent.reply_stream(transport):
+ events.append(event)
+
+ async with agent, transport:
+ await model.iterator_started[0].wait()
+ stream_task = asyncio.create_task(_collect())
+ queue = model.event_queues[0]
+ queue.put_nowait(me.ResponseCreatedEvent(item_id="r1"))
+ queue.put_nowait(
+ me.TranscriptDeltaEvent(
+ item_id="r1",
+ delta="I did not hear that.",
+ ),
+ )
+ queue.put_nowait(
+ me.AudioDeltaEvent(
+ item_id="r1",
+ pcm=PCM_100MS,
+ sample_rate=24000,
+ ),
+ )
+ if tool_call is not None:
+ queue.put_nowait(
+ me.ToolCallEvent(item_id="r1", tool_call=tool_call),
+ )
+ await transport.audio_sent.wait()
+ while (
+ tool_call is not None and tool_call.id not in agent._pending_tools
+ ):
+ await asyncio.sleep(0)
+
+ interrupt_task = asyncio.create_task(agent.interrupt())
+ await transport.clear_started.wait()
+ queue.put_nowait(terminal_event)
+ queue.put_nowait(None)
+ await asyncio.sleep(0)
+ await asyncio.sleep(0)
+ state_while_clearing = {
+ "reply_open": agent._reply is not None,
+ "reply_id": agent._reply_id,
+ "input_tokens": agent._metrics.input_tokens,
+ "pending_tools": sorted(agent._pending_tools),
+ }
+
+ transport.clear_release.set()
+ await interrupt_task
+ await asyncio.wait_for(model.iterator_finished[0].wait(), timeout=1)
+ transport.gate.set()
+ await stream_task
+
+ return events, state_while_clearing
+
+
class EndOnSecondFrameVAD(VADBase):
"""Reports the user starting on the first chunk and stopping on the
second."""
@@ -251,6 +436,46 @@ class EndOnSecondFrameVAD(VADBase):
self.seen = 0
+class RealtimeCheckpointSnapshotTest(IsolatedAsyncioTestCase):
+ """Checkpoint state must stay aligned with its emitted event."""
+
+ async def test_checkpoint_snapshot_stays_at_its_event_boundary(
+ self,
+ ) -> None:
+ """A queued later response cannot advance an earlier checkpoint."""
+ agent = RealtimeAgent(
+ "Friday",
+ "be brief",
+ ScriptedModel([[]]),
+ )
+ agent.state.context.append(
+ AssistantMsg(id="r1", name="Friday", content="first"),
+ )
+ agent._emit(ReplyEndEvent(session_id="s1", reply_id="r1"))
+ agent.state.context.append(
+ AssistantMsg(id="r2", name="Friday", content="second"),
+ )
+
+ checkpoint = agent._out.get_nowait().checkpoint
+ assert checkpoint is not None
+ self.assertEqual(
+ {
+ "checkpoint": [
+ (msg.id, msg.get_text_content())
+ for msg in checkpoint.context
+ ],
+ "current": [
+ (msg.id, msg.get_text_content())
+ for msg in agent.state.context
+ ],
+ },
+ {
+ "checkpoint": [("r1", "first")],
+ "current": [("r1", "first"), ("r2", "second")],
+ },
+ )
+
+
class RealtimeAgentTest(IsolatedAsyncioTestCase):
"""Behaviour of the turn-taking state machine."""
@@ -275,9 +500,8 @@ class RealtimeAgentTest(IsolatedAsyncioTestCase):
summary.append(("reply_end", event.finished_reason))
return summary
- async def test_barge_in_truncates_to_what_was_heard(self) -> None:
- """A barge-in mid-reply cuts both contexts to the played prefix
- and the duplicate speech_started is swallowed by the lock."""
+ async def test_barge_in_keeps_generated_text(self) -> None:
+ """A barge-in keeps generated text and closes the active reply."""
script = REPLY_R1 + [
me.SpeechStartedEvent(item_id="u2"),
me.SpeechStartedEvent(item_id="u2"),
@@ -286,8 +510,7 @@ class RealtimeAgentTest(IsolatedAsyncioTestCase):
agent = RealtimeAgent("Friday", "be brief", model)
transport = FakeTransport(frames=3)
- # Rebuild the agent's message from its events the way a client
- # does; the text deltas ran ahead of what was heard.
+ # Rebuild the agent's message from its events the way a client does.
summary = []
rebuilt = Msg(id="r1", role="assistant", name="Friday", content=[])
async with agent, transport:
@@ -306,20 +529,23 @@ class RealtimeAgentTest(IsolatedAsyncioTestCase):
summary,
[
("user_start", "u1"),
- "讲个故事",
+ "Tell me a story",
("reply_end", "completed"), # the user's turn
- "从前",
- "有座山",
- "山里",
- "有座庙",
- "庙里",
- "有个",
- "老和尚",
+ "Once ",
+ "upon ",
+ "a time, ",
+ "there ",
+ "was ",
+ "an old ",
+ "monk.",
("user_start", "u2"),
("reply_end", "interrupted"),
],
)
- self.assertEqual(rebuilt.get_text_content(), "从前有座山山里有座庙")
+ self.assertEqual(
+ rebuilt.get_text_content(),
+ "Once upon a time, there was an old monk.",
+ )
self.assertEqual(transport.cleared, 1)
# Audio frames interleave with model events on the transport's
# clock, so they are counted rather than positioned.
@@ -327,7 +553,6 @@ class RealtimeAgentTest(IsolatedAsyncioTestCase):
[c for c in model.calls if c != "push_audio"],
[
"connect(session=1,td_off=False)",
- "truncate(r1,320ms,'从前有座山山里有座庙')",
"cancel",
"close",
],
@@ -335,12 +560,187 @@ class RealtimeAgentTest(IsolatedAsyncioTestCase):
self.assertEqual(model.calls.count("push_audio"), 3)
self.assertListEqual(
[(m.role, m.get_text_content()) for m in agent.state.context],
- [("user", "讲个故事"), ("assistant", "从前有座山山里有座庙")],
+ [
+ ("user", "Tell me a story"),
+ ("assistant", "Once upon a time, there was an old monk."),
+ ],
)
self.assertEqual(agent.last_turn_metrics.first_audio_played_at, 1.0)
+ async def test_barge_in_after_response_done_clears_playout(self) -> None:
+ """A completed response remains interruptible while its queued
+ audio is still playing."""
+ script = REPLY_R1 + [
+ me.ResponseDoneEvent(
+ item_id="r1",
+ input_tokens=10,
+ output_tokens=20,
+ ),
+ me.SpeechStartedEvent(item_id="u2"),
+ ]
+ model = ScriptedModel([script])
+ agent = RealtimeAgent("Friday", "be brief", model)
+ transport = FakeTransport(frames=3)
+ rebuilt = Msg(
+ id="r1",
+ role="assistant",
+ name="Friday",
+ content=[],
+ )
+ async with agent, transport:
+ async for event in agent.reply_stream(transport):
+ if getattr(event, "reply_id", None) == "r1":
+ rebuilt.append_event(event)
+
+ self.assertEqual(
+ rebuilt.get_text_content(),
+ "Once upon a time, there was an old monk.",
+ )
+ self.assertEqual(transport.cleared, 1)
+ self.assertListEqual(
+ [call for call in model.calls if call != "push_audio"],
+ [
+ "connect(session=1,td_off=False)",
+ "close",
+ ],
+ )
+ self.assertListEqual(
+ [
+ (
+ message.role,
+ message.get_text_content(),
+ message.finished_reason,
+ )
+ for message in agent.state.context
+ ],
+ [
+ ("user", "Tell me a story", None),
+ (
+ "assistant",
+ "Once upon a time, there was an old monk.",
+ ReplyFinishedReason.COMPLETED,
+ ),
+ ],
+ )
+
+ async def test_stale_response_done_does_not_run_pending_tools(
+ self,
+ ) -> None:
+ """A completion queued behind barge-in cannot start its tools."""
+ model = QueueSessionModel()
+ agent = RealtimeAgent(
+ "Friday",
+ "be brief",
+ model,
+ toolkit=Toolkit(tools=[StreamTool()]),
+ )
+ (
+ events,
+ state_while_clearing,
+ ) = await _run_terminal_event_during_barge_in(
+ agent,
+ model,
+ me.ResponseDoneEvent(
+ item_id="r1",
+ input_tokens=7,
+ output_tokens=2,
+ ),
+ ToolCallBlock(
+ id="c1",
+ name="stream_tool",
+ input='{"q": "x"}',
+ ),
+ )
+
+ terminal_events = [
+ event.model_dump(
+ mode="json",
+ exclude={"id", "created_at"},
+ )
+ for event in events
+ if isinstance(event, (TextBlockEndEvent, ReplyEndEvent))
+ ]
+ self.assertEqual(
+ {
+ "state_while_clearing": state_while_clearing,
+ "terminal_events": terminal_events,
+ "context": [
+ {
+ "id": message.id,
+ "finished_reason": message.finished_reason,
+ "content": [
+ block.model_dump(
+ mode="json",
+ exclude={"created_at", "finished_at"},
+ )
+ for block in message.content
+ ],
+ }
+ for message in agent.state.context
+ ],
+ "input_tokens": agent._metrics.input_tokens,
+ "pending_tools": sorted(agent._pending_tools),
+ "model_calls": [
+ call for call in model.calls if call != "push_audio"
+ ],
+ },
+ {
+ "state_while_clearing": {
+ "reply_open": True,
+ "reply_id": "r1",
+ "input_tokens": 0,
+ "pending_tools": ["c1"],
+ },
+ "terminal_events": [
+ {
+ "type": "TEXT_BLOCK_END",
+ "metadata": {},
+ "reply_id": "r1",
+ "block_id": AnyString(),
+ "text": None,
+ },
+ {
+ "type": "REPLY_END",
+ "metadata": {},
+ "session_id": AnyString(),
+ "reply_id": "r1",
+ "finished_reason": "interrupted",
+ "error": None,
+ },
+ ],
+ "context": [
+ {
+ "id": "r1",
+ "finished_reason": "interrupted",
+ "content": [
+ {
+ "type": "text",
+ "text": "I did not hear that.",
+ "id": AnyString(),
+ },
+ {
+ "type": "tool_call",
+ "id": "c1",
+ "name": "stream_tool",
+ "input": '{"q": "x"}',
+ "state": "pending",
+ "suggested_rules": [],
+ },
+ ],
+ },
+ ],
+ "input_tokens": 0,
+ "pending_tools": [],
+ "model_calls": [
+ "connect(session=1,td_off=False)",
+ "cancel",
+ "close",
+ ],
+ },
+ )
+
async def test_interrupt_stops_active_reply(self) -> None:
- """``interrupt()`` cuts the reply in flight to what was heard."""
+ """``interrupt()`` stops generation but preserves its text."""
model = ScriptedModel([REPLY_R1])
agent = RealtimeAgent("Friday", "be brief", model)
transport = GatedTransport([])
@@ -349,7 +749,7 @@ class RealtimeAgentTest(IsolatedAsyncioTestCase):
async with agent, transport:
async for event in agent.reply_stream(transport):
if isinstance(event, TextBlockDeltaEvent):
- if event.delta == "老和尚":
+ if event.delta == "monk.":
await agent.interrupt()
transport.gate.set()
elif isinstance(event, ReplyEndEvent):
@@ -362,7 +762,10 @@ class RealtimeAgentTest(IsolatedAsyncioTestCase):
self.assertEqual(transport.cleared, 1)
self.assertListEqual(
[(m.role, m.get_text_content()) for m in agent.state.context],
- [("user", "讲个故事"), ("assistant", "从前有座山山里有座庙")],
+ [
+ ("user", "Tell me a story"),
+ ("assistant", "Once upon a time, there was an old monk."),
+ ],
)
async def test_interrupt_frame_stops_active_reply(self) -> None:
@@ -377,7 +780,7 @@ class RealtimeAgentTest(IsolatedAsyncioTestCase):
async with agent, transport:
async for event in agent.reply_stream(transport):
if isinstance(event, TextBlockDeltaEvent):
- if event.delta == "老和尚":
+ if event.delta == "monk.":
transport.gate.set()
elif isinstance(event, ReplyEndEvent):
reply_ends.append((event.reply_id, event.finished_reason))
@@ -390,7 +793,6 @@ class RealtimeAgentTest(IsolatedAsyncioTestCase):
model.calls,
[
"connect(session=1,td_off=False)",
- "truncate(r1,320ms,'从前有座山山里有座庙')",
"cancel",
"close",
],
@@ -422,27 +824,304 @@ class RealtimeAgentTest(IsolatedAsyncioTestCase):
summary = await self._collect(agent, FakeTransport(frames=2))
self.assertEqual(model.sessions, 2)
- # The orphaned reply was dropped, so one message carried over,
- # riding along in the instructions of the new session.
+ # Reconnection starts with the context available when the previous
+ # model session ended.
self.assertIn("connect(session=2,td_off=False)", model.calls)
self.assertEqual(
model.instructions,
- "be brief\n\n## Conversation so far\nuser: 讲个故事",
+ f"{agent.system_prompt}\n\n## Conversation so far\n"
+ f"user: Tell me a story\n{agent.name}: Once ",
)
# Events produced while no run was active are delivered first;
# a reply streamed with nobody listening is cut off exactly once.
self.assertListEqual(
summary,
[
- ("user", "讲个故事"),
+ ("user", "Tell me a story"),
("reply_end", "interrupted"),
- ("user", "你好"),
+ ("user", "Hello"),
("reply_end", "completed"),
],
)
self.assertListEqual(
[(m.role, m.get_text_content()) for m in agent.state.context],
- [("user", "讲个故事"), ("user", "你好"), ("assistant", "你好呀")],
+ [
+ ("user", "Tell me a story"),
+ ("assistant", "Once "),
+ ("user", "Hello"),
+ ("assistant", "Hi there."),
+ ],
+ )
+
+ async def test_structured_history_is_replayed_on_reconnect(self) -> None:
+ """A replay-capable provider gets roles, summary, and no fallback."""
+ state = AgentState(
+ summary="Earlier summary",
+ context=[
+ UserMsg(name="user", content="hello"),
+ AssistantMsg(
+ name="Friday",
+ content="hi",
+ finished_reason=ReplyFinishedReason.COMPLETED,
+ ),
+ AssistantMsg(
+ name="Friday",
+ content="partial",
+ ),
+ AssistantMsg(
+ name="Friday",
+ content="legacy complete",
+ finished_at="2026-01-01T00:00:00",
+ ),
+ AssistantMsg(
+ name="Friday",
+ content="unfinished",
+ finished_reason=ReplyFinishedReason.INTERRUPTED,
+ ),
+ AssistantMsg(
+ name="Friday",
+ content=[
+ TextBlock(text="calling a tool"),
+ ToolCallBlock(
+ id="call-1",
+ name="lookup",
+ input="{}",
+ ),
+ ],
+ finished_reason=ReplyFinishedReason.INTERRUPTED,
+ ),
+ ],
+ )
+ model = HistoryScriptedModel(
+ [
+ [me.SessionEndedEvent(reason="idle")],
+ [],
+ ],
+ )
+ agent = RealtimeAgent("Friday", "be brief", model, state=state)
+
+ async with agent:
+ await asyncio.sleep(0.1)
+ disconnected_before_reconnect = not agent._connected
+ await self._collect(agent, FakeTransport(frames=1))
+
+ replayed = [
+ [
+ (
+ message.role,
+ message.name,
+ message.get_text_content(),
+ message.model_dump(mode="json")["finished_reason"],
+ )
+ for message in replay
+ ]
+ for replay in model.replayed
+ ]
+ expected_replay = [
+ ("system", "summary", "Earlier summary", None),
+ ("user", "user", "hello", None),
+ ("assistant", "Friday", "hi", "completed"),
+ ("assistant", "Friday", "partial", None),
+ ("assistant", "Friday", "legacy complete", None),
+ ("assistant", "Friday", "unfinished", "interrupted"),
+ ("assistant", "Friday", "calling a tool", "interrupted"),
+ ]
+ self.assertEqual(
+ {
+ "disconnected_before_reconnect": (
+ disconnected_before_reconnect
+ ),
+ "instructions": model.instructions,
+ "sessions": model.sessions,
+ "calls": model.calls,
+ "replayed": replayed,
+ },
+ {
+ "disconnected_before_reconnect": True,
+ "instructions": "be brief",
+ "sessions": 2,
+ "calls": [
+ "connect(session=1,td_off=False)",
+ "replay_history",
+ "connect(session=2,td_off=False)",
+ "replay_history",
+ "push_audio",
+ "close",
+ ],
+ "replayed": [expected_replay, expected_replay],
+ },
+ )
+
+ async def test_completed_chat_reply_is_replayed_in_realtime(self) -> None:
+ """Switching modes preserves the complete preceding chat turn."""
+ story = (
+ "A small cat waited by the window every day for its friend "
+ "to return."
+ )
+ chat_model = MockModel()
+ chat_model.set_responses(
+ [
+ ChatResponse(
+ content=[TextBlock(text=story)],
+ is_last=True,
+ ),
+ ],
+ )
+ chat_agent = Agent(
+ name="Friday",
+ system_prompt="be brief",
+ model=chat_model,
+ injection_config=InjectionConfig(inject_runtime_state=False),
+ )
+ await chat_agent.reply(
+ UserMsg(name="user", content="Tell me a short story"),
+ )
+
+ realtime_model = HistoryScriptedModel([[]])
+ realtime_agent = RealtimeAgent(
+ "Friday",
+ "be brief",
+ realtime_model,
+ state=chat_agent.state,
+ )
+ async with realtime_agent:
+ replayed = [
+ message.model_dump(mode="json")
+ for message in realtime_model.replayed[0]
+ ]
+
+ fallback_model = ScriptedModel([[]])
+ fallback_agent = RealtimeAgent(
+ "Friday",
+ "be brief",
+ fallback_model,
+ state=chat_agent.state,
+ )
+ async with fallback_agent:
+ instructions = fallback_model.instructions
+
+ self.assertDictEqual(
+ {
+ "replayed": replayed,
+ "fallback_instructions": instructions,
+ },
+ {
+ "replayed": [
+ message.model_dump(mode="json")
+ for message in chat_agent.state.context
+ ],
+ "fallback_instructions": (
+ "be brief\n\n## Conversation so far\n"
+ "user: Tell me a short story\n"
+ f"Friday: {story}"
+ ),
+ },
+ )
+
+ async def test_history_fallback_keeps_only_recent_whole_messages(
+ self,
+ ) -> None:
+ """Text fallback drops old messages instead of slicing one in half."""
+ old_text = "o" * 20_000
+ recent_text = "n" * 20_000
+ model = ScriptedModel([[]])
+ agent = RealtimeAgent(
+ "Friday",
+ "be brief",
+ model,
+ state=AgentState(
+ context=[
+ UserMsg(name="old", content=old_text),
+ UserMsg(name="recent", content=recent_text),
+ ],
+ ),
+ )
+ async with agent:
+ instructions = model.instructions
+
+ fallback = instructions.removeprefix(
+ "be brief\n\n## Conversation so far\n",
+ )
+
+ self.assertDictEqual(
+ {
+ "fallback": fallback,
+ "contains_old_message": old_text in fallback,
+ "length": len(fallback),
+ },
+ {
+ "fallback": f"recent: {recent_text}",
+ "contains_old_message": False,
+ "length": len("recent: ") + len(recent_text),
+ },
+ )
+
+ async def test_old_downlink_cannot_disconnect_new_session(self) -> None:
+ """Late completion of an old iterator leaves reconnection active."""
+ model = QueueSessionModel()
+ agent = RealtimeAgent("Friday", "be brief", model)
+
+ async with agent:
+ await model.iterator_started[0].wait()
+ old_queue = model.event_queues[0]
+ old_queue.put_nowait(me.SpeechStartedEvent(item_id="u1"))
+ old_queue.put_nowait(me.ResponseCreatedEvent(item_id="r1"))
+ old_queue.put_nowait(
+ me.TranscriptDeltaEvent(item_id="r1", delta="partial"),
+ )
+ while agent._reply is None: # pylint: disable=W0212
+ await asyncio.sleep(0)
+ agent._mark_disconnected() # pylint: disable=protected-access
+ await agent.connect()
+ old_queue.put_nowait(None)
+ await model.iterator_finished[0].wait()
+ await model.iterator_started[1].wait()
+
+ active_state = {
+ "connected": agent._connected, # pylint: disable=W0212
+ "connection_generation": agent._connection_generation,
+ "sessions": model.sessions,
+ "reply_open": agent._reply is not None,
+ "user_turn_open": agent._user_turn_open,
+ "iterator_started": [
+ event.is_set() for event in model.iterator_started
+ ],
+ "iterator_finished": [
+ event.is_set() for event in model.iterator_finished
+ ],
+ }
+
+ self.assertDictEqual(
+ {
+ "active": active_state,
+ "closed": {
+ "connected": agent._connected,
+ "iterator_finished": [
+ event.is_set() for event in model.iterator_finished
+ ],
+ "calls": model.calls,
+ },
+ },
+ {
+ "active": {
+ "connected": True,
+ "connection_generation": 2,
+ "sessions": 2,
+ "reply_open": False,
+ "user_turn_open": False,
+ "iterator_started": [True, True],
+ "iterator_finished": [True, False],
+ },
+ "closed": {
+ "connected": False,
+ "iterator_finished": [True, True],
+ "calls": [
+ "connect(session=1,td_off=False)",
+ "connect(session=2,td_off=False)",
+ "close",
+ ],
+ },
+ },
)
async def test_provider_timeout_reconnects_on_text(self) -> None:
@@ -579,7 +1258,7 @@ class RealtimeAgentTest(IsolatedAsyncioTestCase):
self.assertListEqual(
summary,
- [("user", "讲个故事"), ("reply_end", "interrupted")],
+ [("user", "Tell me a story"), ("reply_end", "interrupted")],
)
self.assertIn("cancel", model.calls)
@@ -592,13 +1271,13 @@ class RealtimeAgentTest(IsolatedAsyncioTestCase):
async def test_backchannel_is_dropped(self) -> None:
"""A bare acknowledgement never becomes a turn."""
model = ScriptedModel(
- [[me.InputTranscriptionEvent(item_id="u1", text="嗯。")]],
+ [[me.InputTranscriptionEvent(item_id="u1", text="okay.")]],
)
agent = RealtimeAgent(
"Friday",
"be brief",
model,
- aggregator=TurnAggregator(backchannels=frozenset({"嗯"})),
+ aggregator=TurnAggregator(backchannels=frozenset({"okay"})),
)
async with agent:
summary = await self._collect(agent, FakeTransport(frames=1))
@@ -607,6 +1286,141 @@ class RealtimeAgentTest(IsolatedAsyncioTestCase):
self.assertListEqual(agent.state.context, [])
+class RealtimeAgentTranscriptionTest(IsolatedAsyncioTestCase):
+ """Verify user reply boundaries around delayed transcription."""
+
+ async def test_user_reply_ends_after_transcription_result(self) -> None:
+ """Success and failure both close their delayed user replies."""
+ model = ScriptedModel(
+ [
+ [
+ me.SpeechStartedEvent(item_id="u1"),
+ me.SpeechEndedEvent(item_id="u1"),
+ me.ResponseCreatedEvent(item_id="r1"),
+ me.InputTranscriptionEvent(item_id="u1", text="hello"),
+ me.ResponseDoneEvent(item_id="r1"),
+ me.SpeechStartedEvent(item_id="u2"),
+ me.SpeechEndedEvent(item_id="u2"),
+ me.InputTranscriptionFailedEvent(item_id="u2"),
+ ],
+ ],
+ input_audio_transcription=True,
+ )
+ agent = RealtimeAgent("Friday", "be brief", model)
+ user_events = []
+
+ async with agent:
+ transport = FakeTransport(frames=3)
+ async with transport:
+ async for event in agent.reply_stream(transport):
+ if getattr(event, "role", None) == "user" or getattr(
+ event,
+ "reply_id",
+ None,
+ ) in {"u1", "u2"}:
+ user_events.append(
+ (
+ event.type,
+ getattr(event, "role", None),
+ getattr(event, "delta", None),
+ getattr(event, "finished_reason", None),
+ ),
+ )
+
+ self.assertEqual(
+ {
+ "events": user_events,
+ "context": [
+ (message.role, message.get_text_content())
+ for message in agent.state.context
+ ],
+ },
+ {
+ "events": [
+ ("REPLY_START", "user", None, None),
+ ("TEXT_BLOCK_START", None, None, None),
+ ("TEXT_BLOCK_DELTA", None, "hello", None),
+ ("TEXT_BLOCK_END", None, None, None),
+ ("REPLY_END", None, None, "completed"),
+ ("REPLY_START", "user", None, None),
+ ("REPLY_END", None, None, "completed"),
+ ],
+ "context": [("user", "hello")],
+ },
+ )
+
+
+class RealtimeAgentLifecycleTest(IsolatedAsyncioTestCase):
+ """Verify interruption and terminal events are synchronized."""
+
+ async def test_model_error_waits_for_barge_in_reconciliation(self) -> None:
+ """A terminal error waits for an in-progress interruption."""
+ model = QueueSessionModel()
+ agent = RealtimeAgent("Friday", "be brief", model)
+ (
+ events,
+ state_while_clearing,
+ ) = await _run_terminal_event_during_barge_in(
+ agent,
+ model,
+ me.ModelErrorEvent(code="provider_error", message="failed"),
+ )
+
+ self.assertEqual(
+ {
+ "state_while_clearing": state_while_clearing,
+ "terminal_events": [
+ (
+ event.type,
+ event.text
+ if isinstance(event, TextBlockEndEvent)
+ else event.finished_reason,
+ )
+ for event in events
+ if isinstance(event, (TextBlockEndEvent, ReplyEndEvent))
+ ],
+ "context": [
+ _message_summary(message)
+ for message in agent.state.context
+ ],
+ "model_calls": [
+ call for call in model.calls if call != "push_audio"
+ ],
+ },
+ {
+ "state_while_clearing": {
+ "reply_open": True,
+ "reply_id": "r1",
+ "input_tokens": 0,
+ "pending_tools": [],
+ },
+ "terminal_events": [
+ ("TEXT_BLOCK_END", None),
+ ("REPLY_END", ReplyFinishedReason.INTERRUPTED),
+ ],
+ "context": [
+ {
+ "role": "assistant",
+ "id": "r1",
+ "content": [
+ {
+ "type": "text",
+ "text": "I did not hear that.",
+ },
+ ],
+ "usage": None,
+ "finished_reason": "interrupted",
+ },
+ ],
+ "model_calls": [
+ "connect(session=1,td_off=False)",
+ "cancel",
+ "close",
+ ],
+ },
+ )
+
+
class StreamTool(ToolBase):
"""Streams two chunks, then the completed result."""
@@ -641,6 +1455,19 @@ class StreamTool(ToolBase):
yield ToolResponse(content=[TextBlock(text=f"{q}-final")])
+class BlockingTool(StreamTool):
+ """Wait until the test releases a tool already in progress."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.release = asyncio.Event()
+
+ async def __call__(self, q: str, **kwargs: Any) -> Any:
+ """Hold the tool result until a barge-in has completed."""
+ await self.release.wait()
+ yield ToolResponse(content=[TextBlock(text=f"{q}-final")])
+
+
class AskTool(StreamTool):
"""Requires user confirmation before running. Not read-only, or the
permission engine's read-only fast path would allow it unasked."""
@@ -691,7 +1518,7 @@ class RealtimeAgentToolTest(IsolatedAsyncioTestCase):
self,
tool: ToolBase,
confirm: bool | None = None,
- ) -> tuple[list[tuple[str, Any]], ScriptedModel]:
+ ) -> tuple[list[tuple[Any, ...]], ScriptedModel]:
"""Run one tool-calling reply; answer a permission prompt with
*confirm* if one appears. Returns the tool-related events."""
model = ScriptedModel([_tool_script(tool.name)])
@@ -701,7 +1528,18 @@ class RealtimeAgentToolTest(IsolatedAsyncioTestCase):
model,
toolkit=Toolkit(tools=[tool]),
)
- events: list[tuple[str, Any]] = []
+
+ def _checkpoint_tool_state(event: Any) -> str:
+ checkpoint = agent.checkpoint_snapshot(event)
+ if checkpoint is None:
+ self.fail("The tool lifecycle event has no checkpoint.")
+ tool_calls = checkpoint.context[-1].get_content_blocks(
+ "tool_call",
+ )
+ self.assertEqual([call.id for call in tool_calls], ["c1"])
+ return str(tool_calls[0].state)
+
+ events: list[tuple[Any, ...]] = []
async with agent:
transport = FakeTransport(frames=4)
async with transport:
@@ -713,7 +1551,11 @@ class RealtimeAgentToolTest(IsolatedAsyncioTestCase):
events.append(("call_end", event.tool_call_id))
case RequireUserConfirmEvent():
events.append(
- ("ask", [c.name for c in event.tool_calls]),
+ (
+ "ask",
+ [c.name for c in event.tool_calls],
+ _checkpoint_tool_state(event),
+ ),
)
await agent.send(
UserConfirmResultEvent(
@@ -733,7 +1575,13 @@ class RealtimeAgentToolTest(IsolatedAsyncioTestCase):
case ToolResultTextDeltaEvent():
events.append(("delta", event.delta))
case ToolResultEndEvent():
- events.append(("result_end", event.state))
+ events.append(
+ (
+ "result_end",
+ event.state,
+ _checkpoint_tool_state(event),
+ ),
+ )
return events, model
async def test_streamed_tool_result_is_not_duplicated(self) -> None:
@@ -749,7 +1597,7 @@ class RealtimeAgentToolTest(IsolatedAsyncioTestCase):
("result_start", "stream_tool"),
("delta", "x-a"),
("delta", "x-b"),
- ("result_end", "success"),
+ ("result_end", "success", "finished"),
],
)
self.assertListEqual(
@@ -771,11 +1619,11 @@ class RealtimeAgentToolTest(IsolatedAsyncioTestCase):
[
("call_start", "ask_tool"),
("call_end", "c1"),
- ("ask", ["ask_tool"]),
+ ("ask", ["ask_tool"], "asking"),
("result_start", "ask_tool"),
("delta", "x-a"),
("delta", "x-b"),
- ("result_end", "success"),
+ ("result_end", "success", "finished"),
],
)
self.assertIn("tool_result(c1,'x-final')", model.calls)
@@ -789,10 +1637,10 @@ class RealtimeAgentToolTest(IsolatedAsyncioTestCase):
[
("call_start", "ask_tool"),
("call_end", "c1"),
- ("ask", ["ask_tool"]),
+ ("ask", ["ask_tool"], "asking"),
("result_start", "ask_tool"),
("delta", 'Tool "ask_tool" denied by user.'),
- ("result_end", "denied"),
+ ("result_end", "denied", "finished"),
],
)
self.assertIn(
@@ -812,7 +1660,7 @@ class RealtimeAgentToolTest(IsolatedAsyncioTestCase):
("call_end", "c1"),
("result_start", "broken_tool"),
("delta", "boom"),
- ("result_end", "error"),
+ ("result_end", "error", "finished"),
],
)
self.assertIn("tool_result(c1,'boom')", model.calls)
@@ -881,9 +1729,15 @@ class RealtimeAgentFullStreamTest(IsolatedAsyncioTestCase):
[
[
me.SpeechEndedEvent(item_id="u1"),
- me.InputTranscriptionEvent(item_id="u1", text="查天气"),
+ me.InputTranscriptionEvent(
+ item_id="u1",
+ text="What is the weather?",
+ ),
me.ResponseCreatedEvent(item_id="r1"),
- me.TranscriptDeltaEvent(item_id="r1", delta="我查一下"),
+ me.TranscriptDeltaEvent(
+ item_id="r1",
+ delta="Let me check.",
+ ),
me.AudioDeltaEvent(
item_id="r1",
pcm=b"\x01\x00",
@@ -904,7 +1758,10 @@ class RealtimeAgentFullStreamTest(IsolatedAsyncioTestCase):
),
"WAIT",
me.ResponseCreatedEvent(item_id="r2"),
- me.TranscriptDeltaEvent(item_id="r2", delta="今天晴"),
+ me.TranscriptDeltaEvent(
+ item_id="r2",
+ delta="It is sunny.",
+ ),
me.AudioDeltaEvent(
item_id="r2",
pcm=b"\x01\x00",
@@ -929,370 +1786,136 @@ class RealtimeAgentFullStreamTest(IsolatedAsyncioTestCase):
transport = FakeTransport(frames=6)
async with transport:
async for event in agent.reply_stream(transport):
- events.append(event.model_dump(mode="json"))
+ events.append(
+ (
+ event.type,
+ getattr(event, "reply_id", None),
+ getattr(event, "role", None),
+ getattr(event, "delta", None),
+ getattr(event, "tool_call_id", None),
+ getattr(event, "finished_reason", None),
+ ),
+ )
self.assertListEqual(
events,
[
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "REPLY_START",
- "session_id": AnyString(),
- "reply_id": "u1",
- "name": "user",
- "role": "user",
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "TEXT_BLOCK_START",
- "reply_id": "u1",
- "block_id": AnyString(),
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "TEXT_BLOCK_DELTA",
- "reply_id": "u1",
- "block_id": AnyString(),
- "delta": "查天气",
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "TEXT_BLOCK_END",
- "reply_id": "u1",
- "block_id": AnyString(),
- "text": None,
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "REPLY_END",
- "session_id": AnyString(),
- "reply_id": "u1",
- "finished_reason": "completed",
- "error": None,
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "REPLY_START",
- "session_id": AnyString(),
- "reply_id": "r1",
- "name": "Friday",
- "role": "assistant",
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "MODEL_CALL_START",
- "reply_id": "r1",
- "model_name": "scripted",
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "TEXT_BLOCK_START",
- "reply_id": "r1",
- "block_id": AnyString(),
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "TEXT_BLOCK_DELTA",
- "reply_id": "r1",
- "block_id": AnyString(),
- "delta": "我查一下",
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "DATA_BLOCK_START",
- "reply_id": "r1",
- "block_id": AnyString(),
- "media_type": "audio/pcm;rate=24000",
- "name": None,
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "DATA_BLOCK_DELTA",
- "reply_id": "r1",
- "block_id": AnyString(),
- "media_type": "audio/pcm;rate=24000",
- "data": "AQA=",
- "url": None,
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "TEXT_BLOCK_END",
- "reply_id": "r1",
- "block_id": AnyString(),
- "text": None,
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "DATA_BLOCK_END",
- "reply_id": "r1",
- "block_id": AnyString(),
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "MODEL_CALL_END",
- "reply_id": "r1",
- "input_tokens": 5,
- "output_tokens": 2,
- "cache_input_tokens": 0,
- "cache_creation_input_tokens": 0,
- "finished_reason": "completed",
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "TOOL_CALL_START",
- "reply_id": "r1",
- "tool_call_id": "c1",
- "tool_call_name": "stream_tool",
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "TOOL_CALL_DELTA",
- "reply_id": "r1",
- "tool_call_id": "c1",
- "delta": '{"q": "x"}',
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "TOOL_CALL_END",
- "reply_id": "r1",
- "tool_call_id": "c1",
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "TOOL_RESULT_START",
- "reply_id": "r1",
- "tool_call_id": "c1",
- "tool_call_name": "stream_tool",
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "TOOL_RESULT_TEXT_DELTA",
- "reply_id": "r1",
- "tool_call_id": "c1",
- "delta": "x-a",
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "TOOL_RESULT_TEXT_DELTA",
- "reply_id": "r1",
- "tool_call_id": "c1",
- "delta": "x-b",
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "TOOL_RESULT_END",
- "reply_id": "r1",
- "tool_call_id": "c1",
- "state": "success",
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "MODEL_CALL_START",
- "reply_id": "r1",
- "model_name": "scripted",
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "TEXT_BLOCK_START",
- "reply_id": "r1",
- "block_id": AnyString(),
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "TEXT_BLOCK_DELTA",
- "reply_id": "r1",
- "block_id": AnyString(),
- "delta": "今天晴",
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "DATA_BLOCK_START",
- "reply_id": "r1",
- "block_id": AnyString(),
- "media_type": "audio/pcm;rate=24000",
- "name": None,
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "DATA_BLOCK_DELTA",
- "reply_id": "r1",
- "block_id": AnyString(),
- "media_type": "audio/pcm;rate=24000",
- "data": "AQA=",
- "url": None,
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "TEXT_BLOCK_END",
- "reply_id": "r1",
- "block_id": AnyString(),
- "text": None,
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "DATA_BLOCK_END",
- "reply_id": "r1",
- "block_id": AnyString(),
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "MODEL_CALL_END",
- "reply_id": "r1",
- "input_tokens": 9,
- "output_tokens": 3,
- "cache_input_tokens": 0,
- "cache_creation_input_tokens": 0,
- "finished_reason": "completed",
- },
- {
- "id": AnyString(),
- "created_at": AnyString(),
- "metadata": {},
- "type": "REPLY_END",
- "session_id": AnyString(),
- "reply_id": "r1",
- "finished_reason": "completed",
- "error": None,
- },
+ ("REPLY_START", "u1", "user", None, None, None),
+ ("TEXT_BLOCK_START", "u1", None, None, None, None),
+ (
+ "TEXT_BLOCK_DELTA",
+ "u1",
+ None,
+ "What is the weather?",
+ None,
+ None,
+ ),
+ ("TEXT_BLOCK_END", "u1", None, None, None, None),
+ ("REPLY_END", "u1", None, None, None, "completed"),
+ ("REPLY_START", "r1", "assistant", None, None, None),
+ ("MODEL_CALL_START", "r1", None, None, None, None),
+ ("TEXT_BLOCK_START", "r1", None, None, None, None),
+ (
+ "TEXT_BLOCK_DELTA",
+ "r1",
+ None,
+ "Let me check.",
+ None,
+ None,
+ ),
+ ("DATA_BLOCK_START", "r1", None, None, None, None),
+ ("DATA_BLOCK_DELTA", "r1", None, None, None, None),
+ ("TEXT_BLOCK_END", "r1", None, None, None, None),
+ ("DATA_BLOCK_END", "r1", None, None, None, None),
+ ("MODEL_CALL_END", "r1", None, None, None, "completed"),
+ ("TOOL_CALL_START", "r1", None, None, "c1", None),
+ (
+ "TOOL_CALL_DELTA",
+ "r1",
+ None,
+ '{"q": "x"}',
+ "c1",
+ None,
+ ),
+ ("TOOL_CALL_END", "r1", None, None, "c1", None),
+ ("TOOL_RESULT_START", "r1", None, None, "c1", None),
+ (
+ "TOOL_RESULT_TEXT_DELTA",
+ "r1",
+ None,
+ "x-a",
+ "c1",
+ None,
+ ),
+ (
+ "TOOL_RESULT_TEXT_DELTA",
+ "r1",
+ None,
+ "x-b",
+ "c1",
+ None,
+ ),
+ ("TOOL_RESULT_END", "r1", None, None, "c1", None),
+ ("MODEL_CALL_START", "r1", None, None, None, None),
+ ("TEXT_BLOCK_START", "r1", None, None, None, None),
+ (
+ "TEXT_BLOCK_DELTA",
+ "r1",
+ None,
+ "It is sunny.",
+ None,
+ None,
+ ),
+ ("DATA_BLOCK_START", "r1", None, None, None, None),
+ ("DATA_BLOCK_DELTA", "r1", None, None, None, None),
+ ("TEXT_BLOCK_END", "r1", None, None, None, None),
+ ("DATA_BLOCK_END", "r1", None, None, None, None),
+ ("MODEL_CALL_END", "r1", None, None, None, "completed"),
+ ("REPLY_END", "r1", None, None, None, "completed"),
],
)
# The context records the whole turn as one assistant message: the
# first words, the tool call and its result, then the spoken answer.
- self.assertListEqual(
- [m.model_dump() for m in agent.state.context],
+ self.assertEqual(
+ [_message_summary(message) for message in agent.state.context],
[
{
- "name": "user",
"role": "user",
"id": "u1",
"content": [
- {
- "type": "text",
- "text": "查天气",
- "id": AnyString(),
- "created_at": AnyString(),
- "finished_at": None,
- },
+ {"type": "text", "text": "What is the weather?"},
],
- "metadata": {},
- "created_at": AnyString(),
"usage": None,
- "finished_at": AnyString(),
"finished_reason": None,
- "structured_output": None,
- "error": None,
},
{
- "name": "Friday",
"role": "assistant",
"id": "r1",
"content": [
- {
- "type": "text",
- "text": "我查一下",
- "id": AnyString(),
- "created_at": AnyString(),
- "finished_at": None,
- },
+ {"type": "text", "text": "Let me check."},
{
"type": "tool_call",
- "id": "c1",
"name": "stream_tool",
"input": '{"q": "x"}',
- "state": "pending",
- "suggested_rules": [],
- "created_at": AnyString(),
- "finished_at": None,
+ "state": "finished",
+ "id": "c1",
},
{
"type": "tool_result",
- "id": "c1",
"name": "stream_tool",
"output": "x-final",
"state": "success",
- "metadata": {},
- "created_at": AnyString(),
- "finished_at": None,
- },
- {
- "type": "text",
- "text": "今天晴",
- "id": AnyString(),
- "created_at": AnyString(),
- "finished_at": None,
+ "id": "c1",
},
+ {"type": "text", "text": "It is sunny."},
],
- "metadata": {},
- "created_at": AnyString(),
- # Both model calls of the reply, summed.
"usage": {
"input_tokens": 14,
"output_tokens": 5,
"cache_input_tokens": 0,
"cache_creation_input_tokens": 0,
},
- "finished_at": None,
- "finished_reason": None,
- "structured_output": None,
- "error": None,
+ "finished_reason": "completed",
},
],
)
@@ -1306,6 +1929,296 @@ class RealtimeAgentFullStreamTest(IsolatedAsyncioTestCase):
],
)
+ async def test_barge_in_during_followup_keeps_generated_text(
+ self,
+ ) -> None:
+ """Barge-in keeps text from every response in the reply."""
+ model = ScriptedModel(
+ [
+ [
+ me.SpeechEndedEvent(item_id="u1"),
+ me.InputTranscriptionEvent(
+ item_id="u1",
+ text="What is the weather?",
+ ),
+ me.ResponseCreatedEvent(item_id="r1"),
+ me.TranscriptDeltaEvent(
+ item_id="r1",
+ delta="Let me check.",
+ ),
+ me.AudioDeltaEvent(
+ item_id="r1",
+ pcm=PCM_100MS,
+ sample_rate=24000,
+ ),
+ me.ToolCallEvent(
+ item_id="r1",
+ tool_call=ToolCallBlock(
+ id="c1",
+ name="stream_tool",
+ input='{"q": "x"}',
+ ),
+ ),
+ me.ResponseDoneEvent(item_id="r1"),
+ "WAIT",
+ me.ResponseCreatedEvent(item_id="r2"),
+ me.TranscriptDeltaEvent(
+ item_id="r2",
+ delta="It is sunny.",
+ ),
+ me.AudioDeltaEvent(
+ item_id="r2",
+ pcm=PCM_100MS,
+ sample_rate=24000,
+ ),
+ ],
+ ],
+ )
+ agent = RealtimeAgent(
+ "Friday",
+ "be brief",
+ model,
+ toolkit=Toolkit(tools=[StreamTool()]),
+ )
+ audio_deltas = 0
+ async with agent:
+ transport = FakeTransport(frames=10)
+ async with transport:
+ async for event in agent.reply_stream(transport):
+ if isinstance(event, DataBlockDeltaEvent):
+ audio_deltas += 1
+ if audio_deltas == 2:
+ await agent.interrupt()
+
+ assistant = [
+ message
+ for message in agent.state.context
+ if message.role == "assistant"
+ ][-1]
+ self.assertEqual(
+ _message_summary(assistant),
+ {
+ "role": "assistant",
+ "id": "r1",
+ "content": [
+ {"type": "text", "text": "Let me check."},
+ {
+ "type": "tool_call",
+ "name": "stream_tool",
+ "input": '{"q": "x"}',
+ "state": "finished",
+ "id": "c1",
+ },
+ {
+ "type": "tool_result",
+ "name": "stream_tool",
+ "output": "x-final",
+ "state": "success",
+ "id": "c1",
+ },
+ {"type": "text", "text": "It is sunny."},
+ ],
+ "usage": {
+ "input_tokens": 0,
+ "output_tokens": 0,
+ "cache_input_tokens": 0,
+ "cache_creation_input_tokens": 0,
+ },
+ "finished_reason": "interrupted",
+ },
+ )
+ self.assertListEqual(
+ [call for call in model.calls if call != "push_audio"],
+ [
+ "connect(session=1,td_off=False)",
+ "tool_result(c1,'x-final')",
+ "request_response",
+ "cancel",
+ "close",
+ ],
+ )
+
+ async def test_barge_in_after_completed_followup_keeps_reply(
+ self,
+ ) -> None:
+ """Stopping queued audio does not alter a completed reply."""
+ model = ScriptedModel(
+ [
+ [
+ me.ResponseCreatedEvent(item_id="r1"),
+ me.TranscriptDeltaEvent(
+ item_id="r1",
+ delta="Let me check.",
+ ),
+ me.AudioDeltaEvent(
+ item_id="r1",
+ pcm=PCM_100MS,
+ sample_rate=24000,
+ ),
+ me.ToolCallEvent(
+ item_id="r1",
+ tool_call=ToolCallBlock(
+ id="c1",
+ name="stream_tool",
+ input='{"q": "x"}',
+ ),
+ ),
+ me.ResponseDoneEvent(item_id="r1"),
+ "WAIT",
+ me.ResponseCreatedEvent(item_id="r2"),
+ me.TranscriptDeltaEvent(
+ item_id="r2",
+ delta="It is sunny.",
+ ),
+ me.AudioDeltaEvent(
+ item_id="r2",
+ pcm=PCM_100MS,
+ sample_rate=24000,
+ ),
+ me.ResponseDoneEvent(item_id="r2"),
+ me.SpeechStartedEvent(item_id="u2"),
+ ],
+ ],
+ )
+ agent = RealtimeAgent(
+ "Friday",
+ "be brief",
+ model,
+ toolkit=Toolkit(tools=[StreamTool()]),
+ )
+ transport = FakeTransport(frames=10)
+
+ async with agent, transport:
+ async for _ in agent.reply_stream(transport):
+ pass
+
+ self.assertEqual(
+ [_message_summary(message) for message in agent.state.context],
+ [
+ {
+ "role": "assistant",
+ "id": "r1",
+ "content": [
+ {"type": "text", "text": "Let me check."},
+ {
+ "type": "tool_call",
+ "name": "stream_tool",
+ "input": '{"q": "x"}',
+ "state": "finished",
+ "id": "c1",
+ },
+ {
+ "type": "tool_result",
+ "name": "stream_tool",
+ "output": "x-final",
+ "state": "success",
+ "id": "c1",
+ },
+ {"type": "text", "text": "It is sunny."},
+ ],
+ "usage": {
+ "input_tokens": 0,
+ "output_tokens": 0,
+ "cache_input_tokens": 0,
+ "cache_creation_input_tokens": 0,
+ },
+ "finished_reason": "completed",
+ },
+ ],
+ )
+ self.assertListEqual(
+ [call for call in model.calls if call != "push_audio"],
+ [
+ "connect(session=1,td_off=False)",
+ "tool_result(c1,'x-final')",
+ "request_response",
+ "close",
+ ],
+ )
+
+ async def test_barge_in_while_tool_runs_clears_first_audio(self) -> None:
+ """A reply waiting on a tool still clears its queued audio."""
+ tool = BlockingTool()
+ model = ScriptedModel(
+ [
+ [
+ me.ResponseCreatedEvent(item_id="r1"),
+ me.TranscriptDeltaEvent(
+ item_id="r1",
+ delta="Let me check.",
+ ),
+ me.AudioDeltaEvent(
+ item_id="r1",
+ pcm=PCM_100MS,
+ sample_rate=24000,
+ ),
+ me.ToolCallEvent(
+ item_id="r1",
+ tool_call=ToolCallBlock(
+ id="c1",
+ name="stream_tool",
+ input='{"q": "x"}',
+ ),
+ ),
+ me.ResponseDoneEvent(item_id="r1"),
+ ],
+ ],
+ )
+ agent = RealtimeAgent(
+ "Friday",
+ "be brief",
+ model,
+ toolkit=Toolkit(tools=[tool]),
+ )
+ transport = FakeTransport(frames=10)
+
+ async with agent, transport:
+ async for event in agent.reply_stream(transport):
+ if isinstance(event, ToolResultStartEvent):
+ await agent.interrupt()
+ tool.release.set()
+
+ self.assertEqual(transport.cleared, 1)
+ self.assertNotIn("truncate", " ".join(model.calls))
+ assistant_messages = [
+ _message_summary(message)
+ for message in agent.state.context
+ if message.role == "assistant"
+ ]
+ self.assertEqual(
+ assistant_messages,
+ [
+ {
+ "role": "assistant",
+ "id": "r1",
+ "content": [
+ {"type": "text", "text": "Let me check."},
+ {
+ "type": "tool_call",
+ "name": "stream_tool",
+ "input": '{"q": "x"}',
+ "state": "finished",
+ "id": "c1",
+ },
+ {
+ "type": "tool_result",
+ "name": "stream_tool",
+ "output": "x-final",
+ "state": "success",
+ "id": "c1",
+ },
+ ],
+ "usage": {
+ "input_tokens": 0,
+ "output_tokens": 0,
+ "cache_input_tokens": 0,
+ "cache_creation_input_tokens": 0,
+ },
+ "finished_reason": "interrupted",
+ },
+ ],
+ )
+
class DropsSocketModel(ScriptedModel):
"""Raises on the first push after the provider closed the socket,
diff --git a/tests/realtime_dashscope_test.py b/tests/realtime_dashscope_test.py
index 29c7ed3cf..3d46d548a 100644
--- a/tests/realtime_dashscope_test.py
+++ b/tests/realtime_dashscope_test.py
@@ -2,24 +2,63 @@
"""Unit tests for the DashScope realtime adapters: cards, session config
and frame parsing. Nothing here opens a connection."""
# pylint: disable=protected-access
+import asyncio
import base64
+import json
import unittest
from unittest.async_case import IsolatedAsyncioTestCase
+from unittest.mock import AsyncMock, call, patch
from agentscope.credential import DashScopeCredential
from agentscope.realtime import (
DashScopeAudioRealtimeModel,
DashScopeRealtimeModel,
ModelDisconnectedError,
- TruncationSupport,
)
from agentscope.realtime import _events as me
+from agentscope.realtime._dashscope._model import _realtime_url
+from agentscope.message import (
+ AssistantMsg,
+ SystemMsg,
+ TextBlock,
+ ToolCallBlock,
+ ToolResultBlock,
+ UserMsg,
+)
CRED = DashScopeCredential(api_key="sk-x")
TRANSCRIPTION_DONE = "conversation.item.input_audio_transcription.completed"
AMBIENT_DELTA = "conversation.item.ambient_audio_transcription.delta"
+class _OpenSocket:
+ """Yield one setup frame, then remain open until cancelled."""
+
+ def __init__(self, first_frame: dict | None = None) -> None:
+ self.first_frame = first_frame or {"type": "session.updated"}
+ self.first_sent = False
+ self.closed = False
+ self.sent: list[str] = []
+
+ def __aiter__(self) -> "_OpenSocket":
+ return self
+
+ async def __anext__(self) -> str:
+ if not self.first_sent:
+ self.first_sent = True
+ return json.dumps(self.first_frame)
+ await asyncio.Future()
+ raise StopAsyncIteration
+
+ async def send(self, payload: str) -> None:
+ """Capture an outgoing WebSocket frame."""
+ self.sent.append(payload)
+
+ async def close(self) -> None:
+ """Record that the socket was closed."""
+ self.closed = True
+
+
class DashScopeCardsTest(unittest.TestCase):
"""Each adapter lists only its own cards, tagged with its type."""
@@ -59,7 +98,7 @@ class DashScopeCardsTest(unittest.TestCase):
)
def test_audio_cards(self) -> None:
- """The Audio adapter lists the two Audio cards."""
+ """The Audio adapter lists the three Audio cards."""
self.assertListEqual(
[
(
@@ -83,9 +122,197 @@ class DashScopeCardsTest(unittest.TestCase):
50,
300,
),
+ (
+ "qwen-audio-3.1-realtime-plus",
+ "dashscope_audio_realtime",
+ 50,
+ 300,
+ ),
],
)
+ def test_omni_cards_apply_model_specific_voice_defaults(self) -> None:
+ """Card defaults drive runtime parameters unless explicitly set."""
+ cards = {
+ card.name: card for card in DashScopeRealtimeModel.list_models()
+ }
+ self.assertDictEqual(
+ {
+ name: {
+ "schema": cards[name].parameter_schema["properties"][
+ "voice"
+ ],
+ "runtime_default": DashScopeRealtimeModel(
+ name,
+ CRED,
+ ).parameters.voice,
+ }
+ for name in cards
+ },
+ {
+ "qwen-omni-turbo-realtime": {
+ "schema": {
+ "default": "Chelsie",
+ "enum": ["Cherry", "Serena", "Ethan", "Chelsie"],
+ "title": "Voice",
+ "type": "string",
+ },
+ "runtime_default": "Chelsie",
+ },
+ "qwen3-omni-flash-realtime": {
+ "schema": {
+ "default": "Cherry",
+ "enum": ["Cherry", "Serena", "Ethan", "Chelsie"],
+ "title": "Voice",
+ "type": "string",
+ },
+ "runtime_default": "Cherry",
+ },
+ "qwen3.5-omni-flash-realtime": {
+ "schema": {
+ "default": "Tina",
+ "enum": ["Tina", "Serena", "Ethan"],
+ "title": "Voice",
+ "type": "string",
+ },
+ "runtime_default": "Tina",
+ },
+ "qwen3.5-omni-plus-realtime": {
+ "schema": {
+ "default": "Tina",
+ "enum": ["Tina", "Serena", "Ethan"],
+ "title": "Voice",
+ "type": "string",
+ },
+ "runtime_default": "Tina",
+ },
+ },
+ )
+
+ explicit = DashScopeRealtimeModel(
+ "qwen3.5-omni-flash-realtime",
+ CRED,
+ parameters=DashScopeRealtimeModel.Parameters(voice="Serena"),
+ )
+ self.assertEqual(explicit.parameters.voice, "Serena")
+
+ def test_audio_cards_apply_model_specific_voice_defaults(self) -> None:
+ """Audio cards expose and apply their complete voice schemas."""
+ cards = {
+ card.name: card
+ for card in DashScopeAudioRealtimeModel.list_models()
+ }
+ self.assertDictEqual(
+ {
+ name: {
+ "schema": cards[name].parameter_schema["properties"][
+ "voice"
+ ],
+ "runtime_default": DashScopeAudioRealtimeModel(
+ name,
+ CRED,
+ ).parameters.voice,
+ }
+ for name in cards
+ },
+ {
+ "qwen-audio-3.0-realtime-flash": {
+ "schema": {
+ "default": "longanqian",
+ "enum": [
+ "longanqian",
+ "longanlingxin",
+ "longanlingxi",
+ "longanxiaoxin",
+ "longanlufeng",
+ ],
+ "title": "Voice",
+ "type": "string",
+ },
+ "runtime_default": "longanqian",
+ },
+ "qwen-audio-3.0-realtime-plus": {
+ "schema": {
+ "default": "longanqian",
+ "enum": [
+ "longanqian",
+ "longanlingxin",
+ "longanlingxi",
+ "longanxiaoxin",
+ "longanlufeng",
+ ],
+ "title": "Voice",
+ "type": "string",
+ },
+ "runtime_default": "longanqian",
+ },
+ "qwen-audio-3.1-realtime-plus": {
+ "schema": {
+ "default": "longanqian_v3.1",
+ "enum": [
+ "longanqian",
+ "longanlingxin",
+ "longanlingxi",
+ "longanxiaoxin",
+ "longanlufeng",
+ "longanqian_v3.1",
+ "longanhuan_v3.1",
+ "longanlingxin_v3.1",
+ "longanfengyue_v3.1",
+ "xunanchuan_v3.1",
+ "beth_v3.1",
+ "betty_v3.1",
+ "cally_v3.1",
+ ],
+ "title": "Voice",
+ "type": "string",
+ },
+ "runtime_default": "longanqian_v3.1",
+ },
+ },
+ )
+
+ def test_adapter_builds_regional_realtime_urls(self) -> None:
+ """Realtime URLs preserve the configured HTTP endpoint host."""
+ self.assertListEqual(
+ [
+ _realtime_url(
+ "https://dashscope.aliyuncs.com/compatible-mode/v1",
+ "model-x",
+ ),
+ _realtime_url(
+ (
+ "https://dashscope-intl.aliyuncs.com"
+ "/compatible-mode/v1"
+ ),
+ "model-x",
+ ),
+ _realtime_url(
+ (
+ "https://llm-beijing.cn-beijing.maas.aliyuncs.com"
+ "/compatible-mode/v1"
+ ),
+ "model-x",
+ ),
+ _realtime_url(
+ "http://localhost:8080/custom/dashscope/path",
+ "model-x",
+ ),
+ ],
+ [
+ "wss://dashscope.aliyuncs.com/api-ws/v1/realtime"
+ "?model=model-x",
+ "wss://dashscope-intl.aliyuncs.com/api-ws/v1/realtime"
+ "?model=model-x",
+ "wss://llm-beijing.cn-beijing.maas.aliyuncs.com"
+ "/api-ws/v1/realtime?model=model-x",
+ "ws://localhost:8080/api-ws/v1/realtime?model=model-x",
+ ],
+ )
+
+ with self.assertRaisesRegex(ValueError, "Invalid DashScope"):
+ _realtime_url("not-a-url", "model-x")
+
def test_credential_maps_card_back_to_class(self) -> None:
"""The service-layer lookup: card.model_type -> class, no scan."""
classes = {c.type: c for c in CRED.get_realtime_model_classes()}
@@ -97,6 +324,7 @@ class DashScopeCardsTest(unittest.TestCase):
{
"qwen-audio-3.0-realtime-flash": "DashScopeAudioRealtimeModel",
"qwen-audio-3.0-realtime-plus": "DashScopeAudioRealtimeModel",
+ "qwen-audio-3.1-realtime-plus": "DashScopeAudioRealtimeModel",
"qwen-omni-turbo-realtime": "DashScopeRealtimeModel",
"qwen3-omni-flash-realtime": "DashScopeRealtimeModel",
"qwen3.5-omni-flash-realtime": "DashScopeRealtimeModel",
@@ -123,7 +351,7 @@ class DashScopeSessionUpdateTest(unittest.TestCase):
"session": {
"instructions": "be nice",
"modalities": ["audio", "text"],
- "voice": "Cherry",
+ "voice": "Tina",
"input_audio_format": "pcm16",
"output_audio_format": "pcm24",
"turn_detection": {
@@ -196,12 +424,18 @@ class DashScopeSessionUpdateTest(unittest.TestCase):
)
self.assertListEqual(
[
- (omni.truncation, omni.supports_text_input),
- (audio.truncation, audio.supports_text_input),
+ (
+ omni.supports_text_input,
+ omni.supports_history_replay,
+ ),
+ (
+ audio.supports_text_input,
+ audio.supports_history_replay,
+ ),
],
[
- (TruncationSupport.NONE, False),
- (TruncationSupport.NONE, True),
+ (False, False),
+ (True, True),
],
)
@@ -314,6 +548,10 @@ class DashScopeParseTest(unittest.TestCase):
"item_id": "u1",
"transcript": "天气",
},
+ {
+ "type": "conversation.item.input_audio_transcription.failed",
+ "item_id": "u2",
+ },
{
"type": "response.done",
"response": {
@@ -334,6 +572,7 @@ class DashScopeParseTest(unittest.TestCase):
),
me.SpeechStartedEvent(item_id="u1", at_ms=120),
me.InputTranscriptionEvent(item_id="u1", text="天气"),
+ me.InputTranscriptionFailedEvent(item_id="u2"),
me.ResponseDoneEvent(
item_id="r1",
input_tokens=10,
@@ -451,10 +690,175 @@ class DashScopeAudioTextInputTest(IsolatedAsyncioTestCase):
],
)
+ async def test_history_replay_preserves_roles_and_tool_order(self) -> None:
+ """History items are inserted silently and incomplete tools drop."""
+ model = DashScopeAudioRealtimeModel(
+ "qwen-audio-3.0-realtime-plus",
+ CRED,
+ )
+ sent: list[dict] = []
+
+ async def capture(payload: dict) -> None:
+ sent.append(payload)
+
+ model._send = capture # type: ignore[method-assign]
+ model._session_ready.set()
+ await model.replay_history(
+ [
+ SystemMsg(name="summary", content="Earlier summary"),
+ UserMsg(name="user", content="Weather?"),
+ AssistantMsg(
+ name="assistant",
+ content=[
+ TextBlock(text="Let me check."),
+ ToolCallBlock(
+ id="call-1",
+ name="weather",
+ input='{"city":"Shanghai"}',
+ ),
+ ToolResultBlock(
+ id="call-1",
+ name="weather",
+ output="sunny",
+ state="success",
+ ),
+ TextBlock(text="It is sunny."),
+ ToolCallBlock(
+ id="call-unfinished",
+ name="other",
+ input="{}",
+ ),
+ ],
+ ),
+ ],
+ )
+
+ self.assertListEqual(
+ sent,
+ [
+ {
+ "type": "conversation.item.create",
+ "item": {
+ "type": "message",
+ "role": "system",
+ "content": [
+ {
+ "type": "input_text",
+ "text": "Earlier summary",
+ },
+ ],
+ },
+ },
+ {
+ "type": "conversation.item.create",
+ "item": {
+ "type": "message",
+ "role": "user",
+ "content": [
+ {"type": "input_text", "text": "Weather?"},
+ ],
+ },
+ },
+ {
+ "type": "conversation.item.create",
+ "item": {
+ "type": "message",
+ "role": "assistant",
+ "content": [
+ {
+ "type": "output_text",
+ "text": "Let me check.",
+ },
+ ],
+ },
+ },
+ {
+ "type": "conversation.item.create",
+ "item": {
+ "type": "function_call",
+ "call_id": "call-1",
+ "name": "weather",
+ "arguments": '{"city":"Shanghai"}',
+ },
+ },
+ {
+ "type": "conversation.item.create",
+ "item": {
+ "type": "function_call_output",
+ "call_id": "call-1",
+ "output": "sunny",
+ },
+ },
+ {
+ "type": "conversation.item.create",
+ "item": {
+ "type": "message",
+ "role": "assistant",
+ "content": [
+ {
+ "type": "output_text",
+ "text": "It is sunny.",
+ },
+ ],
+ },
+ },
+ ],
+ )
+
class DashScopeDisconnectTest(IsolatedAsyncioTestCase):
"""A closed WebSocket surfaces as ModelDisconnectedError."""
+ async def test_workspace_endpoint_connects_models(self) -> None:
+ """Both adapters connect through the credential endpoint."""
+
+ credential = DashScopeCredential(
+ api_key="sk-workspace",
+ base_url=(
+ "https://llm-workspace.ap-southeast-1.maas.aliyuncs.com"
+ "/compatible-mode/v1"
+ ),
+ )
+ omni = DashScopeRealtimeModel(
+ "qwen3.5-omni-plus-realtime",
+ credential,
+ )
+ audio = DashScopeAudioRealtimeModel(
+ "qwen-audio-3.1-realtime-plus",
+ credential,
+ )
+ connect = AsyncMock(
+ side_effect=[_OpenSocket(), _OpenSocket()],
+ )
+
+ with patch("websockets.connect", new=connect):
+ await omni.connect(instructions="test")
+ await audio.connect(instructions="test")
+
+ await omni.close()
+ await audio.close()
+ base_url = (
+ "wss://llm-workspace.ap-southeast-1.maas.aliyuncs.com"
+ "/api-ws/v1/realtime"
+ )
+ headers = {
+ "Authorization": "Bearer sk-workspace",
+ "X-DashScope-DataInspection": "disable",
+ }
+ self.assertListEqual(
+ connect.await_args_list,
+ [
+ call(
+ f"{base_url}?model=qwen3.5-omni-plus-realtime",
+ additional_headers=headers,
+ ),
+ call(
+ f"{base_url}?model=qwen-audio-3.1-realtime-plus",
+ additional_headers=headers,
+ ),
+ ],
+ )
+
async def test_send_on_closed_socket(self) -> None:
"""websockets' ConnectionClosed becomes the realtime-level error
and the socket reference is dropped."""
@@ -487,3 +891,113 @@ class DashScopeDisconnectTest(IsolatedAsyncioTestCase):
model = DashScopeRealtimeModel("qwen3.5-omni-flash-realtime", CRED)
with self.assertRaises(ModelDisconnectedError):
await model.commit_turn()
+
+ async def test_reconnect_replaces_the_previous_event_queue(self) -> None:
+ """Termination markers from an old socket cannot end a new one."""
+
+ model = DashScopeRealtimeModel(
+ "qwen3.5-omni-flash-realtime",
+ CRED,
+ )
+ old_queue = model._queue
+ old_queue.put_nowait(me.SessionEndedEvent(reason="closed"))
+ old_queue.put_nowait(None)
+ socket = _OpenSocket()
+
+ with patch(
+ "websockets.connect",
+ new=AsyncMock(return_value=socket),
+ ):
+ await model.connect(instructions="test")
+
+ connection_state = {
+ "queue_replaced": model._queue is not old_queue,
+ "new_queue_size": model._queue.qsize(),
+ "old_queue_size": old_queue.qsize(),
+ "sent": [json.loads(payload) for payload in socket.sent],
+ }
+ await asyncio.sleep(0)
+ await model.close()
+
+ self.assertDictEqual(
+ {
+ "connected": connection_state,
+ "closed": {
+ "socket": socket.closed,
+ "reader": model._reader,
+ "websocket": model._ws,
+ },
+ },
+ {
+ "connected": {
+ "queue_replaced": True,
+ "new_queue_size": 0,
+ "old_queue_size": 2,
+ "sent": [
+ {
+ "type": "session.update",
+ "session": {
+ "instructions": "test",
+ "modalities": ["audio", "text"],
+ "voice": "Tina",
+ "input_audio_format": "pcm16",
+ "output_audio_format": "pcm24",
+ "turn_detection": {
+ "type": "server_vad",
+ "threshold": 0.5,
+ "silence_duration_ms": 800,
+ },
+ "input_audio_transcription": {
+ "model": "gummy-realtime-v1",
+ },
+ },
+ },
+ ],
+ },
+ "closed": {
+ "socket": True,
+ "reader": None,
+ "websocket": None,
+ },
+ },
+ )
+
+ async def test_connect_surfaces_session_setup_error(self) -> None:
+ """An invalid session update fails connect with provider detail."""
+ socket = _OpenSocket(
+ {
+ "type": "error",
+ "error": {
+ "code": "invalid_parameter",
+ "message": "Voice 'Cherry' is not supported.",
+ },
+ },
+ )
+ model = DashScopeRealtimeModel(
+ "qwen3.5-omni-flash-realtime",
+ CRED,
+ parameters=DashScopeRealtimeModel.Parameters(voice="Cherry"),
+ )
+
+ with patch(
+ "websockets.connect",
+ new=AsyncMock(return_value=socket),
+ ):
+ with self.assertRaisesRegex(
+ ModelDisconnectedError,
+ "Voice 'Cherry' is not supported",
+ ):
+ await model.connect(instructions="test")
+
+ self.assertDictEqual(
+ {
+ "closed": socket.closed,
+ "reader": model._reader,
+ "websocket": model._ws,
+ },
+ {
+ "closed": True,
+ "reader": None,
+ "websocket": None,
+ },
+ )
diff --git a/tests/realtime_gemini_test.py b/tests/realtime_gemini_test.py
index 1125b8186..85a4084c1 100644
--- a/tests/realtime_gemini_test.py
+++ b/tests/realtime_gemini_test.py
@@ -13,7 +13,6 @@ from agentscope.message import ToolResultBlock
from agentscope.realtime import (
GeminiRealtimeModel,
ModelDisconnectedError,
- TruncationSupport,
)
CRED = GeminiCredential(api_key="key-x")
@@ -103,14 +102,12 @@ class GeminiCardsTest(unittest.TestCase):
self.assertListEqual(
[
model.type,
- model.truncation,
model.supports_text_input,
model.input_sample_rate,
model.output_sample_rate,
],
[
"gemini_realtime",
- TruncationSupport.SERVER,
True,
16000,
24000,
diff --git a/tests/realtime_openai_test.py b/tests/realtime_openai_test.py
index f0c52e1cc..d589fc1a5 100644
--- a/tests/realtime_openai_test.py
+++ b/tests/realtime_openai_test.py
@@ -11,7 +11,6 @@ from agentscope.credential import OpenAICredential
from agentscope.realtime import (
ModelDisconnectedError,
OpenAIRealtimeModel,
- TruncationSupport,
)
from agentscope.realtime import _events as me
from agentscope.message import ToolResultBlock
@@ -96,21 +95,33 @@ class OpenAICardsTest(unittest.TestCase):
def test_adapter_facts(self) -> None:
"""Protocol facts are constant across the OpenAI models."""
- model = OpenAIRealtimeModel("gpt-realtime-2.1", CRED)
+
+ class ExtendedParameters(OpenAIRealtimeModel.Parameters):
+ """Parameters extended by an application."""
+
+ custom_field: str = "preserved"
+
+ model = OpenAIRealtimeModel(
+ "gpt-realtime-2.1",
+ CRED,
+ parameters=ExtendedParameters(),
+ )
self.assertListEqual(
[
model.type,
- model.truncation,
model.supports_text_input,
model.input_sample_rate,
model.output_sample_rate,
+ type(model.parameters),
+ model.parameters.custom_field,
],
[
"openai_realtime",
- TruncationSupport.EXPLICIT,
True,
24000,
24000,
+ ExtendedParameters,
+ "preserved",
],
)
@@ -378,6 +389,10 @@ class OpenAIParseTest(unittest.TestCase):
"item_id": "user_1",
"transcript": "what is the weather",
},
+ {
+ "type": "conversation.item.input_audio_transcription.failed",
+ "item_id": "user_2",
+ },
{
"type": "error",
"error": {
@@ -396,6 +411,7 @@ class OpenAIParseTest(unittest.TestCase):
item_id="user_1",
text="what is the weather",
),
+ me.InputTranscriptionFailedEvent(item_id="user_2"),
me.ModelErrorEvent(code="invalid_value", message="boom"),
],
)
@@ -499,25 +515,12 @@ class OpenAIWireTest(IsolatedAsyncioTestCase):
],
)
- async def test_barge_in_truncates_then_cancels(self) -> None:
- """A barge-in rewrites the item to the audio heard and cancels
- the response; with none in flight the cancel is skipped."""
- await self.model.truncate("item_1", 1200, "hel")
+ async def test_cancel_only_sends_with_a_response_in_flight(self) -> None:
+ """Cancel is skipped until a response is in flight."""
await self.model.cancel_response()
self.model._response_id = "resp_1"
await self.model.cancel_response()
- self.assertListEqual(
- self.sent,
- [
- {
- "type": "conversation.item.truncate",
- "item_id": "item_1",
- "content_index": 0,
- "audio_end_ms": 1200,
- },
- {"type": "response.cancel"},
- ],
- )
+ self.assertListEqual(self.sent, [{"type": "response.cancel"}])
class OpenAIDisconnectTest(IsolatedAsyncioTestCase):
diff --git a/tests/realtime_reconnect_test.py b/tests/realtime_reconnect_test.py
index bb21a2102..bd178d484 100644
--- a/tests/realtime_reconnect_test.py
+++ b/tests/realtime_reconnect_test.py
@@ -71,7 +71,7 @@ class ReconnectTest(IsolatedAsyncioTestCase):
"qwen-omni-turbo-realtime",
DashScopeCredential(api_key="sk-x"),
),
- [],
+ [{"type": "session.updated"}],
),
(
XAIRealtimeModel(
diff --git a/tests/realtime_service_test.py b/tests/realtime_service_test.py
new file mode 100644
index 000000000..2ddbd10a5
--- /dev/null
+++ b/tests/realtime_service_test.py
@@ -0,0 +1,265 @@
+# -*- coding: utf-8 -*-
+"""Tests for realtime service runtime assembly."""
+
+import unittest
+from types import SimpleNamespace
+from typing import cast
+from unittest.mock import AsyncMock, patch
+
+from agentscope.app._service._realtime import RealtimeService
+from agentscope.app.channel import ChatKind
+from agentscope.app.storage import (
+ AgentData,
+ AgentRecord,
+ ChannelOrigin,
+ SessionConfig,
+ SessionRecord,
+)
+from agentscope.realtime import RealtimeModelBase
+
+
+class RealtimeServiceTest(unittest.IsolatedAsyncioTestCase):
+ """Verify complete toolkit and session-context assembly."""
+
+ async def test_create_agent_assembles_the_session_toolkit(self) -> None:
+ """Build the same persisted toolkit context for realtime use."""
+ user_id = "user-1"
+ agent_id = "agent-1"
+ session_id = "session-1"
+ agent_record = AgentRecord(
+ id=agent_id,
+ user_id=user_id,
+ data=AgentData(
+ name="Friday",
+ system_prompt="Be concise.",
+ ),
+ )
+ session = SessionRecord(
+ id=session_id,
+ user_id=user_id,
+ agent_id=agent_id,
+ team_id="team-1",
+ origin=ChannelOrigin(
+ channel_id="channel-1",
+ chat_id="chat-1",
+ channel_user_id="staff-1",
+ ),
+ config=SessionConfig(workspace_id="workspace-1"),
+ )
+ storage = SimpleNamespace(
+ get_session=AsyncMock(return_value=session),
+ get_team=AsyncMock(
+ return_value=SimpleNamespace(session_id=session_id),
+ ),
+ )
+ workspace = SimpleNamespace(workdir="/workspace/session-1")
+ workspace_manager = SimpleNamespace(
+ get_workspace=AsyncMock(return_value=workspace),
+ )
+ channel_tool = SimpleNamespace(name="send_message")
+ channel = SimpleNamespace(
+ display_name="ExampleChat",
+ list_tools=AsyncMock(return_value=[channel_tool]),
+ chat_kind=AsyncMock(return_value=ChatKind.GROUP),
+ chat_name=AsyncMock(return_value="Operations"),
+ )
+ channel_clients = SimpleNamespace(
+ get=AsyncMock(return_value=channel),
+ )
+ access = SimpleNamespace(
+ resolve_agent=AsyncMock(return_value=agent_record),
+ )
+ scheduler = object()
+ background_tasks = object()
+ message_bus = object()
+ extra_factory = AsyncMock()
+ templates = {"researcher": object()}
+ toolkit = object()
+ model = object()
+ service = RealtimeService(
+ storage=storage,
+ workspace_manager=workspace_manager,
+ scheduler_manager=scheduler,
+ background_task_manager=background_tasks,
+ message_bus=message_bus,
+ resource_access_service=access,
+ extra_agent_tools=extra_factory,
+ custom_subagent_templates=templates,
+ channel_clients=channel_clients,
+ )
+
+ with patch(
+ "agentscope.app._service._realtime.get_toolkit",
+ new=AsyncMock(return_value=toolkit),
+ ) as get_toolkit_mock:
+ agent = await service.create_agent(
+ user_id=user_id,
+ agent_id=agent_id,
+ session_id=session_id,
+ model=model, # type: ignore[arg-type]
+ )
+
+ self.assertDictEqual(
+ {
+ "name": agent.name,
+ "system_prompt": agent.system_prompt,
+ "model": agent.model,
+ "toolkit": agent.toolkit,
+ "state": agent.state,
+ "working_directories": {
+ key: value.model_dump()
+ for key, value in (
+ agent.state.permission_context.working_directories
+ ).items()
+ },
+ },
+ {
+ "name": "Friday",
+ "system_prompt": (
+ "Be concise.\n\n<system-notification>You're within a "
+ "session (id=session-1). This session is bound to a "
+ "chat named \"Operations\" (id 'chat-1') on the "
+ "ExampleChat platform. It is a group chat with "
+ "multiple people. These ExampleChat tools are "
+ "available: send_message. Use this chat's id as their "
+ "target.</system-notification>"
+ ),
+ "model": model,
+ "toolkit": toolkit,
+ "state": session.state,
+ "working_directories": {
+ "/workspace/session-1": {
+ "path": "/workspace/session-1",
+ "source": "session",
+ },
+ },
+ },
+ )
+ access.resolve_agent.assert_awaited_once_with(user_id, agent_id)
+ storage.get_session.assert_awaited_once_with(
+ user_id,
+ agent_id,
+ session_id,
+ )
+ storage.get_team.assert_awaited_once_with(user_id, "team-1")
+ workspace_manager.get_workspace.assert_awaited_once_with(
+ user_id,
+ agent_id,
+ session_id,
+ "workspace-1",
+ )
+ channel_clients.get.assert_awaited_once_with("channel-1")
+ channel.list_tools.assert_awaited_once_with(workspace, None)
+ channel.chat_kind.assert_awaited_once_with("chat-1")
+ channel.chat_name.assert_awaited_once_with("chat-1")
+ get_toolkit_mock.assert_awaited_once_with(
+ storage=storage,
+ workspace=workspace,
+ workspace_manager=workspace_manager,
+ scheduler_manager=scheduler,
+ background_task_manager=background_tasks,
+ message_bus=message_bus,
+ middlewares=[],
+ user_id=user_id,
+ agent_record=agent_record,
+ session_record=session,
+ resource_access_service=access,
+ extra_factory=extra_factory,
+ sub_agent_templates=templates,
+ team_role="leader",
+ channel_tools=[channel_tool],
+ )
+
+ async def test_private_chat_tools_receive_channel_user_id(self) -> None:
+ """Bind identity-dependent channel tools to the private-chat user."""
+ user_id = "user-1"
+ agent_id = "agent-1"
+ session_id = "session-1"
+ agent_record = AgentRecord(
+ id=agent_id,
+ user_id=user_id,
+ data=AgentData(name="Friday", system_prompt="Be concise."),
+ )
+ session = SessionRecord(
+ id=session_id,
+ user_id=user_id,
+ agent_id=agent_id,
+ origin=ChannelOrigin(
+ channel_id="channel-1",
+ chat_id="chat-1",
+ chat_name="Direct Message",
+ channel_user_id="staff-1",
+ ),
+ config=SessionConfig(workspace_id="workspace-1"),
+ )
+ storage = SimpleNamespace(
+ get_session=AsyncMock(return_value=session),
+ )
+ workspace = SimpleNamespace(workdir="/workspace/session-1")
+ workspace_manager = SimpleNamespace(
+ get_workspace=AsyncMock(return_value=workspace),
+ )
+ channel_tool = SimpleNamespace(name="list_wiki_spaces")
+ channel = SimpleNamespace(
+ display_name="ExampleChat",
+ list_tools=AsyncMock(return_value=[channel_tool]),
+ chat_kind=AsyncMock(return_value=ChatKind.PRIVATE),
+ chat_name=AsyncMock(),
+ )
+ service = RealtimeService(
+ storage=storage,
+ workspace_manager=workspace_manager,
+ scheduler_manager=object(),
+ background_task_manager=object(),
+ message_bus=object(),
+ resource_access_service=SimpleNamespace(
+ resolve_agent=AsyncMock(return_value=agent_record),
+ ),
+ channel_clients=SimpleNamespace(
+ get=AsyncMock(return_value=channel),
+ ),
+ )
+ toolkit = object()
+ model = cast(RealtimeModelBase, object())
+
+ with patch(
+ "agentscope.app._service._realtime.get_toolkit",
+ new=AsyncMock(return_value=toolkit),
+ ) as get_toolkit_mock:
+ agent = await service.create_agent(
+ user_id=user_id,
+ agent_id=agent_id,
+ session_id=session_id,
+ model=model,
+ )
+
+ self.assertDictEqual(
+ {
+ "system_prompt": agent.system_prompt,
+ "toolkit": agent.toolkit,
+ "channel_tools": get_toolkit_mock.await_args.kwargs[
+ "channel_tools"
+ ],
+ "list_tools_args": channel.list_tools.await_args.args,
+ },
+ {
+ "system_prompt": (
+ "Be concise.\n\n<system-notification>You're within a "
+ "session (id=session-1). This session is bound to a "
+ "chat named \"Direct Message\" (id 'chat-1') on the "
+ "ExampleChat platform. It is a one-to-one private chat. "
+ "These ExampleChat tools are available: "
+ "list_wiki_spaces. Use this chat's id as their target."
+ "</system-notification>"
+ ),
+ "toolkit": toolkit,
+ "channel_tools": [channel_tool],
+ "list_tools_args": (workspace, "staff-1"),
+ },
+ )
+ channel.chat_kind.assert_awaited_once_with("chat-1")
+ channel.chat_name.assert_not_awaited()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/realtime_xai_test.py b/tests/realtime_xai_test.py
index f4c6cc2ab..207163b45 100644
--- a/tests/realtime_xai_test.py
+++ b/tests/realtime_xai_test.py
@@ -12,7 +12,6 @@ from agentscope.credential import XAICredential
from agentscope.message import TextBlock, ToolResultBlock
from agentscope.realtime import (
ModelDisconnectedError,
- TruncationSupport,
XAIRealtimeModel,
)
from agentscope.realtime import _events as me
@@ -78,11 +77,11 @@ class XAICardsTest(unittest.TestCase):
XAIRealtimeModel("no-such-model", CRED)
def test_adapter_facts(self) -> None:
- """Grok takes text turns but documents no truncate frame."""
+ """Grok accepts text turns."""
model = XAIRealtimeModel("grok-voice-latest", CRED)
self.assertListEqual(
- [model.type, model.truncation, model.supports_text_input],
- ["xai_realtime", TruncationSupport.NONE, True],
+ [model.type, model.supports_text_input],
+ ["xai_realtime", True],
)
@@ -184,6 +183,10 @@ class XAIParseTest(unittest.TestCase):
"item_id": "msg_003",
"transcript": "Hello, how are you?",
},
+ {
+ "type": "conversation.item.input_audio_transcription.failed",
+ "item_id": "msg_004",
+ },
{
"type": "response.output_audio_transcript.delta",
"item_id": "msg_008",
@@ -216,6 +219,7 @@ class XAIParseTest(unittest.TestCase):
item_id="msg_003",
text="Hello, how are you?",
),
+ me.InputTranscriptionFailedEvent(item_id="msg_004"),
me.TranscriptDeltaEvent(
item_id="resp_001",
delta="Hello! I'm doing",
@@ -372,13 +376,12 @@ class XAIClientFramesTest(IsolatedAsyncioTestCase):
],
)
- async def test_barge_in_cancels_without_truncating(self) -> None:
- """A barge-in cancels the response; there is no truncate frame."""
+ async def test_barge_in_cancels_the_response(self) -> None:
+ """A barge-in cancels the response."""
self.model._parse(
{"type": "response.created", "response": {"id": "resp_001"}},
)
await self.model.cancel_response()
- await self.model.truncate("resp_001", 1500, "Hello! I'm")
self.assertListEqual(self.sent, [{"type": "response.cancel"}])
diff --git a/tests/service_cancel_dispatcher_test.py b/tests/service_cancel_dispatcher_test.py
index 463b26ce9..3a3dad47e 100644
--- a/tests/service_cancel_dispatcher_test.py
+++ b/tests/service_cancel_dispatcher_test.py
@@ -16,6 +16,7 @@ import asyncio
from contextlib import asynccontextmanager
from typing import AsyncGenerator, Callable
from unittest import IsolatedAsyncioTestCase
+from unittest.mock import Mock
from agentscope.app._manager import (
BackgroundTaskManager,
@@ -269,6 +270,29 @@ class TestCancelDispatcher(IsolatedAsyncioTestCase):
self.assertFalse(bg_task_b.cancelled())
bg_task_b.cancel()
+ async def test_cancel_signal_closes_local_realtime_run(self) -> None:
+ """A session cancel reaches the local WebRTC runner."""
+ bus = _FakeBus()
+ registry = ChatRunRegistry()
+ bg_manager = BackgroundTaskManager(message_bus=bus)
+ realtime_runner = Mock()
+
+ async with bg_manager, registry, CancelDispatcher(
+ message_bus=bus,
+ registry=registry,
+ bg_manager=bg_manager,
+ realtime_connections={
+ ("alice", "sess-A"): realtime_runner,
+ },
+ ):
+ await bus.session_publish_cancel("sess-A")
+ for _ in range(50):
+ if realtime_runner.request_close.called:
+ break
+ await asyncio.sleep(0.01)
+
+ realtime_runner.request_close.assert_called_once_with()
+
async def test_cancel_signal_for_remote_session_is_noop(self) -> None:
"""Broadcast for a session held on another process is silently
ignored — no exception, no spurious cancel."""
diff --git a/tests/service_team_tools_test.py b/tests/service_team_tools_test.py
index 3666bbfdf..5f62a093d 100644
--- a/tests/service_team_tools_test.py
+++ b/tests/service_team_tools_test.py
@@ -906,12 +906,12 @@ class TestAgentCreateTemplates(_TeamToolsTestBase):
team.data.member_ids[1],
)
self.assertIsNot(
- a1.data.context_config,
- a2.data.context_config,
+ a1.data.chat_config.context_config,
+ a2.data.chat_config.context_config,
)
self.assertIsNot(
- a1.data.react_config,
- a2.data.react_config,
+ a1.data.chat_config.react_config,
+ a2.data.chat_config.react_config,
)
@@ -1374,8 +1374,11 @@ class TestAgentDataInvitableValidator(IsolatedAsyncioTestCase):
invite_description="draft",
),
)
- self.assertEqual(data.invite_config.invite_description, "draft")
- self.assertFalse(data.invite_config.invitable)
+ self.assertEqual(
+ data.chat_config.invite_config.invite_description,
+ "draft",
+ )
+ self.assertFalse(data.chat_config.invite_config.invitable)
class _AgentInviteTestBase(_TeamToolsTestBase):
@@ -1731,8 +1734,8 @@ class TestAgentInviteRejections(_AgentInviteTestBase):
"""Snapshot said invitable but fresh read shows the toggle off."""
# Flip the toggle off in storage while pool snapshot still has it.
stale = self.monday_agent
- stale.data.invite_config.invitable = False
- stale.data.invite_config.invite_description = None
+ stale.data.chat_config.invite_config.invitable = False
+ stale.data.chat_config.invite_config.invite_description = None
await self.storage.upsert_agent(self.user_id, stale)
chunk = await self._tool(pool=[stale])(
diff --git a/tests/session_auto_naming_test.py b/tests/session_auto_naming_test.py
index 326a36f18..0a941a0dd 100644
--- a/tests/session_auto_naming_test.py
+++ b/tests/session_auto_naming_test.py
@@ -123,6 +123,7 @@ class SessionNameOwnershipTest(IsolatedAsyncioTestCase):
"chat_model_config": None,
"fallback_chat_model_config": None,
"tts_model_config": None,
+ "realtime_model_config": None,
"knowledge_config": None,
},
)
@@ -143,6 +144,7 @@ class SessionNameOwnershipTest(IsolatedAsyncioTestCase):
"chat_model_config": None,
"fallback_chat_model_config": None,
"tts_model_config": None,
+ "realtime_model_config": None,
"knowledge_config": None,
},
)
@@ -169,6 +171,7 @@ class SessionNameOwnershipTest(IsolatedAsyncioTestCase):
"chat_model_config": None,
"fallback_chat_model_config": None,
"tts_model_config": None,
+ "realtime_model_config": None,
"knowledge_config": None,
},
)
@@ -195,6 +198,7 @@ class SessionNameOwnershipTest(IsolatedAsyncioTestCase):
"chat_model_config": None,
"fallback_chat_model_config": None,
"tts_model_config": None,
+ "realtime_model_config": None,
"knowledge_config": None,
},
)
@@ -220,6 +224,7 @@ class SessionNameOwnershipTest(IsolatedAsyncioTestCase):
"chat_model_config": None,
"fallback_chat_model_config": None,
"tts_model_config": None,
+ "realtime_model_config": None,
"knowledge_config": None,
},
)
@@ -342,6 +347,7 @@ class AutoNameSessionTest(IsolatedAsyncioTestCase):
},
"fallback_chat_model_config": None,
"tts_model_config": None,
+ "realtime_model_config": None,
"knowledge_config": None,
},
],
diff --git a/tests/session_config_patch_test.py b/tests/session_config_patch_test.py
index 92a1799a1..e2d8f9d49 100644
--- a/tests/session_config_patch_test.py
+++ b/tests/session_config_patch_test.py
@@ -21,7 +21,12 @@ from fastapi.testclient import TestClient
from agentscope.agent import ContextConfig, ReActConfig
from agentscope.app import create_app
from agentscope.app.message_bus import MessageBusKeys, RedisMessageBus
-from agentscope.app.storage import AgentData, AgentRecord, RedisStorage
+from agentscope.app.storage import (
+ AgentData,
+ AgentRecord,
+ RealtimeModelConfig,
+ RedisStorage,
+)
from agentscope.app.workspace_manager import LocalWorkspaceManager
from agentscope.permission import PermissionMode
from agentscope.message import UserMsg
@@ -156,6 +161,53 @@ class SessionConfigPatchTest(IsolatedAsyncioTestCase):
# never offered a state to write".
self.assertEqual(self.recorded_states, [None])
+ async def test_realtime_config_omission_and_explicit_null(self) -> None:
+ """Omission keeps realtime config while null clears it."""
+ record = await self.storage.get_session(
+ "alice",
+ self.agent_id,
+ self.session_id,
+ )
+ realtime_config = RealtimeModelConfig(
+ type="dashscope_omni_realtime",
+ credential_id="credential-1",
+ model="qwen3.5-omni-plus-realtime",
+ parameters={"voice": "Tina"},
+ )
+ await self.storage.upsert_session(
+ user_id="alice",
+ agent_id=self.agent_id,
+ config=record.config.model_copy(
+ update={"realtime_model_config": realtime_config},
+ ),
+ session_id=self.session_id,
+ )
+ self.recorded_states.clear()
+
+ omitted = self._patch({"name": "after"})
+ cleared = self._patch({"realtime_model_config": None})
+
+ self.assertDictEqual(
+ {
+ "omitted_status": omitted.status_code,
+ "omitted_config": omitted.json()["config"][
+ "realtime_model_config"
+ ],
+ "cleared_status": cleared.status_code,
+ "cleared_config": cleared.json()["config"][
+ "realtime_model_config"
+ ],
+ "written_states": self.recorded_states,
+ },
+ {
+ "omitted_status": 200,
+ "omitted_config": realtime_config.model_dump(mode="json"),
+ "cleared_status": 200,
+ "cleared_config": None,
+ "written_states": [None, None],
+ },
+ )
+
def test_permission_mode_patch_writes_only_that_field(self) -> None:
"""``permission_mode`` is the one field that must carry state."""
response = self._patch({"permission_mode": "accept_edits"})
diff --git a/tests/session_event_stream_test.py b/tests/session_event_stream_test.py
new file mode 100644
index 000000000..bbfbdc9bb
--- /dev/null
+++ b/tests/session_event_stream_test.py
@@ -0,0 +1,80 @@
+# -*- coding: utf-8 -*-
+"""Regression tests for the session SSE replay/live seam."""
+
+import asyncio
+from contextlib import aclosing
+import json
+from unittest import IsolatedAsyncioTestCase
+
+from agentscope.app._bus_ops import publish_session_event
+from agentscope.app._router._session import stream_session_events
+from agentscope.app.message_bus import InMemoryMessageBus
+
+
+class _Storage:
+ """Return one session for the route ownership check."""
+
+ async def get_session(self, *_: object) -> object:
+ """Return a sentinel existing session."""
+ return object()
+
+
+class _SeamBus(InMemoryMessageBus):
+ """Publish once while the route is reading its replay log."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self._published = False
+
+ async def log_read(
+ self,
+ key: str,
+ since: str | None = None,
+ max_count: int = 100,
+ ) -> list[tuple[str, dict]]:
+ """Put one event into both the replay and live paths."""
+ if not self._published:
+ self._published = True
+ await publish_session_event(self, "s-1", {"sequence": 2})
+ return await super().log_read(
+ key,
+ since=since,
+ max_count=max_count,
+ )
+
+
+def _decode(frame: str | bytes) -> dict:
+ """Decode one SSE data frame."""
+ if isinstance(frame, bytes):
+ frame = frame.decode()
+ return json.loads(frame.removeprefix("data: ").strip())
+
+
+class SessionEventStreamTest(IsolatedAsyncioTestCase):
+ """The session route changes from replay to live without a gap."""
+
+ async def test_event_at_replay_live_seam_is_delivered_once(self) -> None:
+ """A seam event is deduplicated without hiding the next event."""
+ bus = _SeamBus()
+ await publish_session_event(bus, "s-1", {"sequence": 1})
+ response = await stream_session_events(
+ session_id="s-1",
+ agent_id="a-1",
+ user_id="u-1",
+ storage=_Storage(), # type: ignore[arg-type]
+ message_bus=bus,
+ after=None,
+ )
+
+ async with aclosing(response.body_iterator) as stream:
+ first = _decode(await anext(stream))
+ second = _decode(await anext(stream))
+ await publish_session_event(bus, "s-1", {"sequence": 3})
+ third = _decode(
+ await asyncio.wait_for(anext(stream), timeout=1),
+ )
+
+ self.assertListEqual(
+ [first, second, third],
+ [{"sequence": 1}, {"sequence": 2}, {"sequence": 3}],
+ )
diff --git a/tests/storage_redis_test.py b/tests/storage_redis_test.py
index dd409cd32..536e7eb06 100644
--- a/tests/storage_redis_test.py
+++ b/tests/storage_redis_test.py
@@ -3,6 +3,7 @@
"""Unit tests for RedisStorage using fakeredis."""
from unittest.async_case import IsolatedAsyncioTestCase
+from unittest.mock import patch
import fakeredis.aioredis
@@ -276,17 +277,41 @@ class TestSession(IsolatedAsyncioTestCase):
make_session_config(self.workspace_id),
)
records = await self.storage.list_sessions(self.user_id, self.agent_id)
+ session_id = records[0].id
+ message_key = self.storage._message_key(self.user_id, session_id)
+ message_index_key = self.storage._message_index_key(
+ self.user_id,
+ session_id,
+ )
+ await self.storage.upsert_message(
+ self.user_id,
+ session_id,
+ UserMsg(name="alice", content="hello"),
+ )
result = await self.storage.delete_session(
self.user_id,
self.agent_id,
- records[0].id,
+ session_id,
)
- self.assertTrue(result)
remaining = await self.storage.list_sessions(
self.user_id,
self.agent_id,
)
- self.assertEqual(remaining, [])
+ self.assertDictEqual(
+ {
+ "deleted": result,
+ "remaining": remaining,
+ "message_key_count": await self.storage._client.exists(
+ message_key,
+ message_index_key,
+ ),
+ },
+ {
+ "deleted": True,
+ "remaining": [],
+ "message_key_count": 0,
+ },
+ )
async def test_delete_cascades_lookup_key(self) -> None:
"""Deleting a session must remove the lookup key so a subsequent upsert
@@ -358,17 +383,61 @@ class TestMessage(IsolatedAsyncioTestCase):
[msg.model_dump()],
)
- async def test_upsert_refreshes_message_list_ttl(self) -> None:
- """Message list keys expire with the session storage TTL."""
+ async def test_upsert_refreshes_message_keys_ttl(self) -> None:
+ """Message list and index expire with the session storage TTL."""
self.storage.key_ttl = 60
msg = UserMsg(name="alice", content="hello")
await self.storage.upsert_message(self.user_id, self.session_id, msg)
- ttl = await self.storage._client.ttl(
+ list_ttl = await self.storage._client.ttl(
self.storage._message_key(self.user_id, self.session_id),
)
- self.assertGreater(ttl, 0)
+ index_ttl = await self.storage._client.ttl(
+ self.storage._message_index_key(self.user_id, self.session_id),
+ )
+ self.assertGreater(list_ttl, 0)
+ self.assertGreater(index_ttl, 0)
+
+ async def test_upsert_lazily_indexes_legacy_messages(self) -> None:
+ """A legacy list gains an ID index without scanning for a new ID."""
+ legacy = UserMsg(name="alice", content="legacy")
+ new = AssistantMsg(name="bot", content="new")
+ key = self.storage._message_key(self.user_id, self.session_id)
+ index_key = self.storage._message_index_key(
+ self.user_id,
+ self.session_id,
+ )
+ await self.storage._client.rpush(key, legacy.model_dump_json())
+
+ with patch.object(
+ self.storage,
+ "_find_message_index",
+ ) as find_index:
+ await self.storage.upsert_message(
+ self.user_id,
+ self.session_id,
+ new,
+ )
+ find_index.assert_not_awaited()
+
+ messages, has_more = await self.storage.list_messages(
+ self.user_id,
+ self.session_id,
+ )
+ indexed_ids = await self.storage._client.smembers(index_key)
+ self.assertDictEqual(
+ {
+ "messages": [message.model_dump() for message in messages],
+ "has_more": has_more,
+ "indexed_ids": indexed_ids,
+ },
+ {
+ "messages": [legacy.model_dump(), new.model_dump()],
+ "has_more": False,
+ "indexed_ids": {legacy.id, new.id},
+ },
+ )
async def test_upsert_replaces_last_message_with_same_id(self) -> None:
"""Upserting a message whose id matches the last entry replaces it
@@ -420,13 +489,20 @@ class TestMessage(IsolatedAsyncioTestCase):
)
self.assertGreater(ttl, 0)
- async def test_upsert_appends_when_id_differs_from_last(self) -> None:
- """Upserting a message with a different id than the last always
- appends, even if an earlier message shares the same id."""
+ async def test_upsert_replaces_earlier_message_with_same_id(self) -> None:
+ """Upserting by id replaces a non-tail message without duplication."""
msg1 = UserMsg(name="alice", content="first")
msg2 = UserMsg(name="alice", content="second")
await self.storage.upsert_message(self.user_id, self.session_id, msg1)
await self.storage.upsert_message(self.user_id, self.session_id, msg2)
+ updated = msg1.model_copy(
+ update={"content": [TextBlock(text="updated first")]},
+ )
+ await self.storage.upsert_message(
+ self.user_id,
+ self.session_id,
+ updated,
+ )
messages, has_more = await self.storage.list_messages(
self.user_id,
self.session_id,
@@ -434,7 +510,7 @@ class TestMessage(IsolatedAsyncioTestCase):
self.assertFalse(has_more)
self.assertListEqual(
[m.model_dump() for m in messages],
- [msg1.model_dump(), msg2.model_dump()],
+ [updated.model_dump(), msg2.model_dump()],
)
async def test_get_message_returns_correct_message(self) -> None:
@@ -461,6 +537,69 @@ class TestMessage(IsolatedAsyncioTestCase):
)
self.assertIsNone(result)
+ async def test_delete_message(self) -> None:
+ """Deleting by id removes the matching message."""
+ first = UserMsg(name="alice", content="first")
+ second = AssistantMsg(name="bot", content="second")
+ updated_first = UserMsg(
+ id=first.id,
+ name="alice",
+ content="updated first",
+ )
+ await self.storage.upsert_message(
+ self.user_id,
+ self.session_id,
+ first,
+ )
+ await self.storage.upsert_message(
+ self.user_id,
+ self.session_id,
+ second,
+ )
+ await self.storage.upsert_message(
+ self.user_id,
+ self.session_id,
+ updated_first,
+ )
+
+ deleted = await self.storage.delete_message(
+ self.user_id,
+ self.session_id,
+ first.id,
+ )
+ deleted_again = await self.storage.delete_message(
+ self.user_id,
+ self.session_id,
+ first.id,
+ )
+ messages, has_more = await self.storage.list_messages(
+ self.user_id,
+ self.session_id,
+ )
+ indexed_ids = await self.storage._client.smembers(
+ self.storage._message_index_key(
+ self.user_id,
+ self.session_id,
+ ),
+ )
+
+ self.assertDictEqual(
+ {
+ "deleted": deleted,
+ "deleted_again": deleted_again,
+ "messages": [message.model_dump() for message in messages],
+ "has_more": has_more,
+ "indexed_ids": indexed_ids,
+ },
+ {
+ "deleted": True,
+ "deleted_again": False,
+ "messages": [second.model_dump()],
+ "has_more": False,
+ "indexed_ids": {second.id},
+ },
+ )
+
async def test_list_messages_empty_session(self) -> None:
"""list_messages returns an empty list for a session with no
messages."""
diff --git a/tests/storage_sql_test.py b/tests/storage_sql_test.py
index 2ad2e65c4..3b9d2b6a5 100644
--- a/tests/storage_sql_test.py
+++ b/tests/storage_sql_test.py
@@ -21,7 +21,7 @@ from sqlalchemy.dialects import mysql
from utils import AnyString
from agentscope.app.storage._sql._mappers import _to_record
-from agentscope.app.storage._sql._tables import SessionRow
+from agentscope.app.storage._sql._tables import AgentRow, SessionRow
from agentscope.app.storage import (
AgentData,
AgentRecord,
@@ -266,16 +266,58 @@ class AsyncSQLAlchemyStorageTest(IsolatedAsyncioTestCase):
# ------------------------------------------------------------------
async def test_agents_round_trip_and_source_filter(self) -> None:
- """``list_agents`` filters out ``source='team'`` workers."""
- user_agent = _agent_record("user-1", "usr")
+ """Legacy agent rows load grouped and team workers stay hidden."""
+ record_id = "agent-legacy"
+ data_id = "agent-data-legacy"
+ now = datetime.now()
+ # Insert at the row layer so AgentData cannot normalize the legacy
+ # payload before it reaches SQL storage.
+ # pylint: disable=protected-access
+ async with self.storage._session() as sess:
+ sess.add(
+ AgentRow(
+ id=record_id,
+ created_at=now,
+ updated_at=now,
+ user_id="user-1",
+ source="user",
+ payload={
+ "data": {
+ "id": data_id,
+ "name": "usr",
+ "system_prompt": "You are usr.",
+ "context_config": {"max_image_num": 3},
+ "react_config": {"max_iters": 7},
+ },
+ },
+ ),
+ )
+ await sess.commit()
+
team_agent = _agent_record("user-1", "team-worker")
team_agent.source = "team"
-
- await self.storage.upsert_agent("user-1", user_agent)
await self.storage.upsert_agent("user-1", team_agent)
listed = await self.storage.list_agents("user-1")
- self.assertEqual([a.id for a in listed], [user_agent.id])
+ self.assertEqual([agent.id for agent in listed], [record_id])
+ self.assertDictEqual(
+ listed[0].model_dump(mode="json", exclude_defaults=True),
+ {
+ "id": record_id,
+ "updated_at": now.isoformat(),
+ "created_at": now.isoformat(),
+ "user_id": "user-1",
+ "data": {
+ "id": data_id,
+ "name": "usr",
+ "system_prompt": "You are usr.",
+ "chat_config": {
+ "context_config": {"max_image_num": 3},
+ "react_config": {"max_iters": 7},
+ },
+ },
+ },
+ )
# But direct get works for the team-spawned worker
self.assertEqual(
(await self.storage.get_agent("user-1", team_agent.id)).id,
@@ -505,6 +547,43 @@ class AsyncSQLAlchemyStorageTest(IsolatedAsyncioTestCase):
)
self.assertEqual([m.id for m in listed], [long_msg_id])
+ async def test_delete_message(self) -> None:
+ """Deleting by id removes only the matching persisted message."""
+ first = UserMsg(name="u", content="first")
+ second = AssistantMsg(name="a", content="second")
+ await self.storage.upsert_message("user-1", "sess-1", first)
+ await self.storage.upsert_message("user-1", "sess-1", second)
+
+ deleted = await self.storage.delete_message(
+ "user-1",
+ "sess-1",
+ first.id,
+ )
+ deleted_again = await self.storage.delete_message(
+ "user-1",
+ "sess-1",
+ first.id,
+ )
+ messages, has_more = await self.storage.list_messages(
+ "user-1",
+ "sess-1",
+ )
+
+ self.assertDictEqual(
+ {
+ "deleted": deleted,
+ "deleted_again": deleted_again,
+ "messages": [message.model_dump() for message in messages],
+ "has_more": has_more,
+ },
+ {
+ "deleted": True,
+ "deleted_again": False,
+ "messages": [second.model_dump()],
+ "has_more": False,
+ },
+ )
+
# ------------------------------------------------------------------
# SOPs
# ------------------------------------------------------------------
diff --git a/tests/webrtc_audio_transport_test.py b/tests/webrtc_audio_transport_test.py
new file mode 100644
index 000000000..4d1dd8eb7
--- /dev/null
+++ b/tests/webrtc_audio_transport_test.py
@@ -0,0 +1,1458 @@
+# -*- coding: utf-8 -*-
+"""Tests for browser WebRTC audio and control transport."""
+# pylint: disable=protected-access
+
+import asyncio
+import json
+import unittest
+from collections.abc import Callable
+from contextlib import asynccontextmanager
+from fractions import Fraction
+from types import SimpleNamespace
+from typing import Any, AsyncIterator, cast
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import numpy as np
+from aiortc import MediaStreamTrack
+from aiortc.mediastreams import MediaStreamError
+from av import AudioFrame as AVAudioFrame
+from fastapi import HTTPException
+
+from agentscope.app._router._realtime import _create_realtime_offer
+from agentscope.app._router._schema import (
+ RealtimeOfferRequest,
+ RealtimeOfferResponse,
+)
+from agentscope.app._service import get_realtime_model
+from agentscope.app._service._webrtc_audio_transport import (
+ WebRTCAudioTransport,
+)
+from agentscope.app._service._webrtc_session import WebRTCSession
+from agentscope.app.message_bus import MessageBusKeys
+from agentscope.app.storage import CredentialRecord, RealtimeModelConfig
+from agentscope.event import (
+ DataBlockDeltaEvent,
+ DataBlockEndEvent,
+ DataBlockStartEvent,
+ ReplyEndEvent,
+ ReplyStartEvent,
+ RequireUserConfirmEvent,
+ TextBlockDeltaEvent,
+ TextBlockEndEvent,
+ TextBlockStartEvent,
+ ToolResultEndEvent,
+)
+from agentscope.message import ToolCallBlock, ToolResultState
+from agentscope.realtime import AudioFrame, DashScopeAudioRealtimeModel
+
+
+class _FakeDataChannel:
+ """Minimal event-emitter-compatible RTCDataChannel double."""
+
+ def __init__(self) -> None:
+ self.readyState = "open"
+ self.sent: list[dict] = []
+ self.handlers: dict[str, Callable[..., object]] = {}
+
+ def on(
+ self,
+ event: str,
+ ) -> Callable[[Callable[..., object]], Callable[..., object]]:
+ """Register one event callback."""
+
+ def _register(
+ callback: Callable[..., object],
+ ) -> Callable[..., object]:
+ self.handlers[event] = callback
+ return callback
+
+ return _register
+
+ def send(self, raw: str) -> None:
+ """Decode and retain one outbound JSON message."""
+ self.sent.append(json.loads(raw))
+
+ def emit_message(self, payload: dict) -> None:
+ """Deliver one inbound JSON message."""
+ callback = self.handlers["message"]
+ callback(json.dumps(payload))
+
+
+class _OneFrameAudioTrack(MediaStreamTrack):
+ """Yield one browser-format audio frame, then end."""
+
+ kind = "audio"
+
+ def __init__(self) -> None:
+ super().__init__()
+ self._sent = False
+
+ async def recv(self) -> AVAudioFrame:
+ """Return one 48 kHz mono frame."""
+ if self._sent:
+ raise MediaStreamError
+ self._sent = True
+ samples = np.full((1, 960), 1_000, dtype=np.int16)
+ frame = AVAudioFrame.from_ndarray(
+ samples,
+ format="s16",
+ layout="mono",
+ )
+ frame.sample_rate = 48_000
+ frame.pts = 0
+ frame.time_base = Fraction(1, 48_000)
+ return frame
+
+
+class _FakeMessage(dict):
+ """Dictionary fixture exposing the ``Msg.id`` attribute contract."""
+
+ @property
+ def id(self) -> str:
+ """Return the fixture's message id."""
+ return self["id"]
+
+ def model_dump_json(self) -> str:
+ """Return stable JSON for changed-message detection."""
+ return json.dumps(self, sort_keys=True)
+
+
+class _FakeAgent:
+ """Finite-event realtime agent double."""
+
+ def __init__(self, message: object, event: Any | list[Any]) -> None:
+ context_message = (
+ _FakeMessage(message) if isinstance(message, dict) else message
+ )
+ self.state = SimpleNamespace(context=[context_message])
+ self.events = event if isinstance(event, list) else [event]
+
+ async def __aenter__(self) -> "_FakeAgent":
+ return self
+
+ async def __aexit__(self, *exc: object) -> None:
+ return None
+
+ async def reply_stream(
+ self,
+ transport: object,
+ ) -> AsyncIterator[Any]:
+ """Yield one event and complete."""
+ del transport
+ for event in self.events:
+ yield event
+
+ def checkpoint_snapshot(self, event: Any) -> object | None:
+ """Return state for the same boundaries as the real agent."""
+ if isinstance(
+ event,
+ (
+ ReplyEndEvent,
+ RequireUserConfirmEvent,
+ ToolResultEndEvent,
+ ),
+ ):
+ return self.state
+ return None
+
+
+class _FakeTransport:
+ """Idempotently closing transport double."""
+
+ def __init__(self) -> None:
+ self.closed = False
+ self.errors: list[str] = []
+
+ async def __aenter__(self) -> "_FakeTransport":
+ return self
+
+ async def __aexit__(self, *exc: object) -> None:
+ await self.close()
+
+ async def close(self) -> None:
+ """Mark the transport closed."""
+ self.closed = True
+
+ def send_error(self, detail: str) -> None:
+ """Record a session error."""
+ self.errors.append(detail)
+
+
+class _FakePeerConnection:
+ """Peer connection close double."""
+
+ def __init__(self) -> None:
+ self.closed = False
+
+ async def close(self) -> None:
+ """Mark the connection closed."""
+ self.closed = True
+
+
+class _FakeStorage:
+ """Record the complete persistence call sequence."""
+
+ def __init__(self) -> None:
+ self.calls: list[dict] = []
+ self.messages: dict[str, object] = {}
+
+ async def upsert_message(
+ self,
+ user_id: str,
+ session_id: str,
+ message: object,
+ ) -> None:
+ """Record one message write."""
+ message_id = (
+ message["id"]
+ if isinstance(message, dict)
+ else getattr(message, "id")
+ )
+ self.messages[message_id] = message
+ self.calls.append(
+ {
+ "method": "upsert_message",
+ "user_id": user_id,
+ "session_id": session_id,
+ "message": message,
+ },
+ )
+
+ async def delete_message(
+ self,
+ user_id: str,
+ session_id: str,
+ message_id: str,
+ ) -> bool:
+ """Delete and record one persisted message."""
+ deleted = self.messages.pop(message_id, None) is not None
+ self.calls.append(
+ {
+ "method": "delete_message",
+ "user_id": user_id,
+ "session_id": session_id,
+ "message_id": message_id,
+ },
+ )
+ return deleted
+
+ async def update_session_state(self, **kwargs: object) -> None:
+ """Record the state snapshot write."""
+ self.calls.append({"method": "update_session_state", **kwargs})
+
+
+class _LockAwareStorage(_FakeStorage):
+ """Record whether each state write holds the session run lock."""
+
+ def __init__(self, message_bus: "_FakeMessageBus") -> None:
+ super().__init__()
+ self._message_bus = message_bus
+ self.writes_under_session_lock: list[bool] = []
+
+ async def update_session_state(self, **kwargs: object) -> None:
+ """Record the lock state alongside the normal write."""
+ session_id = str(kwargs["session_id"])
+ self.writes_under_session_lock.append(
+ MessageBusKeys.session_lock(session_id)
+ in self._message_bus.held_locks,
+ )
+ await super().update_session_state(**kwargs)
+
+
+class _FakeMessageBus:
+ """Record lock, replay-log, and publication operations."""
+
+ def __init__(self, sequence_entries: bool = False) -> None:
+ self.calls: list[dict] = []
+ self.held_locks: set[str] = set()
+ self._sequence_entries = sequence_entries
+ self._entry_count = 0
+
+ @asynccontextmanager
+ async def acquire_lock(
+ self,
+ key: str,
+ *,
+ ttl_secs: int,
+ ) -> AsyncIterator[None]:
+ """Record the held lock around the runner."""
+ self.calls.append(
+ {"method": "acquire_lock", "key": key, "ttl_secs": ttl_secs},
+ )
+ self.held_locks.add(key)
+ try:
+ yield
+ finally:
+ self.held_locks.remove(key)
+
+ async def log_append(
+ self,
+ key: str,
+ event: dict,
+ *,
+ max_len: int,
+ ) -> str:
+ """Record an SSE replay event."""
+ self.calls.append(
+ {
+ "method": "log_append",
+ "key": key,
+ "event": event,
+ "max_len": max_len,
+ },
+ )
+ if self._sequence_entries:
+ self._entry_count += 1
+ return f"{self._entry_count}-0"
+ return "1-0"
+
+ async def publish(self, key: str, event: dict) -> None:
+ """Record one live SSE publication."""
+ self.calls.append({"method": "publish", "key": key, "event": event})
+
+ async def log_trim(
+ self,
+ key: str,
+ before_id: str | None = None,
+ ) -> None:
+ """Record replay-log cleanup."""
+ self.calls.append(
+ {
+ "method": "log_trim",
+ "key": key,
+ "before_id": before_id,
+ },
+ )
+
+ async def registry_set(
+ self,
+ namespace: str,
+ field: str,
+ value: str,
+ *,
+ ttl_secs: int | None = None,
+ ) -> None:
+ """Record one registry write."""
+ self.calls.append(
+ {
+ "method": "registry_set",
+ "namespace": namespace,
+ "field": field,
+ "value": value,
+ "ttl_secs": ttl_secs,
+ },
+ )
+
+ async def registry_drop(self, namespace: str) -> None:
+ """Record registry cleanup."""
+ self.calls.append(
+ {"method": "registry_drop", "namespace": namespace},
+ )
+
+
+class _BlockedMessageBus(_FakeMessageBus):
+ """Keep a session waiting before it can acquire the lock."""
+
+ @asynccontextmanager
+ async def acquire_lock(
+ self,
+ key: str,
+ *,
+ ttl_secs: int,
+ ) -> AsyncIterator[None]:
+ """Wait forever unless the session task is cancelled."""
+ self.calls.append(
+ {"method": "acquire_lock", "key": key, "ttl_secs": ttl_secs},
+ )
+ await asyncio.Event().wait()
+ yield
+
+
+def _make_session(
+ *,
+ agent_factory: Any,
+ storage: Any,
+ message_bus: Any,
+ on_closed: Callable[[WebRTCSession], None],
+ transport: Any | None = None,
+ peer_connection: Any | None = None,
+) -> WebRTCSession:
+ """Build a session with the shared test identity."""
+ return WebRTCSession(
+ peer_connection=peer_connection or _FakePeerConnection(),
+ transport=transport or _FakeTransport(),
+ agent_factory=agent_factory,
+ storage=storage,
+ message_bus=message_bus,
+ user_id="alice",
+ agent_id="agent-1",
+ session_id="session-1",
+ on_closed=on_closed,
+ )
+
+
+class WebRTCAudioTransportTest(unittest.IsolatedAsyncioTestCase):
+ """Verify complete control structures and decoded media."""
+
+ async def asyncSetUp(self) -> None:
+ self.channel = _FakeDataChannel()
+ self.transport = WebRTCAudioTransport(
+ input_sample_rate=16_000,
+ output_sample_rate=24_000,
+ )
+ self.transport.set_data_channel( # type: ignore[arg-type]
+ self.channel,
+ )
+ await self.transport.start()
+
+ async def asyncTearDown(self) -> None:
+ await self.transport.close()
+
+ async def test_audio_control_and_playout_protocol(self) -> None:
+ """Move media and full control payloads in both directions."""
+ pcm = np.full((2_400,), 2_000, dtype="<i2").tobytes()
+ await self.transport.send_audio(pcm, "item-1")
+ self.assertListEqual(
+ self.channel.sent,
+ [
+ {
+ "type": "audio_duration",
+ "item_id": "item-1",
+ "duration_ms": 100,
+ },
+ ],
+ )
+
+ output = await self.transport.output_track.recv()
+ self.assertDictEqual(
+ {
+ "sample_rate": output.sample_rate,
+ "samples": output.samples,
+ "pts": output.pts,
+ "time_base": output.time_base,
+ "has_audio": bool(np.any(output.to_ndarray())),
+ },
+ {
+ "sample_rate": 48_000,
+ "samples": 960,
+ "pts": 0,
+ "time_base": Fraction(1, 48_000),
+ "has_audio": True,
+ },
+ )
+ self.assertListEqual(
+ self.channel.sent,
+ [
+ {
+ "type": "audio_duration",
+ "item_id": "item-1",
+ "duration_ms": 100,
+ },
+ {
+ "type": "audio_start",
+ "item_id": "item-1",
+ "track_time_ms": 0,
+ },
+ ],
+ )
+
+ self.transport.set_input_track(_OneFrameAudioTrack())
+ incoming = self.transport.incoming()
+ audio = await anext(incoming)
+ self.assertIsInstance(audio, AudioFrame)
+ self.assertDictEqual(
+ {
+ "byte_length": len(audio.pcm),
+ "has_audio": bool(np.any(np.frombuffer(audio.pcm, "<i2"))),
+ },
+ {"byte_length": 608, "has_audio": True},
+ )
+
+ self.channel.emit_message(
+ {
+ "type": "control",
+ "control": "interrupt",
+ "data": {},
+ },
+ )
+ control = await anext(incoming)
+ self.assertDictEqual(
+ control.model_dump(mode="json"),
+ {"type": "interrupt", "data": {}},
+ )
+
+ confirm_data = {
+ "type": "USER_CONFIRM_RESULT",
+ "id": "confirm-event-1",
+ "created_at": "2026-01-01T00:00:00",
+ "reply_id": "reply-1",
+ "confirm_results": [],
+ }
+ self.channel.emit_message(
+ {
+ "type": "control",
+ "control": "user_confirm",
+ "data": confirm_data,
+ },
+ )
+ confirmation = await anext(incoming)
+ self.assertDictEqual(
+ confirmation.model_dump(mode="json"),
+ {"type": "user_confirm", "data": confirm_data},
+ )
+
+ clear_task = asyncio.create_task(self.transport.clear_audio())
+ while self.channel.sent[-1].get("type") != "clear_audio":
+ await asyncio.sleep(0)
+ clear_request = self.channel.sent[-1]
+ self.assertDictEqual(
+ {
+ "keys": set(clear_request),
+ "type": clear_request["type"],
+ "resume_track_time_ms": clear_request["resume_track_time_ms"],
+ },
+ {
+ "keys": {
+ "type",
+ "request_id",
+ "resume_track_time_ms",
+ },
+ "type": "clear_audio",
+ "resume_track_time_ms": 20,
+ },
+ )
+ self.channel.emit_message(
+ {
+ "type": "playout_cleared",
+ "request_id": clear_request["request_id"],
+ "item_id": "",
+ "played_ms": 125,
+ },
+ )
+ position = await clear_task
+ self.assertDictEqual(
+ self.transport.playout().model_dump(),
+ {
+ "item_id": "",
+ "played_ms": 0,
+ "first_played_at": None,
+ },
+ )
+
+ sent_after_clear = len(self.channel.sent)
+ await self.transport.send_audio(pcm, "item-1")
+ self.assertEqual(len(self.channel.sent), sent_after_clear)
+ await self.transport.send_audio(pcm, "item-2")
+ self.assertDictEqual(
+ self.channel.sent[-1],
+ {
+ "type": "audio_duration",
+ "item_id": "item-2",
+ "duration_ms": 100,
+ },
+ )
+ state_after_item_2 = {
+ "sent": self.channel.sent.copy(),
+ "audio_bytes": self.transport._audio_bytes.copy(),
+ "latest_item_id": self.transport._latest_item_id,
+ "blocked_item_id": self.transport._blocked_item_id,
+ }
+ await self.transport.send_audio(pcm, "item-1")
+ self.assertDictEqual(
+ {
+ "sent": self.channel.sent,
+ "audio_bytes": self.transport._audio_bytes,
+ "latest_item_id": self.transport._latest_item_id,
+ "blocked_item_id": self.transport._blocked_item_id,
+ },
+ state_after_item_2,
+ )
+ self.assertDictEqual(
+ {
+ "item_id": position.item_id,
+ "played_ms": position.played_ms,
+ "has_first_played_at": position.first_played_at is not None,
+ },
+ {
+ "item_id": "item-1",
+ "played_ms": 125,
+ "has_first_played_at": True,
+ },
+ )
+
+ async def test_audio_duration_discards_completed_item_counts(self) -> None:
+ """Only the current sequential output item keeps byte counts."""
+ pcm = np.full((2_400,), 2_000, dtype="<i2").tobytes()
+
+ await self.transport.send_audio(pcm, "item-1")
+ await self.transport.send_audio(pcm, "item-1")
+ await self.transport.send_audio(pcm, "item-2")
+
+ self.assertDictEqual(
+ {
+ "audio_bytes": self.transport._audio_bytes,
+ "latest_item_id": self.transport._latest_item_id,
+ "sent": self.channel.sent,
+ },
+ {
+ "audio_bytes": {"item-2": len(pcm)},
+ "latest_item_id": "item-2",
+ "sent": [
+ {
+ "type": "audio_duration",
+ "item_id": "item-1",
+ "duration_ms": 100,
+ },
+ {
+ "type": "audio_duration",
+ "item_id": "item-1",
+ "duration_ms": 200,
+ },
+ {
+ "type": "audio_duration",
+ "item_id": "item-2",
+ "duration_ms": 100,
+ },
+ ],
+ },
+ )
+
+ async def test_audio_queue_drops_only_the_oldest_audio(self) -> None:
+ """A stalled consumer keeps recent audio and every control frame."""
+ self.transport._max_queued_audio_frames = 2
+ self.transport._enqueue_incoming(AudioFrame(pcm=b"first"))
+ self.transport._enqueue_incoming(AudioFrame(pcm=b"second"))
+ self.channel.emit_message(
+ {
+ "type": "control",
+ "control": "interrupt",
+ "data": {},
+ },
+ )
+ self.transport._enqueue_incoming(AudioFrame(pcm=b"third"))
+
+ incoming = self.transport.incoming()
+ frames = [await anext(incoming) for _ in range(3)]
+ await incoming.aclose()
+
+ self.assertListEqual(
+ [
+ (
+ {"type": "audio", "pcm": frame.pcm}
+ if isinstance(frame, AudioFrame)
+ else frame.model_dump(mode="json")
+ )
+ for frame in frames
+ ],
+ [
+ {"type": "audio", "pcm": b"second"},
+ {"type": "interrupt", "data": {}},
+ {"type": "audio", "pcm": b"third"},
+ ],
+ )
+
+ async def test_late_clear_ack_does_not_reset_the_next_item(self) -> None:
+ """Ignore a timed-out clear acknowledgement from an old item."""
+ pcm = np.full((2_400,), 2_000, dtype="<i2").tobytes()
+ await self.transport.send_audio(pcm, "item-1")
+ await self.transport.output_track.recv()
+
+ with patch(
+ "agentscope.app._service._webrtc_audio_transport."
+ "_CLEAR_TIMEOUT_SECONDS",
+ 0,
+ ):
+ cleared = await self.transport.clear_audio()
+ clear_request = self.channel.sent[-1]
+
+ await self.transport.send_audio(pcm, "item-2")
+ await self.transport.output_track.recv()
+ before_late_ack = self.transport.playout()
+ self.channel.emit_message(
+ {
+ "type": "playout_cleared",
+ "request_id": clear_request["request_id"],
+ "item_id": "item-1",
+ "played_ms": 20,
+ },
+ )
+ await asyncio.sleep(0)
+
+ self.assertDictEqual(
+ {
+ "cleared": cleared.model_dump(),
+ "before_late_ack": before_late_ack.model_dump(),
+ "after_late_ack": self.transport.playout().model_dump(),
+ },
+ {
+ "cleared": {
+ "item_id": "item-1",
+ "played_ms": 0,
+ "first_played_at": None,
+ },
+ "before_late_ack": {
+ "item_id": "item-2",
+ "played_ms": 0,
+ "first_played_at": None,
+ },
+ "after_late_ack": {
+ "item_id": "item-2",
+ "played_ms": 0,
+ "first_played_at": None,
+ },
+ },
+ )
+
+ async def test_realtime_config_resolves_the_matching_adapter(self) -> None:
+ """The persisted adapter type selects the intended model class."""
+ access = AsyncMock()
+ access.resolve_credential.return_value = CredentialRecord(
+ user_id="alice",
+ data={
+ "type": "dashscope_credential",
+ "id": "credential-1",
+ "name": "DashScope",
+ "api_key": "secret",
+ },
+ )
+ model = await get_realtime_model(
+ "alice",
+ RealtimeModelConfig(
+ type="dashscope_audio_realtime",
+ credential_id="credential-1",
+ model="qwen-audio-3.0-realtime-flash",
+ parameters={"voice": "longxiaochun"},
+ ),
+ access,
+ )
+
+ self.assertIsInstance(model, DashScopeAudioRealtimeModel)
+ self.assertDictEqual(
+ {
+ "type": model.type,
+ "name": model.model,
+ "input_sample_rate": model.input_sample_rate,
+ "output_sample_rate": model.output_sample_rate,
+ "parameters": model.parameters.model_dump(),
+ },
+ {
+ "type": "dashscope_audio_realtime",
+ "name": "qwen-audio-3.0-realtime-flash",
+ "input_sample_rate": 16_000,
+ "output_sample_rate": 24_000,
+ "parameters": {
+ "voice": "longxiaochun",
+ "turn_detection": "server_vad",
+ "vad_threshold": 0.5,
+ "vad_silence_duration_ms": 800,
+ "voiceprint_audio_urls": [],
+ "max_history_turns": 20,
+ },
+ },
+ )
+ access.resolve_credential.assert_awaited_once_with(
+ "alice",
+ "credential-1",
+ )
+
+
+class RealtimeOfferTest(unittest.IsolatedAsyncioTestCase):
+ """Verify browser offer validation and resource ownership."""
+
+ def setUp(self) -> None:
+ self.config = SimpleNamespace(
+ parameters={"turn_detection": "server_vad"},
+ )
+ self.session = SimpleNamespace(
+ config=SimpleNamespace(realtime_model_config=self.config),
+ )
+ self.storage = SimpleNamespace(
+ get_session=AsyncMock(return_value=self.session),
+ )
+ self.access = SimpleNamespace(resolve_agent=AsyncMock())
+ self.connections: dict[tuple[str, str], object] = {}
+ self.request = SimpleNamespace(
+ app=SimpleNamespace(
+ state=SimpleNamespace(
+ realtime_connections=self.connections,
+ realtime_ice_servers=[],
+ ),
+ ),
+ )
+ self.message_bus = SimpleNamespace(
+ is_locked=AsyncMock(return_value=False),
+ )
+ self.realtime_service = SimpleNamespace(create_agent=AsyncMock())
+ self.model = SimpleNamespace(
+ input_sample_rate=16_000,
+ output_sample_rate=24_000,
+ )
+ self.peer = MagicMock()
+ self.peer.connectionState = "new"
+ self.peer.on.side_effect = lambda _: lambda callback: callback
+ self.peer.setRemoteDescription = AsyncMock()
+ self.peer.createAnswer = AsyncMock(
+ return_value=SimpleNamespace(sdp="answer", type="answer"),
+ )
+ self.peer.setLocalDescription = AsyncMock()
+ self.peer.localDescription = SimpleNamespace(
+ sdp="answer",
+ type="answer",
+ )
+ self.peer.close = AsyncMock()
+ self.transport = MagicMock()
+ self.transport.output_track = object()
+ self.transport.close = AsyncMock()
+ self.runner = MagicMock()
+ self.runner.wait_until_lock_acquired = AsyncMock(return_value=True)
+ self.runner.close = AsyncMock()
+
+ def _create_runner(**kwargs: object) -> MagicMock:
+ on_closed = cast(
+ Callable[[object], None],
+ kwargs["on_closed"],
+ )
+
+ async def _close() -> None:
+ on_closed(self.runner)
+
+ self.runner.close.side_effect = _close
+ return self.runner
+
+ self.runner_factory = MagicMock(side_effect=_create_runner)
+ self.patchers = [
+ patch(
+ "agentscope.app._router._realtime.get_realtime_model",
+ new=AsyncMock(return_value=self.model),
+ ),
+ patch("aiortc.RTCPeerConnection", return_value=self.peer),
+ patch(
+ "agentscope.app._service._webrtc_audio_transport."
+ "WebRTCAudioTransport",
+ return_value=self.transport,
+ ),
+ patch(
+ "agentscope.app._service._webrtc_session.WebRTCSession",
+ self.runner_factory,
+ ),
+ ]
+ self.get_model = self.patchers[0].start()
+ for patcher in self.patchers[1:]:
+ patcher.start()
+
+ def _stop_patchers() -> None:
+ for patcher in reversed(self.patchers):
+ patcher.stop()
+
+ self.addCleanup(_stop_patchers)
+
+ async def _offer(self) -> RealtimeOfferResponse:
+ """Create an offer using the shared browser fixtures."""
+ return await _create_realtime_offer(
+ session_id="session-1",
+ body=RealtimeOfferRequest(agent_id="agent-1", sdp="v=0"),
+ request=self.request,
+ user_id="alice",
+ storage=self.storage,
+ message_bus=self.message_bus,
+ access=self.access,
+ realtime_service=self.realtime_service,
+ )
+
+ async def test_browser_rejects_manual_turn_detection(self) -> None:
+ """Browser voice requires provider-owned turn detection."""
+ self.config.parameters["turn_detection"] = "none"
+
+ with self.assertRaises(HTTPException) as raised:
+ await self._offer()
+
+ self.assertDictEqual(
+ {
+ "status_code": raised.exception.status_code,
+ "detail": raised.exception.detail,
+ "model_calls": self.get_model.await_count,
+ },
+ {
+ "status_code": 409,
+ "detail": (
+ "Browser voice mode does not support "
+ "turn_detection='none'. Select provider turn detection."
+ ),
+ "model_calls": 0,
+ },
+ )
+
+ async def test_offer_replaces_the_previous_connection(self) -> None:
+ """A reconnect closes the previous local runner before reload."""
+ previous = SimpleNamespace(close=AsyncMock())
+ self.connections[("alice", "session-1")] = previous
+
+ response = await self._offer()
+
+ self.assertDictEqual(
+ {
+ "response": response.model_dump(),
+ "session_loads": self.storage.get_session.await_count,
+ "connection_is_new": (
+ self.connections[("alice", "session-1")] is self.runner
+ ),
+ "runner_started": self.runner.start.call_count,
+ },
+ {
+ "response": {"sdp": "answer", "type": "answer"},
+ "session_loads": 2,
+ "connection_is_new": True,
+ "runner_started": 1,
+ },
+ )
+ previous.close.assert_awaited_once_with()
+
+ async def test_negotiation_failure_closes_created_resources(self) -> None:
+ """A failed SDP negotiation closes both created resources."""
+ self.peer.createAnswer.side_effect = RuntimeError("bad offer")
+
+ with self.assertRaises(HTTPException) as raised:
+ await self._offer()
+
+ self.assertDictEqual(
+ {
+ "status_code": raised.exception.status_code,
+ "detail": raised.exception.detail,
+ "runner_created": self.runner_factory.call_count,
+ "connections": self.connections,
+ },
+ {
+ "status_code": 400,
+ "detail": "WebRTC negotiation failed: bad offer",
+ "runner_created": 0,
+ "connections": {},
+ },
+ )
+ self.transport.close.assert_awaited_once_with()
+ self.peer.close.assert_awaited_once_with()
+
+ async def test_lock_timeout_closes_runner_and_resources(self) -> None:
+ """A lost session-lock race returns 409 without leaking resources."""
+ self.runner.wait_until_lock_acquired.return_value = False
+
+ with self.assertRaises(HTTPException) as raised:
+ await self._offer()
+
+ self.assertDictEqual(
+ {
+ "status_code": raised.exception.status_code,
+ "detail": raised.exception.detail,
+ "connections": self.connections,
+ },
+ {
+ "status_code": 409,
+ "detail": "Session 'session-1' is already running.",
+ "connections": {},
+ },
+ )
+ self.runner.close.assert_awaited_once_with()
+ self.transport.close.assert_awaited_once_with()
+ self.peer.close.assert_awaited_once_with()
+
+
+class WebRTCSessionTest(unittest.IsolatedAsyncioTestCase):
+ """Verify that a WebRTC run keeps the normal session contract."""
+
+ async def test_request_close_owns_and_deduplicates_the_task(self) -> None:
+ """Synchronous callbacks share one retained asynchronous close."""
+ transport = _FakeTransport()
+ peer_connection = _FakePeerConnection()
+ storage = _FakeStorage()
+ message_bus = _FakeMessageBus()
+ closed_sessions: list[WebRTCSession] = []
+
+ async def _create_agent() -> _FakeAgent:
+ raise AssertionError(
+ "An unstarted session must not load an agent.",
+ )
+
+ session = _make_session(
+ peer_connection=peer_connection,
+ transport=transport,
+ agent_factory=_create_agent,
+ storage=storage,
+ message_bus=message_bus,
+ on_closed=closed_sessions.append,
+ )
+
+ session.request_close()
+ close_task = session._close_task
+ session.request_close()
+ if close_task is None:
+ self.fail("request_close() did not retain its task.")
+ await close_task
+
+ self.assertDictEqual(
+ {
+ "same_task": session._close_task is close_task,
+ "task_done": close_task.done(),
+ "transport_closed": transport.closed,
+ "peer_connection_closed": peer_connection.closed,
+ "storage_calls": storage.calls,
+ "message_bus_calls": message_bus.calls,
+ "closed_sessions": closed_sessions,
+ },
+ {
+ "same_task": True,
+ "task_done": True,
+ "transport_closed": True,
+ "peer_connection_closed": True,
+ "storage_calls": [],
+ "message_bus_calls": [],
+ "closed_sessions": [session],
+ },
+ )
+
+ async def test_run_publishes_persists_and_closes(self) -> None:
+ """Persist full agent state after publishing events to SSE."""
+ message = {"id": "message-1", "role": "assistant"}
+ event = ReplyEndEvent(
+ id="event-1",
+ created_at="2026-01-01T00:00:00",
+ session_id="session-1",
+ reply_id="message-1",
+ )
+ agent = _FakeAgent(message, event)
+ transport = _FakeTransport()
+ peer_connection = _FakePeerConnection()
+ message_bus = _FakeMessageBus()
+ storage = _LockAwareStorage(message_bus)
+ closed = asyncio.Event()
+ closed_sessions: list[WebRTCSession] = []
+
+ async def _create_agent() -> _FakeAgent:
+ message_bus.calls.append({"method": "agent_factory"})
+ return agent
+
+ def _on_closed(session: WebRTCSession) -> None:
+ closed_sessions.append(session)
+ closed.set()
+
+ session = _make_session(
+ peer_connection=peer_connection,
+ transport=transport,
+ agent_factory=_create_agent,
+ storage=storage,
+ message_bus=message_bus,
+ on_closed=_on_closed,
+ )
+ session.start()
+ await asyncio.wait_for(closed.wait(), timeout=1)
+ await session.close()
+
+ events_key = MessageBusKeys.session_events("session-1")
+ self.assertListEqual(
+ message_bus.calls,
+ [
+ {
+ "method": "acquire_lock",
+ "key": MessageBusKeys.session_lock("session-1"),
+ "ttl_secs": MessageBusKeys.SESSION_RUN_TTL_SECS,
+ },
+ {"method": "agent_factory"},
+ {
+ "method": "log_append",
+ "key": events_key,
+ "event": event.model_dump(mode="json"),
+ "max_len": MessageBusKeys.SESSION_REPLAY_MAX_LEN,
+ },
+ {
+ "method": "publish",
+ "key": events_key,
+ "event": {
+ **event.model_dump(mode="json"),
+ "_entry_id": "1-0",
+ },
+ },
+ {
+ "method": "acquire_lock",
+ "key": MessageBusKeys.session_event_checkpoint_lock(
+ "session-1",
+ ),
+ "ttl_secs": (
+ MessageBusKeys.SESSION_EVENT_CHECKPOINT_LOCK_TTL_SECS
+ ),
+ },
+ {
+ "method": "registry_set",
+ "namespace": (
+ MessageBusKeys.session_event_checkpoint(
+ "session-1",
+ )
+ ),
+ "field": MessageBusKeys.SESSION_EVENT_CURSOR_FIELD,
+ "value": "1-0",
+ "ttl_secs": None,
+ },
+ {
+ "method": "log_trim",
+ "key": events_key,
+ "before_id": "1-0",
+ },
+ {
+ "method": "acquire_lock",
+ "key": MessageBusKeys.session_event_checkpoint_lock(
+ "session-1",
+ ),
+ "ttl_secs": (
+ MessageBusKeys.SESSION_EVENT_CHECKPOINT_LOCK_TTL_SECS
+ ),
+ },
+ ],
+ )
+ self.assertListEqual(
+ storage.calls,
+ [
+ {
+ "method": "update_session_state",
+ "user_id": "alice",
+ "agent_id": "agent-1",
+ "session_id": "session-1",
+ "state": agent.state,
+ },
+ {
+ "method": "update_session_state",
+ "user_id": "alice",
+ "agent_id": "agent-1",
+ "session_id": "session-1",
+ "state": agent.state,
+ },
+ ],
+ )
+ self.assertDictEqual(
+ {
+ "transport_closed": transport.closed,
+ "peer_connection_closed": peer_connection.closed,
+ "transport_errors": transport.errors,
+ "closed_sessions": closed_sessions,
+ "writes_under_session_lock": (
+ storage.writes_under_session_lock
+ ),
+ },
+ {
+ "transport_closed": True,
+ "peer_connection_closed": True,
+ "transport_errors": [],
+ "closed_sessions": [session],
+ "writes_under_session_lock": [True, True],
+ },
+ )
+
+ async def test_delayed_user_transcript_holds_replay_cursor(self) -> None:
+ """Do not skip the user start while its transcript is pending."""
+ agent = _FakeAgent(
+ {"id": "user-1", "role": "user"},
+ [
+ ReplyStartEvent(
+ session_id="session-1",
+ reply_id="user-1",
+ name="user",
+ role="user",
+ ),
+ ReplyEndEvent(
+ session_id="session-1",
+ reply_id="assistant-1",
+ ),
+ TextBlockStartEvent(
+ reply_id="user-1",
+ block_id="text-1",
+ ),
+ TextBlockDeltaEvent(
+ reply_id="user-1",
+ block_id="text-1",
+ delta="hello",
+ ),
+ TextBlockEndEvent(
+ reply_id="user-1",
+ block_id="text-1",
+ ),
+ ReplyEndEvent(
+ session_id="session-1",
+ reply_id="user-1",
+ ),
+ ],
+ )
+ message_bus = _FakeMessageBus(sequence_entries=True)
+ storage = _FakeStorage()
+ closed = asyncio.Event()
+ session = _make_session(
+ agent_factory=AsyncMock(return_value=agent),
+ storage=storage,
+ message_bus=message_bus,
+ on_closed=lambda _: closed.set(),
+ )
+
+ session.start()
+ await asyncio.wait_for(closed.wait(), timeout=1)
+
+ self.assertListEqual(
+ [
+ call["value"]
+ for call in message_bus.calls
+ if call["method"] == "registry_set"
+ ],
+ ["6-0"],
+ )
+
+ async def test_checkpoint_deletes_message_removed_from_context(
+ self,
+ ) -> None:
+ """A later checkpoint removes a message no longer in context."""
+ message = {"id": "reply-1", "role": "assistant"}
+ agent = _FakeAgent(
+ message,
+ ReplyEndEvent(
+ session_id="session-1",
+ reply_id="reply-1",
+ ),
+ )
+ storage = _FakeStorage()
+ session = _make_session(
+ agent_factory=AsyncMock(),
+ storage=storage,
+ message_bus=_FakeMessageBus(),
+ on_closed=lambda _: None,
+ )
+ session.agent = agent # type: ignore[assignment]
+
+ await session._persist_state()
+ agent.state.context.clear()
+ await session._persist_state()
+
+ self.assertDictEqual(
+ {
+ "reloaded_messages": list(storage.messages.values()),
+ "storage_calls": storage.calls,
+ },
+ {
+ "reloaded_messages": [],
+ "storage_calls": [
+ {
+ "method": "upsert_message",
+ "user_id": "alice",
+ "session_id": "session-1",
+ "message": message,
+ },
+ {
+ "method": "update_session_state",
+ "user_id": "alice",
+ "agent_id": "agent-1",
+ "session_id": "session-1",
+ "state": agent.state,
+ },
+ {
+ "method": "update_session_state",
+ "user_id": "alice",
+ "agent_id": "agent-1",
+ "session_id": "session-1",
+ "state": agent.state,
+ },
+ {
+ "method": "delete_message",
+ "user_id": "alice",
+ "session_id": "session-1",
+ "message_id": "reply-1",
+ },
+ ],
+ },
+ )
+
+ async def test_pcm_events_are_not_published_to_session_events(
+ self,
+ ) -> None:
+ """WebRTC carries PCM without duplicating it over session SSE."""
+ message = {"id": "message-1", "role": "assistant"}
+ events = [
+ DataBlockStartEvent(
+ id="event-1",
+ created_at="2026-01-01T00:00:00",
+ reply_id="message-1",
+ block_id="audio-1",
+ media_type="audio/pcm;rate=24000",
+ ),
+ DataBlockDeltaEvent(
+ id="event-2",
+ created_at="2026-01-01T00:00:01",
+ reply_id="message-1",
+ block_id="audio-1",
+ data="AQA=",
+ media_type="audio/pcm;rate=24000",
+ ),
+ DataBlockEndEvent(
+ id="event-3",
+ created_at="2026-01-01T00:00:02",
+ reply_id="message-1",
+ block_id="audio-1",
+ ),
+ ]
+ agent = _FakeAgent(message, events)
+ transport = _FakeTransport()
+ peer_connection = _FakePeerConnection()
+ storage = _FakeStorage()
+ message_bus = _FakeMessageBus()
+ closed = asyncio.Event()
+
+ async def _create_agent() -> _FakeAgent:
+ message_bus.calls.append({"method": "agent_factory"})
+ return agent
+
+ session = _make_session(
+ peer_connection=peer_connection,
+ transport=transport,
+ agent_factory=_create_agent,
+ storage=storage,
+ message_bus=message_bus,
+ on_closed=lambda _: closed.set(),
+ )
+ session.start()
+ await asyncio.wait_for(closed.wait(), timeout=1)
+
+ self.assertListEqual(
+ message_bus.calls,
+ [
+ {
+ "method": "acquire_lock",
+ "key": MessageBusKeys.session_lock("session-1"),
+ "ttl_secs": MessageBusKeys.SESSION_RUN_TTL_SECS,
+ },
+ {"method": "agent_factory"},
+ {
+ "method": "acquire_lock",
+ "key": MessageBusKeys.session_event_checkpoint_lock(
+ "session-1",
+ ),
+ "ttl_secs": (
+ MessageBusKeys.SESSION_EVENT_CHECKPOINT_LOCK_TTL_SECS
+ ),
+ },
+ ],
+ )
+
+ async def test_close_cancels_a_runner_waiting_for_the_lock(self) -> None:
+ """A losing concurrent offer closes without waiting indefinitely."""
+ transport = _FakeTransport()
+ peer_connection = _FakePeerConnection()
+ storage = _FakeStorage()
+ message_bus = _BlockedMessageBus()
+ closed_sessions: list[WebRTCSession] = []
+
+ async def _create_agent() -> _FakeAgent:
+ raise AssertionError("The agent must not load without the lock.")
+
+ session = _make_session(
+ peer_connection=peer_connection,
+ transport=transport,
+ agent_factory=_create_agent,
+ storage=storage,
+ message_bus=message_bus,
+ on_closed=closed_sessions.append,
+ )
+ session.start()
+
+ acquired = await session.wait_until_lock_acquired(0.01)
+ await session.close()
+
+ self.assertDictEqual(
+ {
+ "acquired": acquired,
+ "message_bus_calls": message_bus.calls,
+ "storage_calls": storage.calls,
+ "transport_closed": transport.closed,
+ "peer_connection_closed": peer_connection.closed,
+ "closed_sessions": closed_sessions,
+ },
+ {
+ "acquired": False,
+ "message_bus_calls": [
+ {
+ "method": "acquire_lock",
+ "key": MessageBusKeys.session_lock("session-1"),
+ "ttl_secs": MessageBusKeys.SESSION_RUN_TTL_SECS,
+ },
+ ],
+ "storage_calls": [],
+ "transport_closed": True,
+ "peer_connection_closed": True,
+ "closed_sessions": [session],
+ },
+ )
+
+ async def test_checkpoint_boundaries_persist_state(self) -> None:
+ """Persist tool boundaries but not ordinary text block endings."""
+ message = {"id": "message-1", "role": "assistant"}
+ tool_call = ToolCallBlock(
+ id="call-1",
+ name="Read",
+ input='{"path":"README.md"}',
+ )
+ events = [
+ TextBlockEndEvent(
+ id="event-0",
+ created_at="2026-01-01T00:00:00",
+ reply_id="message-1",
+ block_id="block-1",
+ ),
+ RequireUserConfirmEvent(
+ id="event-1",
+ created_at="2026-01-01T00:00:01",
+ reply_id="message-1",
+ tool_calls=[tool_call],
+ ),
+ ToolResultEndEvent(
+ id="event-2",
+ created_at="2026-01-01T00:00:02",
+ reply_id="message-1",
+ tool_call_id="call-1",
+ state=ToolResultState.SUCCESS,
+ ),
+ ]
+ agent = _FakeAgent(message, events)
+ transport = _FakeTransport()
+ peer_connection = _FakePeerConnection()
+ storage = _FakeStorage()
+ message_bus = _FakeMessageBus()
+ closed = asyncio.Event()
+
+ async def _create_agent() -> _FakeAgent:
+ return agent
+
+ session = _make_session(
+ peer_connection=peer_connection,
+ transport=transport,
+ agent_factory=_create_agent,
+ storage=storage,
+ message_bus=message_bus,
+ on_closed=lambda _: closed.set(),
+ )
+ session.start()
+ await asyncio.wait_for(closed.wait(), timeout=1)
+
+ self.assertDictEqual(
+ {
+ "storage_methods": [call["method"] for call in storage.calls],
+ "published_event_types": [
+ call["event"]["type"]
+ for call in message_bus.calls
+ if call["method"] == "publish"
+ ],
+ "cursor_values": [
+ call["value"]
+ for call in message_bus.calls
+ if call["method"] == "registry_set"
+ ],
+ },
+ {
+ "storage_methods": ["update_session_state"] * 3,
+ "published_event_types": [event.type for event in events],
+ "cursor_values": ["1-0"] * 2,
+ },
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()