Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(channel): bind channel credentials interactively (#2484)
DavdGao180b409b870f
diff --git a/examples/web_ui/frontend/package.json b/examples/web_ui/frontend/package.jsonindex 86cc6e4dd..191252c55 100644--- a/examples/web_ui/frontend/package.json+++ b/examples/web_ui/frontend/package.json@@ -33,6 +33,7 @@"mime-types": "^3.0.2","next-themes": "^0.4.6","onborda": "^1.2.5",+ "qrcode.react": "^4.2.0","radix-ui": "^1.4.3","react": "^19.2.6","react-day-picker": "^10.0.1",diff --git a/examples/web_ui/frontend/src/api/channel.ts b/examples/web_ui/frontend/src/api/channel.tsindex cd5859bef..14e7ba188 100644--- a/examples/web_ui/frontend/src/api/channel.ts+++ b/examples/web_ui/frontend/src/api/channel.ts@@ -1,5 +1,6 @@import { client } from './client';import type {+ BindingView,ChannelChatIdsResponse,ChannelRecord,ChannelSessionsResponse,@@ -35,4 +36,18 @@ export const channelApi = {listChatIds: (channelId: string) =>client.get<ChannelChatIdsResponse>(`/channels/${channelId}/chat_ids`),++ startBinding: (channelType: string) =>+ client.post<BindingView>('/channels/bindings', { channel_type: channelType }),++ /** Report the session; this call is also what advances it. */+ pollBinding: (bindingId: string) => client.get<BindingView>(`/channels/bindings/${bindingId}`),++ cancelBinding: (bindingId: string, options?: { silent?: boolean }) =>+ client.post<{ status: string }>(+ `/channels/bindings/${bindingId}/cancel`,+ undefined,+ undefined,+ options,+ ),};diff --git a/examples/web_ui/frontend/src/api/types.ts b/examples/web_ui/frontend/src/api/types.tsindex 4c22daf9c..b9ed157ea 100644--- a/examples/web_ui/frontend/src/api/types.ts+++ b/examples/web_ui/frontend/src/api/types.ts@@ -1166,7 +1166,9 @@ export interface ChannelRecord {export interface CreateChannelRequest {channel_type: string;name?: string | null;- credentials: Record<string, unknown>;+ credentials?: Record<string, unknown>;+ /** Completed binding to take the credentials from, instead of sending them. */+ credential_binding_id?: string | null;platform_config?: Record<string, unknown>;routing: RoutingConfig;session: SessionSettings;@@ -1189,6 +1191,19 @@ export interface ChannelTypeSchema {credentials_schema: Record<string, unknown>;config_schema: Record<string, unknown>;platform_bot_id_field?: string;+ /** Whether the platform can hand its credentials over interactively. */+ supports_credential_binding?: boolean;+}++export type BindingState = 'pending' | 'authorized' | 'failed' | 'cancelled';++export interface BindingView {+ binding_id: string;+ state: BindingState;+ /** Where the operator must approve; rendered as a QR code. */+ verification_url: string;+ error: string;+ retry_after_secs: number;}export type ChannelState = 'stopped' | 'connecting' | 'retrying' | 'connected' | 'failed';diff --git a/examples/web_ui/frontend/src/i18n/locales/en.json b/examples/web_ui/frontend/src/i18n/locales/en.jsonindex d3fcbff43..7d574dc57 100644--- a/examples/web_ui/frontend/src/i18n/locales/en.json+++ b/examples/web_ui/frontend/src/i18n/locales/en.json@@ -668,6 +668,15 @@}},"channel": {+ "credentialBinding": {+ "tab": "Scan QR code",+ "manualTab": "Enter manually",+ "scanHint": "Scan with the platform app and approve to create the credentials.",+ "authorized": "Approved. Credentials are ready.",+ "failed": "The binding could not be completed.",+ "unsafeUrl": "The platform returned a link that cannot be shown safely.",+ "retry": "Try again"+ },"title": "Channels","subtitle": "Connect external platforms like Feishu and Discord so agents work in group chats","status": "Status",diff --git a/examples/web_ui/frontend/src/i18n/locales/zh.json b/examples/web_ui/frontend/src/i18n/locales/zh.jsonindex c13ec5196..8d4e4f33a 100644--- a/examples/web_ui/frontend/src/i18n/locales/zh.json+++ b/examples/web_ui/frontend/src/i18n/locales/zh.json@@ -668,6 +668,15 @@}},"channel": {+ "credentialBinding": {+ "tab": "扫码授权",+ "manualTab": "手动填写",+ "scanHint": "用平台 App 扫码并确认,凭据将自动生成。",+ "authorized": "已确认,凭据已就绪。",+ "failed": "授权未能完成。",+ "unsafeUrl": "平台返回的链接无法安全展示。",+ "retry": "重新生成"+ },"title": "频道","subtitle": "接入飞书、Discord 等外部平台,让智能体在群聊里工作","status": "状态",diff --git a/examples/web_ui/frontend/src/pages/channel/channel-form.tsx b/examples/web_ui/frontend/src/pages/channel/channel-form.tsxindex 9afb5ba84..3b0251948 100644--- a/examples/web_ui/frontend/src/pages/channel/channel-form.tsx+++ b/examples/web_ui/frontend/src/pages/channel/channel-form.tsx@@ -23,13 +23,19 @@ import {import { Input } from '@/components/ui/input';import { Separator } from '@/components/ui/separator';import { Switch } from '@/components/ui/switch';+import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';import { useAvailableModels } from '@/hooks/useAvailableModels';import { useTranslation } from '@/i18n/useI18n';import { BindingsEditor } from '@/pages/channel/bindings-editor';+import { CredentialBindingPanel } from '@/pages/channel/credential-binding-panel';export interface ChannelFormValue {channelType: string;name: string;+ /** How the credentials are being supplied on a create. */+ credentialMode: 'form' | 'binding';+ /** Set once an interactive binding has been approved. */+ credentialBindingId: string;credentials: Record<string, string>;platformConfig: Record<string, unknown>;bindings: ChannelBinding[];@@ -42,6 +48,8 @@ export function defaultChannelForm(agentId = ''): ChannelFormValue {return {channelType: 'feishu',name: '',+ credentialMode: 'form',+ credentialBindingId: '',credentials: {},platformConfig: {},bindings: [@@ -62,6 +70,8 @@ export function channelFormFromRecord(record: ChannelRecord): ChannelFormValue {return {channelType: record.channel_type,name: record.name ?? '',+ credentialMode: 'form',+ credentialBindingId: '',credentials: {},platformConfig: record.platform_config ?? {},bindings: record.routing.bindings,@@ -82,10 +92,16 @@ function sessionSettings(v: ChannelFormValue) {}export function toCreateRequest(v: ChannelFormValue): CreateChannelRequest {+ // A completed binding replaces the fields; the server takes the+ // credentials from it so they never travel through the browser.+ const credentials =+ v.credentialMode === 'binding'+ ? { credential_binding_id: v.credentialBindingId }+ : { credentials: v.credentials };return {channel_type: v.channelType,name: v.name.trim() || null,- credentials: v.credentials,+ ...credentials,platform_config: v.platformConfig,routing: { bindings: v.bindings },enabled: true,@@ -118,11 +134,33 @@ export function ChannelForm({ value, onChange, agents, channelTypes, mode }: Proconst set = <K extends keyof ChannelFormValue>(key: K, v: ChannelFormValue[K]) =>onChange({ ...value, [key]: v });+ // Read by the platform-change effect, which must not re-run just+ // because some unrelated field moved.+ const valueRef = React.useRef(value);+ React.useEffect(() => {+ valueRef.current = value;+ });+const typeSchema = React.useMemo(() => channelTypes.find((ct) => ct.channel_type === value.channelType),[channelTypes, value.channelType],);+ const bindingSupported = Boolean(typeSchema?.supports_credential_binding);++ // Switching platform invalidates whatever was collected for the old+ // one, and decides which path is even on offer.+ React.useEffect(() => {+ if (mode !== 'create') return;+ onChange({+ ...valueRef.current,+ credentialMode: bindingSupported ? 'binding' : 'form',+ credentialBindingId: '',+ credentials: {},+ });+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [value.channelType, bindingSupported]);+const credentialFields = React.useMemo(() => {const schema = typeSchema?.credentials_schema as| { properties?: Record<string, Record<string, unknown>>; required?: string[] }@@ -197,7 +235,37 @@ export function ChannelForm({ value, onChange, agents, channelTypes, mode }: Pro/></Field>+ {mode === 'create' && bindingSupported && (+ <Tabs+ value={value.credentialMode}+ onValueChange={(m) =>+ onChange({+ ...value,+ credentialMode: m as ChannelFormValue['credentialMode'],+ credentialBindingId: '',+ })+ }+ >+ <TabsList className="w-full">+ <TabsTrigger value="binding">+ {t('channel.credentialBinding.tab')}+ </TabsTrigger>+ <TabsTrigger value="form">+ {t('channel.credentialBinding.manualTab')}+ </TabsTrigger>+ </TabsList>+ </Tabs>+ )}++ {mode === 'create' && value.credentialMode === 'binding' && bindingSupported && (+ <CredentialBindingPanel+ channelType={value.channelType}+ onAuthorized={(bindingId) => set('credentialBindingId', bindingId)}+ />+ )}+{mode === 'create' &&+ value.credentialMode === 'form' &&credentialFields.map((field) => (<Field key={field.key}><FieldLabel>@@ -331,5 +399,7 @@ export function isChannelFormValid(v: ChannelFormValue, mode: 'create' | 'edit')if (v.bindings.length === 0) return false;if (v.bindings.some((b) => !b.agent_id)) return false;if (mode === 'create' && !v.channelType) return false;+ // An unfinished binding has no credentials to create the channel with.+ if (mode === 'create' && v.credentialMode === 'binding' && !v.credentialBindingId) return false;return true;}diff --git a/examples/web_ui/frontend/src/pages/channel/credential-binding-panel.tsx b/examples/web_ui/frontend/src/pages/channel/credential-binding-panel.tsxnew file mode 100644index 000000000..98cc56503--- /dev/null+++ b/examples/web_ui/frontend/src/pages/channel/credential-binding-panel.tsx@@ -0,0 +1,153 @@+import { CircleAlert, Loader2, RotateCcw } from 'lucide-react';+import { QRCodeSVG } from 'qrcode.react';+import * as React from 'react';++import { channelApi } from '@/api';+import type { BindingState } from '@/api';+import { Alert, AlertDescription } from '@/components/ui/alert';+import { Button } from '@/components/ui/button';+import { useTranslation } from '@/i18n/useI18n';++interface Props {+ channelType: string;+ /** Handed the binding id once the operator has approved it. */+ onAuthorized: (bindingId: string) => void;+}++/** Only ever render a code the platform served over https. */+function isSafeVerificationUrl(value: string): boolean {+ try {+ return new URL(value).protocol === 'https:';+ } catch {+ return false;+ }+}++/**+ * Open a credential binding and show its QR code until approved.+ *+ * The polling here is not just a status read — it is what advances the+ * session server-side, so it must keep going until the state is terminal.+ */+export function CredentialBindingPanel({ channelType, onAuthorized }: Props) {+ const { t } = useTranslation();+ const [state, setState] = React.useState<BindingState | 'starting'>('starting');+ const [url, setUrl] = React.useState('');+ const [error, setError] = React.useState('');+ const [attempt, setAttempt] = React.useState(0);++ // Kept in a ref so a new callback identity does not restart the session.+ const onAuthorizedRef = React.useRef(onAuthorized);+ React.useEffect(() => {+ onAuthorizedRef.current = onAuthorized;+ }, [onAuthorized]);++ React.useEffect(() => {+ let cancelled = false;+ let bindingId = '';+ let timer: ReturnType<typeof setTimeout> | undefined;++ const poll = async () => {+ try {+ const view = await channelApi.pollBinding(bindingId);+ if (cancelled) return;+ setState(view.state);+ if (view.state === 'authorized') {+ onAuthorizedRef.current(view.binding_id);+ return;+ }+ if (view.state !== 'pending') {+ setError(view.error);+ return;+ }+ timer = setTimeout(poll, 1500);+ } catch (e) {+ if (cancelled) return;+ setState('failed');+ setError(e instanceof Error ? e.message : String(e));+ }+ };++ setState('starting');+ setError('');+ setUrl('');+ channelApi+ .startBinding(channelType)+ .then((view) => {+ if (cancelled) {+ void channelApi+ .cancelBinding(view.binding_id, { silent: true })+ .catch(() => {});+ return;+ }+ bindingId = view.binding_id;+ setState(view.state);+ if (view.state !== 'pending') {+ setError(view.error);+ return;+ }+ setUrl(view.verification_url);+ timer = setTimeout(poll, 1000);+ })+ .catch((e) => {+ if (cancelled) return;+ setState('failed');+ setError(e instanceof Error ? e.message : String(e));+ });++ return () => {+ cancelled = true;+ if (timer) clearTimeout(timer);+ // Abandoning the dialog abandons the session, rather than+ // leaving credentials claimable until the TTL runs out.+ // Best effort: the create request may already have consumed it.+ if (bindingId)+ void channelApi.cancelBinding(bindingId, { silent: true }).catch(() => {});+ };+ }, [channelType, attempt]);++ const showable = url && isSafeVerificationUrl(url);++ return (+ <div className="flex flex-col items-center gap-3 rounded-md border p-6">+ {state === 'starting' && <Loader2 className="size-6 animate-spin opacity-60" />}++ {showable && (+ <>+ <div className="rounded-md bg-white p-3">+ <QRCodeSVG value={url} size={168} />+ </div>+ <p className="text-muted-foreground text-center text-xs">+ {t('channel.credentialBinding.scanHint')}+ </p>+ </>+ )}++ {url && !showable && (+ <Alert variant="destructive">+ <CircleAlert />+ <AlertDescription>{t('channel.credentialBinding.unsafeUrl')}</AlertDescription>+ </Alert>+ )}++ {state === 'authorized' && (+ <p className="text-sm">{t('channel.credentialBinding.authorized')}</p>+ )}++ {(state === 'failed' || state === 'cancelled') && (+ <>+ <Alert variant="destructive">+ <CircleAlert />+ <AlertDescription>+ {error || t('channel.credentialBinding.failed')}+ </AlertDescription>+ </Alert>+ <Button variant="outline" size="sm" onClick={() => setAttempt((n) => n + 1)}>+ <RotateCcw className="size-3.5" />+ {t('channel.credentialBinding.retry')}+ </Button>+ </>+ )}+ </div>+ );+}diff --git a/examples/web_ui/pnpm-lock.yaml b/examples/web_ui/pnpm-lock.yamlindex ac7fd5830..6b81501ec 100644--- a/examples/web_ui/pnpm-lock.yaml+++ b/examples/web_ui/pnpm-lock.yaml@@ -123,6 +123,9 @@ importers:onborda:specifier: ^1.2.5version: 1.2.5(@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected](@babel/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ qrcode.react:+ specifier: ^4.2.0+ version: 4.2.0([email protected])radix-ui:specifier: ^1.4.3version: 1.4.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])@@ -4215,6 +4218,11 @@ packages:resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}engines: {node: '>=6'}+ resolution: {integrity: sha512-QpgqWi8rD9DsS9EP3z7BT+5lY5SFhsqGjpgW5DY/i3mK4M9DTBNz3ErMi8BWYEfI3L0d8GIbGmcdFAS1uIRGjA==}+ peerDependencies:+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0+resolution: {integrity: sha512-6YHEFRL9mfgcAvql/XhwTvf5jKcOiiupt2FiJxHkiX1z4j7WL8J/jRHYLluORvc1XxB5rV20KoeK00gVJamspg==}engines: {node: '>=0.6'}@@ -9416,6 +9424,10 @@ snapshots:+ dependencies:+ react: 19.2.6+dependencies:side-channel: 1.1.0diff --git a/src/agentscope/app/_lifespan.py b/src/agentscope/app/_lifespan.pyindex 94023df8b..779e08c83 100644--- a/src/agentscope/app/_lifespan.py+++ b/src/agentscope/app/_lifespan.py@@ -14,6 +14,7 @@ from ._manager import ()from ._service import (ChannelService,+ CredentialBindingService,ChatService,IndexSweeper,IndexTaskConsumer,@@ -137,6 +138,12 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:message_bus=message_bus,type_registry=channel_type_registry,)+ # Binding sessions live in the bus and hold no connection,+ # so this is available wherever the channel API is.+ app.state.credential_binding_service = CredentialBindingService(+ message_bus=message_bus,+ type_registry=channel_type_registry,+ )# The dispatcher is what holds the long connections, so a# deployment that runs dedicated channel workers turns it# off here and every replica stays connection-free.diff --git a/src/agentscope/app/_router/_channel.py b/src/agentscope/app/_router/_channel.pyindex 338d1295a..3a2aa58d3 100644--- a/src/agentscope/app/_router/_channel.py+++ b/src/agentscope/app/_router/_channel.py@@ -2,6 +2,9 @@"""Channel HTTP API.GET /channels/types List channel types + schemas+ POST /channels/bindings Open a credential binding+ GET /channels/bindings/{id} Poll it, advancing one step+ POST /channels/bindings/{id}/cancel Abandon itGET /channels/ List the user's channelsPOST /channels/ Create a channelGET /channels/{id} Channel details@@ -21,9 +24,15 @@ from ..channel import (ChannelTypeRegistry,ChannelTypeSchema,)-from .._service import ChannelService+from .._service import (+ ChannelService,+ CredentialBindingError,+ CredentialBindingService,+)+from .._service._credential_binding import BindingViewfrom ..deps import (get_channel_clients,+ get_credential_binding_service,get_channel_service,get_channel_type_registry,get_current_user_id,@@ -37,6 +46,7 @@ from ._schema import (ChannelResponse,ChannelSessionsResponse,CreateChannelRequest,+ StartCredentialBindingRequest,UpdateChannelRequest,)@@ -130,15 +140,29 @@ async def create_channel(body: CreateChannelRequest,service: ChannelService = Depends(get_channel_service),registry: ChannelTypeRegistry = Depends(get_channel_type_registry),+ bindings: CredentialBindingService = Depends(+ get_credential_binding_service,+ ),user_id: str = Depends(get_current_user_id),) -> ChannelResponse:- """Create a channel."""+ """Create a channel, from a completed binding or from the body."""+ credentials = body.credentials+ if body.credential_binding_id:+ try:+ credentials = await bindings.claim(+ user_id,+ body.credential_binding_id,+ body.channel_type,+ )+ except CredentialBindingError as e:+ raise HTTPException(e.status_code, str(e)) from e+try:record = await service.create(user_id=user_id,channel_type=body.channel_type,name=body.name,- credentials=body.credentials,+ credentials=credentials,platform_config=body.platform_config,routing=body.routing,session=body.session,@@ -151,6 +175,60 @@ async def create_channel(return _to_response(record, registry)+@channel_router.post("/bindings", response_model=BindingView)+async def start_credential_binding(+ body: StartCredentialBindingRequest,+ bindings: CredentialBindingService = Depends(+ get_credential_binding_service,+ ),+ user_id: str = Depends(get_current_user_id),+) -> BindingView:+ """Open a session and return the URL the operator must approve.++ Returns immediately; the client polls for the outcome, and each poll+ is what advances the session.+ """+ try:+ return await bindings.start(user_id, body.channel_type)+ except CredentialBindingError as e:+ raise HTTPException(e.status_code, str(e)) from e+++@channel_router.get("/bindings/{binding_id}", response_model=BindingView)+async def poll_credential_binding(+ binding_id: str,+ bindings: CredentialBindingService = Depends(+ get_credential_binding_service,+ ),+ user_id: str = Depends(get_current_user_id),+) -> BindingView:+ """Report the session, asking the platform once when due.++ Never returns the credentials themselves — those are handed over+ only by creating a channel with this ``binding_id``.+ """+ try:+ return await bindings.poll(user_id, binding_id)+ except CredentialBindingError as e:+ raise HTTPException(e.status_code, str(e)) from e+++@channel_router.post("/bindings/{binding_id}/cancel")+async def cancel_credential_binding(+ binding_id: str,+ bindings: CredentialBindingService = Depends(+ get_credential_binding_service,+ ),+ user_id: str = Depends(get_current_user_id),+) -> ChannelActionResponse:+ """Abandon the session, from whichever replica takes this call."""+ try:+ await bindings.cancel(user_id, binding_id)+ except CredentialBindingError as e:+ raise HTTPException(e.status_code, str(e)) from e+ return ChannelActionResponse(status="cancelled")++@channel_router.get("/{channel_id}")async def get_channel(channel_id: str,diff --git a/src/agentscope/app/_router/_schema/__init__.py b/src/agentscope/app/_router/_schema/__init__.pyindex 07de4b6a5..5bb04b786 100644--- a/src/agentscope/app/_router/_schema/__init__.py+++ b/src/agentscope/app/_router/_schema/__init__.py@@ -2,6 +2,7 @@"""Schema models for the agent service."""from ._channel import (+ StartCredentialBindingRequest,ChannelActionResponse,ChannelChatId,ChannelChatIdsResponse,@@ -123,6 +124,7 @@ __all__ = ["ChannelResponse","ChannelSessionsResponse","CreateChannelRequest",+ "StartCredentialBindingRequest","UpdateChannelRequest",# Chat"ChatRequest",diff --git a/src/agentscope/app/_router/_schema/_channel.py b/src/agentscope/app/_router/_schema/_channel.pyindex 4c17dad81..077a9e875 100644--- a/src/agentscope/app/_router/_schema/_channel.py+++ b/src/agentscope/app/_router/_schema/_channel.py@@ -19,7 +19,16 @@ class CreateChannelRequest(BaseModel):default=None,description="Optional display name.",)- credentials: dict = Field(description="Platform credentials.")+ credentials: dict = Field(+ default_factory=dict,+ description="Platform credentials. Omit when "+ "``credential_binding_id`` supplies them.",+ )+ credential_binding_id: str | None = Field(+ default=None,+ description="Completed credential-binding session to take the "+ "credentials from, instead of passing them here.",+ )platform_config: dict = Field(default_factory=dict,description="Non-secret platform options.",@@ -80,3 +89,9 @@ class ChannelChatIdsResponse(BaseModel):"""Chats available for routing configuration."""chats: list[ChannelChatId] = Field(default_factory=list)+++class StartCredentialBindingRequest(BaseModel):+ """Request body for opening a credential-binding session."""++ channel_type: str = Field(description="Channel type id, e.g. 'feishu'.")diff --git a/src/agentscope/app/_service/__init__.py b/src/agentscope/app/_service/__init__.pyindex a1ce68f15..060cfc2f0 100644--- a/src/agentscope/app/_service/__init__.py+++ b/src/agentscope/app/_service/__init__.py@@ -8,6 +8,10 @@ from ._access import (ResourceAccessService,)from ._channel import ChannelService+from ._credential_binding import (+ CredentialBindingError,+ CredentialBindingService,+)from ._chat import ChatServicefrom ._embedding import get_embedding_modelfrom ._index_sweeper import IndexSweeper@@ -27,6 +31,8 @@ from ._workspace import GitStatus, WorkspaceService, WorkspaceStatus__all__ = ["AgentView","ChannelService",+ "CredentialBindingService",+ "CredentialBindingError","ChatService","CredentialView","GitStatus",diff --git a/src/agentscope/app/_service/_credential_binding.py b/src/agentscope/app/_service/_credential_binding.pynew file mode 100644index 000000000..7af09f27e--- /dev/null+++ b/src/agentscope/app/_service/_credential_binding.py@@ -0,0 +1,361 @@+# -*- coding: utf-8 -*-+"""Drive channel credential-binding sessions from any replica.++A binding session outlives the request that opened it but not by much,+and its steps are spread across whichever replicas the operator's client+happens to reach. So the session lives entirely in the message bus and+this service keeps nothing: every method reads the record, does one+thing, and writes it back under compare-and-set.++That is also why there is no background task polling the platform. The+client already polls us for the session's status, so that request is+what advances it — nothing outlives it, nothing needs an owner, and a+replica dying mid-session costs the operator one retry.+"""+import json+import secrets+import time+from typing import Any++from pydantic import BaseModel, Field++from .._bus_ops import MessageBusKeys+from ..channel import BindingState, ChannelTypeRegistry+from ..message_bus import MessageBus+++class BindingSession(BaseModel):+ """One credential-binding session, as stored in the bus.++ Holds the platform's credentials once obtained. They are in the+ clear, as they are in :class:`~agentscope.app.storage.ChannelRecord`+ once the channel exists — at-rest encryption is a future hook for+ both. Here the exposure is bounded by+ :attr:`MessageBusKeys.CREDENTIAL_BINDING_CLAIM_TTL_SECS` and by+ being claimable only once.+ """++ user_id: str+ channel_type: str+ state: BindingState = BindingState.PENDING+ verification_url: str = ""+ error: str = ""+ credentials: dict[str, Any] = Field(default_factory=dict)+ provider_state: dict[str, Any] = Field(default_factory=dict)+ retry_after_secs: int = 5+ last_stepped_at: float = 0.0+++class BindingView(BaseModel):+ """What a client is allowed to see while a session is open."""++ binding_id: str+ state: BindingState+ verification_url: str = ""+ error: str = ""+ retry_after_secs: int = 5+++class CredentialBindingError(Exception):+ """A binding request that maps onto an HTTP status."""++ def __init__(self, message: str, status_code: int = 400) -> None:+ """Carry the status the router should answer with.++ Args:+ message (`str`): Operator-facing detail.+ status_code (`int`, defaults to ``400``): HTTP status.+ """+ super().__init__(message)+ self.status_code = status_code+++class CredentialBindingService:+ """Open, advance, and claim credential-binding sessions."""++ def __init__(+ self,+ message_bus: MessageBus,+ type_registry: ChannelTypeRegistry,+ ) -> None:+ """Bind the dependencies; the service holds no session state.++ Args:+ message_bus (`MessageBus`):+ Where sessions live, so any replica can serve any step.+ type_registry (`ChannelTypeRegistry`):+ Resolves a channel type to its binding provider.+ """+ self._bus = message_bus+ self._types = type_registry++ async def start(self, user_id: str, channel_type: str) -> BindingView:+ """Open a session and return where the operator must go.++ Args:+ user_id (`str`): The operator; only they may drive it.+ channel_type (`str`): The platform to bind.++ Returns:+ `BindingView`: The new session.++ Raises:+ `CredentialBindingError`: The type is unknown or offers no+ interactive binding.+ """+ provider = self._provider(channel_type)+ step = await provider.begin()++ session = BindingSession(+ user_id=user_id,+ channel_type=channel_type,+ state=step.state,+ verification_url=step.verification_url,+ error=step.error,+ credentials=step.credentials,+ provider_state=step.provider_state,+ retry_after_secs=(+ 5 if step.retry_after_secs is None else step.retry_after_secs+ ),+ )+ binding_id = secrets.token_urlsafe(24)+ await self._bus.registry_set(+ MessageBusKeys.channel_credential_binding(binding_id),+ MessageBusKeys.CREDENTIAL_BINDING_FIELD,+ session.model_dump_json(),+ ttl_secs=step.expires_in_secs,+ )+ return self._view(binding_id, session)++ async def poll(self, user_id: str, binding_id: str) -> BindingView:+ """Report the session, advancing it by one step when due.++ Args:+ user_id (`str`): Must own the session.+ binding_id (`str`): The session to report.++ Returns:+ `BindingView`: The session's state after this call.++ Raises:+ `CredentialBindingError`: Unknown session (404) or not the+ caller's (403).+ """+ raw, session = await self._load(user_id, binding_id)++ # Terminal, or asked again sooner than the platform allows: the+ # stored record is already the answer.+ if session.state.is_terminal or (+ time.time() - session.last_stepped_at < session.retry_after_secs+ ):+ return self._view(binding_id, session)++ # Claim the upstream call before making it. Two replicas polled+ # at once would otherwise both pass the check above and both ask+ # the platform, doubling a rate the platform sets.+ session.last_stepped_at = time.time()+ reserved = session.model_dump_json()+ if not await self._bus.registry_set_if(+ MessageBusKeys.channel_credential_binding(binding_id),+ MessageBusKeys.CREDENTIAL_BINDING_FIELD,+ reserved,+ expected=raw,+ ):+ _, session = await self._load(user_id, binding_id)+ return self._view(binding_id, session)++ step = await self._provider(session.channel_type).advance(+ session.provider_state,+ )+ session.state = step.state+ session.error = step.error+ session.credentials = step.credentials or session.credentials+ session.provider_state = step.provider_state or session.provider_state+ if step.retry_after_secs is not None:+ session.retry_after_secs = step.retry_after_secs++ # A losing write means the operator cancelled while we were+ # asking the platform. Drop this result rather than reviving it.+ if not await self._bus.registry_set_if(+ MessageBusKeys.channel_credential_binding(binding_id),+ MessageBusKeys.CREDENTIAL_BINDING_FIELD,+ session.model_dump_json(),+ expected=reserved,+ ttl_secs=(+ MessageBusKeys.CREDENTIAL_BINDING_CLAIM_TTL_SECS+ if session.state is BindingState.AUTHORIZED+ else None+ ),+ ):+ _, session = await self._load(user_id, binding_id)++ return self._view(binding_id, session)++ async def cancel(self, user_id: str, binding_id: str) -> None:+ """Abandon a session from whichever replica took the request.++ Args:+ user_id (`str`): Must own the session.+ binding_id (`str`): The session to abandon.++ Idempotent: a session that no longer exists is already in the+ state this asks for.+ """+ while True:+ try:+ raw, session = await self._load(user_id, binding_id)+ except CredentialBindingError:+ # Already claimed, expired, or never ours. Cancelling is+ # asking for it to be gone, and it is — the common case+ # is the create request having consumed it moments ago.+ return++ # Approved but unclaimed: the operator walked away from+ # credentials that would otherwise stay claimable until the+ # TTL. Take them off the record instead of leaving them.+ if session.state is BindingState.AUTHORIZED:+ await self._bus.registry_pop(+ MessageBusKeys.channel_credential_binding(binding_id),+ MessageBusKeys.CREDENTIAL_BINDING_FIELD,+ )+ return++ if session.state.is_terminal:+ return++ session.state = BindingState.CANCELLED+ session.credentials = {}+ # Losing means a poll wrote first; re-read and insist, or+ # this would report success on a session that stays live.+ if await self._bus.registry_set_if(+ MessageBusKeys.channel_credential_binding(binding_id),+ MessageBusKeys.CREDENTIAL_BINDING_FIELD,+ session.model_dump_json(),+ expected=raw,+ ):+ return++ async def claim(+ self,+ user_id: str,+ binding_id: str,+ channel_type: str,+ ) -> dict[str, Any]:+ """Take the credentials, consuming the session.++ Args:+ user_id (`str`): Must own the session.+ binding_id (`str`): The session to claim.+ channel_type (`str`): The type the channel is being created+ as; must match what was bound.++ Returns:+ `dict[str, Any]`: The platform credentials.++ Raises:+ `CredentialBindingError`: Unknown, not the caller's, for a+ different type, or not authorized yet.+ """+ # Check before taking: a pop first would let anyone holding an+ # id destroy someone else's session, and would burn the+ # operator's own on a mismatched type or an early claim.+ _, session = await self._load(user_id, binding_id)+ if session.channel_type != channel_type:+ raise CredentialBindingError(+ f"Binding is for channel type '{session.channel_type}'.",+ 409,+ )+ if session.state is not BindingState.AUTHORIZED:+ raise CredentialBindingError(+ f"Binding is {session.state.value}, not authorized.",+ 409,+ )++ # ``AUTHORIZED`` is terminal, so the record cannot have changed+ # underneath — but two create requests can still race here, and+ # only the one that takes it gets the credentials.+ raw = await self._bus.registry_pop(+ MessageBusKeys.channel_credential_binding(binding_id),+ MessageBusKeys.CREDENTIAL_BINDING_FIELD,+ )+ if raw is None:+ raise CredentialBindingError("Binding not found.", 404)+ return BindingSession.model_validate(json.loads(raw)).credentials++ def _provider(self, channel_type: str) -> Any:+ """Resolve a channel type's binding provider.++ Args:+ channel_type (`str`): The platform type.++ Returns:+ `CredentialBindingBase`: Its provider.++ Raises:+ `CredentialBindingError`: Unknown type, or one that only+ supports pasting credentials in.+ """+ channel_cls = self._types.get(channel_type)+ if channel_cls is None:+ raise CredentialBindingError(+ f"Channel type '{channel_type}' is not registered.",+ 404,+ )+ if channel_cls.credential_binding is None:+ raise CredentialBindingError(+ f"Channel type '{channel_type}' has no interactive "+ f"credential binding.",+ 400,+ )+ return channel_cls.credential_binding()++ async def _load(+ self,+ user_id: str,+ binding_id: str,+ ) -> tuple[str, BindingSession]:+ """Read a session, returning the raw value for compare-and-set.++ Args:+ user_id (`str`): The caller.+ binding_id (`str`): The session to read.++ Returns:+ `tuple[str, BindingSession]`: The stored string and its+ parsed form.++ Raises:+ `CredentialBindingError`: Absent, expired, or another+ user's — all reported as 404 so a session id cannot be+ probed.+ """+ raw = await self._bus.registry_get(+ MessageBusKeys.channel_credential_binding(binding_id),+ MessageBusKeys.CREDENTIAL_BINDING_FIELD,+ )+ if raw is None:+ raise CredentialBindingError("Binding not found.", 404)++ session = BindingSession.model_validate(json.loads(raw))+ if session.user_id != user_id:+ raise CredentialBindingError("Binding not found.", 404)+ return raw, session++ @staticmethod+ def _view(binding_id: str, session: BindingSession) -> BindingView:+ """Strip a session down to what a client may see.++ Args:+ binding_id (`str`): The session id.+ session (`BindingSession`): The stored session.++ Returns:+ `BindingView`: Without credentials or provider state.+ """+ return BindingView(+ binding_id=binding_id,+ state=session.state,+ verification_url=session.verification_url,+ error=session.error,+ retry_after_secs=session.retry_after_secs,+ )diff --git a/src/agentscope/app/channel/__init__.py b/src/agentscope/app/channel/__init__.pyindex c17b7ffc5..4a5f5de38 100644--- a/src/agentscope/app/channel/__init__.py+++ b/src/agentscope/app/channel/__init__.py@@ -21,6 +21,11 @@ from ._clients import ChannelClientsfrom ._dispatcher import ChannelLifecycleDispatcherfrom ._errors import ChannelErrorfrom ._gateway import ChannelGateway+from ._credential_binding import (+ BindingState,+ BindingStep,+ CredentialBindingBase,+)from ._registry import ChannelTypeRegistry, ChannelTypeSchemafrom ._dingtalk import DingTalkChannelfrom ._discord import DiscordChannel@@ -39,6 +44,9 @@ __all__ = ["ChannelGateway","ChannelLifecycleDispatcher","ChannelTypeRegistry",+ "BindingState",+ "BindingStep",+ "CredentialBindingBase","ChannelTypeSchema","DingTalkChannel","DiscordChannel",diff --git a/src/agentscope/app/channel/_base.py b/src/agentscope/app/channel/_base.pyindex 2f9db46a0..15ea1f363 100644--- a/src/agentscope/app/channel/_base.py+++ b/src/agentscope/app/channel/_base.py@@ -33,6 +33,7 @@ from ...message import (from ...types import ReplyFinishedReasonif TYPE_CHECKING:+ from ._credential_binding import CredentialBindingBasefrom ...tool import ToolBasefrom ...workspace import WorkspaceBase@@ -254,6 +255,11 @@ class ChannelBase(ABC):"""Non-secret per-channel behaviour switches. Subclasses override;left empty when the platform exposes no options."""+ credential_binding: type["CredentialBindingBase"] | None = None+ """Provider letting an operator hand over credentials out of band+ (scan a QR code, approve a consent screen) instead of pasting them.+ Left ``None`` by platforms that only support the form."""+def __init__(self,channel_id: str,diff --git a/src/agentscope/app/channel/_credential_binding.py b/src/agentscope/app/channel/_credential_binding.pynew file mode 100644index 000000000..4d0502e29--- /dev/null+++ b/src/agentscope/app/channel/_credential_binding.py@@ -0,0 +1,114 @@+# -*- coding: utf-8 -*-+"""Interactive credential acquisition for a channel type.++Most platforms let an operator hand their credentials over out of band —+scanning a QR code, approving a consent screen — instead of pasting an+app secret into a form. What they have in common is a session: it opens,+the operator acts on another device, and it ends with the same+:class:`~agentscope.app.channel.ChannelBase.Credentials` the form would+have produced.++The service drives that session one step at a time and keeps every step's+state in the message bus, so any replica can serve any request. A+provider therefore holds **no** state of its own: whatever it needs+between steps it returns as ``provider_state``, and receives back on the+next call.+"""+from enum import Enum+from typing import Any++from pydantic import BaseModel, Field+++class BindingState(str, Enum):+ """Where a binding session is in its lifecycle."""++ PENDING = "pending"+ """Opened, waiting for the operator to act."""++ AUTHORIZED = "authorized"+ """Credentials obtained, waiting to be claimed."""++ FAILED = "failed"+ """The platform refused or the session expired."""++ CANCELLED = "cancelled"+ """Abandoned by the operator."""++ @property+ def is_terminal(self) -> bool:+ """Whether no further step can move this session."""+ return self in (+ BindingState.AUTHORIZED,+ BindingState.FAILED,+ BindingState.CANCELLED,+ )+++class BindingStep(BaseModel):+ """What one call to a provider produced."""++ state: BindingState = BindingState.PENDING+ """The session's state after this step."""++ verification_url: str = ""+ """Where the operator must go to approve. Rendered as a QR code by+ the frontend; set on the opening step and unchanged afterwards."""++ credentials: dict[str, Any] = Field(default_factory=dict)+ """The platform's credentials, once :attr:`state` is+ ``AUTHORIZED``."""++ error: str = ""+ """Why the session failed, for the operator to read."""++ provider_state: dict[str, Any] = Field(default_factory=dict)+ """Whatever the provider needs on the next step (a device code, a+ PKCE verifier, the domain a tenant was redirected to). Opaque to+ everything but the provider that produced it."""++ retry_after_secs: int | None = None+ """How long to wait before stepping again — the platform's polling+ interval, enforced service-side so a client cannot poll upstream+ faster than the platform allows. ``None`` keeps the session's+ current interval; a platform that asks us to slow down returns a+ larger one."""++ expires_in_secs: int = 600+ """How long the session stays usable."""+++class CredentialBindingBase:+ """Base for a channel type's interactive credential flow.++ Subclasses are instantiated once per process and must stay+ stateless: two consecutive steps of one session routinely land on+ different replicas.+ """++ async def begin(self) -> BindingStep:+ """Open a session and return what the operator must visit.++ Returns:+ `BindingStep`:+ ``PENDING`` with :attr:`~BindingStep.verification_url`+ and the ``provider_state`` to hand back to+ :meth:`advance`.+ """+ raise NotImplementedError++ async def advance(self, provider_state: dict[str, Any]) -> BindingStep:+ """Ask the platform once whether the operator has approved.++ Called on the client's status poll rather than from a loop of+ our own, so nothing outlives the request that triggered it.++ Args:+ provider_state (`dict[str, Any]`):+ What the previous step returned.++ Returns:+ `BindingStep`:+ Still ``PENDING``, or a terminal state.+ """+ raise NotImplementedErrordiff --git a/src/agentscope/app/channel/_feishu/_channel.py b/src/agentscope/app/channel/_feishu/_channel.pyindex 2d29819e5..539c2f889 100644--- a/src/agentscope/app/channel/_feishu/_channel.py+++ b/src/agentscope/app/channel/_feishu/_channel.py@@ -33,6 +33,7 @@ from .._base import (ChatKind,_EVENT_ADAPTER,)+from ._credential_binding import FeishuCredentialBindingfrom ._card_templates import (_build_action_response,_build_approval_card,@@ -95,6 +96,7 @@ class FeishuChannel(ChannelBase):description = "Group and direct-message bot with card interactions."icon_url = "https://www.google.com/s2/favicons?domain=feishu.cn&sz=128"platform_bot_id_field = "app_id"+ credential_binding = FeishuCredentialBindingclass Credentials(BaseModel):"""Feishu bot application credentials."""diff --git a/src/agentscope/app/channel/_feishu/_credential_binding.py b/src/agentscope/app/channel/_feishu/_credential_binding.pynew file mode 100644index 000000000..2173b2621--- /dev/null+++ b/src/agentscope/app/channel/_feishu/_credential_binding.py@@ -0,0 +1,124 @@+# -*- coding: utf-8 -*-+"""Feishu app registration by QR code.++Feishu registers an app through an OAuth device flow: we open a session,+show the operator a URL as a QR code, and ask the platform every few+seconds whether they have approved it. ``lark_oapi.aregister_app`` wraps+that in a loop of its own and never surfaces the device code, which+would pin the whole session to one process — so the two calls are made+directly here instead, one step per request.+"""+from typing import Any++import httpx++from .._credential_binding import (+ BindingState,+ BindingStep,+ CredentialBindingBase,+)++_ENDPOINT = "/oauth/v1/app/registration"++_FEISHU_DOMAIN = "https://accounts.feishu.cn"+_LARK_DOMAIN = "https://accounts.larksuite.com"+++class FeishuCredentialBinding(CredentialBindingBase):+ """Drive Feishu's device flow one step per call."""++ async def begin(self) -> BindingStep:+ """Open a registration session. See base."""+ payload = await self._post(+ _FEISHU_DOMAIN,+ {+ "action": "begin",+ "archetype": "PersonalAgent",+ "auth_method": "client_secret",+ "request_user_info": "open_id",+ },+ )+ if "device_code" not in payload:+ return BindingStep(+ state=BindingState.FAILED,+ error=payload.get("error_description")+ or payload.get("error")+ or "Feishu did not return a device code.",+ )++ return BindingStep(+ verification_url=payload["verification_uri_complete"],+ provider_state={+ "device_code": payload["device_code"],+ "domain": _FEISHU_DOMAIN,+ "interval": int(payload.get("interval", 5)),+ },+ retry_after_secs=int(payload.get("interval", 5)),+ expires_in_secs=int(payload.get("expires_in", 600)),+ )++ async def advance(self, provider_state: dict[str, Any]) -> BindingStep:+ """Ask Feishu once whether the QR code has been approved.++ Args:+ provider_state (`dict[str, Any]`):+ Carries the device code and the domain, which moves to+ Lark for a tenant that lives there.++ Returns:+ `BindingStep`: The session's state after this poll.+ """+ domain = provider_state.get("domain", _FEISHU_DOMAIN)+ payload = await self._post(+ domain,+ {"action": "poll", "device_code": provider_state["device_code"]},+ )++ if payload.get("client_id") and payload.get("client_secret"):+ return BindingStep(+ state=BindingState.AUTHORIZED,+ credentials={+ "app_id": str(payload["client_id"]),+ "app_secret": str(payload["client_secret"]),+ },+ )++ # A Lark tenant answers on its own domain; keep polling there.+ user_info = payload.get("user_info") or {}+ if user_info.get("tenant_brand") == "lark" and domain != _LARK_DOMAIN:+ return BindingStep(+ provider_state={**provider_state, "domain": _LARK_DOMAIN},+ )++ error = payload.get("error", "")+ if error == "authorization_pending":+ return BindingStep(provider_state=provider_state)++ if error == "slow_down":+ # Feishu wants a wider gap; widen it the way its own SDK+ # does and keep the new value for the next step.+ interval = int(provider_state.get("interval", 5)) + 5+ return BindingStep(+ provider_state={**provider_state, "interval": interval},+ retry_after_secs=interval,+ )++ return BindingStep(+ state=BindingState.FAILED,+ error=payload.get("error_description") or error or "unknown",+ )++ @staticmethod+ async def _post(domain: str, data: dict[str, str]) -> dict:+ """POST one form-encoded action to the registration endpoint.++ Args:+ domain (`str`): Feishu or Lark accounts host.+ data (`dict[str, str]`): The action and its arguments.++ Returns:+ `dict`: The decoded response body.+ """+ async with httpx.AsyncClient(timeout=10) as client:+ response = await client.post(domain + _ENDPOINT, data=data)+ return response.json()diff --git a/src/agentscope/app/channel/_registry.py b/src/agentscope/app/channel/_registry.pyindex c4e81ef02..f3ef7dd88 100644--- a/src/agentscope/app/channel/_registry.py+++ b/src/agentscope/app/channel/_registry.py@@ -33,6 +33,9 @@ class ChannelTypeSchema(BaseModel):credentials_schema: dictconfig_schema: dictplatform_bot_id_field: str+ supports_credential_binding: bool = False+ """Whether the type offers interactive binding as well as the+ credential form."""class ChannelTypeRegistry:@@ -135,6 +138,9 @@ class ChannelTypeRegistry:credentials_schema=channel_cls.Credentials.model_json_schema(),config_schema=channel_cls.Config.model_json_schema(),platform_bot_id_field=channel_cls.platform_bot_id_field,+ supports_credential_binding=(+ channel_cls.credential_binding is not None+ ),)def list_types(self) -> list[ChannelTypeSchema]:diff --git a/src/agentscope/app/deps.py b/src/agentscope/app/deps.pyindex 93eecf50f..9ed62286a 100644--- a/src/agentscope/app/deps.py+++ b/src/agentscope/app/deps.py@@ -14,6 +14,7 @@ from ._manager import ()from ._service import (ChannelService,+ CredentialBindingService,ChatService,KnowledgeBaseService,ResourceAccessService,@@ -419,6 +420,23 @@ async def get_channel_service(request: Request) -> ChannelService:return request.app.state.channel_service+async def get_credential_binding_service(+ request: Request,+) -> CredentialBindingService:+ """Return the application-wide credential-binding service.++ Present in every process: a binding session lives in the bus, so any+ replica can serve any step of it.++ Args:+ request (`Request`): The incoming FastAPI request.++ Returns:+ `CredentialBindingService`: The service stored in ``app.state``.+ """+ return request.app.state.credential_binding_service++async def get_channel_clients(request: Request,) -> ChannelClients:diff --git a/src/agentscope/app/message_bus/_base.py b/src/agentscope/app/message_bus/_base.pyindex 5ed20aa5a..50675f7ca 100644--- a/src/agentscope/app/message_bus/_base.py+++ b/src/agentscope/app/message_bus/_base.py@@ -425,6 +425,59 @@ class MessageBus(ABC): # pylint: disable=too-many-public-methodsRefresh the namespace expiry to this many seconds."""+ @abstractmethod+ async def registry_set_if(+ self,+ namespace: str,+ field: str,+ value: str,+ *,+ expected: str,+ ttl_secs: int | None = None,+ ) -> bool:+ """Set ``field`` only while it still holds ``expected``.++ Compare-and-set, so a caller that read a value, decided on a new+ one, and comes back to write it can tell whether anyone else+ moved it meanwhile — without holding a lock across the think+ time. The bus never interprets the value.++ Args:+ namespace (`str`):+ Registry key.+ field (`str`):+ Field name within the registry.+ value (`str`):+ Serialized value to store.+ expected (`str`):+ The value the caller last read. The write is skipped+ when the stored value differs.+ ttl_secs (`int | None`, optional):+ Refresh the namespace expiry when the write happens.++ Returns:+ `bool`:+ ``True`` when the value was written.+ """++ @abstractmethod+ async def registry_pop(self, namespace: str, field: str) -> str | None:+ """Read ``field`` and remove it in one step.++ Lets a value be consumed exactly once however many callers race+ for it: only one sees it, the rest get ``None``.++ Args:+ namespace (`str`):+ Registry key.+ field (`str`):+ Field to take.++ Returns:+ `str | None`:+ The stored value, or ``None`` when absent.+ """+@abstractmethodasync def registry_del(self, namespace: str, field: str) -> None:"""Remove ``field`` from the registry at ``namespace``.diff --git a/src/agentscope/app/message_bus/_in_memory_message_bus.py b/src/agentscope/app/message_bus/_in_memory_message_bus.pyindex 34e8f1937..0d20e4480 100644--- a/src/agentscope/app/message_bus/_in_memory_message_bus.py+++ b/src/agentscope/app/message_bus/_in_memory_message_bus.py@@ -27,7 +27,9 @@ from typing import Callable, Selffrom ._base import MessageBus-class InMemoryMessageBus(MessageBus):+class InMemoryMessageBus(+ MessageBus,+): # pylint: disable=too-many-public-methods"""In-memory implementation of :class:`MessageBus`.Mapping of bus modes to in-memory structures:@@ -437,6 +439,26 @@ class InMemoryMessageBus(MessageBus):"""self._registries[namespace][field] = value+ async def registry_set_if(+ self,+ namespace: str,+ field: str,+ value: str,+ *,+ expected: str,+ ttl_secs: int | None = None,+ ) -> bool:+ """Compare-and-set one field; ``ttl_secs`` ignored. See base."""+ _ = ttl_secs+ if self._registries.get(namespace, {}).get(field) != expected:+ return False+ self._registries.setdefault(namespace, {})[field] = value+ return True++ async def registry_pop(self, namespace: str, field: str) -> str | None:+ """Read and remove one field. See base."""+ return self._registries.get(namespace, {}).pop(field, None)+async def registry_del(self, namespace: str, field: str) -> None:"""Remove ``field`` from the registry at ``namespace``.diff --git a/src/agentscope/app/message_bus/_keys.py b/src/agentscope/app/message_bus/_keys.pyindex ff7ebcefc..b5b4f73c1 100644--- a/src/agentscope/app/message_bus/_keys.py+++ b/src/agentscope/app/message_bus/_keys.py@@ -308,6 +308,20 @@ class MessageBusKeys: # pylint: disable=too-many-public-methods# per-chat buffers.# ------------------------------------------------------------------+ _CHANNEL_CREDENTIAL_BINDING = "agentscope:channel:binding"++ CREDENTIAL_BINDING_FIELD = "record"+ """Field holding the serialised binding session."""++ CREDENTIAL_BINDING_CLAIM_TTL_SECS = 300+ """How long obtained credentials stay claimable. Short on purpose —+ they sit here in the clear until the channel is created."""++ @classmethod+ def channel_credential_binding(cls, binding_id: str) -> str:+ """Registry namespace holding one credential-binding session."""+ return f"{cls._CHANNEL_CREDENTIAL_BINDING}:{binding_id}"+_CHANNEL_LIFECYCLE = "agentscope:channel:lifecycle"_CHANNEL_LIVENESS = "agentscope:channel:liveness:{cid}"_CHANNEL_MEDIA = "agentscope:channel:media:{cid}:{chat}:{uid}"diff --git a/src/agentscope/app/message_bus/_redis_message_bus.py b/src/agentscope/app/message_bus/_redis_message_bus.pyindex b5f824922..89adcb0c0 100644--- a/src/agentscope/app/message_bus/_redis_message_bus.py+++ b/src/agentscope/app/message_bus/_redis_message_bus.py@@ -27,7 +27,25 @@ return entries"""-class RedisMessageBus(MessageBus):+# Compare-and-set on one hash field, so a caller can write back a value+# it decided on earlier without holding a lock across the think time.+_REGISTRY_SET_IF_LUA = """+if redis.call('HGET', KEYS[1], ARGV[1]) ~= ARGV[3] then return 0 end+redis.call('HSET', KEYS[1], ARGV[1], ARGV[2])+if tonumber(ARGV[4]) > 0 then redis.call('EXPIRE', KEYS[1], ARGV[4]) end+return 1+"""++# Read and remove in one step, so a value is consumed exactly once+# however many callers race for it.+_REGISTRY_POP_LUA = """+local value = redis.call('HGET', KEYS[1], ARGV[1])+if value then redis.call('HDEL', KEYS[1], ARGV[1]) end+return value+"""+++class RedisMessageBus(MessageBus): # pylint: disable=too-many-public-methods"""Redis-backed implementation of :class:`MessageBus`.Mapping of bus modes to Redis primitives:@@ -413,6 +431,36 @@ class RedisMessageBus(MessageBus):if ttl_secs is not None:await self._client.expire(namespace, ttl_secs)+ async def registry_set_if(+ self,+ namespace: str,+ field: str,+ value: str,+ *,+ expected: str,+ ttl_secs: int | None = None,+ ) -> bool:+ """Compare-and-set one Hash field via Lua. See base."""+ written = await self._client.eval(+ _REGISTRY_SET_IF_LUA,+ 1,+ namespace,+ field,+ value,+ expected,+ ttl_secs or 0,+ )+ return bool(written)++ async def registry_pop(self, namespace: str, field: str) -> str | None:+ """``HGET`` + ``HDEL`` as one Lua step. See base."""+ return await self._client.eval(+ _REGISTRY_POP_LUA,+ 1,+ namespace,+ field,+ )+async def registry_del(self, namespace: str, field: str) -> None:"""Remove ``field`` from the Redis Hash at ``namespace``.diff --git a/tests/channel_credential_binding_test.py b/tests/channel_credential_binding_test.pynew file mode 100644index 000000000..7e013e69e--- /dev/null+++ b/tests/channel_credential_binding_test.py@@ -0,0 +1,367 @@+# -*- coding: utf-8 -*-+"""Tests for interactive channel credential binding.++A session lives in the message bus rather than in any one process, so+every test drives it through *two* services sharing one bus — the two+replicas a client's requests would land on in turn.+"""+import asyncio+from contextlib import AsyncExitStack+from typing import Any+from unittest import IsolatedAsyncioTestCase++from utils import AnyString++from agentscope.app._service import (+ CredentialBindingError,+ CredentialBindingService,+)+from agentscope.app.channel import (+ BindingState,+ BindingStep,+ ChannelBase,+ ChannelTypeRegistry,+ CredentialBindingBase,+)+from agentscope.app._router._channel import (+ cancel_credential_binding,+ poll_credential_binding,+ start_credential_binding,+)+from agentscope.app._router._schema import StartCredentialBindingRequest+from agentscope.app.message_bus import InMemoryMessageBus+++class _ScriptedBinding(CredentialBindingBase):+ """Return a scripted step per call, recording how often it was asked."""++ script: list[BindingStep] = []+ calls: int = 0+ retry_after_secs: int = 0+ during_advance: Any = None+ """Awaited while "the platform" is being asked, to interleave a+ concurrent request the way a real round trip would allow."""++ async def begin(self) -> BindingStep:+ """Open with a verification URL."""+ return BindingStep(+ verification_url="https://example.test/qr",+ provider_state={"device_code": "dc-1"},+ retry_after_secs=type(self).retry_after_secs,+ expires_in_secs=600,+ )++ async def advance(self, provider_state: dict[str, Any]) -> BindingStep:+ """Pop the next scripted outcome."""+ _ = provider_state+ type(self).calls += 1+ hook = type(self).during_advance+ if hook is not None:+ await hook()+ return type(self).script.pop(0)+++class _ContendingBus(InMemoryMessageBus):+ """Hold registry reads until several callers have the same value.++ Nothing in the in-memory bus suspends, so two gathered polls would+ otherwise run one after the other and never contend.+ """++ def __init__(self, readers: int) -> None:+ super().__init__()+ self._barrier = asyncio.Barrier(readers)++ async def registry_get(self, namespace: str, field: str) -> str | None:+ """Read, then wait for the other readers to have read too."""+ value = await super().registry_get(namespace, field)+ if self._barrier.n_waiting < self._barrier.parties:+ try:+ await asyncio.wait_for(self._barrier.wait(), timeout=1)+ except (TimeoutError, asyncio.BrokenBarrierError):+ pass+ return value+++class _BoundChannel(ChannelBase):+ """A channel type offering interactive binding."""++ channel_type = "scripted"+ display_name = "Scripted"+ platform_bot_id_field = "app_id"+ credential_binding = _ScriptedBinding++ @property+ def channel_id(self) -> str:+ """Unused by these tests."""+ return "scripted"++ async def start_listening(self, emit: Any) -> None:+ """Unused by these tests."""++ async def send_response(self, *args: Any, **kwargs: Any) -> None:+ """Unused by these tests."""+++class _FormOnlyChannel(_BoundChannel):+ """A channel type with no interactive binding."""++ channel_type = "form-only"+ display_name = "Form only"+ credential_binding = None+++class CredentialBindingTest(IsolatedAsyncioTestCase):+ """Sessions are driven from any replica and consumed exactly once."""++ async def asyncSetUp(self) -> None:+ self._stack = AsyncExitStack()+ self.bus = await self._stack.enter_async_context(+ InMemoryMessageBus(),+ )+ registry = ChannelTypeRegistry([_BoundChannel, _FormOnlyChannel])+ # Two services, one bus: the replicas a client hops between.+ self.node_a = CredentialBindingService(self.bus, registry)+ self.node_b = CredentialBindingService(self.bus, registry)+ _ScriptedBinding.script = []+ _ScriptedBinding.calls = 0+ _ScriptedBinding.retry_after_secs = 0+ _ScriptedBinding.during_advance = None++ async def asyncTearDown(self) -> None:+ await self._stack.aclose()++ async def test_a_session_opened_on_one_node_advances_on_another(+ self,+ ) -> None:+ """The client hops replicas between every step and still wins."""+ opened = await self.node_a.start("u", "scripted")+ self.assertDictEqual(+ opened.model_dump(),+ {+ "binding_id": AnyString(),+ "state": BindingState.PENDING,+ "verification_url": "https://example.test/qr",+ "error": "",+ "retry_after_secs": 0,+ },+ )++ _ScriptedBinding.script = [+ BindingStep(provider_state={"device_code": "dc-1"}),+ BindingStep(+ state=BindingState.AUTHORIZED,+ credentials={"app_id": "a", "app_secret": "s"},+ ),+ ]++ still_waiting = await self.node_b.poll("u", opened.binding_id)+ self.assertEqual(still_waiting.state, BindingState.PENDING)++ # The whole view, so a secret can never leak into it unnoticed.+ self.assertDictEqual(+ (await self.node_a.poll("u", opened.binding_id)).model_dump(),+ {+ "binding_id": opened.binding_id,+ "state": BindingState.AUTHORIZED,+ "verification_url": "https://example.test/qr",+ "error": "",+ "retry_after_secs": 0,+ },+ )++ self.assertDictEqual(+ await self.node_b.claim("u", opened.binding_id, "scripted"),+ {"app_id": "a", "app_secret": "s"},+ )++ async def test_credentials_can_only_be_claimed_once(self) -> None:+ """A second claim finds nothing, however it races the first."""+ opened = await self.node_a.start("u", "scripted")+ _ScriptedBinding.script = [+ BindingStep(+ state=BindingState.AUTHORIZED,+ credentials={"app_id": "a", "app_secret": "s"},+ ),+ ]+ await self.node_a.poll("u", opened.binding_id)++ await self.node_a.claim("u", opened.binding_id, "scripted")+ with self.assertRaises(CredentialBindingError) as ctx:+ await self.node_b.claim("u", opened.binding_id, "scripted")+ self.assertEqual(ctx.exception.status_code, 404)++ async def test_a_cancel_during_an_upstream_poll_wins(self) -> None:+ """The regression this design exists for: node A read the+ session, then the operator cancelled on node B while A was+ asking the platform. A's approval must not revive it."""+ opened = await self.node_a.start("u", "scripted")++ async def _cancel_midway() -> None:+ await self.node_b.cancel("u", opened.binding_id)++ _ScriptedBinding.during_advance = _cancel_midway+ _ScriptedBinding.script = [+ BindingStep(+ state=BindingState.AUTHORIZED,+ credentials={"app_id": "a", "app_secret": "s"},+ ),+ ]++ self.assertDictEqual(+ (await self.node_a.poll("u", opened.binding_id)).model_dump(),+ {+ "binding_id": opened.binding_id,+ "state": BindingState.CANCELLED,+ "verification_url": "https://example.test/qr",+ "error": "",+ "retry_after_secs": 0,+ },+ )+ with self.assertRaises(CredentialBindingError):+ await self.node_b.claim("u", opened.binding_id, "scripted")++ async def test_polling_faster_than_the_platform_allows_is_absorbed(+ self,+ ) -> None:+ """The client sets the request rate, the platform's interval+ still sets the upstream rate."""+ _ScriptedBinding.retry_after_secs = 60+ opened = await self.node_a.start("u", "scripted")++ _ScriptedBinding.script = [BindingStep(), BindingStep()]+ await self.node_a.poll("u", opened.binding_id)+ await self.node_b.poll("u", opened.binding_id)+ await self.node_a.poll("u", opened.binding_id)++ self.assertEqual(_ScriptedBinding.calls, 1)++ async def test_a_session_is_invisible_to_other_users(self) -> None:+ """Another user cannot even tell the id exists."""+ opened = await self.node_a.start("u", "scripted")+ with self.assertRaises(CredentialBindingError) as ctx:+ await self.node_b.poll("intruder", opened.binding_id)+ self.assertEqual(ctx.exception.status_code, 404)++ async def test_a_form_only_type_is_rejected(self) -> None:+ """A type without a provider says so instead of half-starting."""+ with self.assertRaises(CredentialBindingError) as ctx:+ await self.node_a.start("u", "form-only")+ self.assertEqual(ctx.exception.status_code, 400)++ async def test_a_rejected_claim_leaves_the_session_usable(self) -> None:+ """Checks come before the destructive take, so a claim for the+ wrong type — or one from an intruder — cannot burn a session."""+ opened = await self.node_a.start("u", "scripted")++ with self.assertRaises(CredentialBindingError) as early:+ await self.node_a.claim("u", opened.binding_id, "scripted")+ self.assertEqual(early.exception.status_code, 409)++ with self.assertRaises(CredentialBindingError) as intruder:+ await self.node_b.claim("hacker", opened.binding_id, "scripted")+ self.assertEqual(intruder.exception.status_code, 404)++ _ScriptedBinding.script = [+ BindingStep(+ state=BindingState.AUTHORIZED,+ credentials={"app_id": "a", "app_secret": "s"},+ ),+ ]+ await self.node_a.poll("u", opened.binding_id)++ with self.assertRaises(CredentialBindingError) as wrong_type:+ await self.node_b.claim("u", opened.binding_id, "form-only")+ self.assertEqual(wrong_type.exception.status_code, 409)++ # Still there after all of that.+ self.assertDictEqual(+ await self.node_a.claim("u", opened.binding_id, "scripted"),+ {"app_id": "a", "app_secret": "s"},+ )++ async def test_only_one_of_two_concurrent_polls_reaches_upstream(+ self,+ ) -> None:+ """Two replicas that read the same record must not both ask the+ platform — the reservation, not the read, is what decides."""+ _ScriptedBinding.retry_after_secs = 60+ registry = ChannelTypeRegistry([_BoundChannel, _FormOnlyChannel])+ bus = await self._stack.enter_async_context(_ContendingBus(2))+ node_a = CredentialBindingService(bus, registry)+ node_b = CredentialBindingService(bus, registry)++ opened = await node_a.start("u", "scripted")+ _ScriptedBinding.script = [BindingStep(), BindingStep()]++ await asyncio.gather(+ node_a.poll("u", opened.binding_id),+ node_b.poll("u", opened.binding_id),+ )++ self.assertEqual(_ScriptedBinding.calls, 1)++ async def test_cancelling_an_approved_session_discards_it(self) -> None:+ """Walking away from an approved binding must not leave the+ credentials claimable until the TTL runs out."""+ opened = await self.node_a.start("u", "scripted")+ _ScriptedBinding.script = [+ BindingStep(+ state=BindingState.AUTHORIZED,+ credentials={"app_id": "a", "app_secret": "s"},+ ),+ ]+ await self.node_a.poll("u", opened.binding_id)++ await self.node_b.cancel("u", opened.binding_id)++ with self.assertRaises(CredentialBindingError) as ctx:+ await self.node_a.claim("u", opened.binding_id, "scripted")+ self.assertEqual(ctx.exception.status_code, 404)++ async def test_cancelling_a_claimed_session_is_not_an_error(+ self,+ ) -> None:+ """What creating a channel actually looks like: the claim+ consumes the session, then the closing dialog cancels it. That+ second call must not report a failure over a success."""+ opened = await self.node_a.start("u", "scripted")+ _ScriptedBinding.script = [+ BindingStep(+ state=BindingState.AUTHORIZED,+ credentials={"app_id": "a", "app_secret": "s"},+ ),+ ]+ await self.node_a.poll("u", opened.binding_id)+ await self.node_a.claim("u", opened.binding_id, "scripted")++ await self.node_b.cancel("u", opened.binding_id)+++class CredentialBindingRouterTest(CredentialBindingTest):+ """The endpoints answer with what their response models declare."""++ async def test_the_endpoints_round_trip_a_session(self) -> None:+ """Exercised through the route functions, so a response model+ that cannot be built shows up here rather than as a 500."""+ opened = await start_credential_binding(+ StartCredentialBindingRequest(channel_type="scripted"),+ bindings=self.node_a,+ user_id="u",+ )+ self.assertEqual(opened.state, BindingState.PENDING)++ _ScriptedBinding.script = [BindingStep()]+ polled = await poll_credential_binding(+ opened.binding_id,+ bindings=self.node_b,+ user_id="u",+ )+ self.assertEqual(polled.binding_id, opened.binding_id)++ cancelled = await cancel_credential_binding(+ opened.binding_id,+ bindings=self.node_a,+ user_id="u",+ )+ self.assertEqual(cancelled.status, "cancelled")diff --git a/tests/channel_feishu_credential_binding_test.py b/tests/channel_feishu_credential_binding_test.pynew file mode 100644index 000000000..0ae904393--- /dev/null+++ b/tests/channel_feishu_credential_binding_test.py@@ -0,0 +1,178 @@+# -*- coding: utf-8 -*-+"""Tests for Feishu's device-flow credential binding.++The provider is driven one step per call rather than by a loop of its+own, so each response the platform can give is checked on its own.+"""+from typing import Any+from unittest import IsolatedAsyncioTestCase+from unittest.mock import patch++from agentscope.app.channel import BindingState+from agentscope.app.channel._feishu._credential_binding import (+ FeishuCredentialBinding,+)+++class _Response:+ """Minimal stand-in for an ``httpx`` response."""++ def __init__(self, payload: dict) -> None:+ self._payload = payload++ def json(self) -> dict:+ """Return the canned body."""+ return self._payload+++class _Client:+ """Records each POST and answers from a script."""++ posts: list[tuple[str, dict]] = []+ script: list[dict] = []++ def __init__(self, *args: Any, **kwargs: Any) -> None:+ _ = args, kwargs++ async def __aenter__(self) -> "_Client":+ return self++ async def __aexit__(self, *exc: object) -> None:+ pass++ async def post(self, url: str, data: dict) -> _Response:+ """Record the call and return the next scripted body."""+ type(self).posts.append((url, data))+ return _Response(type(self).script.pop(0))+++class FeishuCredentialBindingTest(IsolatedAsyncioTestCase):+ """Each device-flow outcome maps onto one binding step."""++ def setUp(self) -> None:+ _Client.posts = []+ _Client.script = []+ self.binding = FeishuCredentialBinding()+ patcher = patch("httpx.AsyncClient", _Client)+ patcher.start()+ self.addCleanup(patcher.stop)++ async def test_begin_returns_the_url_and_the_platform_interval(+ self,+ ) -> None:+ """The opening call carries everything the next step needs."""+ _Client.script = [+ {+ "device_code": "dc-1",+ "verification_uri_complete": "https://feishu.test/qr?x=1",+ "interval": 7,+ "expires_in": 300,+ },+ ]++ step = await self.binding.begin()++ self.assertDictEqual(+ step.model_dump(),+ {+ "state": BindingState.PENDING,+ "verification_url": "https://feishu.test/qr?x=1",+ "credentials": {},+ "error": "",+ "provider_state": {+ "device_code": "dc-1",+ "domain": "https://accounts.feishu.cn",+ "interval": 7,+ },+ "retry_after_secs": 7,+ "expires_in_secs": 300,+ },+ )+ self.assertEqual(+ _Client.posts[0][0],+ "https://accounts.feishu.cn/oauth/v1/app/registration",+ )++ async def test_begin_reports_a_refusal_instead_of_half_starting(+ self,+ ) -> None:+ """No device code means the session never opened."""+ _Client.script = [{"error_description": "app quota exceeded"}]++ step = await self.binding.begin()++ self.assertEqual(step.state, BindingState.FAILED)+ self.assertEqual(step.error, "app quota exceeded")++ async def test_approval_yields_the_credentials(self) -> None:+ """The platform's client id/secret become channel credentials."""+ _Client.script = [{"client_id": "cli-1", "client_secret": "sec-1"}]++ step = await self.binding.advance(+ {"device_code": "dc-1", "domain": "https://accounts.feishu.cn"},+ )++ self.assertEqual(step.state, BindingState.AUTHORIZED)+ self.assertDictEqual(+ step.credentials,+ {"app_id": "cli-1", "app_secret": "sec-1"},+ )++ async def test_pending_keeps_the_state_and_the_interval(self) -> None:+ """Waiting must not disturb the pace already agreed."""+ _Client.script = [{"error": "authorization_pending"}]+ state = {+ "device_code": "dc-1",+ "domain": "https://accounts.feishu.cn",+ "interval": 7,+ }++ step = await self.binding.advance(state)++ self.assertEqual(step.state, BindingState.PENDING)+ self.assertIsNone(step.retry_after_secs)+ self.assertDictEqual(step.provider_state, state)++ async def test_slow_down_widens_the_gap_for_later_steps(self) -> None:+ """A throttled session must actually back off, not keep its+ original rate."""+ _Client.script = [{"error": "slow_down"}]++ step = await self.binding.advance(+ {+ "device_code": "dc-1",+ "domain": "https://accounts.feishu.cn",+ "interval": 5,+ },+ )++ self.assertEqual(step.retry_after_secs, 10)+ self.assertEqual(step.provider_state["interval"], 10)++ async def test_a_lark_tenant_moves_to_its_own_domain(self) -> None:+ """The next poll must go where that tenant actually answers."""+ _Client.script = [{"user_info": {"tenant_brand": "lark"}}]++ step = await self.binding.advance(+ {"device_code": "dc-1", "domain": "https://accounts.feishu.cn"},+ )++ self.assertEqual(step.state, BindingState.PENDING)+ self.assertEqual(+ step.provider_state["domain"],+ "https://accounts.larksuite.com",+ )++ async def test_a_denial_ends_the_session(self) -> None:+ """A refused approval is terminal, not something to keep+ polling."""+ _Client.script = [+ {"error": "access_denied", "error_description": "user said no"},+ ]++ step = await self.binding.advance(+ {"device_code": "dc-1", "domain": "https://accounts.feishu.cn"},+ )++ self.assertEqual(step.state, BindingState.FAILED)+ self.assertEqual(step.error, "user said no")diff --git a/tests/service_cancel_dispatcher_test.py b/tests/service_cancel_dispatcher_test.pyindex d37b2e83a..463b26ce9 100644--- a/tests/service_cancel_dispatcher_test.py+++ b/tests/service_cancel_dispatcher_test.py@@ -142,6 +142,20 @@ class _FakeBus(MessageBus):) -> None:self._registries.setdefault(namespace, {})[field] = value+ async def registry_set_if(+ self,+ namespace: str,+ field: str,+ value: str,+ *,+ expected: str,+ ttl_secs: int | None = None,+ ) -> bool:+ raise NotImplementedError++ async def registry_pop(self, namespace: str, field: str) -> str | None:+ raise NotImplementedError+async def registry_del(self, namespace: str, field: str) -> None:if namespace in self._registries:self._registries[namespace].pop(field, None)diff --git a/tests/service_inbox_middleware_test.py b/tests/service_inbox_middleware_test.pyindex 04ae31c90..5b8d8924c 100644--- a/tests/service_inbox_middleware_test.py+++ b/tests/service_inbox_middleware_test.py@@ -149,6 +149,20 @@ class _FakeBus(MessageBus):) -> None:raise NotImplementedError+ async def registry_set_if(+ self,+ namespace: str,+ field: str,+ value: str,+ *,+ expected: str,+ ttl_secs: int | None = None,+ ) -> bool:+ raise NotImplementedError++ async def registry_pop(self, namespace: str, field: str) -> str | None:+ raise NotImplementedError+async def registry_del(self, namespace: str, field: str) -> None:raise NotImplementedErrordiff --git a/tests/service_index_task_consumer_test.py b/tests/service_index_task_consumer_test.pyindex 000008c13..4f292f171 100644--- a/tests/service_index_task_consumer_test.py+++ b/tests/service_index_task_consumer_test.py@@ -156,6 +156,20 @@ class _FakeBus(MessageBus):) -> None:raise NotImplementedError+ async def registry_set_if(+ self,+ namespace: str,+ field: str,+ value: str,+ *,+ expected: str,+ ttl_secs: int | None = None,+ ) -> bool:+ raise NotImplementedError++ async def registry_pop(self, namespace: str, field: str) -> str | None:+ raise NotImplementedError+async def registry_del(self, namespace: str, field: str) -> None:raise NotImplementedErrordiff --git a/tests/service_message_bus_test.py b/tests/service_message_bus_test.pyindex 86a78da47..5484eb6fe 100644--- a/tests/service_message_bus_test.py+++ b/tests/service_message_bus_test.py@@ -109,6 +109,74 @@ class TestQueuePrimitive(IsolatedAsyncioTestCase):self.assertEqual(len(issued), 1)+class TestRegistryConditionalPrimitives(IsolatedAsyncioTestCase):+ """Mode F — the compare-and-set and take-once registry ops."""++ async def asyncSetUp(self) -> None:+ self.fr = fakeredis.aioredis.FakeRedis(decode_responses=True)+ self._stack = AsyncExitStack()+ self.bus = await self._stack.enter_async_context(_make_bus(self.fr))++ async def asyncTearDown(self) -> None:+ await self._stack.aclose()+ await self.fr.aclose()++ async def test_set_if_writes_only_on_the_expected_value(self) -> None:+ """A caller whose read is stale loses, and changes nothing."""+ await self.bus.registry_set("ns", "f", "v1")++ self.assertFalse(+ await self.bus.registry_set_if(+ "ns",+ "f",+ "v2",+ expected="stale",+ ),+ )+ self.assertEqual(await self.bus.registry_get("ns", "f"), "v1")++ self.assertTrue(+ await self.bus.registry_set_if("ns", "f", "v2", expected="v1"),+ )+ self.assertEqual(await self.bus.registry_get("ns", "f"), "v2")++ async def test_set_if_refreshes_the_expiry_only_when_it_writes(+ self,+ ) -> None:+ """A losing caller must not extend someone else's lifetime."""+ await self.bus.registry_set("ns", "f", "v1", ttl_secs=1000)++ await self.bus.registry_set_if(+ "ns",+ "f",+ "v2",+ expected="stale",+ ttl_secs=5000,+ )+ self.assertLessEqual(await self.fr.ttl("ns"), 1000)++ await self.bus.registry_set_if(+ "ns",+ "f",+ "v2",+ expected="v1",+ ttl_secs=5000,+ )+ self.assertGreater(await self.fr.ttl("ns"), 1000)++ async def test_pop_hands_the_value_to_exactly_one_caller(self) -> None:+ """Whatever races for it, only the first take succeeds."""+ await self.bus.registry_set("ns", "f", "v1")++ self.assertEqual(await self.bus.registry_pop("ns", "f"), "v1")+ self.assertIsNone(await self.bus.registry_pop("ns", "f"))+ self.assertIsNone(await self.bus.registry_get("ns", "f"))++ async def test_pop_of_an_absent_field_is_not_an_error(self) -> None:+ """An expired session reads as gone, not as a failure."""+ self.assertIsNone(await self.bus.registry_pop("missing", "f"))++class TestLogPrimitive(IsolatedAsyncioTestCase):"""Mode C — replay log: append / read with cursor / trim."""diff --git a/tests/service_wakeup_dispatcher_test.py b/tests/service_wakeup_dispatcher_test.pyindex c945bf5b7..c66c63d7e 100644--- a/tests/service_wakeup_dispatcher_test.py+++ b/tests/service_wakeup_dispatcher_test.py@@ -172,6 +172,20 @@ class _FakeBus(MessageBus):) -> None:raise NotImplementedError+ async def registry_set_if(+ self,+ namespace: str,+ field: str,+ value: str,+ *,+ expected: str,+ ttl_secs: int | None = None,+ ) -> bool:+ raise NotImplementedError++ async def registry_pop(self, namespace: str, field: str) -> str | None:+ raise NotImplementedError+async def registry_del(self, namespace: str, field: str) -> None:raise NotImplementedError