Skip to content

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

feat(app): add client-declared external tools and interactive user input (#2394)

qbc6dd669b090e8
diff --git a/examples/console/README.md b/examples/console/README.md
index f5b65e625..48f45e24d 100644
--- a/examples/console/README.md
+++ b/examples/console/README.md
@@ -22,6 +22,8 @@ service or writing any UI code.
blocks and token usage;
- tool-call confirmation — `y` allows once, `a` also accepts the
suggested permission rules so matching calls won't ask again;
+ - structured choices — `AskUser` supports single/multi-select questions,
+ plus an `Other` option for a custom answer;
- Ctrl+C interrupts the current reply; `exit`/`quit`/Ctrl+D leaves.
## Quickstart
diff --git a/examples/console/main.py b/examples/console/main.py
index c34bafa56..a949a9509 100644
--- a/examples/console/main.py
+++ b/examples/console/main.py
@@ -22,7 +22,7 @@ from agentscope.console import launch_console
from agentscope.credential import DashScopeCredential
from agentscope.middleware import AgenticMemoryMiddleware
from agentscope.model import DashScopeChatModel
-from agentscope.tool import Toolkit
+from agentscope.tool import AskUser, Toolkit
from agentscope.workspace import LocalWorkspace
@@ -68,7 +68,10 @@ async def main() -> None:
toolkit=Toolkit(
# Filesystem tools and skills both come from the
# workspace, bound to its backend and skill partition
- tools=await workspace.list_tools(),
+ tools=[
+ *await workspace.list_tools(),
+ AskUser(),
+ ],
skills_or_loaders=await workspace.list_skills(),
),
middlewares=[
diff --git a/examples/web_ui/frontend/package.json b/examples/web_ui/frontend/package.json
index d766e5e85..db3a3d327 100644
--- a/examples/web_ui/frontend/package.json
+++ b/examples/web_ui/frontend/package.json
@@ -21,6 +21,7 @@
"@streamdown/mermaid": "^1.0.2",
"@tailwindcss/vite": "^4.3.0",
"@tanstack/react-query": "^5.102.8",
+ "ajv": "^8.20.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cron-parser": "^5.5.0",
diff --git a/examples/web_ui/frontend/src/api/chat.ts b/examples/web_ui/frontend/src/api/chat.ts
index 128689ac9..2e7ccf8b1 100644
--- a/examples/web_ui/frontend/src/api/chat.ts
+++ b/examples/web_ui/frontend/src/api/chat.ts
@@ -2,6 +2,10 @@ import type { Msg } from '@agentscope-ai/agentscope/message';
import { client } from './client';
import type { ChatRequest } from './types';
+import {
+ getEnabledClientBuiltinTools,
+ getEnabledClientExternalToolDefinitions,
+} from '@/lib/client-external-tool-store';
export interface ChatQueueItem {
/** Stable business id used by queue mutation endpoints. */
@@ -45,7 +49,15 @@ export const chatApi = {
status: 'started' | 'queued';
session_id: string;
queue_item_id: string | null;
- }>('/chat/', body),
+ }>('/chat/', {
+ ...body,
+ client_builtin_tools:
+ body.client_builtin_tools ??
+ getEnabledClientBuiltinTools(body.agent_id, body.session_id),
+ client_external_tools:
+ body.client_external_tools ??
+ getEnabledClientExternalToolDefinitions(body.agent_id, body.session_id),
+ }),
/**
* Read the complete editable pending queue.
diff --git a/examples/web_ui/frontend/src/api/types.ts b/examples/web_ui/frontend/src/api/types.ts
index 48453b255..74207dda0 100644
--- a/examples/web_ui/frontend/src/api/types.ts
+++ b/examples/web_ui/frontend/src/api/types.ts
@@ -526,10 +526,19 @@ import type {
} from '@agentscope-ai/agentscope/event';
import type { Msg } from '@agentscope-ai/agentscope/message';
+export interface ClientExternalToolDefinition {
+ name: string;
+ description: string;
+ read_only: boolean;
+ input_schema: Record<string, unknown>;
+}
+
export interface ChatRequest {
agent_id: string;
session_id: string;
input: Msg | Msg[] | UserConfirmResultEvent | ExternalExecutionResultEvent | null;
+ client_external_tools?: ClientExternalToolDefinition[];
+ client_builtin_tools?: Array<'AskUser'>;
}
// ─── MCP ──────────────────────────────────────────────────────────────────────
diff --git a/examples/web_ui/frontend/src/components/chat/AskUserCard.tsx b/examples/web_ui/frontend/src/components/chat/AskUserCard.tsx
new file mode 100644
index 000000000..adb0ec17a
--- /dev/null
+++ b/examples/web_ui/frontend/src/components/chat/AskUserCard.tsx
@@ -0,0 +1,267 @@
+import { Check, ChevronLeft, ChevronRight, X } from 'lucide-react';
+import { useEffect, useRef, useState, type KeyboardEvent } from 'react';
+
+import { Button } from '@/components/ui/button';
+import { Textarea } from '@/components/ui/textarea';
+import { useTranslation } from '@/i18n/useI18n';
+import {
+ parseAskUserPayload,
+ getNextRadioIndex,
+ shouldSubmitOtherInput,
+ type AskUserAnswer,
+ type AskUserQuestion,
+} from '@/lib/ask-user';
+import type { PendingClientExternalToolProps } from '@/lib/client-external-tools';
+import { cn } from '@/lib/utils';
+
+export function AskUserCard(props: PendingClientExternalToolProps) {
+ const { t } = useTranslation();
+ const payload = parseAskUserPayload(props.toolCall.input);
+ if (!payload)
+ return (
+ <section className="rounded-[28px] bg-muted p-5 text-sm ring-1 ring-border">
+ <p role="alert">{t('askUser.invalidDescription')}</p>
+ <Button
+ className="mt-3"
+ variant="outline"
+ onClick={props.onCancel}
+ disabled={props.cancelling}
+ >
+ <X />
+ {t('askUser.cancel')}
+ </Button>
+ </section>
+ );
+ return <AskUserForm key={props.toolCall.input} {...props} questions={payload.questions} />;
+}
+
+function AskUserForm({
+ questions,
+ onSubmit,
+ onCancel,
+ cancelling,
+}: PendingClientExternalToolProps & { questions: AskUserQuestion[] }) {
+ const { t } = useTranslation();
+ const [index, setIndex] = useState(0);
+ const [answers, setAnswers] = useState<AskUserAnswer[]>(() =>
+ questions.map((question) => ({
+ question: question.question,
+ selected: question.multi_select ? [] : [question.options[0].label],
+ other: null,
+ })),
+ );
+ const [focused, setFocused] = useState(0);
+ const [submitting, setSubmitting] = useState(false);
+ const submittingRef = useRef(false);
+ const optionsRef = useRef<Array<HTMLButtonElement | null>>([]);
+ const otherRef = useRef<HTMLTextAreaElement>(null);
+ const question = questions[index];
+ const answer = answers[index];
+ const disabled = submitting || cancelling;
+ const canSubmit = answer.selected.length > 0 || Boolean(answer.other?.trim());
+
+ useEffect(() => {
+ const active = optionsRef.current.find(
+ (option) => option?.getAttribute('aria-checked') === 'true',
+ );
+ (active ?? optionsRef.current[0])?.focus();
+ }, [index]);
+
+ const update = (next: AskUserAnswer) =>
+ setAnswers((current) => current.map((value, i) => (i === index ? next : value)));
+ const choose = (optionIndex: number): AskUserAnswer => {
+ if (optionIndex === question.options.length) {
+ const next = {
+ ...answer,
+ selected: question.multi_select ? answer.selected : [],
+ other: question.multi_select && answer.other !== null ? null : (answer.other ?? ''),
+ };
+ update(next);
+ return next;
+ }
+ const label = question.options[optionIndex].label;
+ const selected = question.multi_select
+ ? question.options
+ .map((option) => option.label)
+ .filter((value) =>
+ value === label
+ ? !answer.selected.includes(value)
+ : answer.selected.includes(value),
+ )
+ : [label];
+ const next = { ...answer, selected, other: question.multi_select ? answer.other : null };
+ update(next);
+ return next;
+ };
+ const advance = async (next = answer) => {
+ if (disabled || submittingRef.current || (!next.selected.length && !next.other?.trim()))
+ return;
+ const complete = answers.map((value, i) =>
+ i === index ? { ...next, other: next.other?.trim() || null } : value,
+ );
+ setAnswers(complete);
+ if (index < questions.length - 1) {
+ setIndex(index + 1);
+ return;
+ }
+ submittingRef.current = true;
+ setSubmitting(true);
+ try {
+ await onSubmit({ answers: complete });
+ } catch {
+ submittingRef.current = false;
+ setSubmitting(false);
+ }
+ };
+ const keyDown = (event: KeyboardEvent<HTMLButtonElement>, optionIndex: number) => {
+ if (event.nativeEvent.isComposing || disabled) return;
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ if (optionIndex === question.options.length) {
+ if (answer.other?.trim()) void advance();
+ else {
+ if (answer.other === null) choose(optionIndex);
+ otherRef.current?.focus();
+ }
+ } else void advance(question.multi_select ? answer : choose(optionIndex));
+ return;
+ }
+ const next = getNextRadioIndex(optionIndex, event.key, question.options.length + 1);
+ if (next === null) return;
+ event.preventDefault();
+ setFocused(next);
+ if (!question.multi_select) choose(next);
+ optionsRef.current[next]?.focus();
+ };
+
+ return (
+ <section className="flex max-h-[min(72vh,42rem)] flex-col rounded-[28px] bg-muted p-5 text-sm ring-1 ring-border sm:p-6">
+ <div className="min-h-0 overflow-y-auto px-1 pb-1">
+ <div className="mb-4 flex items-center justify-between gap-3 text-xs text-muted-foreground">
+ <span>{question.header}</span>
+ <span>
+ {index + 1} / {questions.length}
+ </span>
+ </div>
+ <h2 className="text-base font-medium">{question.question}</h2>
+ {question.context && (
+ <pre className="mt-3 max-h-48 overflow-auto whitespace-pre-wrap break-words rounded-xl bg-background p-3 font-sans text-sm">
+ {question.context}
+ </pre>
+ )}
+ {question.multi_select && (
+ <p className="mt-2 text-xs text-muted-foreground">{t('askUser.multiSelect')}</p>
+ )}
+ <div
+ className="mt-4 space-y-2"
+ role={question.multi_select ? 'group' : 'radiogroup'}
+ aria-label={question.question}
+ >
+ {[...question.options, { label: t('askUser.other'), description: '' }].map(
+ (option, optionIndex) => {
+ const isOther = optionIndex === question.options.length;
+ const active = isOther
+ ? answer.other !== null
+ : answer.selected.includes(option.label);
+ return (
+ <button
+ key={optionIndex}
+ ref={(element) => {
+ optionsRef.current[optionIndex] = element;
+ }}
+ type="button"
+ role={question.multi_select ? 'checkbox' : 'radio'}
+ aria-checked={active}
+ tabIndex={focused === optionIndex ? 0 : -1}
+ disabled={disabled}
+ onFocus={() => setFocused(optionIndex)}
+ onKeyDown={(event) => keyDown(event, optionIndex)}
+ onClick={() => {
+ choose(optionIndex);
+ if (isOther) otherRef.current?.focus();
+ }}
+ className={cn(
+ 'flex w-full items-start gap-3 rounded-xl border p-3 text-left outline-none focus-visible:ring-3 focus-visible:ring-ring/50',
+ active
+ ? 'border-foreground/20 bg-background'
+ : 'border-border/70 bg-background/45 hover:bg-background/80',
+ )}
+ >
+ <span
+ className={cn(
+ 'mt-0.5 flex size-5 shrink-0 items-center justify-center border',
+ question.multi_select ? 'rounded-md' : 'rounded-full',
+ active && 'bg-foreground text-background',
+ )}
+ >
+ {active && <Check className="size-3" />}
+ </span>
+ <span className="min-w-0">
+ <span className="font-medium">{option.label}</span>
+ {option.description && (
+ <span className="mt-1 block text-muted-foreground">
+ {option.description}
+ </span>
+ )}
+ </span>
+ </button>
+ );
+ },
+ )}
+ </div>
+ {!question.multi_select && question.options[focused]?.preview && (
+ <pre className="mt-3 max-h-48 overflow-auto whitespace-pre-wrap break-words rounded-xl bg-background p-3 text-xs">
+ {question.options[focused].preview}
+ </pre>
+ )}
+ <Textarea
+ ref={otherRef}
+ value={answer.other ?? ''}
+ disabled={disabled}
+ aria-label={t('askUser.other')}
+ placeholder={t('askUser.otherPlaceholder')}
+ className="mt-3 min-h-20 bg-background"
+ onChange={(event) =>
+ update({
+ ...answer,
+ selected: question.multi_select ? answer.selected : [],
+ other: event.target.value,
+ })
+ }
+ onKeyDown={(event) => {
+ if (
+ shouldSubmitOtherInput(
+ event.key,
+ event.shiftKey,
+ event.nativeEvent.isComposing,
+ )
+ ) {
+ event.preventDefault();
+ void advance();
+ }
+ }}
+ />
+ </div>
+ <div className="mt-4 flex shrink-0 flex-wrap justify-end gap-2">
+ <Button variant="outline" onClick={onCancel} disabled={disabled}>
+ <X />
+ {t('askUser.cancel')}
+ </Button>
+ {index > 0 && (
+ <Button
+ variant="outline"
+ disabled={disabled}
+ onClick={() => setIndex(index - 1)}
+ >
+ <ChevronLeft />
+ {t('askUser.back')}
+ </Button>
+ )}
+ <Button disabled={disabled || !canSubmit} onClick={() => void advance()}>
+ {index < questions.length - 1 ? t('askUser.next') : t('askUser.submit')}
+ <ChevronRight />
+ </Button>
+ </div>
+ </section>
+ );
+}
diff --git a/examples/web_ui/frontend/src/components/chat/ChatContent.tsx b/examples/web_ui/frontend/src/components/chat/ChatContent.tsx
index 775cfde84..08592f2f8 100644
--- a/examples/web_ui/frontend/src/components/chat/ChatContent.tsx
+++ b/examples/web_ui/frontend/src/components/chat/ChatContent.tsx
@@ -14,9 +14,11 @@ import React, { useEffect, useMemo, useState } from 'react';
import type { GitStatus } from '@/api';
import type { ChatQueueItem } from '@/api/chat';
import { ASMessageBubble, SteeringMessageBubble } from '@/components/chat/ASMessageBubble.tsx';
+import { ClientToolsMenu } from '@/components/chat/ClientToolsMenu';
import { ConfirmCard } from '@/components/chat/ConfirmCard.tsx';
import { ExternalExecutionCard } from '@/components/chat/ExternalExecutionCard.tsx';
import { FlipCard } from '@/components/chat/FlipCard.tsx';
+import { ManualClientToolCard } from '@/components/chat/ManualClientToolCard';
import { QueuedMessages } from '@/components/chat/QueuedMessages.tsx';
import { TextInput } from '@/components/chat/TextInput.tsx';
import { DiffStats } from '@/components/chat/tool-renderers/_shared';
@@ -37,6 +39,10 @@ import type { ReplyPhase } from '@/hooks/useMessages';
import { useTranslation } from '@/i18n/useI18n';
import type { RealtimeASRConfig } from '@/lib/browserRealtimeASRTransport';
import type { RealtimeConnectionState } from '@/lib/browserWebRTCTransport';
+import {
+ getClientExternalToolRegistration,
+ type ClientExternalToolResult,
+} from '@/lib/client-external-tools';
import { getPendingHitlCalls } from '@/lib/pendingToolCalls';
import { cn } from '@/lib/utils';
@@ -94,6 +100,11 @@ interface ChatContentProps {
replyId: string,
rules?: ToolCallBlock['suggested_rules'],
) => Promise<void>;
+ onClientExternalToolResult: (
+ toolCall: ToolCallBlock,
+ result: ClientExternalToolResult,
+ replyId: string,
+ ) => Promise<void>;
onExternalExecutionResult: (event: ExternalExecutionResultEvent) => Promise<void>;
autoComplete?: (input: string) => string | null;
className?: string;
@@ -156,6 +167,7 @@ const ChatContentComponent: React.FC<ChatContentProps> = ({
disabled,
onSend,
onUserConfirm,
+ onClientExternalToolResult,
onExternalExecutionResult,
autoComplete,
className,
@@ -227,6 +239,34 @@ const ChatContentComponent: React.FC<ChatContentProps> = ({
const toConfirmedToolCalls = pendingHitlCalls.filter((call) => call.kind === 'confirmation');
const externalToolCalls = pendingHitlCalls.filter((call) => call.kind === 'external_execution');
+ const pendingExternalTool = externalToolCalls[0];
+ const pendingExternalToolRegistration = pendingExternalTool
+ ? getClientExternalToolRegistration(pendingExternalTool.toolCall.name)
+ : undefined;
+ const PendingExternalToolComponent = pendingExternalToolRegistration?.PendingComponent;
+ const isManualClientTool =
+ pendingExternalTool?.toolCall.name.startsWith('client__') === true &&
+ !PendingExternalToolComponent;
+ const acceptsInput =
+ Boolean(pendingExternalToolRegistration?.composerResult) &&
+ (!pendingExternalToolRegistration?.canCompose ||
+ Boolean(
+ pendingExternalTool &&
+ pendingExternalToolRegistration.canCompose(pendingExternalTool.toolCall),
+ ));
+
+ const handleSend = async (content: ContentBlock[]) => {
+ const pending = pendingExternalTool;
+ if (!pending || !acceptsInput) {
+ await onSend(content);
+ return;
+ }
+
+ const result = pendingExternalToolRegistration?.composerResult?.(content, pending.toolCall);
+ if (result === null || result === undefined) return;
+ await onClientExternalToolResult(pending.toolCall, result, pending.replyId);
+ };
+
// On an empty session the prompt and the input centre together, so every box
// down to the message list shrinks to its content instead of filling.
return (
@@ -363,13 +403,43 @@ const ChatContentComponent: React.FC<ChatContentProps> = ({
)
}
/>
- ) : externalToolCalls.length > 0 ? (
- <ExternalExecutionCard
- key={`${externalToolCalls[0].replyId}:${externalToolCalls[0].toolCall.id}`}
- replyId={externalToolCalls[0].replyId}
- toolCall={externalToolCalls[0].toolCall}
- onResult={onExternalExecutionResult}
- />
+ ) : pendingExternalTool ? (
+ PendingExternalToolComponent ? (
+ <PendingExternalToolComponent
+ key={`${pendingExternalTool.replyId}:${pendingExternalTool.toolCall.id}`}
+ toolCall={pendingExternalTool.toolCall}
+ onSubmit={(result) =>
+ onClientExternalToolResult(
+ pendingExternalTool.toolCall,
+ result,
+ pendingExternalTool.replyId,
+ )
+ }
+ onCancel={onInterrupt}
+ cancelling={phase === 'interrupting'}
+ />
+ ) : isManualClientTool ? (
+ <ManualClientToolCard
+ key={`${pendingExternalTool.replyId}:${pendingExternalTool.toolCall.id}`}
+ toolCall={pendingExternalTool.toolCall}
+ onSubmit={(result) =>
+ onClientExternalToolResult(
+ pendingExternalTool.toolCall,
+ result,
+ pendingExternalTool.replyId,
+ )
+ }
+ onCancel={onInterrupt}
+ cancelling={phase === 'interrupting'}
+ />
+ ) : (
+ <ExternalExecutionCard
+ key={`${pendingExternalTool.replyId}:${pendingExternalTool.toolCall.id}`}
+ replyId={pendingExternalTool.replyId}
+ toolCall={pendingExternalTool.toolCall}
+ onResult={onExternalExecutionResult}
+ />
+ )
) : (
footerSlot
)}
@@ -392,12 +462,13 @@ const ChatContentComponent: React.FC<ChatContentProps> = ({
<TextInput
key={JSON.stringify([agentId, sessionId])}
className="min-w-full max-w-full w-full rounded-[32px] bg-muted p-1"
- onSend={onSend}
+ onSend={handleSend}
disabled={disabled}
autoComplete={autoComplete}
- allowedInputTypes={allowedInputTypes}
+ allowedInputTypes={acceptsInput ? [] : allowedInputTypes}
fileProcessor={fileProcessor}
phase={phase}
+ acceptsInput={acceptsInput}
queuedCount={queuedCount}
onInterrupt={onInterrupt}
voiceState={voiceState}
@@ -417,39 +488,42 @@ const ChatContentComponent: React.FC<ChatContentProps> = ({
value={cwd}
onChange={onCwdChange}
/>
- {git && (
- <Button
- className="font-mono"
- variant="secondary"
- size="sm"
- onClick={() => void onRefreshGit?.()}
- title={t('workdir.gitTooltip', {
- staged: git.staged,
- unstaged: git.unstaged,
- untracked: git.untracked,
- })}
- >
- <GitBranch />
- {/* A detached HEAD has no branch to name, so
- fall back to the commit it sits on. The
- server sends no git at all when it has
- neither. */}
- {git.branch ?? git.head?.slice(0, 7)}
- {git.ahead !== null && git.ahead > 0 && (
- <span className="text-xs">↑{git.ahead}</span>
- )}
- {git.behind !== null && git.behind > 0 && (
- <span className="text-xs">↓{git.behind}</span>
- )}
- {/* Renders nothing when both are zero, so a
- clean tree shows just the branch. */}
- <DiffStats
- className="text-xs font-mono"
- insertions={git.insertions}
- deletions={git.deletions}
- />
- </Button>
- )}
+ <div className="flex items-center gap-1.5">
+ <ClientToolsMenu agentId={agentId} sessionId={sessionId} />
+ {git && (
+ <Button
+ className="font-mono"
+ variant="secondary"
+ size="sm"
+ onClick={() => void onRefreshGit?.()}
+ title={t('workdir.gitTooltip', {
+ staged: git.staged,
+ unstaged: git.unstaged,
+ untracked: git.untracked,
+ })}
+ >
+ <GitBranch />
+ {/* A detached HEAD has no branch to name, so
+ fall back to the commit it sits on. The
+ server sends no git at all when it has
+ neither. */}
+ {git.branch ?? git.head?.slice(0, 7)}
+ {git.ahead !== null && git.ahead > 0 && (
+ <span className="text-xs">↑{git.ahead}</span>
+ )}
+ {git.behind !== null && git.behind > 0 && (
+ <span className="text-xs">↓{git.behind}</span>
+ )}
+ {/* Renders nothing when both are zero, so a
+ clean tree shows just the branch. */}
+ <DiffStats
+ className="text-xs font-mono"
+ insertions={git.insertions}
+ deletions={git.deletions}
+ />
+ </Button>
+ )}
+ </div>
</div>
}
/>
diff --git a/examples/web_ui/frontend/src/components/chat/ClientToolEditorDialog.tsx b/examples/web_ui/frontend/src/components/chat/ClientToolEditorDialog.tsx
new file mode 100644
index 000000000..e35386f87
--- /dev/null
+++ b/examples/web_ui/frontend/src/components/chat/ClientToolEditorDialog.tsx
@@ -0,0 +1,191 @@
+import { Braces, Save } from 'lucide-react';
+import { type FormEvent, useId, useState } from 'react';
+
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import { Textarea } from '@/components/ui/textarea';
+import { useTranslation } from '@/i18n/useI18n';
+import {
+ saveCustomClientExternalTool,
+ type CustomClientExternalTool,
+ type CustomClientExternalToolDraft,
+ type CustomToolValidationError,
+} from '@/lib/client-external-tool-store';
+
+const EMPTY_SCHEMA = JSON.stringify(
+ {
+ type: 'object',
+ properties: {},
+ additionalProperties: false,
+ },
+ null,
+ 2,
+);
+
+function getInitialDraft(tool: CustomClientExternalTool | null): CustomClientExternalToolDraft {
+ if (!tool) {
+ return { displayName: '', name: '', description: '', inputSchema: EMPTY_SCHEMA };
+ }
+ return {
+ displayName: tool.display_name,
+ name: tool.definition.name.replace(/^client__/, ''),
+ description: tool.definition.description,
+ inputSchema: JSON.stringify(tool.definition.input_schema, null, 2),
+ };
+}
+
+export function ClientToolEditorDialog({
+ tool,
+ agentId,
+ sessionId,
+ onClose,
+}: {
+ tool: CustomClientExternalTool | null;
+ agentId: string | null;
+ sessionId: string | null;
+ onClose: () => void;
+}) {
+ const { t } = useTranslation();
+ const baseId = useId();
+ const [draft, setDraft] = useState(() => getInitialDraft(tool));
+ const [error, setError] = useState<CustomToolValidationError | null>(null);
+
+ const setField = (field: keyof CustomClientExternalToolDraft, value: string) => {
+ setDraft((current) => ({ ...current, [field]: value }));
+ if (error?.field === field) setError(null);
+ };
+
+ const handleSubmit = (event: FormEvent) => {
+ event.preventDefault();
+ const result = saveCustomClientExternalTool(
+ draft,
+ tool?.definition.name ?? null,
+ agentId,
+ sessionId,
+ );
+ if (!result.ok) {
+ setError(result.error);
+ return;
+ }
+ onClose();
+ };
+
+ const fieldError = (field: CustomToolValidationError['field']) => {
+ if (error?.field !== field) return null;
+ return (
+ <p className="text-xs leading-5 text-destructive" role="alert">
+ {t(`clientTools.validation.${error.code}`)}
+ </p>
+ );
+ };
+
+ return (
+ <Dialog open onOpenChange={(open) => !open && onClose()}>
+ <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-xl">
+ <DialogHeader>
+ <DialogTitle>
+ {t(tool ? 'clientTools.editor.editTitle' : 'clientTools.editor.addTitle')}
+ </DialogTitle>
+ <DialogDescription>{t('clientTools.editor.description')}</DialogDescription>
+ </DialogHeader>
+
+ <form id={`${baseId}-form`} className="space-y-4" onSubmit={handleSubmit}>
+ <div className="space-y-1.5">
+ <Label htmlFor={`${baseId}-display-name`}>
+ {t('clientTools.editor.displayName')}
+ </Label>
+ <Input
+ id={`${baseId}-display-name`}
+ value={draft.displayName}
+ maxLength={80}
+ autoFocus
+ aria-invalid={error?.field === 'displayName'}
+ placeholder={t('clientTools.editor.displayNamePlaceholder')}
+ onChange={(event) => setField('displayName', event.target.value)}
+ />
+ {fieldError('displayName')}
+ </div>
+
+ <div className="space-y-1.5">
+ <Label htmlFor={`${baseId}-name`}>{t('clientTools.editor.toolName')}</Label>
+ <div className="flex rounded-lg border border-input bg-background focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50">
+ <span className="flex items-center border-r border-input px-2.5 font-mono text-xs text-muted-foreground">
+ client__
+ </span>
+ <Input
+ id={`${baseId}-name`}
+ value={draft.name}
+ maxLength={56}
+ aria-invalid={error?.field === 'name'}
+ className="border-0 font-mono focus-visible:ring-0"
+ placeholder={t('clientTools.editor.toolNamePlaceholder')}
+ onChange={(event) => setField('name', event.target.value)}
+ />
+ </div>
+ <p className="text-xs leading-5 text-muted-foreground">
+ {t('clientTools.editor.toolNameHint')}
+ </p>
+ {fieldError('name')}
+ </div>
+
+ <div className="space-y-1.5">
+ <Label htmlFor={`${baseId}-description`}>
+ {t('clientTools.editor.modelDescription')}
+ </Label>
+ <Textarea
+ id={`${baseId}-description`}
+ value={draft.description}
+ maxLength={2000}
+ aria-invalid={error?.field === 'description'}
+ className="min-h-20 resize-y"
+ placeholder={t('clientTools.editor.descriptionPlaceholder')}
+ onChange={(event) => setField('description', event.target.value)}
+ />
+ {fieldError('description')}
+ </div>
+
+ <div className="space-y-1.5">
+ <Label htmlFor={`${baseId}-schema`} className="gap-1.5">
+ <Braces className="size-3.5 text-muted-foreground" />
+ {t('clientTools.inputSchema')}
+ </Label>
+ <Textarea
+ id={`${baseId}-schema`}
+ value={draft.inputSchema}
+ spellCheck={false}
+ aria-invalid={error?.field === 'inputSchema'}
+ className="min-h-52 resize-y font-mono text-xs leading-5"
+ onChange={(event) => setField('inputSchema', event.target.value)}
+ />
+ <p className="text-xs leading-5 text-muted-foreground">
+ {t('clientTools.editor.schemaHint')}
+ </p>
+ <p className="text-xs leading-5 text-muted-foreground">
+ {t('clientTools.editor.permissionHint')}
+ </p>
+ {fieldError('inputSchema')}
+ </div>
+ </form>
+
+ <DialogFooter>
+ <Button type="button" variant="ghost" onClick={onClose}>
+ {t('common.cancel')}
+ </Button>
+ <Button type="submit" form={`${baseId}-form`}>
+ <Save className="size-3.5" />
+ {t('common.save')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/examples/web_ui/frontend/src/components/chat/ClientToolsMenu.tsx b/examples/web_ui/frontend/src/components/chat/ClientToolsMenu.tsx
new file mode 100644
index 000000000..dca9e0e43
--- /dev/null
+++ b/examples/web_ui/frontend/src/components/chat/ClientToolsMenu.tsx
@@ -0,0 +1,309 @@
+import { Braces, ChevronRight, Monitor, Pencil, Plus, Trash2, Wrench } from 'lucide-react';
+import { useState, useSyncExternalStore } from 'react';
+
+import { ClientToolEditorDialog } from './ClientToolEditorDialog';
+import { DeleteDialog } from '@/components/dialog/DeleteDialog';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import {
+ Popover,
+ PopoverContent,
+ PopoverDescription,
+ PopoverHeader,
+ PopoverTitle,
+ PopoverTrigger,
+} from '@/components/ui/popover';
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
+ SheetTrigger,
+} from '@/components/ui/sheet';
+import { Switch } from '@/components/ui/switch';
+import { useIsMobile } from '@/hooks/use-mobile';
+import { useTranslation } from '@/i18n/useI18n';
+import {
+ deleteCustomClientExternalTool,
+ getClientExternalToolServerSnapshot,
+ getClientExternalToolStoreSnapshot,
+ getEnabledClientExternalToolNames,
+ setClientExternalToolEnabled,
+ subscribeClientExternalToolStore,
+ type CustomClientExternalTool,
+} from '@/lib/client-external-tool-store';
+import { CLIENT_EXTERNAL_TOOL_REGISTRY } from '@/lib/client-external-tools';
+
+type ToolEntry =
+ | {
+ kind: 'built-in';
+ name: string;
+ displayName: string;
+ description: string;
+ inputSchema?: Record<string, unknown>;
+ }
+ | {
+ kind: 'custom';
+ name: string;
+ displayName: string;
+ description: string;
+ inputSchema: Record<string, unknown>;
+ tool: CustomClientExternalTool;
+ };
+
+function ClientToolsContent({
+ agentId,
+ sessionId,
+ onAdd,
+ onEdit,
+ onDelete,
+}: {
+ agentId: string | null;
+ sessionId: string | null;
+ onAdd: () => void;
+ onEdit: (tool: CustomClientExternalTool) => void;
+ onDelete: (tool: CustomClientExternalTool) => void;
+}) {
+ const { t } = useTranslation();
+ const state = useSyncExternalStore(
+ subscribeClientExternalToolStore,
+ getClientExternalToolStoreSnapshot,
+ getClientExternalToolServerSnapshot,
+ );
+ const enabledNames = new Set(getEnabledClientExternalToolNames(agentId, sessionId, state));
+ const entries: ToolEntry[] = [
+ ...CLIENT_EXTERNAL_TOOL_REGISTRY.map((registration) => ({
+ kind: 'built-in' as const,
+ name: registration.name,
+ displayName: t(registration.displayNameKey),
+ description: t(registration.displayDescriptionKey),
+ })),
+ ...state.customTools.map((tool) => ({
+ kind: 'custom' as const,
+ name: tool.definition.name,
+ displayName: tool.display_name,
+ description: tool.definition.description,
+ inputSchema: tool.definition.input_schema,
+ tool,
+ })),
+ ];
+ const canSelect = Boolean(agentId && sessionId);
+
+ return (
+ <div className="space-y-3 px-1 pb-1">
+ <div className="flex items-center justify-between gap-3">
+ <p className="text-xs leading-5 text-muted-foreground">
+ {canSelect ? t('clientTools.selectionNote') : t('clientTools.noSessionNote')}
+ </p>
+ <Button type="button" variant="outline" size="sm" onClick={onAdd}>
+ <Plus className="size-3.5" />
+ {t('clientTools.add')}
+ </Button>
+ </div>
+
+ <div className="space-y-2">
+ {entries.map((entry) => {
+ const enabled = enabledNames.has(entry.name);
+ return (
+ <div
+ key={entry.name}
+ className="overflow-hidden rounded-xl bg-muted/60 ring-1 ring-border/70"
+ >
+ <div className="flex items-start gap-3 px-3 py-3">
+ <div className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-background text-muted-foreground ring-1 ring-border">
+ <Monitor className="size-4" />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="font-medium text-foreground">
+ {entry.displayName}
+ </span>
+ <Badge
+ variant="outline"
+ className="bg-background font-normal"
+ >
+ {t(
+ entry.kind === 'built-in'
+ ? 'clientTools.builtInBadge'
+ : 'clientTools.customBadge',
+ )}
+ </Badge>
+ </div>
+ <code className="mt-1 block truncate text-[11px] text-muted-foreground">
+ {entry.name}
+ </code>
+ <p className="mt-1 text-xs leading-5 text-muted-foreground">
+ {entry.description}
+ </p>
+ </div>
+ <div className="flex shrink-0 items-center gap-1">
+ {entry.kind === 'custom' ? (
+ <>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ tooltip={t('common.edit')}
+ onClick={() => onEdit(entry.tool)}
+ >
+ <Pencil />
+ </Button>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ tooltip={t('common.delete')}
+ onClick={() => onDelete(entry.tool)}
+ >
+ <Trash2 />
+ </Button>
+ </>
+ ) : null}
+ <Switch
+ checked={enabled}
+ disabled={!canSelect}
+ aria-label={t('clientTools.toggleLabel', {
+ name: entry.displayName,
+ })}
+ onCheckedChange={(checked) => {
+ if (agentId && sessionId) {
+ setClientExternalToolEnabled(
+ agentId,
+ sessionId,
+ entry.name,
+ checked,
+ );
+ }
+ }}
+ />
+ </div>
+ </div>
+
+ {entry.inputSchema && (
+ <details className="group border-t border-border/70">
+ <summary className="flex cursor-pointer list-none items-center gap-2 px-3 py-2 text-xs font-medium text-muted-foreground outline-none hover:bg-muted focus-visible:ring-3 focus-visible:ring-ring/50 [&::-webkit-details-marker]:hidden">
+ <Braces className="size-3.5" />
+ {t('clientTools.inputSchema')}
+ <ChevronRight className="ml-auto size-3.5 transition-transform group-open:rotate-90" />
+ </summary>
+ <div className="px-3 pb-3">
+ <pre className="max-h-56 overflow-auto rounded-lg bg-background p-3 font-mono text-[11px] leading-5 text-secondary-foreground ring-1 ring-border">
+ {JSON.stringify(entry.inputSchema, null, 2)}
+ </pre>
+ </div>
+ </details>
+ )}
+ </div>
+ );
+ })}
+ </div>
+
+ <p className="px-1 text-xs leading-5 text-muted-foreground">
+ {t('clientTools.availabilityNote')}
+ </p>
+ </div>
+ );
+}
+
+export function ClientToolsMenu({
+ agentId,
+ sessionId,
+}: {
+ agentId: string | null;
+ sessionId: string | null;
+}) {
+ const { t } = useTranslation();
+ const isMobile = useIsMobile();
+ const state = useSyncExternalStore(
+ subscribeClientExternalToolStore,
+ getClientExternalToolStoreSnapshot,
+ getClientExternalToolServerSnapshot,
+ );
+ const enabledCount = getEnabledClientExternalToolNames(agentId, sessionId, state).length;
+ const totalCount = CLIENT_EXTERNAL_TOOL_REGISTRY.length + state.customTools.length;
+ const [editorTool, setEditorTool] = useState<CustomClientExternalTool | null | undefined>();
+ const [deleteTool, setDeleteTool] = useState<CustomClientExternalTool | null>(null);
+ const content = (
+ <ClientToolsContent
+ agentId={agentId}
+ sessionId={sessionId}
+ onAdd={() => setEditorTool(null)}
+ onEdit={setEditorTool}
+ onDelete={setDeleteTool}
+ />
+ );
+ const trigger = (
+ <Button
+ type="button"
+ variant="secondary"
+ size="sm"
+ className="gap-1.5"
+ aria-label={t('clientTools.triggerLabel', {
+ enabled: enabledCount,
+ total: totalCount,
+ })}
+ >
+ <Wrench className="size-3.5" />
+ <span className="hidden sm:inline">{t('clientTools.trigger')}</span>
+ <Badge variant="outline" className="h-4 min-w-4 bg-background px-1 text-[10px]">
+ {enabledCount}/{totalCount}
+ </Badge>
+ </Button>
+ );
+
+ return (
+ <>
+ {isMobile ? (
+ <Sheet>
+ <SheetTrigger asChild>{trigger}</SheetTrigger>
+ <SheetContent
+ side="bottom"
+ className="max-h-[85vh] rounded-t-[24px] px-4 pb-5 pt-1"
+ >
+ <SheetHeader className="px-1 pb-2 pt-4 text-left">
+ <SheetTitle>{t('clientTools.title')}</SheetTitle>
+ <SheetDescription>{t('clientTools.description')}</SheetDescription>
+ </SheetHeader>
+ <div className="overflow-y-auto">{content}</div>
+ </SheetContent>
+ </Sheet>
+ ) : (
+ <Popover>
+ <PopoverTrigger asChild>{trigger}</PopoverTrigger>
+ <PopoverContent align="end" side="top" className="max-h-[70vh] w-[26rem] p-3">
+ <PopoverHeader className="px-1 pb-2">
+ <PopoverTitle className="flex items-center gap-2">
+ <Wrench className="size-4 text-muted-foreground" />
+ {t('clientTools.title')}
+ </PopoverTitle>
+ <PopoverDescription>{t('clientTools.description')}</PopoverDescription>
+ </PopoverHeader>
+ <div className="max-h-[calc(70vh-5rem)] overflow-y-auto">{content}</div>
+ </PopoverContent>
+ </Popover>
+ )}
+
+ {editorTool !== undefined ? (
+ <ClientToolEditorDialog
+ key={editorTool?.definition.name ?? 'new-client-tool'}
+ tool={editorTool}
+ agentId={agentId}
+ sessionId={sessionId}
+ onClose={() => setEditorTool(undefined)}
+ />
+ ) : null}
+
+ <DeleteDialog
+ open={deleteTool !== null}
+ onOpenChange={(open) => !open && setDeleteTool(null)}
+ title={t('clientTools.deleteTitle', { name: deleteTool?.display_name ?? '' })}
+ description={t('clientTools.deleteDescription')}
+ confirmLabel={t('common.delete')}
+ onConfirm={async () => {
+ if (deleteTool) deleteCustomClientExternalTool(deleteTool.definition.name);
+ }}
+ />
+ </>
+ );
+}
diff --git a/examples/web_ui/frontend/src/components/chat/ManualClientToolCard.tsx b/examples/web_ui/frontend/src/components/chat/ManualClientToolCard.tsx
new file mode 100644
index 000000000..3da831b2b
--- /dev/null
+++ b/examples/web_ui/frontend/src/components/chat/ManualClientToolCard.tsx
@@ -0,0 +1,173 @@
+import type { ToolCallBlock } from '@agentscope-ai/agentscope/message';
+import { Braces, Check, FileText, Wrench, X } from 'lucide-react';
+import { useMemo, useState } from 'react';
+
+import { Button } from '@/components/ui/button';
+import { Spinner } from '@/components/ui/spinner';
+import { Textarea } from '@/components/ui/textarea';
+import { useTranslation } from '@/i18n/useI18n';
+import type { ClientExternalToolResult } from '@/lib/client-external-tools';
+import { cn } from '@/lib/utils';
+
+type ResultMode = 'text' | 'json';
+
+function formatToolInput(input: string): string {
+ try {
+ return JSON.stringify(JSON.parse(input), null, 2);
+ } catch {
+ return input;
+ }
+}
+
+export function ManualClientToolCard({
+ toolCall,
+ onSubmit,
+ onCancel,
+ cancelling,
+}: {
+ toolCall: ToolCallBlock;
+ onSubmit: (result: ClientExternalToolResult) => Promise<void>;
+ onCancel?: () => void;
+ cancelling: boolean;
+}) {
+ const { t } = useTranslation();
+ const [mode, setMode] = useState<ResultMode>('text');
+ const [textResult, setTextResult] = useState('');
+ const [jsonResult, setJsonResult] = useState('{}');
+ const [jsonError, setJsonError] = useState(false);
+ const [submitting, setSubmitting] = useState(false);
+ const formattedInput = useMemo(() => formatToolInput(toolCall.input), [toolCall.input]);
+
+ const handleSubmit = async () => {
+ if (submitting) return;
+ let result: ClientExternalToolResult;
+ if (mode === 'text') {
+ const text = textResult.trim();
+ if (!text) return;
+ result = text;
+ } else {
+ try {
+ result = JSON.parse(jsonResult) as ClientExternalToolResult;
+ setJsonError(false);
+ } catch {
+ setJsonError(true);
+ return;
+ }
+ }
+
+ setSubmitting(true);
+ try {
+ await onSubmit(result);
+ } catch {
+ setSubmitting(false);
+ }
+ };
+
+ const canSubmit = mode === 'json' || textResult.trim().length > 0;
+
+ return (
+ <section className="max-h-[min(72vh,40rem)] w-full overflow-y-auto rounded-[28px] bg-muted px-5 py-5 text-sm ring-1 ring-border sm:px-6">
+ <div className="flex items-start gap-3">
+ <div className="flex size-8 shrink-0 items-center justify-center rounded-full bg-background text-muted-foreground ring-1 ring-border">
+ <Wrench className="size-4" />
+ </div>
+ <div className="min-w-0 flex-1">
+ <p className="text-xs font-medium uppercase tracking-[0.14em] text-muted-foreground">
+ {t('clientTools.manual.eyebrow')}
+ </p>
+ <h2 className="mt-1 break-all text-base font-medium leading-6 text-foreground">
+ {toolCall.name}
+ </h2>
+ <p className="mt-1 leading-5 text-muted-foreground">
+ {t('clientTools.manual.description')}
+ </p>
+ </div>
+ </div>
+
+ <details className="group mt-4 overflow-hidden rounded-xl bg-background/60 ring-1 ring-border/70">
+ <summary className="flex cursor-pointer list-none items-center gap-2 px-3 py-2.5 font-medium text-muted-foreground outline-none focus-visible:ring-3 focus-visible:ring-ring/50 [&::-webkit-details-marker]:hidden">
+ <Braces className="size-3.5" />
+ {t('clientTools.manual.arguments')}
+ </summary>
+ <pre className="max-h-48 overflow-auto border-t border-border/70 p-3 font-mono text-xs leading-5 text-secondary-foreground">
+ {formattedInput}
+ </pre>
+ </details>
+
+ <div className="mt-4">
+ <div className="inline-flex rounded-lg bg-background/60 p-1 ring-1 ring-border/70">
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className={cn(mode === 'text' && 'bg-background shadow-sm')}
+ onClick={() => setMode('text')}
+ >
+ <FileText className="size-3.5" />
+ {t('clientTools.manual.text')}
+ </Button>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className={cn(mode === 'json' && 'bg-background shadow-sm')}
+ onClick={() => setMode('json')}
+ >
+ <Braces className="size-3.5" />
+ JSON
+ </Button>
+ </div>
+
+ <Textarea
+ value={mode === 'text' ? textResult : jsonResult}
+ disabled={submitting || cancelling}
+ spellCheck={mode === 'text'}
+ aria-invalid={mode === 'json' && jsonError}
+ className={cn(
+ 'mt-2 min-h-28 resize-y bg-background',
+ mode === 'json' && 'font-mono text-xs leading-5',
+ )}
+ placeholder={t(
+ mode === 'text'
+ ? 'clientTools.manual.textPlaceholder'
+ : 'clientTools.manual.jsonPlaceholder',
+ )}
+ onChange={(event) => {
+ if (mode === 'text') setTextResult(event.target.value);
+ else {
+ setJsonResult(event.target.value);
+ setJsonError(false);
+ }
+ }}
+ />
+ {mode === 'json' && jsonError ? (
+ <p className="mt-1.5 text-xs text-destructive" role="alert">
+ {t('clientTools.manual.invalidJson')}
+ </p>
+ ) : null}
+ </div>
+
+ <div className="mt-4 flex justify-end gap-2">
+ {onCancel ? (
+ <Button
+ type="button"
+ variant="outline"
+ disabled={submitting || cancelling}
+ onClick={onCancel}
+ >
+ {cancelling ? <Spinner className="size-4" /> : <X className="size-4" />}
+ {t(cancelling ? 'clientTools.cancelling' : 'clientTools.cancel')}
+ </Button>
+ ) : null}
+ <Button
+ type="button"
+ disabled={!canSubmit || submitting || cancelling}
+ onClick={() => void handleSubmit()}
+ >
+ {submitting ? <Spinner className="size-4" /> : <Check className="size-4" />}
+ {t('clientTools.manual.submit')}
+ </Button>
+ </div>
+ </section>
+ );
+}
diff --git a/examples/web_ui/frontend/src/components/chat/TextInput.tsx b/examples/web_ui/frontend/src/components/chat/TextInput.tsx
index 0e673600d..652ee4720 100644
--- a/examples/web_ui/frontend/src/components/chat/TextInput.tsx
+++ b/examples/web_ui/frontend/src/components/chat/TextInput.tsx
@@ -90,6 +90,8 @@ interface TextInputProps {
* appending another turn to the queue.
*/
phase?: ReplyPhase;
+ /** Allow sending while a reply is parked awaiting structured input. */
+ acceptsInput?: boolean;
/** Number of accepted user turns that have not started a reply yet. */
queuedCount?: number;
onInterrupt?: () => void;
@@ -167,6 +169,7 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(
allowedInputTypes,
fileProcessor,
phase = 'idle',
+ acceptsInput = false,
queuedCount = 0,
onInterrupt,
voiceState = 'idle',
@@ -360,7 +363,15 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(
};
const handleSend = async () => {
- if (!hasContent || disabled || hasProcessing || submitting || speechInputBusy) return;
+ if (
+ !hasContent ||
+ disabled ||
+ hasProcessing ||
+ submitting ||
+ speechInputBusy ||
+ (acceptsInput && files.length > 0)
+ )
+ return;
const blocks: ContentBlock[] = [];
@@ -439,9 +450,15 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(
if (hasContent || replyActive || submitting) {
return {
icon: submitting ? Loader2 : ArrowUp,
- tooltip: replyActive ? t('textInput.queue') : t('textInput.send'),
+ tooltip:
+ replyActive && !acceptsInput ? t('textInput.queue') : t('textInput.send'),
disabled:
- disabled || !hasContent || hasProcessing || submitting || speechInputBusy,
+ disabled ||
+ !hasContent ||
+ hasProcessing ||
+ submitting ||
+ speechInputBusy ||
+ (acceptsInput && files.length > 0),
variant: 'default',
onClick: handleSend,
};
diff --git a/examples/web_ui/frontend/src/components/chat/tool-renderers/AskUserRenderer.tsx b/examples/web_ui/frontend/src/components/chat/tool-renderers/AskUserRenderer.tsx
new file mode 100644
index 000000000..e866e8fd7
--- /dev/null
+++ b/examples/web_ui/frontend/src/components/chat/tool-renderers/AskUserRenderer.tsx
@@ -0,0 +1,43 @@
+import { toolArgClass, toolLabelClass } from './_shared';
+import { defaultRenderBody } from './DefaultRenderer';
+import type { ToolRenderer } from './types';
+import { parseAskUserPayload, parseAskUserResult } from '@/lib/ask-user';
+
+export const AskUserRenderer: ToolRenderer = {
+ renderHeader(pair, t) {
+ const result = parseAskUserResult(pair.result?.metadata);
+ const payload = parseAskUserPayload(pair.call.input);
+ return (
+ <>
+ <span className={toolLabelClass}>
+ {t(result ? 'askUser.historyAnswered' : 'askUser.historyAsked')}
+ </span>
+ <span className={toolArgClass}>
+ {result?.answers
+ .map((answer) =>
+ [...answer.selected, answer.other].filter(Boolean).join(', '),
+ )
+ .join('; ') ||
+ payload?.questions.map((question) => question.question).join('; ') ||
+ pair.call.name}
+ </span>
+ </>
+ );
+ },
+ renderBody(pair, t) {
+ const result = parseAskUserResult(pair.result?.metadata);
+ if (!result) return pair.result ? defaultRenderBody(pair, t) : null;
+ return (
+ <div className="space-y-3 rounded-lg border bg-background p-3">
+ {result.answers.map((answer) => (
+ <div key={answer.question}>
+ <p className="text-xs text-muted-foreground">{answer.question}</p>
+ <p className="mt-1 whitespace-pre-wrap break-words text-sm">
+ {[...answer.selected, answer.other].filter(Boolean).join(', ')}
+ </p>
+ </div>
+ ))}
+ </div>
+ );
+ },
+};
diff --git a/examples/web_ui/frontend/src/components/chat/tool-renderers/index.tsx b/examples/web_ui/frontend/src/components/chat/tool-renderers/index.tsx
index a119af8b8..b53745c19 100644
--- a/examples/web_ui/frontend/src/components/chat/tool-renderers/index.tsx
+++ b/examples/web_ui/frontend/src/components/chat/tool-renderers/index.tsx
@@ -16,6 +16,7 @@ import { ReadRenderer } from './ReadRenderer';
import { TaskCreateRenderer } from './TaskCreateRenderer';
import type { TFunction, ToolCallWithResult, ToolRenderer } from './types';
import { WriteRenderer } from './WriteRenderer';
+import { getClientExternalToolRegistration } from '@/lib/client-external-tools';
const renderers: Record<string, ToolRenderer> = {
Bash: BashRenderer,
@@ -28,7 +29,9 @@ const renderers: Record<string, ToolRenderer> = {
};
function getRenderer(toolName: string): ToolRenderer {
- return renderers[toolName] ?? {};
+ return (
+ getClientExternalToolRegistration(toolName)?.historyRenderer ?? renderers[toolName] ?? {}
+ );
}
export function getDisplayName(call: ToolCallBlock, t: TFunction): string {
diff --git a/examples/web_ui/frontend/src/hooks/useMessages.ts b/examples/web_ui/frontend/src/hooks/useMessages.ts
index 068a59f13..8d7dde126 100644
--- a/examples/web_ui/frontend/src/hooks/useMessages.ts
+++ b/examples/web_ui/frontend/src/hooks/useMessages.ts
@@ -10,9 +10,9 @@ import type {
ToolResultEndEvent,
UserConfirmResultEvent,
} from '@agentscope-ai/agentscope/event';
-import { appendEvent, AssistantMsg, UserMsg } from '@agentscope-ai/agentscope/message';
+import { AssistantMsg, UserMsg } from '@agentscope-ai/agentscope/message';
import type { Msg, ContentBlock } from '@agentscope-ai/agentscope/message';
-import type { ToolCallBlock } from '@agentscope-ai/agentscope/message';
+import type { ToolCallBlock, ToolResultBlock } from '@agentscope-ai/agentscope/message';
import { useState, useCallback, useRef, useEffect, useMemo, useLayoutEffect } from 'react';
import { toast } from 'sonner';
@@ -26,6 +26,9 @@ import {
useChatQueue,
} from '@/hooks/useChatQueue';
import { useTranslation } from '@/i18n/useI18n';
+import { ASK_USER_TOOL_NAME, formatAskUserOutput, parseAskUserResult } from '@/lib/ask-user';
+import type { ClientExternalToolResult } from '@/lib/client-external-tools';
+import { appendMessageEvent } from '@/lib/message-events';
import { getPendingHitlCalls } from '@/lib/pendingToolCalls';
/**
@@ -372,7 +375,7 @@ export function useMessages(
: (msgsRef.current.find((message) => message.id === event.reply_id) ?? null)
: currentReplyRef.current;
if (reply) {
- appendEvent(reply, event);
+ appendMessageEvent(reply, event);
// ``appendEvent`` mutates in place, which would leave
// every Msg identical across renders and force the whole
// list to re-render on each delta. Republish just the
@@ -697,6 +700,53 @@ export function useMessages(
[agentId, sessionId, session],
);
+ /** Return a client-executed tool result and resume the parked reply. */
+ const onClientExternalToolResult = useCallback(
+ async (toolCall: ToolCallBlock, result: ClientExternalToolResult, replyId: string) => {
+ if (!agentId || !sessionId || activeSessionRef.current !== session) return;
+
+ currentReplyRef.current = msgsRef.current.find((msg) => msg.id === replyId) ?? null;
+ const createdAt = new Date().toISOString();
+ const nativeResult =
+ toolCall.name === ASK_USER_TOOL_NAME ? parseAskUserResult(result) : null;
+ if (toolCall.name === ASK_USER_TOOL_NAME && !nativeResult) {
+ throw new Error('Invalid AskUser answers');
+ }
+ const toolResult: ToolResultBlock = {
+ type: 'tool_result',
+ id: toolCall.id,
+ name: toolCall.name,
+ output: [
+ {
+ type: 'text',
+ id: crypto.randomUUID(),
+ text: nativeResult
+ ? formatAskUserOutput(nativeResult)
+ : typeof result === 'string'
+ ? result
+ : JSON.stringify(result),
+ created_at: createdAt,
+ finished_at: createdAt,
+ },
+ ],
+ state: 'success',
+ metadata: nativeResult ?? {},
+ created_at: createdAt,
+ finished_at: createdAt,
+ };
+ const event: ExternalExecutionResultEvent = {
+ type: EventType.EXTERNAL_EXECUTION_RESULT,
+ id: crypto.randomUUID(),
+ created_at: createdAt,
+ reply_id: replyId,
+ execution_results: [toolResult],
+ };
+
+ await onExternalExecutionResult(event);
+ },
+ [agentId, sessionId, session, onExternalExecutionResult],
+ );
+
/** Abort the current SSE connection. */
const abort = useCallback(() => {
abortRef.current?.abort();
@@ -826,6 +876,7 @@ export function useMessages(
steerQueued,
send,
onUserConfirm,
+ onClientExternalToolResult,
onExternalExecutionResult,
onSubagentConfirm,
subagentHitl: ownsConversation ? subagentHitl : [],
diff --git a/examples/web_ui/frontend/src/i18n/locales/en.json b/examples/web_ui/frontend/src/i18n/locales/en.json
index f5b2b9ea5..a21725e4e 100644
--- a/examples/web_ui/frontend/src/i18n/locales/en.json
+++ b/examples/web_ui/frontend/src/i18n/locales/en.json
@@ -140,6 +140,78 @@
"toConfirm": "to confirm",
"yesWithRule": "Yes, and allow {{toolName}} to execute {{ruleContent}} for this session"
},
+ "askUser": {
+ "multiSelect": "Select one or more options. Space toggles a choice; Enter continues.",
+ "back": "Back",
+ "next": "Next",
+ "other": "Other",
+ "otherPlaceholder": "Enter a different answer",
+ "cancel": "Cancel",
+ "invalidDescription": "Cancel this request and ask the agent to try again.",
+ "historyAsked": "Asked",
+ "historyAnswered": "Selected",
+ "submit": "Continue"
+ },
+ "clientTools": {
+ "trigger": "Tools",
+ "triggerLabel": "{{enabled}} of {{total}} client tools enabled",
+ "title": "Client tools",
+ "description": "Choose the browser tools this Web UI provides to the agent.",
+ "builtInBadge": "Built-in",
+ "customBadge": "Custom",
+ "add": "Add tool",
+ "selectionNote": "Enabled tools are sent on the next turn in this conversation.",
+ "noSessionNote": "Open a conversation to choose enabled tools.",
+ "toggleLabel": "Toggle {{name}}",
+ "inputSchema": "Input schema",
+ "availabilityNote": "Custom tools are completed manually in this browser. No custom code is executed.",
+ "deleteTitle": "Delete custom tool \"{{name}}\"?",
+ "deleteDescription": "The tool will be removed from every conversation in this browser. A call already waiting for a result can still be completed.",
+ "cancel": "Cancel request",
+ "cancelling": "Cancelling",
+ "editor": {
+ "addTitle": "Add custom tool",
+ "editTitle": "Edit custom tool",
+ "description": "Describe a tool the agent can call. You will enter its result manually when it is requested.",
+ "displayName": "Display name",
+ "displayNamePlaceholder": "Enter a display name",
+ "toolName": "Tool name",
+ "toolNamePlaceholder": "Enter a tool name",
+ "toolNameHint": "Use letters, numbers, underscores, or hyphens. The client__ namespace is added automatically.",
+ "modelDescription": "Description for the agent",
+ "descriptionPlaceholder": "Explain when the agent should call this tool and what result it expects.",
+ "schemaHint": "The root must be an object with a properties map. Only local JSON Schema references are allowed.",
+ "permissionHint": "Custom tools are treated as potentially effectful and require confirmation before each call."
+ },
+ "validation": {
+ "required": "This field is required.",
+ "displayNameTooLong": "Display name must be 80 characters or fewer.",
+ "invalidName": "Enter a valid name up to 56 characters using letters, numbers, underscores, or hyphens.",
+ "duplicateName": "A client tool already uses this name.",
+ "descriptionTooLong": "Description must be 2,000 characters or fewer.",
+ "invalidJson": "Enter valid JSON.",
+ "invalidSchema": "Enter a valid JSON Schema using the Draft 2020-12 vocabulary.",
+ "schemaMustBeObject": "The schema must define an object at its root.",
+ "schemaPropertiesRequired": "The schema must include a properties object.",
+ "remoteReference": "Only local schema references beginning with # are allowed.",
+ "schemaTooLarge": "The schema must be 64 KiB or smaller.",
+ "toolLimit": "A browser can provide at most 16 client tools."
+ },
+ "manual": {
+ "eyebrow": "Manual tool result",
+ "description": "Review the arguments and return the result the agent should receive.",
+ "arguments": "Arguments",
+ "text": "Text",
+ "textPlaceholder": "Enter the tool result",
+ "jsonPlaceholder": "Enter a JSON value",
+ "invalidJson": "Enter a valid JSON value before continuing.",
+ "submit": "Return result"
+ },
+ "askUser": {
+ "name": "Request user input",
+ "description": "Ask you to choose from structured options or enter another answer."
+ }
+ },
"messageBubble": {
"thinking": "Thinking",
"thinkingFor": "Thinking for {{duration}}",
diff --git a/examples/web_ui/frontend/src/i18n/locales/zh.json b/examples/web_ui/frontend/src/i18n/locales/zh.json
index 1021743e1..4ac67c388 100644
--- a/examples/web_ui/frontend/src/i18n/locales/zh.json
+++ b/examples/web_ui/frontend/src/i18n/locales/zh.json
@@ -140,6 +140,78 @@
"toConfirm": "确认",
"yesWithRule": "是,且该次对话中都允许 {{toolName}} 执行 {{ruleContent}}"
},
+ "askUser": {
+ "multiSelect": "可选择多项。空格切换选项,回车继续。",
+ "back": "上一题",
+ "next": "下一题",
+ "other": "其他",
+ "otherPlaceholder": "请输入其他方案",
+ "cancel": "取消",
+ "invalidDescription": "请取消本次请求,并让智能体重新发起选择。",
+ "historyAsked": "已询问",
+ "historyAnswered": "已选择",
+ "submit": "继续"
+ },
+ "clientTools": {
+ "trigger": "工具",
+ "triggerLabel": "已启用 {{enabled}} 个客户端工具,共 {{total}} 个",
+ "title": "客户端工具",
+ "description": "选择此 Web UI 在当前对话中向智能体提供的浏览器工具。",
+ "builtInBadge": "内置",
+ "customBadge": "自定义",
+ "add": "添加工具",
+ "selectionNote": "启用的工具会在当前对话的下一轮请求中发送。",
+ "noSessionNote": "打开一个对话后即可选择启用的工具。",
+ "toggleLabel": "启用或停用 {{name}}",
+ "inputSchema": "输入 Schema",
+ "availabilityNote": "自定义工具由你在此浏览器中手动返回结果,不会执行自定义代码。",
+ "deleteTitle": "删除自定义工具“{{name}}”?",
+ "deleteDescription": "该工具会从此浏览器的所有对话中移除;已经在等待结果的调用仍可继续完成。",
+ "cancel": "取消请求",
+ "cancelling": "正在取消",
+ "editor": {
+ "addTitle": "添加自定义工具",
+ "editTitle": "编辑自定义工具",
+ "description": "描述一个可供智能体调用的工具;智能体调用后,由你手动输入返回结果。",
+ "displayName": "显示名称",
+ "displayNamePlaceholder": "请输入显示名称",
+ "toolName": "工具名称",
+ "toolNamePlaceholder": "请输入工具名称",
+ "toolNameHint": "可使用字母、数字、下划线和连字符;系统会自动添加 client__ 命名空间。",
+ "modelDescription": "提供给智能体的描述",
+ "descriptionPlaceholder": "说明智能体应在何时调用此工具,以及期望获得什么结果。",
+ "schemaHint": "根节点必须是包含 properties 的 object,仅允许本地 JSON Schema 引用。",
+ "permissionHint": "自定义工具默认按可能产生副作用处理,每次调用前都需要你确认。"
+ },
+ "validation": {
+ "required": "此项不能为空。",
+ "displayNameTooLong": "显示名称不能超过 80 个字符。",
+ "invalidName": "请输入不超过 56 个字符的有效名称,仅使用字母、数字、下划线或连字符。",
+ "duplicateName": "已有客户端工具使用该名称。",
+ "descriptionTooLong": "描述不能超过 2000 个字符。",
+ "invalidJson": "请输入有效的 JSON。",
+ "invalidSchema": "请输入符合 Draft 2020-12 词汇的有效 JSON Schema。",
+ "schemaMustBeObject": "Schema 根节点必须定义为 object。",
+ "schemaPropertiesRequired": "Schema 必须包含 properties 对象。",
+ "remoteReference": "仅允许以 # 开头的本地 Schema 引用。",
+ "schemaTooLarge": "Schema 不能超过 64 KiB。",
+ "toolLimit": "一个浏览器最多可提供 16 个客户端工具。"
+ },
+ "manual": {
+ "eyebrow": "手动返回工具结果",
+ "description": "检查调用参数,并输入需要返回给智能体的结果。",
+ "arguments": "调用参数",
+ "text": "文本",
+ "textPlaceholder": "输入工具结果",
+ "jsonPlaceholder": "输入 JSON 值",
+ "invalidJson": "请输入有效的 JSON 值后再继续。",
+ "submit": "返回结果"
+ },
+ "askUser": {
+ "name": "请求用户输入",
+ "description": "让智能体提供结构化选项,也允许你输入其他答案。"
+ }
+ },
"messageBubble": {
"thinking": "思考中",
"thinkingFor": "思考 {{duration}}",
diff --git a/examples/web_ui/frontend/src/lib/ask-user.ts b/examples/web_ui/frontend/src/lib/ask-user.ts
new file mode 100644
index 000000000..4f3b47d38
--- /dev/null
+++ b/examples/web_ui/frontend/src/lib/ask-user.ts
@@ -0,0 +1,143 @@
+import type { ContentBlock } from '@agentscope-ai/agentscope/message';
+
+export const ASK_USER_TOOL_NAME = 'AskUser';
+
+export type AskUserQuestion = {
+ question: string;
+ header: string;
+ context?: string | null;
+ options: { label: string; description: string; preview?: string | null }[];
+ multi_select?: boolean;
+};
+export type AskUserAnswer = { question: string; selected: string[]; other: string | null };
+export type AskUserResult = { answers: AskUserAnswer[] };
+
+const record = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+const optionalText = (value: unknown) => value == null || typeof value === 'string';
+
+export function parseAskUserPayload(input: string): { questions: AskUserQuestion[] } | null {
+ try {
+ const value: unknown = JSON.parse(input);
+ if (!record(value) || !Array.isArray(value.questions)) return null;
+ if (value.questions.length < 1 || value.questions.length > 4) return null;
+ for (const question of value.questions) {
+ if (
+ !record(question) ||
+ typeof question.question !== 'string' ||
+ typeof question.header !== 'string' ||
+ [...question.header].length > 12 ||
+ !optionalText(question.context) ||
+ (question.multi_select !== undefined &&
+ typeof question.multi_select !== 'boolean') ||
+ !Array.isArray(question.options) ||
+ question.options.length < 2 ||
+ question.options.length > 4
+ )
+ return null;
+ if (
+ !question.options.every(
+ (option: unknown) =>
+ record(option) &&
+ typeof option.label === 'string' &&
+ typeof option.description === 'string' &&
+ optionalText(option.preview),
+ )
+ )
+ return null;
+ if (
+ new Set(question.options.map((option) => option.label)).size !==
+ question.options.length
+ )
+ return null;
+ }
+ if (
+ new Set(value.questions.map((question) => question.question)).size !==
+ value.questions.length
+ )
+ return null;
+ return value as { questions: AskUserQuestion[] };
+ } catch {
+ return null;
+ }
+}
+
+export function parseAskUserResult(value: unknown): AskUserResult | null {
+ if (!record(value) || !Array.isArray(value.answers)) return null;
+ if (
+ !value.answers.every(
+ (answer: unknown) =>
+ record(answer) &&
+ typeof answer.question === 'string' &&
+ Array.isArray(answer.selected) &&
+ answer.selected.every((label: unknown) => typeof label === 'string') &&
+ optionalText(answer.other),
+ )
+ )
+ return null;
+ return {
+ answers: value.answers.map((answer) => ({
+ question: answer.question,
+ selected: answer.selected,
+ other: answer.other ?? null,
+ })),
+ };
+}
+
+export function formatAskUserOutput(result: AskUserResult): string {
+ return result.answers
+ .map(
+ (answer) =>
+ `${answer.question}\n${[...answer.selected, answer.other].filter(Boolean).join(', ')}`,
+ )
+ .join('\n\n');
+}
+
+export function toAskUserComposerResult(
+ blocks: ContentBlock[],
+ input: string,
+): AskUserResult | null {
+ const payload = parseAskUserPayload(input);
+ if (!payload || payload.questions.length !== 1 || blocks.some((block) => block.type !== 'text'))
+ return null;
+ const text = blocks
+ .filter((block) => block.type === 'text')
+ .map((block) => block.text)
+ .join('\n')
+ .trim();
+ return text
+ ? { answers: [{ question: payload.questions[0].question, selected: [], other: text }] }
+ : null;
+}
+
+export const shouldSubmitOtherInput = (
+ key: string,
+ shiftKey: boolean,
+ isComposing: boolean,
+): boolean => {
+ return key === 'Enter' && !shiftKey && !isComposing;
+};
+
+export const getNextRadioIndex = (
+ currentIndex: number,
+ key: string,
+ itemCount: number,
+): number | null => {
+ if (itemCount <= 0) return null;
+
+ const index = currentIndex >= 0 && currentIndex < itemCount ? currentIndex : 0;
+ switch (key) {
+ case 'ArrowDown':
+ case 'ArrowRight':
+ return (index + 1) % itemCount;
+ case 'ArrowUp':
+ case 'ArrowLeft':
+ return (index - 1 + itemCount) % itemCount;
+ case 'Home':
+ return 0;
+ case 'End':
+ return itemCount - 1;
+ default:
+ return null;
+ }
+};
diff --git a/examples/web_ui/frontend/src/lib/client-external-tool-definitions.ts b/examples/web_ui/frontend/src/lib/client-external-tool-definitions.ts
new file mode 100644
index 000000000..4ce272104
--- /dev/null
+++ b/examples/web_ui/frontend/src/lib/client-external-tool-definitions.ts
@@ -0,0 +1,2 @@
+// Native tool schemas are owned by the server, not sent by the browser.
+export const CLIENT_BUILTIN_TOOL_NAMES = ['AskUser'] as const;
diff --git a/examples/web_ui/frontend/src/lib/client-external-tool-store.ts b/examples/web_ui/frontend/src/lib/client-external-tool-store.ts
new file mode 100644
index 000000000..6a0aca9c1
--- /dev/null
+++ b/examples/web_ui/frontend/src/lib/client-external-tool-store.ts
@@ -0,0 +1,460 @@
+import Ajv2020 from 'ajv/dist/2020.js';
+
+import { CLIENT_BUILTIN_TOOL_NAMES } from './client-external-tool-definitions.ts';
+import type { ClientExternalToolDefinition } from '../api/types.ts';
+
+export const CLIENT_EXTERNAL_TOOL_STORAGE_KEY = 'agentscope.client-external-tools.v1';
+
+const CLIENT_TOOL_PREFIX = 'client__';
+const MAX_TOOL_NAME_LENGTH = 64;
+const MAX_DISPLAY_NAME_LENGTH = 80;
+const MAX_DESCRIPTION_LENGTH = 2000;
+const MAX_SCHEMA_BYTES = 64 * 1024;
+const MAX_CLIENT_TOOLS = 16;
+const TOOL_NAME_PATTERN = /^client__[a-zA-Z0-9_-]+$/;
+const REFERENCE_KEYWORDS = new Set(['$ref', '$dynamicRef', '$recursiveRef']);
+const SUPPORTED_SCHEMA_URIS = new Set([
+ 'https://json-schema.org/draft/2020-12/schema',
+ 'https://json-schema.org/draft/2020-12/schema#',
+]);
+const SINGLE_SCHEMA_KEYWORDS = new Set([
+ 'additionalProperties',
+ 'unevaluatedProperties',
+ 'propertyNames',
+ 'items',
+ 'contains',
+ 'unevaluatedItems',
+ 'not',
+ 'if',
+ 'then',
+ 'else',
+ 'contentSchema',
+]);
+const SCHEMA_MAP_KEYWORDS = new Set([
+ '$defs',
+ 'definitions',
+ 'properties',
+ 'patternProperties',
+ 'dependentSchemas',
+ 'dependencies',
+]);
+const SCHEMA_ARRAY_KEYWORDS = new Set(['allOf', 'anyOf', 'oneOf', 'prefixItems']);
+
+export interface CustomClientExternalTool {
+ display_name: string;
+ definition: ClientExternalToolDefinition;
+}
+
+export interface CustomClientExternalToolDraft {
+ displayName: string;
+ name: string;
+ description: string;
+ inputSchema: string;
+}
+
+export type CustomToolValidationField = 'displayName' | 'name' | 'description' | 'inputSchema';
+
+export type CustomToolValidationCode =
+ | 'required'
+ | 'displayNameTooLong'
+ | 'invalidName'
+ | 'duplicateName'
+ | 'descriptionTooLong'
+ | 'invalidJson'
+ | 'invalidSchema'
+ | 'schemaMustBeObject'
+ | 'schemaPropertiesRequired'
+ | 'remoteReference'
+ | 'schemaTooLarge'
+ | 'toolLimit';
+
+export type CustomToolValidationError = {
+ field: CustomToolValidationField;
+ code: CustomToolValidationCode;
+};
+
+export type CustomToolValidationResult =
+ | { ok: true; tool: CustomClientExternalTool }
+ | { ok: false; error: CustomToolValidationError };
+
+export interface ClientExternalToolStoreState {
+ version: 1;
+ customTools: CustomClientExternalTool[];
+ selections: Record<string, string[]>;
+}
+
+const EMPTY_STATE: ClientExternalToolStoreState = {
+ version: 1,
+ customTools: [],
+ selections: {},
+};
+
+const builtInNames = new Set<string>(CLIENT_BUILTIN_TOOL_NAMES);
+const listeners = new Set<() => void>();
+let storageListenerAttached = false;
+const schemaValidator = new Ajv2020({ strict: false });
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+function isDefinition(value: unknown): value is ClientExternalToolDefinition {
+ return (
+ isRecord(value) &&
+ typeof value.name === 'string' &&
+ typeof value.description === 'string' &&
+ (value.read_only === undefined || typeof value.read_only === 'boolean') &&
+ isRecord(value.input_schema)
+ );
+}
+
+function isCustomTool(value: unknown): value is CustomClientExternalTool {
+ return (
+ isRecord(value) && typeof value.display_name === 'string' && isDefinition(value.definition)
+ );
+}
+
+function sanitizeCustomTools(value: unknown): CustomClientExternalTool[] {
+ if (!Array.isArray(value)) return [];
+ const tools: CustomClientExternalTool[] = [];
+ const occupiedNames = new Set(builtInNames);
+ for (const candidate of value) {
+ if (!isCustomTool(candidate) || tools.length + builtInNames.size >= MAX_CLIENT_TOOLS) {
+ continue;
+ }
+ const validated = validateCustomClientToolDraft(
+ {
+ displayName: candidate.display_name,
+ name: candidate.definition.name,
+ description: candidate.definition.description,
+ inputSchema: JSON.stringify(candidate.definition.input_schema),
+ },
+ occupiedNames,
+ );
+ if (!validated.ok || validated.tool.definition.name !== candidate.definition.name) continue;
+ tools.push(validated.tool);
+ occupiedNames.add(validated.tool.definition.name);
+ }
+ return tools;
+}
+
+function makeSessionKey(agentId: string, sessionId: string): string {
+ return JSON.stringify([agentId, sessionId]);
+}
+
+function readStoredState(): ClientExternalToolStoreState {
+ if (typeof window === 'undefined') return EMPTY_STATE;
+
+ try {
+ return parseClientExternalToolStoreState(
+ window.localStorage.getItem(CLIENT_EXTERNAL_TOOL_STORAGE_KEY),
+ );
+ } catch {
+ return EMPTY_STATE;
+ }
+}
+
+let snapshot = readStoredState();
+
+function emit(nextState: ClientExternalToolStoreState): void {
+ snapshot = nextState;
+ try {
+ window.localStorage.setItem(CLIENT_EXTERNAL_TOOL_STORAGE_KEY, JSON.stringify(nextState));
+ } catch {
+ // Keep the current tab functional when storage is unavailable or full.
+ }
+ listeners.forEach((listener) => listener());
+}
+
+function attachStorageListener(): void {
+ if (storageListenerAttached || typeof window === 'undefined') return;
+ storageListenerAttached = true;
+ window.addEventListener('storage', (event) => {
+ if (event.key !== CLIENT_EXTERNAL_TOOL_STORAGE_KEY) return;
+ snapshot = parseClientExternalToolStoreState(event.newValue);
+ listeners.forEach((listener) => listener());
+ });
+}
+
+function* schemaNodes(value: Record<string, unknown>): Generator<Record<string, unknown>> {
+ // Check explicit schema positions here; the server also resolves references.
+ const pending: unknown[] = [value];
+ while (pending.length) {
+ const node = pending.pop();
+ if (!isRecord(node)) continue;
+ yield node;
+ for (const [keyword, child] of Object.entries(node)) {
+ if (SINGLE_SCHEMA_KEYWORDS.has(keyword)) {
+ pending.push(child);
+ } else if (SCHEMA_MAP_KEYWORDS.has(keyword) && isRecord(child)) {
+ for (const item of Object.values(child)) pending.push(item);
+ } else if (SCHEMA_ARRAY_KEYWORDS.has(keyword) && Array.isArray(child)) {
+ for (const item of child) pending.push(item);
+ }
+ }
+ }
+}
+
+function containsRemoteReference(value: Record<string, unknown>): boolean {
+ for (const node of schemaNodes(value)) {
+ if (
+ Object.entries(node).some(
+ ([key, child]) =>
+ REFERENCE_KEYWORDS.has(key) &&
+ typeof child === 'string' &&
+ !child.startsWith('#'),
+ )
+ )
+ return true;
+ }
+ return false;
+}
+
+function schemaByteLength(schema: Record<string, unknown>): number {
+ return new TextEncoder().encode(JSON.stringify(schema)).byteLength;
+}
+
+function containsUnsupportedSchemaDialect(value: Record<string, unknown>): boolean {
+ for (const node of schemaNodes(value)) {
+ if (typeof node.$schema === 'string' && !SUPPORTED_SCHEMA_URIS.has(node.$schema))
+ return true;
+ }
+ return false;
+}
+
+function isValidDraft202012Schema(schema: Record<string, unknown>): boolean {
+ if ('$schema' in schema && typeof schema.$schema !== 'string') return false;
+ const schemaToValidate = { ...schema };
+ delete schemaToValidate.$schema;
+ try {
+ // Reject dialect switches before using the fixed Draft 2020-12 validator.
+ if (containsUnsupportedSchemaDialect(schema)) return false;
+ return schemaValidator.validateSchema(schemaToValidate) === true;
+ } catch {
+ return false;
+ }
+}
+
+export function normalizeClientToolName(name: string): string {
+ const trimmed = name.trim();
+ return trimmed.startsWith(CLIENT_TOOL_PREFIX) ? trimmed : `${CLIENT_TOOL_PREFIX}${trimmed}`;
+}
+
+export function parseClientExternalToolStoreState(
+ serialized: string | null,
+): ClientExternalToolStoreState {
+ if (!serialized) return EMPTY_STATE;
+
+ try {
+ const value: unknown = JSON.parse(serialized);
+ if (!isRecord(value) || value.version !== 1) return EMPTY_STATE;
+
+ const customTools = sanitizeCustomTools(value.customTools);
+ const selections: Record<string, string[]> = {};
+ if (isRecord(value.selections)) {
+ for (const [key, names] of Object.entries(value.selections)) {
+ if (Array.isArray(names)) {
+ selections[key] = names
+ .filter(
+ (name, index): name is string =>
+ typeof name === 'string' &&
+ (builtInNames.has(name) || TOOL_NAME_PATTERN.test(name)) &&
+ names.indexOf(name) === index,
+ )
+ .slice(0, MAX_CLIENT_TOOLS);
+ }
+ }
+ }
+
+ return { version: 1, customTools, selections };
+ } catch {
+ return EMPTY_STATE;
+ }
+}
+
+export function validateCustomClientToolDraft(
+ draft: CustomClientExternalToolDraft,
+ occupiedNames: ReadonlySet<string> = builtInNames,
+): CustomToolValidationResult {
+ const displayName = draft.displayName.trim();
+ if (!displayName) return { ok: false, error: { field: 'displayName', code: 'required' } };
+ if (displayName.length > MAX_DISPLAY_NAME_LENGTH) {
+ return { ok: false, error: { field: 'displayName', code: 'displayNameTooLong' } };
+ }
+
+ const name = normalizeClientToolName(draft.name);
+ if (name.length > MAX_TOOL_NAME_LENGTH || !TOOL_NAME_PATTERN.test(name)) {
+ return { ok: false, error: { field: 'name', code: 'invalidName' } };
+ }
+ if (occupiedNames.has(name)) {
+ return { ok: false, error: { field: 'name', code: 'duplicateName' } };
+ }
+
+ const description = draft.description.trim();
+ if (!description) return { ok: false, error: { field: 'description', code: 'required' } };
+ if (description.length > MAX_DESCRIPTION_LENGTH) {
+ return { ok: false, error: { field: 'description', code: 'descriptionTooLong' } };
+ }
+
+ let schema: unknown;
+ try {
+ schema = JSON.parse(draft.inputSchema);
+ } catch {
+ return { ok: false, error: { field: 'inputSchema', code: 'invalidJson' } };
+ }
+ if (!isRecord(schema) || schema.type !== 'object') {
+ return { ok: false, error: { field: 'inputSchema', code: 'schemaMustBeObject' } };
+ }
+ if (!isRecord(schema.properties)) {
+ return { ok: false, error: { field: 'inputSchema', code: 'schemaPropertiesRequired' } };
+ }
+ if (!isValidDraft202012Schema(schema)) {
+ return { ok: false, error: { field: 'inputSchema', code: 'invalidSchema' } };
+ }
+ if (containsRemoteReference(schema)) {
+ return { ok: false, error: { field: 'inputSchema', code: 'remoteReference' } };
+ }
+ if (schemaByteLength(schema) > MAX_SCHEMA_BYTES) {
+ return { ok: false, error: { field: 'inputSchema', code: 'schemaTooLarge' } };
+ }
+
+ return {
+ ok: true,
+ tool: {
+ display_name: displayName,
+ definition: { name, description, read_only: false, input_schema: schema },
+ },
+ };
+}
+
+export function subscribeClientExternalToolStore(listener: () => void): () => void {
+ attachStorageListener();
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+}
+
+export function getClientExternalToolStoreSnapshot(): ClientExternalToolStoreState {
+ return snapshot;
+}
+
+export function getClientExternalToolServerSnapshot(): ClientExternalToolStoreState {
+ return EMPTY_STATE;
+}
+
+export function getEnabledClientExternalToolNames(
+ agentId: string | null,
+ sessionId: string | null,
+ state: ClientExternalToolStoreState = snapshot,
+): string[] {
+ if (!agentId || !sessionId) return [];
+ const stored = state.selections[makeSessionKey(agentId, sessionId)];
+ if (!stored) return [...builtInNames];
+ const availableNames = new Set([
+ ...builtInNames,
+ ...state.customTools.map((tool) => tool.definition.name),
+ ]);
+ return stored.filter((name) => availableNames.has(name));
+}
+
+export function getEnabledClientExternalToolDefinitions(
+ agentId: string,
+ sessionId: string,
+ state: ClientExternalToolStoreState = snapshot,
+): ClientExternalToolDefinition[] {
+ const definitions = state.customTools.map((tool) => tool.definition);
+ const byName = new Map(definitions.map((definition) => [definition.name, definition]));
+ return getEnabledClientExternalToolNames(agentId, sessionId, state)
+ .map((name) => byName.get(name))
+ .filter((definition): definition is ClientExternalToolDefinition => Boolean(definition));
+}
+
+export function getEnabledClientBuiltinTools(
+ agentId: string,
+ sessionId: string,
+ state: ClientExternalToolStoreState = snapshot,
+): Array<(typeof CLIENT_BUILTIN_TOOL_NAMES)[number]> {
+ const enabled = new Set(getEnabledClientExternalToolNames(agentId, sessionId, state));
+ return CLIENT_BUILTIN_TOOL_NAMES.filter((name) => enabled.has(name));
+}
+
+export function setClientExternalToolEnabled(
+ agentId: string,
+ sessionId: string,
+ toolName: string,
+ enabled: boolean,
+): void {
+ const current = new Set(getEnabledClientExternalToolNames(agentId, sessionId));
+ if (enabled) current.add(toolName);
+ else current.delete(toolName);
+ emit({
+ ...snapshot,
+ selections: {
+ ...snapshot.selections,
+ [makeSessionKey(agentId, sessionId)]: [...current],
+ },
+ });
+}
+
+export function clearClientExternalToolSelection(agentId: string, sessionId: string): void {
+ const key = makeSessionKey(agentId, sessionId);
+ if (!(key in snapshot.selections)) return;
+ const selections = { ...snapshot.selections };
+ delete selections[key];
+ emit({ ...snapshot, selections });
+}
+
+export function saveCustomClientExternalTool(
+ draft: CustomClientExternalToolDraft,
+ originalName: string | null,
+ agentId: string | null,
+ sessionId: string | null,
+): CustomToolValidationResult {
+ if (
+ !originalName &&
+ CLIENT_BUILTIN_TOOL_NAMES.length + snapshot.customTools.length >= MAX_CLIENT_TOOLS
+ ) {
+ return { ok: false, error: { field: 'name', code: 'toolLimit' } };
+ }
+
+ const occupiedNames = new Set([
+ ...builtInNames,
+ ...snapshot.customTools
+ .map((tool) => tool.definition.name)
+ .filter((name) => name !== originalName),
+ ]);
+ const validated = validateCustomClientToolDraft(draft, occupiedNames);
+ if (!validated.ok) return validated;
+
+ const nextName = validated.tool.definition.name;
+ const customTools = originalName
+ ? snapshot.customTools.map((tool) =>
+ tool.definition.name === originalName ? validated.tool : tool,
+ )
+ : [...snapshot.customTools, validated.tool];
+ const selections = Object.fromEntries(
+ Object.entries(snapshot.selections).map(([key, names]) => [
+ key,
+ names.map((name) => (name === originalName ? nextName : name)),
+ ]),
+ );
+ if (!originalName && agentId && sessionId) {
+ const key = makeSessionKey(agentId, sessionId);
+ selections[key] = [...getEnabledClientExternalToolNames(agentId, sessionId), nextName];
+ }
+
+ emit({ version: 1, customTools, selections });
+ return validated;
+}
+
+export function deleteCustomClientExternalTool(toolName: string): void {
+ emit({
+ version: 1,
+ customTools: snapshot.customTools.filter((tool) => tool.definition.name !== toolName),
+ selections: Object.fromEntries(
+ Object.entries(snapshot.selections).map(([key, names]) => [
+ key,
+ names.filter((name) => name !== toolName),
+ ]),
+ ),
+ });
+}
diff --git a/examples/web_ui/frontend/src/lib/client-external-tools.tsx b/examples/web_ui/frontend/src/lib/client-external-tools.tsx
new file mode 100644
index 000000000..9aea30de2
--- /dev/null
+++ b/examples/web_ui/frontend/src/lib/client-external-tools.tsx
@@ -0,0 +1,57 @@
+import type { ContentBlock, ToolCallBlock } from '@agentscope-ai/agentscope/message';
+import type { ComponentType } from 'react';
+
+import { AskUserCard } from '@/components/chat/AskUserCard';
+import { AskUserRenderer } from '@/components/chat/tool-renderers/AskUserRenderer';
+import type { ToolRenderer } from '@/components/chat/tool-renderers/types';
+import { ASK_USER_TOOL_NAME, parseAskUserPayload, toAskUserComposerResult } from '@/lib/ask-user';
+
+export type ClientExternalToolResult =
+ | string
+ | number
+ | boolean
+ | null
+ | ClientExternalToolResult[]
+ | { [key: string]: ClientExternalToolResult };
+
+export type PendingClientExternalToolProps = {
+ toolCall: ToolCallBlock;
+ onSubmit: (result: ClientExternalToolResult) => Promise<void>;
+ onCancel?: () => void;
+ cancelling: boolean;
+};
+
+export type ClientExternalToolRegistration = {
+ name: string;
+ displayNameKey: string;
+ displayDescriptionKey: string;
+ PendingComponent: ComponentType<PendingClientExternalToolProps>;
+ canCompose?: (toolCall: ToolCallBlock) => boolean;
+ composerResult?: (
+ blocks: ContentBlock[],
+ toolCall: ToolCallBlock,
+ ) => ClientExternalToolResult | null;
+ historyRenderer?: ToolRenderer;
+};
+
+export const CLIENT_EXTERNAL_TOOL_REGISTRY: readonly ClientExternalToolRegistration[] = [
+ {
+ name: ASK_USER_TOOL_NAME,
+ displayNameKey: 'clientTools.askUser.name',
+ displayDescriptionKey: 'clientTools.askUser.description',
+ PendingComponent: AskUserCard,
+ canCompose: (toolCall) => parseAskUserPayload(toolCall.input)?.questions.length === 1,
+ composerResult: (blocks, toolCall) => toAskUserComposerResult(blocks, toolCall.input),
+ historyRenderer: AskUserRenderer,
+ },
+];
+
+const registrationsByName = new Map(
+ CLIENT_EXTERNAL_TOOL_REGISTRY.map((registration) => [registration.name, registration]),
+);
+
+export function getClientExternalToolRegistration(
+ toolName: string,
+): ClientExternalToolRegistration | undefined {
+ return registrationsByName.get(toolName);
+}
diff --git a/examples/web_ui/frontend/src/lib/message-events.ts b/examples/web_ui/frontend/src/lib/message-events.ts
new file mode 100644
index 000000000..774a8e407
--- /dev/null
+++ b/examples/web_ui/frontend/src/lib/message-events.ts
@@ -0,0 +1,17 @@
+import { EventType, type AgentEvent } from '@agentscope-ai/agentscope/event';
+import { appendEvent, type Msg } from '@agentscope-ai/agentscope/message';
+
+/** Apply a streamed event to the reply consumed by the chat UI. */
+export function appendMessageEvent(message: Msg, event: AgentEvent): Msg {
+ appendEvent(message, event);
+ if (event.type === EventType.REQUIRE_EXTERNAL_EXECUTION && event.reply_id === message.id) {
+ // The SDK updates state only; the server may also have repaired the JSON input.
+ for (const toolCall of event.tool_calls) {
+ const block = message.content.find(
+ (block) => block.type === 'tool_call' && block.id === toolCall.id,
+ );
+ if (block?.type === 'tool_call') block.input = toolCall.input;
+ }
+ }
+ return message;
+}
diff --git a/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx
index 2f5cd5318..338946a75 100644
--- a/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx
+++ b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx
@@ -322,6 +322,7 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
moveQueued,
reorderQueued,
onUserConfirm,
+ onClientExternalToolResult,
onExternalExecutionResult,
onSubagentConfirm,
subagentHitl,
@@ -1103,6 +1104,7 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatView
disabled={selectedModel === null || voiceBusy}
onSend={send}
onUserConfirm={onUserConfirm}
+ onClientExternalToolResult={onClientExternalToolResult}
onExternalExecutionResult={onExternalExecutionResult}
onInterrupt={interrupt}
onUpdateQueued={updateQueued}
diff --git a/examples/web_ui/frontend/src/pages/chat/index.tsx b/examples/web_ui/frontend/src/pages/chat/index.tsx
index 5346f5452..80e724dff 100644
--- a/examples/web_ui/frontend/src/pages/chat/index.tsx
+++ b/examples/web_ui/frontend/src/pages/chat/index.tsx
@@ -55,6 +55,7 @@ import { AudioProvider } from '@/context/AudioContext';
import { useAgents } from '@/hooks/useAgents';
import { useSessions } from '@/hooks/useSessions';
import { useTranslation } from '@/i18n/useI18n.ts';
+import { clearClientExternalToolSelection } from '@/lib/client-external-tool-store';
/**
* The chat page's outer shell. Responsibilities split cleanly:
@@ -211,6 +212,7 @@ const ChatPageInner = () => {
const handleDeleteSession = async (sessionId: string) => {
await removeSession(sessionId);
+ if (urlAgentId) clearClientExternalToolSelection(urlAgentId, sessionId);
// If we just removed the session the URL is pointing at, fall
// back to the parent /chat/:agentId path; the redirect effect
// will then pick the next available session.
diff --git a/examples/web_ui/pnpm-lock.yaml b/examples/web_ui/pnpm-lock.yaml
index 6c95ef745..14d02164b 100644
--- a/examples/web_ui/pnpm-lock.yaml
+++ b/examples/web_ui/pnpm-lock.yaml
@@ -87,6 +87,9 @@ importers:
'@tanstack/react-query':
specifier: ^5.102.8
version: 5.102.8([email protected])
+ ajv:
+ specifier: ^8.20.0
+ version: 8.20.0
class-variance-authority:
specifier: ^0.7.1
version: 0.7.1
diff --git a/pyproject.toml b/pyproject.toml
index d9b70bd0f..5c7ad6c53 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -46,6 +46,7 @@ dependencies = [
"tree_sitter",
"tree_sitter_bash",
"jsonschema",
+ "referencing",
"pypdf",
# The IANA timezone database, which is absent on Windows and slim images
"tzdata",
diff --git a/src/agentscope/agent/_agent.py b/src/agentscope/agent/_agent.py
index a4ffaeab9..b7e83f41a 100644
--- a/src/agentscope/agent/_agent.py
+++ b/src/agentscope/agent/_agent.py
@@ -2,8 +2,8 @@
"""The unified agent class in AgentScope library."""
import asyncio
import collections
-import json
import inspect
+import json
import re
import warnings
@@ -22,7 +22,7 @@ from typing import (
)
import jsonschema
-from pydantic import BaseModel
+from pydantic import BaseModel, ValidationError
from ._config import (
ContextConfig,
@@ -31,8 +31,7 @@ from ._config import (
InjectionConfig,
_validate_context_config_ratios,
)
-from ..state import AgentState
-from ..state._state import ReplyContext
+from ..state import AgentState, ReplyContext
from ._utils import _ToolCallBatch, Acting, Exit, Reasoning, _resolve_timezone
from .._logging import logger
from .._utils._common import (
@@ -101,6 +100,8 @@ from ..message import (
HintBlock,
)
from ..tool import (
+ AskUser,
+ AskUserParams,
Toolkit,
ToolBase,
ToolChunk,
@@ -2522,11 +2523,24 @@ class Agent:
# TODO: Maybe some logic to mix the validation error in runtime
try:
jsonschema.validate(parsed_input, tool.input_schema)
+ if isinstance(tool, AskUser):
+ # JSON Schema omits the model's uniqueness validators.
+ AskUserParams.model_validate(parsed_input)
except jsonschema.ValidationError as e:
raise AgentOrientedException(
f"Input validation failed for tool '{tool_call.name}': "
f"{e.message} (at {e.json_path})",
) from e
+ except ValidationError as e:
+ raise AgentOrientedException(
+ f"Input validation failed for tool '{tool_call.name}': "
+ f"{e}",
+ ) from e
+ except Exception as e:
+ raise AgentOrientedException(
+ f"Input schema evaluation failed for tool "
+ f"'{tool_call.name}': {e}",
+ ) from e
# The exceptions that
# - cannot found tool
@@ -2630,6 +2644,12 @@ class Agent:
)
# Send requiring external execution event if it's an external tool
if tool.is_external_tool:
+ # External clients should receive the same repaired and
+ # schema-validated JSON that permission checks consumed.
+ tool_call.input = json.dumps(
+ parsed_input,
+ ensure_ascii=False,
+ )
# Update the state to "submitted" BEFORE yielding
# because the outer loop will break immediately after
# receiving this event, preventing any code after yield
diff --git a/src/agentscope/app/_bus_ops.py b/src/agentscope/app/_bus_ops.py
index 00b364bf6..c6aa427e3 100644
--- a/src/agentscope/app/_bus_ops.py
+++ b/src/agentscope/app/_bus_ops.py
@@ -38,6 +38,10 @@ from ._chat_input_store import (
)
if TYPE_CHECKING:
+ from ._client_external_tool import (
+ ClientBuiltinToolName,
+ ClientExternalToolDefinition,
+ )
from .message_bus._base import MessageBus
from agentscope.event import (
@@ -224,6 +228,8 @@ async def enqueue_run_trigger(
| UserInterruptEvent
| Msg
| None = None,
+ client_external_tools: list[ClientExternalToolDefinition] | None = None,
+ client_builtin_tools: list[ClientBuiltinToolName] | None = None,
signal: bool = True,
) -> None:
"""Enqueue a typed run trigger and optionally signal dispatchers.
@@ -264,21 +270,30 @@ async def enqueue_run_trigger(
should be ``None``) for ``wake`` and ``queued_message``. The
function calls ``model_dump(mode="json")`` internally — callers
pass the model object, not a pre-serialised dict.
+ client_external_tools:
+ External tools supported by the client that produced this
+ trigger. They remain scoped to the resulting run.
+ client_builtin_tools:
+ Native external tool names supported by this trigger's client.
signal:
Whether to publish the shared wakeup signal after pushing.
Recovery sweeps pass ``False`` to batch many durable triggers
behind one signal.
"""
- await bus.queue_push(
- MessageBusKeys.wakeup_queue(),
- {
- "user_id": user_id,
- "session_id": session_id,
- "agent_id": agent_id,
- "kind": kind,
- "input": inputs.model_dump(mode="json") if inputs else None,
- },
- )
+ payload: dict[str, object] = {
+ "user_id": user_id,
+ "session_id": session_id,
+ "agent_id": agent_id,
+ "kind": kind,
+ "input": inputs.model_dump(mode="json") if inputs else None,
+ }
+ if client_builtin_tools:
+ payload["client_builtin_tools"] = client_builtin_tools
+ if client_external_tools:
+ payload["client_external_tools"] = [
+ tool.model_dump(mode="json") for tool in client_external_tools
+ ]
+ await bus.queue_push(MessageBusKeys.wakeup_queue(), payload)
if signal:
await bus.publish(MessageBusKeys.wakeup_signal(), {})
@@ -317,6 +332,9 @@ async def enqueue_chat_input(
session_id: str,
agent_id: str,
inputs: Msg | list[Msg],
+ *,
+ client_external_tools: list[ClientExternalToolDefinition] | None = None,
+ client_builtin_tools: list[ClientBuiltinToolName] | None = None,
) -> dict:
"""Append an ordinary user turn to a session FIFO and wake its pump.
@@ -338,6 +356,10 @@ async def enqueue_chat_input(
Agent that owns the session.
inputs:
One user message or a non-empty ordered message list.
+ client_external_tools:
+ Client tool definitions scoped to this queued turn.
+ client_builtin_tools:
+ Native external tool names supported by this turn's client.
Returns:
`dict`:
@@ -365,6 +387,12 @@ async def enqueue_chat_input(
"input": serialized,
"state": "queued",
}
+ if client_external_tools:
+ item["client_external_tools"] = [
+ tool.model_dump(mode="json") for tool in client_external_tools
+ ]
+ if client_builtin_tools:
+ item["client_builtin_tools"] = client_builtin_tools
async with _chat_input_user_quota(bus, user_id):
if (
await _count_user_chat_inputs(bus, user_id)
diff --git a/src/agentscope/app/_client_external_tool.py b/src/agentscope/app/_client_external_tool.py
new file mode 100644
index 000000000..72f51fbd2
--- /dev/null
+++ b/src/agentscope/app/_client_external_tool.py
@@ -0,0 +1,281 @@
+# -*- coding: utf-8 -*-
+"""Client-provided external tool definitions and runtime adapters."""
+import json
+from collections.abc import Iterator
+from typing import Any, Literal
+
+from jsonschema import Draft202012Validator
+from jsonschema.exceptions import SchemaError
+from pydantic import (
+ BaseModel,
+ ConfigDict,
+ Field,
+ TypeAdapter,
+ field_validator,
+)
+from referencing import Registry
+from referencing.exceptions import Unresolvable
+from referencing.jsonschema import DRAFT202012
+
+from .._logging import logger
+from ..permission import (
+ PermissionBehavior,
+ PermissionContext,
+ PermissionDecision,
+)
+from ..tool import ToolBase
+
+
+_MAX_INPUT_SCHEMA_BYTES = 64 * 1024
+ClientBuiltinToolName = Literal["AskUser"]
+CLIENT_EXTERNAL_TOOL_NAME_PREFIX = "client__"
+_REFERENCE_KEYWORDS = {"$ref", "$dynamicRef", "$recursiveRef"}
+_SUPPORTED_SCHEMA_URIS = {
+ "https://json-schema.org/draft/2020-12/schema",
+ "https://json-schema.org/draft/2020-12/schema#",
+}
+_SINGLE_SCHEMA_KEYWORDS = {
+ "additionalProperties",
+ "unevaluatedProperties",
+ "propertyNames",
+ "items",
+ "contains",
+ "unevaluatedItems",
+ "not",
+ "if",
+ "then",
+ "else",
+ "contentSchema",
+}
+_SCHEMA_MAP_KEYWORDS = {
+ "$defs",
+ "definitions",
+ "properties",
+ "patternProperties",
+ "dependentSchemas",
+ "dependencies",
+}
+_SCHEMA_ARRAY_KEYWORDS = {"allOf", "anyOf", "oneOf", "prefixItems"}
+
+
+def _iter_schema_nodes(value: dict[str, Any]) -> Iterator[dict[str, Any]]:
+ """Walk subschemas and local pointer targets, excluding literal data."""
+ resource = DRAFT202012.create_resource(value)
+ # The default registry cannot retrieve resources from the network.
+ pending = [(value, Registry().resolver_with_root(resource))]
+ seen: set[tuple[int, int]] = set()
+ while pending:
+ node, resolver = pending.pop()
+ if not isinstance(node, dict):
+ continue
+ try:
+ scope = resolver.lookup("#").contents
+ except (Unresolvable, ValueError):
+ scope = None
+ identity = (id(node), id(scope))
+ if identity in seen:
+ continue
+ seen.add(identity)
+ yield node
+ for keyword, child in node.items():
+ children = []
+ if keyword in _SINGLE_SCHEMA_KEYWORDS:
+ children = [child]
+ elif keyword in _SCHEMA_MAP_KEYWORDS and isinstance(child, dict):
+ children = list(child.values())
+ elif keyword in _SCHEMA_ARRAY_KEYWORDS and isinstance(child, list):
+ children = child
+ elif (
+ keyword in _REFERENCE_KEYWORDS
+ and isinstance(child, str)
+ and child.startswith("#")
+ ):
+ try:
+ resolved = resolver.lookup(child)
+ except (Unresolvable, ValueError, TypeError):
+ # Broken references remain tool errors at execution.
+ continue
+ pending.append((resolved.contents, resolved.resolver))
+ for item in children:
+ if isinstance(item, dict):
+ pending.append(
+ (
+ item,
+ resolver.in_subresource(
+ DRAFT202012.create_resource(item),
+ ),
+ ),
+ )
+
+
+def _validate_schema_metadata(value: dict[str, Any]) -> None:
+ """Reject unsupported dialects and references to remote schemas."""
+ for node in _iter_schema_nodes(value):
+ for key, child in node.items():
+ if (
+ key == "$schema"
+ and isinstance(child, str)
+ and child not in _SUPPORTED_SCHEMA_URIS
+ ):
+ raise ValueError(
+ "Client tool schemas only support JSON Schema "
+ "Draft 2020-12.",
+ )
+ if (
+ key in _REFERENCE_KEYWORDS
+ and isinstance(child, str)
+ and not child.startswith("#")
+ ):
+ raise ValueError(
+ f"Client tool schemas only support local {key} values.",
+ )
+
+
+class ClientExternalToolDefinition(BaseModel):
+ """A tool that the active client can execute for one chat run."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ name: str = Field(
+ min_length=1,
+ max_length=64,
+ pattern=r"^client__[a-zA-Z0-9_-]+$",
+ description=(
+ "The namespaced tool name exposed to the model. It must start "
+ f"with '{CLIENT_EXTERNAL_TOOL_NAME_PREFIX}'."
+ ),
+ )
+ description: str = Field(
+ min_length=1,
+ max_length=2000,
+ description="The model-facing tool description.",
+ )
+ read_only: bool = Field(
+ default=False,
+ description=(
+ "Whether executing the tool can only read client-side state."
+ ),
+ )
+ input_schema: dict[str, Any] = Field(
+ description="The tool input schema in JSON Schema format.",
+ )
+
+ @field_validator("input_schema")
+ @classmethod
+ def validate_input_schema(
+ cls,
+ value: dict[str, Any],
+ ) -> dict[str, Any]:
+ """Validate schema syntax and the object shape tools require."""
+ try:
+ schema_size = len(
+ json.dumps(
+ value,
+ ensure_ascii=False,
+ separators=(",", ":"),
+ ).encode("utf-8"),
+ )
+ if schema_size > _MAX_INPUT_SCHEMA_BYTES:
+ raise ValueError(
+ f"Tool input_schema exceeds {_MAX_INPUT_SCHEMA_BYTES} "
+ "bytes.",
+ )
+ Draft202012Validator.check_schema(value)
+ _validate_schema_metadata(value)
+ except SchemaError as error:
+ raise ValueError(
+ f"Invalid JSON Schema: {error.message}",
+ ) from error
+ except RecursionError as error:
+ raise ValueError(
+ "Tool input_schema is nested too deeply.",
+ ) from error
+
+ if value.get("type") != "object" or not isinstance(
+ value.get("properties"),
+ dict,
+ ):
+ raise ValueError(
+ "Tool input_schema must define an object with properties.",
+ )
+
+ return value
+
+
+_CLIENT_EXTERNAL_TOOLS_ADAPTER: TypeAdapter = TypeAdapter(
+ list[ClientExternalToolDefinition],
+)
+_CLIENT_BUILTIN_TOOLS_ADAPTER: TypeAdapter = TypeAdapter(
+ list[ClientBuiltinToolName],
+)
+
+
+def parse_client_tool_capabilities(
+ raw_external_tools: object,
+ raw_builtin_tools: object,
+) -> tuple[list[ClientExternalToolDefinition], list[ClientBuiltinToolName]]:
+ """Decode optional queued capabilities without discarding valid input."""
+ try:
+ external_tools = (
+ _CLIENT_EXTERNAL_TOOLS_ADAPTER.validate_python(raw_external_tools)
+ if raw_external_tools is not None
+ else []
+ )
+ except (ValueError, RecursionError):
+ logger.exception("Ignoring invalid queued client external tools.")
+ external_tools = []
+ try:
+ builtin_tools = (
+ _CLIENT_BUILTIN_TOOLS_ADAPTER.validate_python(raw_builtin_tools)
+ if raw_builtin_tools is not None
+ else []
+ )
+ except (ValueError, RecursionError):
+ logger.exception("Ignoring invalid queued client builtin tools.")
+ builtin_tools = []
+ return external_tools, builtin_tools
+
+
+class ClientExternalTool(ToolBase):
+ """Runtime proxy for a tool executed by the active chat client."""
+
+ is_concurrency_safe: bool = False
+ is_read_only: bool = False
+ is_external_tool: bool = True
+ is_state_injected: bool = False
+ is_mcp: bool = False
+ mcp_name: str | None = None
+
+ def __init__(self, definition: ClientExternalToolDefinition) -> None:
+ """Initialize the proxy from a validated client definition."""
+ super().__init__()
+ self.name = definition.name
+ self.description = definition.description
+ self.is_read_only = definition.read_only
+ self.input_schema = definition.input_schema
+
+ async def check_permissions(
+ self,
+ tool_input: dict[str, Any],
+ context: PermissionContext,
+ ) -> PermissionDecision:
+ """Allow client reads and ask before other client-side effects."""
+ del tool_input, context
+ if self.is_read_only:
+ return PermissionDecision(
+ behavior=PermissionBehavior.ALLOW,
+ message=f"Client external tool '{self.name}' is read-only.",
+ decision_reason=(
+ f"The active client declared '{self.name}' read-only."
+ ),
+ )
+ return PermissionDecision(
+ behavior=PermissionBehavior.ASK,
+ message=(
+ f"Client external tool '{self.name}' may change "
+ "client-side state."
+ ),
+ decision_reason=(
+ f"The active client did not declare '{self.name}' read-only."
+ ),
+ )
diff --git a/src/agentscope/app/_manager/_chat_input_queue.py b/src/agentscope/app/_manager/_chat_input_queue.py
index 85f4f8f39..74cfd630c 100644
--- a/src/agentscope/app/_manager/_chat_input_queue.py
+++ b/src/agentscope/app/_manager/_chat_input_queue.py
@@ -16,6 +16,11 @@ from ...event import (
UserInterruptEvent,
)
from ...message import Msg
+from .._client_external_tool import (
+ ClientBuiltinToolName,
+ ClientExternalToolDefinition,
+ parse_client_tool_capabilities,
+)
from ..message_bus import MessageBusKeys
from ._chat_run_registry import CHAT_RUN_SHUTDOWN
from .._bus_ops import (
@@ -302,6 +307,9 @@ class ChatInputQueue:
| ExternalExecutionResultEvent
| UserInterruptEvent
| None,
+ client_external_tools: list[ClientExternalToolDefinition]
+ | None = None,
+ client_builtin_tools: list[ClientBuiltinToolName] | None = None,
) -> None:
"""Serialize a resume with chat-input claim and parked-state checks.
@@ -315,6 +323,10 @@ class ChatInputQueue:
input_msg:
Typed HITL/external-result/interrupt event, or ``None`` for
a compatible control continuation.
+ client_external_tools:
+ Client tool definitions preserved across resume retries.
+ client_builtin_tools:
+ Native tool names supported by the resuming client.
"""
dispatch_lock = self._bus.acquire_lock_bounded(
MessageBusKeys.chat_input_dispatch_lock(session_id),
@@ -332,6 +344,8 @@ class ChatInputQueue:
agent_id=agent_id,
kind=MessageBusKeys.WAKEUP_KIND_RESUME,
inputs=input_msg,
+ client_external_tools=client_external_tools,
+ client_builtin_tools=client_builtin_tools,
)
return
try:
@@ -340,6 +354,8 @@ class ChatInputQueue:
session_id=session_id,
agent_id=agent_id,
input_msg=input_msg,
+ client_external_tools=client_external_tools,
+ client_builtin_tools=client_builtin_tools,
)
finally:
await dispatch_lock.__aexit__(None, None, None)
@@ -492,6 +508,13 @@ class ChatInputQueue:
continue
queue_item_id = payload.get("id")
+ (
+ client_external_tools,
+ client_builtin_tools,
+ ) = parse_client_tool_capabilities(
+ payload.get("client_external_tools"),
+ payload.get("client_builtin_tools"),
+ )
if not isinstance(queue_item_id, str) or not queue_item_id:
queue_item_id = messages[0].id
message_ids = [msg.id for msg in messages]
@@ -567,6 +590,8 @@ class ChatInputQueue:
input_msg=queued_input,
queue_item_id=queue_item_id,
input_persisted=True,
+ client_external_tools=client_external_tools or None,
+ client_builtin_tools=client_builtin_tools or None,
)
claim_state = _MESSAGE_COMPLETED
await self._acknowledge_completed(session_id, payload)
diff --git a/src/agentscope/app/_manager/_wakeup_dispatcher.py b/src/agentscope/app/_manager/_wakeup_dispatcher.py
index 2500c1dd6..fe4b12c1c 100644
--- a/src/agentscope/app/_manager/_wakeup_dispatcher.py
+++ b/src/agentscope/app/_manager/_wakeup_dispatcher.py
@@ -44,6 +44,11 @@ from ...event import (
)
from ...message import Msg
from ...types import ErrorInfo, ErrorType, ReplyFinishedReason
+from .._client_external_tool import (
+ ClientBuiltinToolName,
+ ClientExternalToolDefinition,
+ parse_client_tool_capabilities,
+)
from ..message_bus import MessageBusKeys
from ._chat_input_queue import ChatInputQueue
@@ -296,6 +301,10 @@ class WakeupDispatcher:
agent_id=agent_id,
kind=kind,
raw_input=payload.get("input"),
+ raw_client_external_tools=payload.get(
+ "client_external_tools",
+ ),
+ raw_client_builtin_tools=payload.get("client_builtin_tools"),
)
async def _dispatch_one(
@@ -305,6 +314,8 @@ class WakeupDispatcher:
agent_id: str,
kind: str,
raw_input: dict | list[dict] | None,
+ raw_client_external_tools: list[dict] | None = None,
+ raw_client_builtin_tools: list[str] | None = None,
) -> None:
"""Dispatch a single trigger entry by its ``kind``.
@@ -321,6 +332,10 @@ class WakeupDispatcher:
raw_input (`dict | list[dict] | None`):
Serialised input event for ``resume`` triggers, else
``None``.
+ raw_client_external_tools (`list[dict] | None`):
+ Serialised client tool definitions for this run.
+ raw_client_builtin_tools (`list[str] | None`):
+ Native external tool names supported by this run's client.
"""
is_resume = kind == MessageBusKeys.WAKEUP_KIND_RESUME
is_message = kind == MessageBusKeys.WAKEUP_KIND_MESSAGE
@@ -357,6 +372,14 @@ class WakeupDispatcher:
| Msg
| None
) = None
+ (
+ client_external_tools,
+ client_builtin_tools,
+ ) = parse_client_tool_capabilities(
+ raw_client_external_tools,
+ raw_client_builtin_tools,
+ )
+
if carries_input:
if raw_input is None:
logger.warning(
@@ -396,6 +419,8 @@ class WakeupDispatcher:
agent_id,
kind,
input_msg,
+ client_external_tools,
+ client_builtin_tools,
)
return
@@ -450,6 +475,8 @@ class WakeupDispatcher:
session_id=session_id,
agent_id=agent_id,
input_msg=input_msg,
+ client_external_tools=client_external_tools or None,
+ client_builtin_tools=client_builtin_tools or None,
)
if is_resume
else self._chat_service.run(
@@ -457,6 +484,8 @@ class WakeupDispatcher:
session_id=session_id,
agent_id=agent_id,
input_msg=input_msg,
+ client_external_tools=client_external_tools or None,
+ client_builtin_tools=client_builtin_tools or None,
)
)
task = self._registry.spawn(
@@ -497,6 +526,8 @@ class WakeupDispatcher:
agent_id,
kind,
input_msg,
+ client_external_tools,
+ client_builtin_tools,
)
def _schedule_retry(
@@ -510,6 +541,8 @@ class WakeupDispatcher:
| UserInterruptEvent
| Msg
| None,
+ client_external_tools: list[ClientExternalToolDefinition],
+ client_builtin_tools: list[ClientBuiltinToolName],
) -> None:
"""Re-enqueue an input-carrying (``resume``/``message``) trigger
after a short backoff.
@@ -530,6 +563,10 @@ class WakeupDispatcher:
The trigger kind to re-enqueue (``resume`` / ``message``).
input_msg:
The parsed input to redeliver.
+ client_external_tools:
+ Client tool definitions to preserve across a retry.
+ client_builtin_tools:
+ Native tool names to preserve across a retry.
"""
async def _retry() -> None:
@@ -542,6 +579,8 @@ class WakeupDispatcher:
agent_id=agent_id,
kind=kind, # type: ignore[arg-type]
inputs=input_msg,
+ client_external_tools=client_external_tools,
+ client_builtin_tools=client_builtin_tools,
)
except asyncio.CancelledError:
pass
diff --git a/src/agentscope/app/_router/_chat.py b/src/agentscope/app/_router/_chat.py
index 639db387f..9e68a7ab3 100644
--- a/src/agentscope/app/_router/_chat.py
+++ b/src/agentscope/app/_router/_chat.py
@@ -495,6 +495,8 @@ async def chat(
agent_id=run_agent_id,
kind=MessageBusKeys.WAKEUP_KIND_RESUME,
inputs=request.input,
+ client_external_tools=request.client_external_tools,
+ client_builtin_tools=request.client_builtin_tools,
)
return ChatTriggerResponse(status="started", session_id=run_session_id)
@@ -515,6 +517,8 @@ async def chat(
session_id=request.session_id,
agent_id=request.agent_id,
inputs=request.input,
+ client_external_tools=request.client_external_tools,
+ client_builtin_tools=request.client_builtin_tools,
)
except ChatQueueFullError as exc:
raise HTTPException(
@@ -542,6 +546,8 @@ async def chat(
session_id=request.session_id,
agent_id=request.agent_id,
input_msg=request.input,
+ client_external_tools=request.client_external_tools,
+ client_builtin_tools=request.client_builtin_tools,
),
session_id=request.session_id,
)
diff --git a/src/agentscope/app/_router/_schema/__init__.py b/src/agentscope/app/_router/_schema/__init__.py
index c291f6bea..a13d20241 100644
--- a/src/agentscope/app/_router/_schema/__init__.py
+++ b/src/agentscope/app/_router/_schema/__init__.py
@@ -18,6 +18,7 @@ from ._channel import (
from ._chat import (
ChatRequest,
ChatTriggerResponse,
+ ClientExternalToolDefinition,
ChatQueueItem,
ChatQueueResponse,
ReorderChatQueueRequest,
@@ -187,6 +188,7 @@ __all__ = [
"StartCredentialBindingRequest",
"UpdateChannelRequest",
# Chat
+ "ClientExternalToolDefinition",
"ChatRequest",
"ChatTriggerResponse",
"ChatQueueItem",
diff --git a/src/agentscope/app/_router/_schema/_chat.py b/src/agentscope/app/_router/_schema/_chat.py
index dd705058d..1d0a71986 100644
--- a/src/agentscope/app/_router/_schema/_chat.py
+++ b/src/agentscope/app/_router/_schema/_chat.py
@@ -3,9 +3,14 @@
from typing import Annotated, Literal, TypeAlias
-from pydantic import BaseModel, Field
-
-from ....message import Msg
+from pydantic import BaseModel, Field, field_validator, model_validator
+
+from ..._client_external_tool import (
+ ClientBuiltinToolName,
+ ClientExternalToolDefinition,
+)
+from ....message import Msg, ToolResultState
+from ....tool import AskUser, AskUserMetadata
from ....event import UserConfirmResultEvent, ExternalExecutionResultEvent
NonEmptyMsgList: TypeAlias = Annotated[list[Msg], Field(min_length=1)]
@@ -32,6 +37,48 @@ class ChatRequest(BaseModel):
description="The input message(s), or agent event, or None.",
)
+ client_builtin_tools: list[ClientBuiltinToolName] = Field(
+ default_factory=list,
+ max_length=1,
+ description="Native external tools supported by this client run.",
+ )
+
+ client_external_tools: list[ClientExternalToolDefinition] = Field(
+ default_factory=list,
+ max_length=16,
+ description=(
+ "External tools the active client can execute for this run."
+ ),
+ )
+
+ @field_validator("client_external_tools")
+ @classmethod
+ def validate_unique_client_external_tools(
+ cls,
+ value: list[ClientExternalToolDefinition],
+ ) -> list[ClientExternalToolDefinition]:
+ """Reject ambiguous duplicate client tool names."""
+ names = [tool.name for tool in value]
+ if len(names) != len(set(names)):
+ raise ValueError("Client external tool names must be unique.")
+ return value
+
+ @model_validator(mode="after")
+ def validate_native_answers(self) -> "ChatRequest":
+ """Validate resumed native results even if the tool was disabled.
+
+ Disabling a tool governs future calls, not the contract of a call
+ already waiting for its result.
+ """
+ if isinstance(self.input, ExternalExecutionResultEvent):
+ for result in self.input.execution_results:
+ if (
+ result.name == AskUser.name
+ and result.state == ToolResultState.SUCCESS
+ ):
+ AskUserMetadata.model_validate(result.metadata)
+ return self
+
class ChatTriggerResponse(BaseModel):
"""Response body for an accepted chat trigger.
diff --git a/src/agentscope/app/_service/_chat.py b/src/agentscope/app/_service/_chat.py
index 97009acf1..dcd7c8b97 100644
--- a/src/agentscope/app/_service/_chat.py
+++ b/src/agentscope/app/_service/_chat.py
@@ -61,6 +61,10 @@ from .._types import (
EventProjector,
SubAgentTemplate,
)
+from .._client_external_tool import (
+ ClientBuiltinToolName,
+ ClientExternalToolDefinition,
+)
from ._access import ResourceAccessService
from ._model import get_model
from ._tts_model import get_tts_model
@@ -300,7 +304,10 @@ class ChatService:
| ExternalExecutionResultEvent
| UserInterruptEvent
| None = None,
+ client_external_tools: list[ClientExternalToolDefinition]
+ | None = None,
sop_dispatch: str | None = None,
+ client_builtin_tools: list[ClientBuiltinToolName] | None = None,
queue_item_id: str | None = None,
input_persisted: bool = False,
) -> None:
@@ -342,6 +349,10 @@ class ChatService:
- ``UserInterruptEvent``: abort a parked reply — the
agent closes pending tool calls with interrupted
results and ends the reply (Case B, no reasoning).
+ client_external_tools:
+ External tools supported by the active client for this run.
+ client_builtin_tools:
+ Native external tools enabled by this client for this run.
sop_dispatch (`str | None`, optional):
``"<run id>:<step index>"`` when a SOP run dispatched
this turn, which gives it a submit tool.
@@ -356,7 +367,9 @@ class ChatService:
session_id,
agent_id,
input_msg,
- sop_dispatch,
+ client_external_tools=client_external_tools,
+ client_builtin_tools=client_builtin_tools,
+ sop_dispatch=sop_dispatch,
input_persisted=input_persisted,
)
except Exception as e:
@@ -904,7 +917,10 @@ class ChatService:
| ExternalExecutionResultEvent
| UserInterruptEvent
| None,
+ client_external_tools: list[ClientExternalToolDefinition]
+ | None = None,
sop_dispatch: str | None = None,
+ client_builtin_tools: list[ClientBuiltinToolName] | None = None,
input_persisted: bool = False,
) -> None:
"""The actual chat-run body; wrapped by :meth:`run` for error
@@ -1232,6 +1248,8 @@ class ChatService:
sub_agent_templates=self._sub_agent_templates,
team_role=team_ctx.role if team_ctx else None,
channel_tools=channel_tools,
+ client_external_tools=client_external_tools,
+ client_builtin_tools=client_builtin_tools,
sop_dispatch=sop_dispatch,
)
diff --git a/src/agentscope/app/_service/_toolkit.py b/src/agentscope/app/_service/_toolkit.py
index f17ed4b5c..16a1a64ea 100644
--- a/src/agentscope/app/_service/_toolkit.py
+++ b/src/agentscope/app/_service/_toolkit.py
@@ -9,6 +9,11 @@ tools, and caller-supplied extras — into one :class:`Toolkit`.
from typing import Any, Literal
from .._manager import BackgroundTaskManager, SchedulerManager
+from .._client_external_tool import (
+ ClientBuiltinToolName,
+ ClientExternalTool,
+ ClientExternalToolDefinition,
+)
from ..message_bus import MessageBus
from .._tool import (
SubmitHandover,
@@ -24,6 +29,7 @@ from ..storage import AgentRecord, SessionRecord, StorageBase
from ..workspace_manager import WorkspaceManagerBase
from ...middleware import MiddlewareBase
from ...tool import (
+ AskUser,
TaskCreate,
TaskGet,
TaskList,
@@ -54,7 +60,9 @@ async def get_toolkit(
sub_agent_templates: dict[str, SubAgentTemplate] | None = None,
team_role: Literal["leader", "worker"] | None = None,
channel_tools: list[ToolBase] | None = None,
+ client_external_tools: list[ClientExternalToolDefinition] | None = None,
sop_dispatch: str | None = None,
+ client_builtin_tools: list[ClientBuiltinToolName] | None = None,
) -> Toolkit:
"""Assemble the complete :class:`Toolkit` for one chat turn.
@@ -75,6 +83,7 @@ async def get_toolkit(
6. Caller-supplied extras (``extra_factory``)
7. Channel platform tools — the caller resolves them (once, shared
with the system-prompt attachment) and passes ``channel_tools``.
+ 8. Client external tools declared for this chat run.
Plus the workspace's skills and MCPs, which become the toolkit's
``skills_or_loaders`` and ``mcps`` parameters.
@@ -88,6 +97,9 @@ async def get_toolkit(
Pre-resolved per-session workspace (caller resolves it
via :meth:`WorkspaceManagerBase.get_workspace`). Used here
for tool / skill / MCP discovery.
+ workspace_manager (`WorkspaceManagerBase`):
+ Workspace manager passed to team tools so they can resolve
+ session workspaces during cross-agent operations.
scheduler_manager (`SchedulerManager`):
Application scheduler. Provides the four schedule tools and
persists schedules through it.
@@ -111,6 +123,9 @@ async def get_toolkit(
session_record (`SessionRecord`):
Pre-loaded session record (loaded once by the caller).
Used for the schedule-tool model configuration.
+ resource_access_service (`ResourceAccessService`):
+ Resource access service used to list agents visible to the
+ caller when constructing the optional ``AgentInvite`` tool.
extra_factory (`AgentToolFactory | None`, optional):
Async factory invoked once per assembly to produce
user/session-specific extra tools.
@@ -129,6 +144,13 @@ optional):
channel_tools (`list[ToolBase] | None`, optional):
Platform tools of the originating channel, resolved once
by the caller. ``None`` / empty when channel-less.
+ client_external_tools (`list[ClientExternalToolDefinition] | None`, \
+optional):
+ Validated external tools supported by the active client for this
+ run. They are not persisted in the session.
+ client_builtin_tools (`list[ClientBuiltinToolName] | None`):
+ Native external tools enabled by the active client for this run.
+ Unattended callers leave this empty.
Returns:
`Toolkit`: Fully populated toolkit (tools + skills + MCPs).
@@ -267,6 +289,25 @@ time or interval"
if channel_tools:
tools += channel_tools
+ if "AskUser" in (client_builtin_tools or []):
+ tools.append(AskUser())
+
+ # Client-provided tools are appended last, but never replace a server
+ # tool. Fail closed on a conflict because the client dispatches pending
+ # calls by name and cannot safely guess which implementation won.
+ server_tool_names = {tool.name for tool in tools}
+ server_tool_names.update(
+ tool.name for group in tool_groups for tool in group.tools
+ )
+ for definition in client_external_tools or []:
+ if definition.name in server_tool_names:
+ raise ValueError(
+ f"Client external tool '{definition.name}' conflicts with "
+ "a server tool.",
+ )
+ tools.append(ClientExternalTool(definition))
+ server_tool_names.add(definition.name)
+
return Toolkit(
tools=tools,
skills_or_loaders=await workspace.list_skills(
diff --git a/src/agentscope/console/_console.py b/src/agentscope/console/_console.py
index 9e120684a..a87eb431e 100644
--- a/src/agentscope/console/_console.py
+++ b/src/agentscope/console/_console.py
@@ -8,18 +8,40 @@ from ..agent import Agent
from ..pipeline import PipelineProtocol
from ..event import (
ConfirmResult,
+ ExternalExecutionResultEvent,
+ ReplyEndEvent,
+ RequireExternalExecutionEvent,
RequireUserConfirmEvent,
UserConfirmResultEvent,
UserInterruptEvent,
)
-from ..message import Msg, UserMsg
+from ..message import (
+ Msg,
+ ToolResultBlock,
+ ToolResultState,
+ UserMsg,
+)
+from ..tool import (
+ AskUser,
+ AskUserAnswer,
+ AskUserMetadata,
+ AskUserParams,
+)
async def _run_reply(
agent: Agent | PipelineProtocol,
renderer: ConsoleRenderer,
- inputs: Msg | UserConfirmResultEvent | UserInterruptEvent,
-) -> RequireUserConfirmEvent | None:
+ inputs: (
+ Msg
+ | UserConfirmResultEvent
+ | UserInterruptEvent
+ | ExternalExecutionResultEvent
+ ),
+ pending_requests: list[
+ RequireUserConfirmEvent | RequireExternalExecutionEvent
+ ],
+) -> RequireUserConfirmEvent | RequireExternalExecutionEvent | None:
"""Consume one ``reply_stream`` call, rendering every event.
Ctrl+C during streaming cancels the reply task; the agent handles the
@@ -27,23 +49,42 @@ async def _run_reply(
as long as ``react_config.interruption_raise_cancelled_error`` keeps
its default ``False``.
+ ``pending_requests`` retains unhandled requests across stream calls.
+ Requests are removed when their reply ends or is interrupted.
+
Returns:
- `RequireUserConfirmEvent | None`:
- The pending confirmation request if the reply parked on
- human-in-the-loop, otherwise `None`.
+ `RequireUserConfirmEvent | RequireExternalExecutionEvent | None`:
+ The next queued outside-interaction request if the reply parked,
+ otherwise `None`.
"""
- pending: RequireUserConfirmEvent | None = None
+ if isinstance(inputs, UserInterruptEvent):
+ pending_requests[:] = [
+ request
+ for request in pending_requests
+ if request.reply_id != inputs.reply_id
+ ]
async def consume() -> None:
- nonlocal pending
try:
async for event in agent.reply_stream(inputs):
renderer.render(event)
- if isinstance(event, RequireUserConfirmEvent):
- pending = event
+ if isinstance(
+ event,
+ (
+ RequireUserConfirmEvent,
+ RequireExternalExecutionEvent,
+ ),
+ ):
+ pending_requests.append(event)
+ elif isinstance(event, ReplyEndEvent):
+ pending_requests[:] = [
+ request
+ for request in pending_requests
+ if request.reply_id != event.reply_id
+ ]
except BaseException:
# Failed streams may omit REPLY_END for several participants.
- pending = None
+ pending_requests.clear()
renderer.reset()
raise
@@ -68,7 +109,7 @@ async def _run_reply(
if sigint_hooked:
loop.remove_signal_handler(signal.SIGINT)
- return pending
+ return pending_requests.pop(0) if pending_requests else None
async def _confirm(
@@ -102,6 +143,103 @@ async def _confirm(
)
+async def _read_other() -> str:
+ """Read a non-empty custom answer for the Other option."""
+ while True:
+ answer = (
+ await asyncio.to_thread(input, "Enter your answer: ")
+ ).strip()
+ if answer:
+ return answer
+ print("The answer cannot be empty.")
+
+
+async def _ask_user(input_json: str) -> tuple[str, dict]:
+ """Collect native question answers and their structured metadata."""
+ params = AskUserParams.model_validate_json(input_json)
+ answers = []
+ for question in params.questions:
+ print(f"\n[{question.header}] {question.question}")
+ if question.context:
+ print(f"{question.context}")
+ for index, option in enumerate(question.options, start=1):
+ print(f" {index}. {option.label}: {option.description}")
+ if option.preview and not question.multi_select:
+ print(f" {option.preview}")
+ other_index = len(question.options) + 1
+ print(f" {other_index}. Other")
+ prompt = (
+ f"Select numbers [1-{other_index}] separated by commas, "
+ f"or type your answer: "
+ if question.multi_select
+ else f"Select a number [1-{other_index}], or type your answer: "
+ )
+ while True:
+ raw = (await asyncio.to_thread(input, prompt)).strip()
+ if not raw:
+ continue
+ parts = [part.strip() for part in raw.split(",")]
+ if not all(part.isdigit() for part in parts):
+ selected, other = [], raw
+ break
+ try:
+ indexes = {int(part) for part in parts}
+ except ValueError:
+ continue
+ if not indexes <= set(range(1, other_index + 1)) or (
+ not question.multi_select and len(indexes) > 1
+ ):
+ print(f"Choose option numbers from 1 to {other_index}.")
+ continue
+ selected = [
+ option.label
+ for i, option in enumerate(question.options, start=1)
+ if i in indexes
+ ]
+ other = await _read_other() if other_index in indexes else None
+ break
+ answers.append(
+ AskUserAnswer(
+ question=question.question,
+ selected=selected,
+ other=other,
+ ),
+ )
+ lines = []
+ for answer in answers:
+ values = answer.selected + ([answer.other] if answer.other else [])
+ lines.append(f"{answer.question}\n{', '.join(values)}")
+ output = "\n\n".join(lines)
+ return output, AskUserMetadata(answers=answers).model_dump(mode="json")
+
+
+async def _request_user_input(
+ pending: RequireExternalExecutionEvent,
+) -> ExternalExecutionResultEvent:
+ """Collect answers for pending native AskUser calls."""
+ results: list[ToolResultBlock] = []
+ for tool_call in pending.tool_calls:
+ if tool_call.name != AskUser.name:
+ raise ValueError(
+ f"The console cannot execute external tool "
+ f"'{tool_call.name}'.",
+ )
+ output, metadata = await _ask_user(tool_call.input)
+ results.append(
+ ToolResultBlock(
+ id=tool_call.id,
+ name=tool_call.name,
+ output=output,
+ metadata=metadata,
+ state=ToolResultState.SUCCESS,
+ ),
+ )
+ return ExternalExecutionResultEvent(
+ reply_id=pending.reply_id,
+ execution_results=results,
+ )
+
+
async def launch_console(
agent: Agent | PipelineProtocol,
user_name: str = "user",
@@ -114,9 +252,9 @@ async def launch_console(
persistence: the conversation lives in ``agent.state`` and ends with
the process. Reads user messages from stdin, renders every streamed
:class:`~agentscope.event.AgentEvent`, asks for tool-call
- confirmation (y/n) when the agent requires it, and turns Ctrl+C into
- an interruption of the current reply. Type ``exit``/``quit`` or
- press Ctrl+D to leave.
+ confirmation (y/n) when the agent requires it, handles structured
+ ``AskUser`` choices, and turns Ctrl+C into an interruption
+ of the current reply. Type ``exit``/``quit`` or press Ctrl+D to leave.
.. code-block:: python
@@ -160,16 +298,32 @@ async def launch_console(
if not query:
continue
- inputs: Msg | UserConfirmResultEvent | UserInterruptEvent = UserMsg(
- name=user_name,
- content=query,
- )
+ inputs: (
+ Msg
+ | UserConfirmResultEvent
+ | UserInterruptEvent
+ | ExternalExecutionResultEvent
+ ) = UserMsg(name=user_name, content=query)
+ pending_requests: list[
+ RequireUserConfirmEvent | RequireExternalExecutionEvent
+ ] = []
while True:
- pending = await _run_reply(agent, renderer, inputs)
+ pending = await _run_reply(
+ agent,
+ renderer,
+ inputs,
+ pending_requests,
+ )
if pending is None:
break
try:
- inputs = await _confirm(pending)
+ if isinstance(pending, RequireUserConfirmEvent):
+ inputs = await _confirm(pending)
+ else:
+ inputs = await _request_user_input(pending)
except (EOFError, KeyboardInterrupt):
# Abort the parked reply so the next input starts clean
inputs = UserInterruptEvent(reply_id=pending.reply_id)
+ except ValueError as error:
+ renderer.console.print(str(error), style="red")
+ inputs = UserInterruptEvent(reply_id=pending.reply_id)
diff --git a/tests/ask_user_console_test.py b/tests/ask_user_console_test.py
new file mode 100644
index 000000000..d595418a5
--- /dev/null
+++ b/tests/ask_user_console_test.py
@@ -0,0 +1,260 @@
+# -*- coding: utf-8 -*-
+"""Tests for native AskUser console interaction."""
+import json
+from unittest import IsolatedAsyncioTestCase
+from unittest.mock import patch
+
+from utils import MockModel
+
+from agentscope.agent import Agent, InjectionConfig
+from agentscope.console import launch_console
+from agentscope.console._console import _ask_user, _request_user_input
+from agentscope.event import RequireExternalExecutionEvent
+from agentscope.message import (
+ TextBlock,
+ ToolCallBlock,
+ ToolCallState,
+ ToolResultBlock,
+ ToolResultState,
+)
+from agentscope.model import ChatResponse
+from agentscope.tool import AskUser, Toolkit
+
+
+def _concurrent_agent() -> Agent:
+ """Create an agent that asks two questions before its final answer."""
+ model = MockModel(context_size=10000)
+ calls = [
+ ToolCallBlock(
+ id=f"call-{index}",
+ name="AskUser",
+ input=json.dumps(
+ {
+ "questions": [
+ {
+ "question": f"Question {index}?",
+ "header": "Pick",
+ "options": [
+ {"label": "A", "description": "First"},
+ {"label": "B", "description": "Second"},
+ ],
+ },
+ ],
+ },
+ ),
+ )
+ for index in (1, 2)
+ ]
+ model.set_responses(
+ [
+ [ChatResponse(content=calls, is_last=True)],
+ [ChatResponse(content=[TextBlock(text="Done")], is_last=True)],
+ ],
+ )
+ return Agent(
+ name="Assistant",
+ system_prompt="You are a helpful assistant.",
+ model=model,
+ toolkit=Toolkit(tools=[AskUser()]),
+ injection_config=InjectionConfig(inject_runtime_state=False),
+ )
+
+
+class AskUserConsoleTest(IsolatedAsyncioTestCase):
+ """Test console collection of preset and custom answers."""
+
+ async def test_concurrent_questions_resume_to_completion(self) -> None:
+ """Every concurrent question receives its own answer in order."""
+ agent = _concurrent_agent()
+ with patch(
+ "builtins.input",
+ side_effect=["hello", "1", "2", "exit"],
+ ) as prompt:
+ await launch_console(agent, verbosity="quiet")
+ self.assertEqual(prompt.call_count, 4)
+ self.assertEqual(
+ [
+ (block.id, block.state, block.output, block.metadata)
+ for message in agent.state.context
+ for block in message.content
+ if isinstance(block, ToolResultBlock)
+ ],
+ [
+ (
+ f"call-{index}",
+ ToolResultState.SUCCESS,
+ f"Question {index}?\n{answer}",
+ {
+ "answers": [
+ {
+ "question": f"Question {index}?",
+ "selected": [answer],
+ "other": None,
+ },
+ ],
+ },
+ )
+ for index, answer in ((1, "A"), (2, "B"))
+ ],
+ )
+ self.assertEqual(agent.state.get_unfinished_tool_calls(agent.name), [])
+ self.assertEqual(agent.state.context[-1].get_text_content(), "Done")
+
+ async def test_interruption_discards_remaining_questions(self) -> None:
+ """Aborted questions do not leak into the next user message."""
+ for error in (EOFError, KeyboardInterrupt, ValueError):
+ with self.subTest(error=error):
+ agent = _concurrent_agent()
+ with patch(
+ "builtins.input",
+ side_effect=["hello", error(), "continue", "exit"],
+ ) as prompt:
+ await launch_console(agent, verbosity="quiet")
+ self.assertEqual(prompt.call_count, 4)
+ self.assertEqual(
+ [
+ (block.id, block.state)
+ for message in agent.state.context
+ for block in message.content
+ if isinstance(block, ToolResultBlock)
+ ],
+ [
+ ("call-1", ToolResultState.INTERRUPTED),
+ ("call-2", ToolResultState.INTERRUPTED),
+ ],
+ )
+ self.assertEqual(
+ agent.state.get_unfinished_tool_calls(agent.name),
+ [],
+ )
+ self.assertEqual(
+ agent.state.context[-1].get_text_content(),
+ "Done",
+ )
+
+ async def test_single_choice_and_non_empty_other(self) -> None:
+ """Single-select and explicit Other follow the native result format."""
+ payload = {
+ "questions": [
+ {
+ "question": "Which approach?",
+ "header": "Approach",
+ "options": [
+ {"label": "A", "description": "First"},
+ {"label": "B", "description": "Second"},
+ ],
+ },
+ ],
+ }
+ for inputs, selected, other, text in [
+ (["1,2", "2"], ["B"], None, "B"),
+ (["3", "", "Custom"], [], "Custom", "Custom"),
+ ]:
+ with self.subTest(inputs=inputs), patch(
+ "builtins.input",
+ side_effect=inputs,
+ ):
+ self.assertEqual(
+ await _ask_user(json.dumps(payload)),
+ (
+ f"Which approach?\n{text}",
+ {
+ "answers": [
+ {
+ "question": "Which approach?",
+ "selected": selected,
+ "other": other,
+ },
+ ],
+ },
+ ),
+ )
+
+ async def test_native_batch_returns_readable_output_and_metadata(
+ self,
+ ) -> None:
+ """Native multi-select and free text obey the shared result schema."""
+ payload = {
+ "questions": [
+ {
+ "question": "Which features?",
+ "header": "Features",
+ "multi_select": True,
+ "context": "Review the plan.",
+ "options": [
+ {"label": "A", "description": "First"},
+ {"label": "B", "description": "Second"},
+ ],
+ },
+ {
+ "question": "Which approach?",
+ "header": "Approach",
+ "options": [
+ {"label": "A", "description": "First"},
+ {"label": "B", "description": "Second"},
+ ],
+ },
+ ],
+ }
+ pending = RequireExternalExecutionEvent(
+ reply_id="native-reply",
+ tool_calls=[
+ ToolCallBlock(
+ id="native-call",
+ name="AskUser",
+ input=json.dumps(payload),
+ state=ToolCallState.SUBMITTED,
+ ),
+ ],
+ )
+ with patch("builtins.input", side_effect=["9", "1,2", "My plan"]):
+ result = await _request_user_input(pending)
+ block = result.execution_results[0]
+ await AskUser().check_external_result(block)
+ self.assertEqual(
+ {
+ "reply_id": result.reply_id,
+ "id": block.id,
+ "name": block.name,
+ "output": block.output,
+ "metadata": block.metadata,
+ "state": block.state,
+ },
+ {
+ "reply_id": "native-reply",
+ "id": "native-call",
+ "name": "AskUser",
+ "state": ToolResultState.SUCCESS,
+ "output": "Which features?\nA, B\n\nWhich approach?\nMy plan",
+ "metadata": {
+ "answers": [
+ {
+ "question": "Which features?",
+ "selected": ["A", "B"],
+ "other": None,
+ },
+ {
+ "question": "Which approach?",
+ "selected": [],
+ "other": "My plan",
+ },
+ ],
+ },
+ },
+ )
+
+ async def test_native_invalid_payload_does_not_prompt(self) -> None:
+ """Malformed native requests reach the console interruption path."""
+ pending = RequireExternalExecutionEvent(
+ reply_id="native-reply",
+ tool_calls=[
+ ToolCallBlock(
+ id="native-call",
+ name="AskUser",
+ input="{}",
+ ),
+ ],
+ )
+ with patch("builtins.input") as prompt, self.assertRaises(ValueError):
+ await _request_user_input(pending)
+ prompt.assert_not_called()
diff --git a/tests/ask_user_tool_test.py b/tests/ask_user_tool_test.py
index 2b520cdb5..7cae29480 100644
--- a/tests/ask_user_tool_test.py
+++ b/tests/ask_user_tool_test.py
@@ -1,13 +1,23 @@
# -*- coding: utf-8 -*-
"""Unittests for the AskUser tool."""
+import json
from unittest import IsolatedAsyncioTestCase
import jsonschema
from pydantic import ValidationError
+from utils import MockModel
-from agentscope.message import ToolResultBlock, ToolResultState
+from agentscope.agent import Agent, InjectionConfig
+from agentscope.event import RequireExternalExecutionEvent
+from agentscope.message import (
+ ToolCallBlock,
+ ToolResultBlock,
+ ToolResultState,
+ UserMsg,
+)
+from agentscope.model import ChatResponse
from agentscope.permission import PermissionBehavior, PermissionContext
-from agentscope.tool import AskUser, AskUserMetadata, AskUserParams
+from agentscope.tool import AskUser, AskUserMetadata, AskUserParams, Toolkit
class AskUserTest(IsolatedAsyncioTestCase):
@@ -99,6 +109,107 @@ class AskUserTest(IsolatedAsyncioTestCase):
with self.assertRaises(ValidationError):
AskUserParams.model_validate(payload)
+ async def test_runtime_rejects_duplicates_before_external_execution(
+ self,
+ ) -> None:
+ """Invalid calls return errors so the model can ask valid questions."""
+ question = {
+ "question": "Which?",
+ "header": "Pick",
+ "options": [
+ {"label": "A", "description": "First"},
+ {"label": "B", "description": "Second"},
+ ],
+ }
+ valid_payload = {"questions": [question]}
+ cases = [
+ (
+ {
+ "questions": [
+ {
+ **question,
+ "options": [
+ {"label": "A", "description": "First"},
+ {"label": "A", "description": "Second"},
+ ],
+ },
+ ],
+ },
+ "option labels must be unique within a question",
+ ),
+ (
+ {"questions": [question, {**question, "header": "Again"}]},
+ "question texts must be unique across the batch",
+ ),
+ ]
+ for invalid_payload, error in cases:
+ with self.subTest(error=error):
+ # Schema validation alone cannot express these constraints.
+ jsonschema.validate(invalid_payload, self.tool.input_schema)
+ model = MockModel(context_size=10000)
+ model.set_responses(
+ [
+ ChatResponse(
+ content=[
+ ToolCallBlock(
+ id=call_id,
+ name="AskUser",
+ input=json.dumps(payload),
+ ),
+ ],
+ is_last=True,
+ )
+ for call_id, payload in (
+ ("invalid", invalid_payload),
+ ("corrected", valid_payload),
+ )
+ ],
+ )
+ agent = Agent(
+ name="Assistant",
+ system_prompt="Help the user.",
+ model=model,
+ toolkit=Toolkit(tools=[self.tool]),
+ injection_config=InjectionConfig(
+ inject_runtime_state=False,
+ ),
+ )
+ requests = [
+ event
+ async for event in agent.reply_stream(
+ UserMsg(name="user", content="Ask me."),
+ )
+ if isinstance(event, RequireExternalExecutionEvent)
+ ]
+ self.assertEqual(
+ [
+ (call.id, call.name, json.loads(call.input))
+ for request in requests
+ for call in request.tool_calls
+ ],
+ [("corrected", "AskUser", valid_payload)],
+ )
+ results = [
+ block
+ for message in agent.state.context
+ for block in message.content
+ if isinstance(block, ToolResultBlock)
+ ]
+ self.assertEqual(
+ [(block.id, block.name, block.state) for block in results],
+ [("invalid", "AskUser", ToolResultState.ERROR)],
+ )
+ self.assertIn(error, results[0].output)
+ self.assertEqual(
+ [
+ call.id
+ for call in agent.state.get_unfinished_tool_calls(
+ agent.name,
+ )
+ ],
+ ["corrected"],
+ )
+
async def test_a_result_that_breaks_its_promise_is_refused(self) -> None:
"""The shape is the caller's to keep; prose alone is not enough."""
result = ToolResultBlock(
diff --git a/tests/chat_input_queue_test.py b/tests/chat_input_queue_test.py
index 2c9625478..6e5fab255 100644
--- a/tests/chat_input_queue_test.py
+++ b/tests/chat_input_queue_test.py
@@ -22,6 +22,7 @@ from agentscope.app._bus_ops import (
reorder_chat_inputs,
update_chat_input,
)
+from agentscope.app._client_external_tool import ClientExternalToolDefinition
from agentscope.app._manager import (
CancelDispatcher,
ChatRunRegistry,
@@ -41,10 +42,12 @@ from agentscope.app.deps import (
get_storage,
)
from agentscope.app.message_bus import InMemoryMessageBus, MessageBusKeys
+from agentscope.event import UserConfirmResultEvent
from agentscope.message import (
AssistantMsg,
Base64Source,
DataBlock,
+ Msg,
ToolCallBlock,
ToolResultBlock,
UserMsg,
@@ -52,6 +55,18 @@ from agentscope.message import (
from agentscope.state import AgentState
+def _deep_tool_definition(depth: int = 120) -> dict:
+ """Build a small schema that exceeds recursive validator stack limits."""
+ schema: dict = {"type": "string"}
+ for _ in range(depth):
+ schema = {"type": "object", "properties": {"child": schema}}
+ return {
+ "name": "client__nested",
+ "description": "Nested input.",
+ "input_schema": schema,
+ }
+
+
class TestQueueStorageAndRecovery(IsolatedAsyncioTestCase):
"""Exercise real bus primitives, including Redis storage layouts."""
@@ -65,8 +80,25 @@ class TestQueueStorageAndRecovery(IsolatedAsyncioTestCase):
with self.subTest(backend=type(backend).__name__):
async with backend as bus:
original = UserMsg("user", "claimed input")
+ definition = ClientExternalToolDefinition(
+ name="client__choose_option",
+ description="Ask the user to choose.",
+ input_schema={"type": "object", "properties": {}},
+ )
items = [
- await enqueue_chat_input(bus, "u", "s", "a", msg)
+ await enqueue_chat_input(
+ bus,
+ "u",
+ "s",
+ "a",
+ msg,
+ client_external_tools=(
+ [definition] if msg is original else []
+ ),
+ client_builtin_tools=(
+ ["AskUser"] if msg is original else []
+ ),
+ )
for msg in (
original,
UserMsg("user", "second"),
@@ -173,13 +205,22 @@ class TestQueueStorageAndRecovery(IsolatedAsyncioTestCase):
await restarted.drain_chat_inputs("u", "s", "a"),
)
self.assertEqual(
+ chat.calls,
[
- call["input_msg"].model_dump(mode="json")
- for call in chat.calls
- ],
- [
- original.model_dump(mode="json"),
- replacement.model_dump(mode="json"),
+ {
+ "user_id": "u",
+ "session_id": "s",
+ "agent_id": "a",
+ "input_msg": original,
+ "client_external_tools": [definition],
+ "client_builtin_tools": ["AskUser"],
+ },
+ {
+ "user_id": "u",
+ "session_id": "s",
+ "agent_id": "a",
+ "input_msg": replacement,
+ },
],
)
self.assertEqual(await list_chat_inputs(bus, "s"), [])
@@ -190,6 +231,103 @@ class TestQueueStorageAndRecovery(IsolatedAsyncioTestCase):
{},
)
+ async def test_invalid_capabilities_preserve_queued_input(self) -> None:
+ """Invalid optional metadata cannot discard messages or valid tools."""
+ definition = ClientExternalToolDefinition(
+ name="client__choose_option",
+ description="Ask the user to choose.",
+ input_schema={"type": "object", "properties": {}},
+ )
+ cases = (
+ ("client_external_tools", ["invalid"]),
+ ("client_builtin_tools", ["invalid"]),
+ ("client_external_tools", [_deep_tool_definition()]),
+ )
+ for index, (invalid_key, invalid_value) in enumerate(cases):
+ with self.subTest(case=index):
+ async with InMemoryMessageBus() as bus:
+ message = UserMsg("user", "Keep this message.")
+ await enqueue_chat_input(
+ bus,
+ "u",
+ "s",
+ "a",
+ message,
+ client_external_tools=[definition],
+ client_builtin_tools=["AskUser"],
+ )
+ entries = await bus.queue_read(
+ MessageBusKeys.chat_inputs("s"),
+ )
+ payload = entries[0][1]
+ payload[invalid_key] = invalid_value
+ await bus.queue_replace(
+ MessageBusKeys.chat_inputs("s"),
+ [payload],
+ )
+ chat = _FakeChatService()
+ queue = ChatInputQueue(bus, _FakeStorage(), chat)
+ self.addAsyncCleanup(queue.close)
+ self.assertTrue(
+ await queue.drain_chat_inputs("u", "s", "a"),
+ )
+ expected = {
+ "user_id": "u",
+ "session_id": "s",
+ "agent_id": "a",
+ "input_msg": message,
+ "client_external_tools": [definition],
+ "client_builtin_tools": ["AskUser"],
+ }
+ del expected[invalid_key]
+ self.assertEqual(chat.calls, [expected])
+ self.assertEqual(await list_chat_inputs(bus, "s"), [])
+
+ async def test_resume_lock_retry_preserves_client_capabilities(
+ self,
+ ) -> None:
+ """Dispatch-lock contention retains the resuming client's tools."""
+ async with InMemoryMessageBus() as bus:
+ chat = _FakeChatService()
+ queue = ChatInputQueue(bus, _FakeStorage(), chat)
+ self.addAsyncCleanup(queue.close)
+ event = UserConfirmResultEvent(reply_id="r", confirm_results=[])
+ definition = ClientExternalToolDefinition(
+ name="client__choose_option",
+ description="Ask the user to choose.",
+ input_schema={"type": "object", "properties": {}},
+ )
+ lock = SimpleNamespace(
+ __aenter__=AsyncMock(side_effect=TimeoutError),
+ )
+ with patch.object(bus, "acquire_lock_bounded", return_value=lock):
+ await queue.run_resume_serialized(
+ "u",
+ "s",
+ "a",
+ event,
+ client_external_tools=[definition],
+ client_builtin_tools=["AskUser"],
+ )
+ self.assertEqual(chat.calls, [])
+ triggers = await bus.queue_read(MessageBusKeys.wakeup_queue())
+ self.assertEqual(
+ [payload for _, payload in triggers],
+ [
+ {
+ "user_id": "u",
+ "session_id": "s",
+ "agent_id": "a",
+ "kind": MessageBusKeys.WAKEUP_KIND_RESUME,
+ "input": event.model_dump(mode="json"),
+ "client_external_tools": [
+ definition.model_dump(mode="json"),
+ ],
+ "client_builtin_tools": ["AskUser"],
+ },
+ ],
+ )
+
async def test_large_attachment_roundtrip_and_cleanup(self) -> None:
"""Base64 bytes survive edits and execution without global copies."""
redis = fakeredis.aioredis.FakeRedis(decode_responses=True)
@@ -615,6 +753,8 @@ class TestQueueFailureScope(IsolatedAsyncioTestCase):
input_msg=message,
queue_item_id=item["id"],
input_persisted=True,
+ client_external_tools=None,
+ client_builtin_tools=None,
)
async def test_parked_detection_uses_owning_agent_and_results(
@@ -955,6 +1095,72 @@ class TestTerminalChatClaims(IsolatedAsyncioTestCase):
class TestChatInputPayloads(IsolatedAsyncioTestCase):
"""Preserve large input compatibility and read only referenced payloads."""
+ async def test_deep_client_schema_returns_422_without_queuing(
+ self,
+ ) -> None:
+ """Small but deeply nested schemas fail validation before dispatch."""
+ async with InMemoryMessageBus() as bus:
+ storage = _FakeStorage()
+ chat = _FakeChatService()
+ registry = ChatRunRegistry()
+ app = FastAPI()
+ app.include_router(chat_router)
+ app.dependency_overrides = {
+ get_current_user_id: lambda: "u",
+ get_storage: lambda: storage,
+ get_message_bus: lambda: bus,
+ get_chat_service: lambda: chat,
+ get_chat_run_registry: lambda: registry,
+ }
+ async with AsyncClient(
+ transport=ASGITransport(
+ app=app,
+ raise_app_exceptions=False,
+ ),
+ base_url="http://test",
+ ) as client:
+ for depth in (120, 200):
+ with self.subTest(depth=depth):
+ definition = _deep_tool_definition(depth)
+ self.assertLess(
+ len(json.dumps(definition).encode("utf-8")),
+ 64 * 1024,
+ )
+ response = await client.post(
+ "/chat/",
+ json={
+ "agent_id": "a",
+ "session_id": "s",
+ "input": UserMsg("u", "Hello").model_dump(
+ mode="json",
+ ),
+ "client_external_tools": [definition],
+ },
+ )
+ self.assertEqual(response.status_code, 422)
+ self.assertEqual(
+ response.json(),
+ {
+ "detail": [
+ {
+ "type": "value_error",
+ "loc": [
+ "body",
+ "client_external_tools",
+ 0,
+ "input_schema",
+ ],
+ "msg": "Value error, Tool "
+ "input_schema is nested too deeply.",
+ "input": definition["input_schema"],
+ "ctx": {"error": {}},
+ },
+ ],
+ },
+ )
+ self.assertEqual(chat.calls, [])
+ self.assertEqual(await list_chat_inputs(bus, "s"), [])
+
async def test_large_attachment_can_be_enqueued_and_edited(self) -> None:
"""Inputs exceeding the removed attachment budget remain accepted."""
message = UserMsg(
@@ -1003,10 +1209,17 @@ class TestChatInputPayloads(IsolatedAsyncioTestCase):
get_chat_service: lambda: chat,
get_chat_run_registry: lambda: registry,
}
+ definition = ClientExternalToolDefinition(
+ name="client__choose_option",
+ description="Ask the user to choose.",
+ input_schema={"type": "object", "properties": {}},
+ )
body = {
"agent_id": "a",
"session_id": "s",
"input": UserMsg("u", "x" * 1_000_001).model_dump(mode="json"),
+ "client_external_tools": [definition.model_dump(mode="json")],
+ "client_builtin_tools": ["AskUser"],
}
async with AsyncClient(
transport=ASGITransport(app=app),
@@ -1039,6 +1252,22 @@ class TestChatInputPayloads(IsolatedAsyncioTestCase):
)
self.assertEqual(await list_chat_inputs(bus, "s"), items)
self.assertEqual(chat.calls, [])
+ queue = ChatInputQueue(bus, storage, chat)
+ self.addAsyncCleanup(queue.close)
+ self.assertTrue(await queue.drain_chat_inputs("u", "s", "a"))
+ self.assertEqual(
+ chat.calls,
+ [
+ {
+ "user_id": "u",
+ "session_id": "s",
+ "agent_id": "a",
+ "input_msg": Msg.model_validate(body["input"]),
+ "client_external_tools": [definition],
+ "client_builtin_tools": ["AskUser"],
+ },
+ ],
+ )
async def test_list_uses_one_hmget_for_only_pending_references(
self,
diff --git a/tests/client_external_tool_test.py b/tests/client_external_tool_test.py
new file mode 100644
index 000000000..22c045b53
--- /dev/null
+++ b/tests/client_external_tool_test.py
@@ -0,0 +1,840 @@
+# -*- coding: utf-8 -*-
+"""Tests for per-run client external tool definitions."""
+import json
+from unittest import IsolatedAsyncioTestCase, TestCase
+from unittest.mock import patch
+
+from jsonschema import Draft202012Validator
+from pydantic import ValidationError
+from utils import MockModel
+
+from agentscope.agent import Agent, InjectionConfig
+from agentscope.app._client_external_tool import (
+ ClientExternalTool,
+ ClientExternalToolDefinition,
+ parse_client_tool_capabilities,
+)
+from agentscope.app._router._schema import ChatRequest
+from agentscope.event import (
+ ExternalExecutionResultEvent,
+ RequireExternalExecutionEvent,
+)
+from agentscope.message import (
+ TextBlock,
+ ToolCallBlock,
+ ToolResultBlock,
+ ToolResultState,
+ UserMsg,
+)
+from agentscope.model import ChatResponse
+from agentscope.permission import (
+ PermissionBehavior,
+ PermissionContext,
+ PermissionDecision,
+)
+from agentscope.tool import AskUser, Toolkit
+
+
+def _definition(
+ name: str = "client__choose_option",
+ read_only: bool = False,
+) -> ClientExternalToolDefinition:
+ """Build a minimal valid client external tool definition."""
+ return ClientExternalToolDefinition(
+ name=name,
+ description="Ask the user to choose.",
+ read_only=read_only,
+ input_schema={
+ "type": "object",
+ "properties": {
+ "question": {"type": "string"},
+ },
+ "required": ["question"],
+ },
+ )
+
+
+class ClientExternalToolDefinitionTest(TestCase):
+ """Validate the public request contract and its guardrails."""
+
+ def test_schema_recursion_is_a_validation_error(self) -> None:
+ """Every recursive validation stage rejects excessive nesting."""
+ definition = _definition().model_dump()
+ for target in (
+ "json.dumps",
+ "Draft202012Validator.check_schema",
+ "_validate_schema_metadata",
+ ):
+ with self.subTest(target=target), patch(
+ f"agentscope.app._client_external_tool.{target}",
+ side_effect=RecursionError,
+ ):
+ with self.assertRaises(ValidationError) as caught:
+ ClientExternalToolDefinition.model_validate(definition)
+ self.assertEqual(
+ caught.exception.errors(
+ include_url=False,
+ include_context=False,
+ include_input=False,
+ ),
+ [
+ {
+ "type": "value_error",
+ "loc": ("input_schema",),
+ "msg": "Value error, Tool input_schema is "
+ "nested too deeply.",
+ },
+ ],
+ )
+
+ def test_schema_size_precedes_recursive_validation(self) -> None:
+ """Oversized schemas never reach recursive JSON Schema validation."""
+ definition = _definition().model_dump()
+ definition["input_schema"]["description"] = "x" * (64 * 1024)
+ with patch(
+ "agentscope.app._client_external_tool."
+ "Draft202012Validator.check_schema",
+ ) as check_schema:
+ with self.assertRaises(ValidationError) as caught:
+ ClientExternalToolDefinition.model_validate(definition)
+ check_schema.assert_not_called()
+ self.assertEqual(
+ caught.exception.errors(
+ include_url=False,
+ include_context=False,
+ include_input=False,
+ ),
+ [
+ {
+ "type": "value_error",
+ "loc": ("input_schema",),
+ "msg": "Value error, Tool input_schema exceeds 65536 "
+ "bytes.",
+ },
+ ],
+ )
+
+ def test_capability_recursion_preserves_other_valid_tools(self) -> None:
+ """Optional capability failures cannot discard the other tool set."""
+ definition = _definition()
+ cases = (
+ ("_CLIENT_EXTERNAL_TOOLS_ADAPTER", ([], ["AskUser"])),
+ ("_CLIENT_BUILTIN_TOOLS_ADAPTER", ([definition], [])),
+ )
+ for adapter, expected in cases:
+ with self.subTest(adapter=adapter), patch(
+ f"agentscope.app._client_external_tool.{adapter}",
+ ) as mocked:
+ mocked.validate_python.side_effect = RecursionError
+ self.assertEqual(
+ parse_client_tool_capabilities(
+ [definition.model_dump()],
+ ["AskUser"],
+ ),
+ expected,
+ )
+
+ def test_native_resume_validates_metadata_when_tool_is_disabled(
+ self,
+ ) -> None:
+ """An existing answer remains valid without enabling future calls."""
+ metadata = {
+ "answers": [
+ {"question": "Which?", "selected": ["A"], "other": None},
+ ],
+ }
+ event = ExternalExecutionResultEvent(
+ reply_id="r",
+ execution_results=[
+ ToolResultBlock(
+ id="c",
+ name="AskUser",
+ output="Which?\nA",
+ state=ToolResultState.SUCCESS,
+ metadata=metadata,
+ ),
+ ],
+ )
+ request = ChatRequest(
+ agent_id="a",
+ session_id="s",
+ input=event,
+ )
+ self.assertEqual(request.client_builtin_tools, [])
+ self.assertEqual(
+ request.input.execution_results[0].metadata,
+ metadata,
+ )
+ event.execution_results[0].metadata = {}
+ with self.assertRaises(ValidationError):
+ ChatRequest(agent_id="a", session_id="s", input=event)
+
+ def test_native_capability_only_accepts_known_tools(self) -> None:
+ """Native declarations carry names, not client-owned schemas."""
+ request = ChatRequest(
+ agent_id="a",
+ session_id="s",
+ input=None,
+ client_builtin_tools=["AskUser"],
+ )
+ self.assertEqual(request.client_builtin_tools, ["AskUser"])
+ self.assertEqual(request.client_external_tools, [])
+ for names in (["Unknown"], ["AskUser", "AskUser"]):
+ with self.subTest(names=names), self.assertRaises(ValidationError):
+ ChatRequest(
+ agent_id="a",
+ session_id="s",
+ input=None,
+ client_builtin_tools=names,
+ )
+
+ def test_chat_request_preserves_valid_definition(self) -> None:
+ """A valid definition is available to the current chat run."""
+ request = ChatRequest(
+ agent_id="agent-1",
+ session_id="session-1",
+ input=None,
+ client_external_tools=[_definition()],
+ )
+
+ self.assertEqual(
+ request.model_dump(mode="json"),
+ {
+ "agent_id": "agent-1",
+ "session_id": "session-1",
+ "input": None,
+ "client_builtin_tools": [],
+ "client_external_tools": [
+ {
+ "name": "client__choose_option",
+ "description": "Ask the user to choose.",
+ "read_only": False,
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "question": {"type": "string"},
+ },
+ "required": ["question"],
+ },
+ },
+ ],
+ },
+ )
+
+ def test_tool_name_rejects_unsupported_characters(self) -> None:
+ """Client tool names only allow provider-safe characters."""
+ with self.assertRaises(ValidationError):
+ _definition("client__invalid tool name")
+
+ def test_tool_name_requires_client_namespace(self) -> None:
+ """Client tools cannot shadow server or toolkit built-ins."""
+ with self.assertRaises(ValidationError):
+ _definition("ResetTools")
+
+ def test_invalid_json_schema_is_rejected(self) -> None:
+ """Malformed JSON Schema cannot enter the runtime toolkit."""
+ with self.assertRaises(ValidationError):
+ ClientExternalToolDefinition(
+ name="client__invalid_schema",
+ description="Invalid schema.",
+ input_schema={
+ "type": 42,
+ "properties": {},
+ },
+ )
+
+ def test_unsupported_schema_dialects_are_rejected(self) -> None:
+ """Root and nested declarations cannot switch execution dialects."""
+ for dialect in (
+ "http://json-schema.org/draft-07/schema#",
+ "https://json-schema.org/draft/2019-09/schema",
+ "https://example.com/unknown-schema",
+ ):
+ schema = {
+ "$schema": dialect,
+ "type": "object",
+ "properties": {},
+ "unevaluatedProperties": False,
+ }
+ for nested in (False, True):
+ with self.subTest(dialect=dialect, nested=nested):
+ value = (
+ {
+ "type": "object",
+ "properties": {},
+ "$defs": {"nested": schema},
+ "$ref": "#/$defs/nested",
+ }
+ if nested
+ else schema
+ )
+ with self.assertRaises(ValidationError) as caught:
+ ClientExternalToolDefinition(
+ name="client__dialect",
+ description="Check schema dialect.",
+ input_schema=value,
+ )
+ self.assertEqual(
+ caught.exception.errors(
+ include_url=False,
+ include_context=False,
+ include_input=False,
+ ),
+ [
+ {
+ "type": "value_error",
+ "loc": ("input_schema",),
+ "msg": "Value error, Client tool schemas "
+ "only support JSON Schema Draft 2020-12.",
+ },
+ ],
+ )
+
+ def test_non_object_input_schema_is_rejected(self) -> None:
+ """Tool schemas must match the toolkit's object contract."""
+ with self.assertRaises(ValidationError):
+ ClientExternalToolDefinition(
+ name="client__string_tool",
+ description="Invalid root type.",
+ input_schema={
+ "type": "string",
+ },
+ )
+
+ def test_remote_schema_reference_is_rejected(self) -> None:
+ """A client schema cannot trigger URI retrieval on the server."""
+ for keyword in ("$ref", "$dynamicRef", "$recursiveRef"):
+ with self.subTest(keyword=keyword):
+ with self.assertRaises(ValidationError):
+ ClientExternalToolDefinition(
+ name="client__remote_reference",
+ description="Invalid remote reference.",
+ input_schema={
+ "type": "object",
+ "properties": {
+ "value": {
+ keyword: (
+ "https://example.com/schema.json"
+ ),
+ },
+ },
+ },
+ )
+
+ def test_schema_metadata_inside_literal_data_is_allowed(self) -> None:
+ """Literal objects do not declare references or schema dialects."""
+ literal = {
+ "$ref": "https://example.com/document",
+ "$dynamicRef": "https://example.com/dynamic",
+ "$recursiveRef": "https://example.com/recursive",
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "properties": {"nested": {"$ref": "https://example.com/nested"}},
+ }
+ for keyword, data in (
+ ("const", literal),
+ ("enum", [literal]),
+ ("default", literal),
+ ("examples", [literal]),
+ ("x-annotation", literal),
+ ):
+ with self.subTest(keyword=keyword):
+ schema = {
+ "type": "object",
+ "properties": {"document": {keyword: data}},
+ }
+ definition = ClientExternalToolDefinition(
+ name="client__document",
+ description="Accept literal documents.",
+ input_schema=schema,
+ )
+ self.assertEqual(definition.input_schema, schema)
+ Draft202012Validator(schema).validate({"document": literal})
+
+ def test_remote_references_in_subschema_positions_are_rejected(
+ self,
+ ) -> None:
+ """All schema-bearing keywords still enforce local references."""
+ remote = {"$ref": "https://example.com/schema"}
+ positions = {
+ **{
+ key: remote
+ for key in (
+ "additionalProperties",
+ "unevaluatedProperties",
+ "propertyNames",
+ "items",
+ "contains",
+ "unevaluatedItems",
+ "not",
+ "if",
+ "then",
+ "else",
+ "contentSchema",
+ )
+ },
+ **{
+ key: {"const": remote}
+ for key in (
+ "properties",
+ "patternProperties",
+ "$defs",
+ "definitions",
+ "dependentSchemas",
+ "dependencies",
+ )
+ },
+ **{
+ key: [remote]
+ for key in ("allOf", "anyOf", "oneOf", "prefixItems")
+ },
+ }
+ for keyword, child in positions.items():
+ with self.subTest(keyword=keyword):
+ with self.assertRaises(ValidationError) as caught:
+ ClientExternalToolDefinition(
+ name="client__remote",
+ description="Reject nested remote references.",
+ input_schema={
+ "type": "object",
+ "properties": {},
+ keyword: child,
+ },
+ )
+ self.assertEqual(
+ caught.exception.errors(include_url=False)[0]["msg"],
+ "Value error, Client tool schemas only support local "
+ "$ref values.",
+ )
+
+ def test_local_reference_targets_are_checked_as_schemas(self) -> None:
+ """References can turn otherwise literal data into active schemas."""
+ targets = (
+ ({"$ref": "https://example.com/schema"}, "local $ref values"),
+ (
+ {"$schema": "http://json-schema.org/draft-07/schema#"},
+ "Draft 2020-12",
+ ),
+ )
+ for target, error in targets:
+ for keyword in ("$ref", "$dynamicRef", "$recursiveRef"):
+ for embedded in (False, True):
+ with self.subTest(
+ target=target,
+ keyword=keyword,
+ embedded=embedded,
+ ):
+ node = {
+ "default": {"a/b~c": [target]},
+ keyword: "#/default/a~1b~0c/%30",
+ }
+ if embedded:
+ node["$id"] = "https://example.com/embedded"
+ schema = (
+ {
+ "type": "object",
+ "properties": {"document": node},
+ }
+ if embedded
+ else {
+ "type": "object",
+ "properties": {},
+ **node,
+ }
+ )
+ with self.assertRaises(ValidationError) as caught:
+ ClientExternalToolDefinition(
+ name="client__indirect",
+ description="Reject indirect metadata.",
+ input_schema=schema,
+ )
+ self.assertIn(error, str(caught.exception))
+
+ def test_recursive_local_references_preserve_literal_data(self) -> None:
+ """Following reference cycles terminates and preserves literals."""
+ schema = {
+ "type": "object",
+ "properties": {"child": {"$ref": "#/$defs/node"}},
+ "$defs": {
+ "node": {
+ "$anchor": "node",
+ "type": "object",
+ "properties": {
+ "next": {"$ref": "#/$defs/node"},
+ "sibling": {"$ref": "#node"},
+ },
+ "default": {"$ref": "https://example.com/literal"},
+ },
+ },
+ "examples": [{"$ref": "#/$defs/node"}],
+ }
+ definition = ClientExternalToolDefinition(
+ name="client__recursive",
+ description="Allow recursive local schemas.",
+ input_schema=schema,
+ )
+ self.assertEqual(definition.input_schema, schema)
+ Draft202012Validator(schema).validate({"child": {"next": {}}})
+
+ def test_referenced_data_id_cannot_hide_a_remote_reference(self) -> None:
+ """Pointer targets retain the validator's reference resolution
+ scope."""
+ schema = {
+ "type": "object",
+ "properties": {},
+ "$ref": "#/default",
+ "default": {
+ "$id": "https://example.com/data",
+ "$ref": "#/x-target",
+ },
+ "x-target": {"$ref": "https://example.com/remote"},
+ }
+ with patch("urllib.request.urlopen") as retrieve:
+ with self.assertRaises(ValidationError) as caught:
+ ClientExternalToolDefinition(
+ name="client__indirect",
+ description="Reject references through literal IDs.",
+ input_schema=schema,
+ )
+ retrieve.assert_not_called()
+ self.assertEqual(
+ caught.exception.errors(include_url=False)[0]["msg"],
+ "Value error, Client tool schemas only support local $ref values.",
+ )
+
+ def test_local_schema_reference_is_allowed(self) -> None:
+ """Local definitions remain available for structured schemas."""
+ definition = ClientExternalToolDefinition(
+ name="client__local_reference",
+ description="Valid local reference.",
+ input_schema={
+ "type": "object",
+ "$defs": {
+ "value": {"type": "string"},
+ },
+ "properties": {
+ "value": {"$ref": "#/$defs/value"},
+ },
+ },
+ )
+
+ self.assertEqual(
+ definition.input_schema["properties"],
+ {"value": {"$ref": "#/$defs/value"}},
+ )
+
+ def test_duplicate_names_are_rejected(self) -> None:
+ """One request cannot register ambiguous duplicate names."""
+ with self.assertRaises(ValidationError):
+ ChatRequest(
+ agent_id="agent-1",
+ session_id="session-1",
+ input=None,
+ client_external_tools=[
+ _definition(),
+ _definition(),
+ ],
+ )
+
+ def test_chat_request_enforces_client_tool_limit(self) -> None:
+ """A request accepts at most sixteen client tool definitions."""
+ definitions = [
+ _definition(f"client__tool_{index}") for index in range(17)
+ ]
+
+ request = ChatRequest(
+ agent_id="agent-1",
+ session_id="session-1",
+ input=None,
+ client_external_tools=definitions[:16],
+ )
+ self.assertEqual(request.client_external_tools, definitions[:16])
+
+ with self.assertRaises(ValidationError):
+ ChatRequest(
+ agent_id="agent-1",
+ session_id="session-1",
+ input=None,
+ client_external_tools=definitions,
+ )
+
+
+class ClientExternalToolRuntimeTest(IsolatedAsyncioTestCase):
+ """Validate failures at the agent's schema evaluation boundary."""
+
+ async def test_supported_dialects_enforce_unevaluated_properties(
+ self,
+ ) -> None:
+ """Saved schemas retain Draft 2020-12 constraints during execution."""
+ for dialect in (
+ None,
+ "https://json-schema.org/draft/2020-12/schema",
+ "https://json-schema.org/draft/2020-12/schema#",
+ ):
+ with self.subTest(dialect=dialect):
+ schema = {
+ "type": "object",
+ "properties": {"known": {"type": "string"}},
+ "unevaluatedProperties": False,
+ }
+ if dialect is not None:
+ schema["$schema"] = dialect
+ definition = ClientExternalToolDefinition(
+ name="client__strict",
+ description="Reject extra arguments.",
+ read_only=True,
+ input_schema=schema,
+ )
+ self.assertEqual(definition.input_schema, schema)
+ model = MockModel()
+ model.set_responses(
+ [
+ ChatResponse(
+ content=[
+ ToolCallBlock(
+ id="strict-call",
+ name=definition.name,
+ input='{"known":"ok","extra":true}',
+ ),
+ ],
+ is_last=True,
+ ),
+ ChatResponse(
+ content=[TextBlock(text="Rejected extra input.")],
+ is_last=True,
+ ),
+ ],
+ )
+ agent = Agent(
+ name="Friday",
+ system_prompt="Help the user.",
+ model=model,
+ toolkit=Toolkit(tools=[ClientExternalTool(definition)]),
+ injection_config=InjectionConfig(
+ inject_runtime_state=False,
+ ),
+ )
+ events = [
+ event
+ async for event in agent.reply_stream(
+ UserMsg(name="user", content="Call the client tool."),
+ )
+ ]
+ self.assertEqual(
+ [
+ event
+ for event in events
+ if isinstance(event, RequireExternalExecutionEvent)
+ ],
+ [],
+ )
+ self.assertEqual(
+ [
+ (result.id, result.name, result.state)
+ for message in agent.state.context
+ for result in message.content
+ if isinstance(result, ToolResultBlock)
+ ],
+ [("strict-call", definition.name, "error")],
+ )
+
+ async def test_native_ask_user_parks_and_resumes_with_metadata(
+ self,
+ ) -> None:
+ """A native question uses the existing external execution loop."""
+ model = MockModel(context_size=10000)
+ model.set_responses(
+ [
+ ChatResponse(
+ content=[
+ ToolCallBlock(
+ id="ask",
+ name="AskUser",
+ input=json.dumps(
+ {
+ "questions": [
+ {
+ "question": "Which?",
+ "header": "Choice",
+ "options": [
+ {
+ "label": "A",
+ "description": "First",
+ },
+ {
+ "label": "B",
+ "description": "Second",
+ },
+ ],
+ },
+ ],
+ },
+ ),
+ ),
+ ],
+ is_last=True,
+ ),
+ ChatResponse(content=[TextBlock(text="Done")], is_last=True),
+ ],
+ )
+ agent = Agent(
+ name="Friday",
+ system_prompt="Help the user.",
+ model=model,
+ toolkit=Toolkit(tools=[AskUser()]),
+ injection_config=InjectionConfig(inject_runtime_state=False),
+ )
+ events = [
+ event
+ async for event in agent.reply_stream(
+ UserMsg(name="user", content="Ask me."),
+ )
+ ]
+ pending = [
+ event
+ for event in events
+ if isinstance(event, RequireExternalExecutionEvent)
+ ]
+ self.assertEqual(len(pending), 1)
+ self.assertEqual(
+ [call.name for call in pending[0].tool_calls],
+ ["AskUser"],
+ )
+ metadata = {
+ "answers": [
+ {"question": "Which?", "selected": ["B"], "other": None},
+ ],
+ }
+ reply = await agent.reply(
+ ExternalExecutionResultEvent(
+ reply_id=pending[0].reply_id,
+ execution_results=[
+ ToolResultBlock(
+ id="ask",
+ name="AskUser",
+ output="Which?\nB",
+ state=ToolResultState.SUCCESS,
+ metadata=metadata,
+ ),
+ ],
+ ),
+ )
+ self.assertEqual(reply.get_text_content(), "Done")
+ results = [
+ result
+ for message in agent.state.context
+ for result in message.content
+ if isinstance(result, ToolResultBlock)
+ ]
+ self.assertEqual([result.metadata for result in results], [metadata])
+
+ async def test_permissions_follow_explicit_read_only_contract(
+ self,
+ ) -> None:
+ """Only explicitly read-only client tools bypass confirmation."""
+ effectful_tool = ClientExternalTool(_definition())
+ read_only_tool = ClientExternalTool(_definition(read_only=True))
+
+ self.assertEqual(
+ await effectful_tool.check_permissions(
+ {},
+ PermissionContext(),
+ ),
+ PermissionDecision(
+ behavior=PermissionBehavior.ASK,
+ message=(
+ "Client external tool 'client__choose_option' "
+ "may change client-side state."
+ ),
+ decision_reason=(
+ "The active client did not declare "
+ "'client__choose_option' read-only."
+ ),
+ ),
+ )
+ self.assertEqual(
+ await read_only_tool.check_permissions(
+ {},
+ PermissionContext(),
+ ),
+ PermissionDecision(
+ behavior=PermissionBehavior.ALLOW,
+ message=(
+ "Client external tool 'client__choose_option' "
+ "is read-only."
+ ),
+ decision_reason=(
+ "The active client declared "
+ "'client__choose_option' read-only."
+ ),
+ ),
+ )
+ self.assertFalse(effectful_tool.is_read_only)
+ self.assertTrue(read_only_tool.is_read_only)
+
+ async def test_unresolvable_local_reference_becomes_tool_error(
+ self,
+ ) -> None:
+ """A broken local reference must not terminate the reply run."""
+ definition = ClientExternalToolDefinition(
+ name="client__broken_reference",
+ description="A client tool with a broken local reference.",
+ input_schema={
+ "type": "object",
+ "properties": {
+ "value": {"$ref": "#/$defs/missing"},
+ },
+ },
+ )
+ model = MockModel()
+ model.set_responses(
+ [
+ ChatResponse(
+ content=[
+ ToolCallBlock(
+ id="broken-reference-call",
+ name=definition.name,
+ input='{"value":"test"}',
+ ),
+ ],
+ is_last=True,
+ ),
+ ChatResponse(
+ content=[TextBlock(text="Recovered from schema error.")],
+ is_last=True,
+ ),
+ ],
+ )
+ agent = Agent(
+ name="Friday",
+ system_prompt="You are a helpful assistant.",
+ model=model,
+ toolkit=Toolkit(tools=[ClientExternalTool(definition)]),
+ injection_config=InjectionConfig(
+ inject_runtime_state=False,
+ ),
+ )
+
+ response = await agent.reply(
+ UserMsg(name="user", content="Call the client tool."),
+ )
+
+ self.assertEqual(
+ response.get_content_blocks("text")[0].text,
+ "Recovered from schema error.",
+ )
+ tool_results = agent.state.context[-1].get_content_blocks(
+ "tool_result",
+ )
+ self.assertEqual(len(tool_results), 1)
+ self.assertEqual(
+ {
+ "id": tool_results[0].id,
+ "name": tool_results[0].name,
+ "state": tool_results[0].state,
+ },
+ {
+ "id": "broken-reference-call",
+ "name": definition.name,
+ "state": "error",
+ },
+ )
diff --git a/tests/console_test.py b/tests/console_test.py
index 90401933c..8e4ac1b14 100644
--- a/tests/console_test.py
+++ b/tests/console_test.py
@@ -18,6 +18,7 @@ from agentscope.event import (
AgentEvent,
ReplyEndEvent,
ReplyStartEvent,
+ RequireExternalExecutionEvent,
RequireUserConfirmEvent,
TextBlockDeltaEvent,
TextBlockStartEvent,
@@ -73,6 +74,9 @@ class ConsoleCancellationTest(IsolatedAsyncioTestCase):
def setUp(self) -> None:
"""Create a real renderer with captured terminal output."""
self.renderer = ConsoleRenderer(console=Console(file=StringIO()))
+ self.pending_requests: list[
+ RequireUserConfirmEvent | RequireExternalExecutionEvent
+ ] = []
async def test_run_reply_propagates_caller_cancellation(self) -> None:
"""Cancelling the console task must remain visible to its caller."""
@@ -82,6 +86,7 @@ class ConsoleCancellationTest(IsolatedAsyncioTestCase):
cast(Agent, agent),
self.renderer,
UserMsg(name="user", content="hello"),
+ self.pending_requests,
),
)
await agent.started.wait()
@@ -90,6 +95,7 @@ class ConsoleCancellationTest(IsolatedAsyncioTestCase):
with self.assertRaises(asyncio.CancelledError):
await task
+ self.assertEqual(self.pending_requests, [])
self.assertIsNone(self.renderer.last_msg)
self.assertEqual(self.renderer._active_msgs, {})
@@ -116,12 +122,14 @@ class ConsoleCancellationTest(IsolatedAsyncioTestCase):
cast(Agent, agent),
self.renderer,
UserMsg(name="user", content="hello"),
+ self.pending_requests,
),
)
await agent.started.wait()
signal_callbacks[0]()
self.assertIsNone(await task)
+ self.assertEqual(self.pending_requests, [])
self.assertIsNone(self.renderer.last_msg)
self.assertEqual(self.renderer._active_msgs, {})
@@ -150,6 +158,10 @@ class ConsoleCancellationTest(IsolatedAsyncioTestCase):
block_id="t1",
delta="partial response",
),
+ RequireExternalExecutionEvent(
+ reply_id=f"member-{index}",
+ tool_calls=[],
+ ),
failure,
],
)
@@ -158,8 +170,10 @@ class ConsoleCancellationTest(IsolatedAsyncioTestCase):
cast(Agent, agent),
self.renderer,
UserMsg(name="user", content="hello"),
+ self.pending_requests,
)
self.assertIs(caught.exception, failure)
+ self.assertEqual(self.pending_requests, [])
self.assertIsNone(self.renderer.last_msg)
self.assertEqual(self.renderer._active_msgs, {})
@@ -171,10 +185,78 @@ class ConsoleCancellationTest(IsolatedAsyncioTestCase):
cast(Agent, agent),
self.renderer,
UserMsg(name="user", content="retry"),
+ self.pending_requests,
)
self.assertEqual(self.renderer._active_msgs, {})
self.assertEqual(self.renderer.last_msg.id, "next")
+ async def test_external_execution_pause_preserves_reply(self) -> None:
+ """External input pauses retain the reply and return the request."""
+ pending = RequireExternalExecutionEvent(
+ reply_id="external",
+ tool_calls=[],
+ )
+ agent = _EventAgent(
+ [
+ ReplyStartEvent(
+ session_id="s",
+ reply_id="external",
+ name="Agent",
+ ),
+ pending,
+ ],
+ )
+
+ result = await _run_reply(
+ cast(Agent, agent),
+ self.renderer,
+ UserMsg(name="user", content="hello"),
+ self.pending_requests,
+ )
+
+ self.assertIs(result, pending)
+ self.assertEqual(self.renderer.last_msg.id, "external")
+ self.assertEqual(
+ self.renderer._active_msgs,
+ {"external": self.renderer.last_msg},
+ )
+
+ async def test_ended_reply_preserves_other_queued_requests(self) -> None:
+ """Reply completion removes only that reply's pending requests."""
+ first = RequireExternalExecutionEvent(reply_id="first", tool_calls=[])
+ stale = RequireExternalExecutionEvent(reply_id="first", tool_calls=[])
+ second = RequireUserConfirmEvent(reply_id="second", tool_calls=[])
+ agent = _EventAgent(
+ [
+ ReplyStartEvent(session_id="s", reply_id="first", name="A"),
+ ReplyStartEvent(session_id="s", reply_id="second", name="B"),
+ first,
+ stale,
+ second,
+ ],
+ )
+ self.assertIs(
+ await _run_reply(
+ cast(Agent, agent),
+ self.renderer,
+ UserMsg(name="user", content="hello"),
+ self.pending_requests,
+ ),
+ first,
+ )
+ self.assertEqual(self.pending_requests, [stale, second])
+ agent.events = [ReplyEndEvent(session_id="s", reply_id="first")]
+ self.assertIs(
+ await _run_reply(
+ cast(Agent, agent),
+ self.renderer,
+ UserMsg(name="user", content="continue"),
+ self.pending_requests,
+ ),
+ second,
+ )
+ self.assertEqual(self.pending_requests, [])
+
async def test_hitl_keeps_pending_replies_across_streams(self) -> None:
"""A normal HITL pause retains both leader and member content."""
pending = RequireUserConfirmEvent(reply_id="member", tool_calls=[])
@@ -208,6 +290,7 @@ class ConsoleCancellationTest(IsolatedAsyncioTestCase):
cast(Agent, agent),
self.renderer,
UserMsg(name="user", content="hello"),
+ self.pending_requests,
)
self.assertIs(result, pending)
member_msg = self.renderer.last_msg
@@ -238,6 +321,7 @@ class ConsoleCancellationTest(IsolatedAsyncioTestCase):
reply_id="member",
confirm_results=[],
),
+ self.pending_requests,
)
warning.assert_not_called()
self.assertIsNone(result)
diff --git a/tests/hitl_external_execution_test.py b/tests/hitl_external_execution_test.py
index 8ed24b4ad..123143524 100644
--- a/tests/hitl_external_execution_test.py
+++ b/tests/hitl_external_execution_test.py
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
# pylint: disable=redefined-builtin
"""Test the external execution events in the agent class."""
+import json
from typing import Any
from unittest.async_case import IsolatedAsyncioTestCase
from unittest.mock import patch
@@ -26,7 +27,10 @@ from agentscope.message import (
UserMsg,
ToolResultState,
)
-from agentscope.event import ExternalExecutionResultEvent
+from agentscope.event import (
+ ExternalExecutionResultEvent,
+ RequireExternalExecutionEvent,
+)
class MockExternalSequentialTool(ToolBase):
@@ -274,6 +278,49 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):
},
]
+ async def test_external_input_is_normalized_after_repair(self) -> None:
+ """External clients receive valid JSON after input repair."""
+ self.agent.toolkit = Toolkit(
+ tools=[MockExternalSequentialTool()],
+ )
+ malformed_input = "{'input': 'test1'}"
+ response = ChatResponse(
+ content=[
+ ToolCallBlock(
+ id=self.tool_call_id_1,
+ name=self.sequential_tool_name,
+ input=malformed_input,
+ ),
+ ],
+ is_last=True,
+ usage=None,
+ )
+ self.model.set_responses([[response]])
+
+ pending = None
+ async for event in self.agent.reply_stream(
+ UserMsg(name="user", content=self.user_input_text),
+ ):
+ if isinstance(event, RequireExternalExecutionEvent):
+ pending = event
+
+ self.assertIsNotNone(pending)
+ assert pending is not None
+ normalized_input = pending.tool_calls[0].input
+ stored_call = self.agent.state.context[-1].content[0]
+ self.assertIsInstance(stored_call, ToolCallBlock)
+ assert isinstance(stored_call, ToolCallBlock)
+ self.assertEqual(
+ {
+ "parsed": json.loads(normalized_input),
+ "stored": stored_call.input,
+ },
+ {
+ "parsed": {"input": "test1"},
+ "stored": normalized_input,
+ },
+ )
+
async def test_single_external_execution(self) -> None:
"""Test single external execution tool call.
diff --git a/tests/pipeline_team_test.py b/tests/pipeline_team_test.py
index d7fab5afc..7328e9c94 100644
--- a/tests/pipeline_team_test.py
+++ b/tests/pipeline_team_test.py
@@ -40,7 +40,7 @@ class AskTool(ToolBase):
is_concurrency_safe: bool = True
is_read_only: bool = False
- async def check_permissions(
+ async def check_permissions( # pylint: disable=unused-argument
self,
tool_input: dict[str, Any],
context: PermissionContext,
@@ -70,7 +70,7 @@ class SlowTool(ToolBase):
super().__init__()
self.started = asyncio.Event()
- async def check_permissions(
+ async def check_permissions( # pylint: disable=unused-argument
self,
tool_input: dict[str, Any],
context: PermissionContext,
@@ -820,8 +820,8 @@ class TeamPipelineTest(IsolatedAsyncioTestCase):
"finished_at": None,
"id": "call-1",
"name": "TeamAssign",
- "input": "{'member': 'researcher', "
- "'prompt': 'Find A'}",
+ "input": '{"member": "researcher", '
+ '"prompt": "Find A"}',
"state": "finished",
"suggested_rules": [],
},
diff --git a/tests/service_chat_run_context_test.py b/tests/service_chat_run_context_test.py
index 203046164..9cbaf0939 100644
--- a/tests/service_chat_run_context_test.py
+++ b/tests/service_chat_run_context_test.py
@@ -251,6 +251,7 @@ class TestRunContextResolution(IsolatedAsyncioTestCase):
worker_session.id,
worker_agent.id,
message,
+ client_builtin_tools=["AskUser"],
)
self.assertTrue(
await queue.drain_chat_inputs(
@@ -265,6 +266,7 @@ class TestRunContextResolution(IsolatedAsyncioTestCase):
worker_session.id,
worker_agent.id,
message,
+ client_builtin_tools=["AskUser"],
)
if message is not None:
save.assert_awaited_once_with(
@@ -308,6 +310,7 @@ class TestRunContextResolution(IsolatedAsyncioTestCase):
"get_team_calls": storage.get_team_calls,
"team_role": toolkit_kwargs["team_role"],
"channel_tools": toolkit_kwargs["channel_tools"],
+ "client_builtin_tools": toolkit_kwargs["client_builtin_tools"],
"replies": replies,
"tts_models": [
mw.tts
@@ -326,6 +329,7 @@ class TestRunContextResolution(IsolatedAsyncioTestCase):
"get_team_calls": 1,
"team_role": "worker",
"channel_tools": [],
+ "client_builtin_tools": ["AskUser"],
"replies": [message],
"tts_models": (
[get_tts_model.return_value] if tts_available else []
diff --git a/tests/service_toolkit_test.py b/tests/service_toolkit_test.py
index 5ad3cd219..b22c2c404 100644
--- a/tests/service_toolkit_test.py
+++ b/tests/service_toolkit_test.py
@@ -9,11 +9,10 @@ Verifies the assembly rules:
- workspace builtins are always included;
- the four ``Task*`` planning tools are always included;
- :class:`ToolStop` (from ``BackgroundTaskManager``) is always included;
+- client external tools are included only when declared for the run;
- the four ``Schedule*`` tools only when ``session.config.chat_model_config``
is set (they need a model to fire new runs with);
-- team tools are role-gated by ``agent_record.source``: ``"team"`` →
- one ``TeamSay`` (worker variant); anything else → the full
- leader-side toolset of four;
+- team tools are role-gated by the caller-resolved ``team_role``;
- caller-supplied ``extra_factory`` results land at the end.
"""
from typing import Any
@@ -25,6 +24,9 @@ from agentscope.app._manager import (
BackgroundTaskManager,
SchedulerManager,
)
+from agentscope.app._client_external_tool import (
+ ClientExternalToolDefinition,
+)
from agentscope.app._service import ResourceAccessService, get_toolkit
from agentscope.app.access import DenyAllResourceAccessPolicy
from agentscope.app.storage import (
@@ -34,7 +36,7 @@ from agentscope.app.storage import (
SessionConfig,
SessionRecord,
)
-from agentscope.tool import ToolBase
+from agentscope.tool import AskUser, ToolBase
class _FakeWorkspace:
@@ -235,6 +237,8 @@ class TestGetToolkitBaseAssembly(IsolatedAsyncioTestCase):
)
# Background task control present.
self.assertIn("ToolStop", names)
+ # No client tool is attached without a per-run declaration.
+ self.assertNotIn("AskUser", names)
# Schedule control present (model_config is set).
self.assertTrue(
{
@@ -250,6 +254,134 @@ class TestGetToolkitBaseAssembly(IsolatedAsyncioTestCase):
{"TeamCreate", "AgentCreate", "TeamSay", "TeamDelete"} <= names,
)
+ async def test_client_external_tool_is_scoped_to_declaring_run(
+ self,
+ ) -> None:
+ """A validated client tool is attached only when supplied."""
+ agent = _make_agent(source="user")
+ session = _make_session(
+ user_id="u",
+ agent_id=agent.id,
+ with_model=True,
+ )
+ definition = ClientExternalToolDefinition(
+ name="client__choose_option",
+ description="Ask the user to choose.",
+ input_schema={
+ "type": "object",
+ "properties": {
+ "question": {"type": "string"},
+ },
+ "required": ["question"],
+ },
+ )
+
+ toolkit = await get_toolkit(
+ storage=_NoOpStorage(), # type: ignore[arg-type]
+ workspace=_FakeWorkspace(), # type: ignore[arg-type]
+ workspace_manager=FakeWorkspaceManager(),
+ scheduler_manager=SchedulerManager(
+ storage=_NoOpStorage(), # type: ignore[arg-type]
+ message_bus=_NullBus(), # type: ignore[arg-type]
+ workspace_manager=FakeWorkspaceManager(),
+ ),
+ background_task_manager=BackgroundTaskManager(
+ message_bus=_NullBus(), # type: ignore[arg-type]
+ ),
+ message_bus=_NullBus(), # type: ignore[arg-type]
+ user_id="u",
+ agent_record=agent,
+ session_record=session,
+ extra_factory=None,
+ middlewares=[],
+ resource_access_service=_make_access(_NoOpStorage()),
+ client_external_tools=[definition],
+ client_builtin_tools=["AskUser"],
+ )
+
+ native_tool = await toolkit.get_tool("AskUser")
+ self.assertIsInstance(native_tool, AskUser)
+ self.assertEqual(native_tool.metadata_schema, AskUser.metadata_schema)
+
+ tool = await toolkit.get_tool("client__choose_option")
+ self.assertIsNotNone(tool)
+ self.assertEqual(
+ {
+ "name": tool.name,
+ "description": tool.description,
+ "input_schema": tool.input_schema,
+ "is_external_tool": tool.is_external_tool,
+ },
+ {
+ "name": "client__choose_option",
+ "description": "Ask the user to choose.",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "question": {"type": "string"},
+ },
+ "required": ["question"],
+ },
+ "is_external_tool": True,
+ },
+ )
+
+ async def test_client_external_tool_does_not_replace_server_tool(
+ self,
+ ) -> None:
+ """A client definition with a server tool name is rejected."""
+
+ class _ServerTool(_StubTool):
+ name: str = "client__shared_name"
+ description: str = "server implementation"
+ input_schema: dict = {
+ "type": "object",
+ "properties": {},
+ }
+
+ agent = _make_agent(source="user")
+ session = _make_session(
+ user_id="u",
+ agent_id=agent.id,
+ with_model=True,
+ )
+ with self.assertRaisesRegex(
+ ValueError,
+ "conflicts with a server tool",
+ ):
+ await get_toolkit(
+ storage=_NoOpStorage(), # type: ignore[arg-type]
+ workspace=_FakeWorkspace(
+ tools=[_ServerTool()],
+ ), # type: ignore[arg-type]
+ workspace_manager=FakeWorkspaceManager(),
+ scheduler_manager=SchedulerManager(
+ storage=_NoOpStorage(), # type: ignore[arg-type]
+ message_bus=_NullBus(), # type: ignore[arg-type]
+ workspace_manager=FakeWorkspaceManager(),
+ ),
+ background_task_manager=BackgroundTaskManager(
+ message_bus=_NullBus(), # type: ignore[arg-type]
+ ),
+ message_bus=_NullBus(), # type: ignore[arg-type]
+ user_id="u",
+ agent_record=agent,
+ session_record=session,
+ extra_factory=None,
+ middlewares=[],
+ resource_access_service=_make_access(_NoOpStorage()),
+ client_external_tools=[
+ ClientExternalToolDefinition(
+ name="client__shared_name",
+ description="client implementation",
+ input_schema={
+ "type": "object",
+ "properties": {},
+ },
+ ),
+ ],
+ )
+
class TestGetToolkitWorkerVariant(IsolatedAsyncioTestCase):
"""A session passed ``team_role="worker"`` only gets ``TeamSay``;
diff --git a/tests/service_wakeup_dispatcher_test.py b/tests/service_wakeup_dispatcher_test.py
index a6cbcc6e6..75bca8fd5 100644
--- a/tests/service_wakeup_dispatcher_test.py
+++ b/tests/service_wakeup_dispatcher_test.py
@@ -27,6 +27,9 @@ from pydantic import ValidationError
from agentscope.app import _bus_ops
from agentscope.app._manager import ChatRunRegistry, WakeupDispatcher
+from agentscope.app._client_external_tool import (
+ ClientExternalToolDefinition,
+)
from agentscope.app._service import ChatService
from agentscope.app._bus_ops import (
ChatQueueBusyError,
@@ -50,7 +53,12 @@ from agentscope.app._router._schema import (
UpdateChatQueueItemRequest,
)
from agentscope.state import AgentState
-from agentscope.message import AssistantMsg, ToolCallBlock, UserMsg
+from agentscope.message import (
+ AssistantMsg,
+ ToolCallBlock,
+ ToolResultBlock,
+ UserMsg,
+)
class _FakeStorage:
@@ -312,18 +320,24 @@ class _FakeChatService:
session_id: str,
agent_id: str,
input_msg: Any = None,
+ client_external_tools: list[ClientExternalToolDefinition]
+ | None = None,
+ client_builtin_tools: list[str] | None = None,
queue_item_id: str | None = None,
input_persisted: bool = False,
) -> None:
"""Record the call and signal a waiter."""
- self.calls.append(
- {
- "user_id": user_id,
- "session_id": session_id,
- "agent_id": agent_id,
- "input_msg": input_msg,
- },
- )
+ call: dict[str, Any] = {
+ "user_id": user_id,
+ "session_id": session_id,
+ "agent_id": agent_id,
+ "input_msg": input_msg,
+ }
+ if client_external_tools is not None:
+ call["client_external_tools"] = client_external_tools
+ if client_builtin_tools is not None:
+ call["client_builtin_tools"] = client_builtin_tools
+ self.calls.append(call)
self.notify.set()
@@ -341,6 +355,9 @@ class _BlockingChatService(_FakeChatService):
session_id: str,
agent_id: str,
input_msg: Any = None,
+ client_external_tools: list[ClientExternalToolDefinition]
+ | None = None,
+ client_builtin_tools: list[str] | None = None,
queue_item_id: str | None = None,
input_persisted: bool = False,
) -> None:
@@ -349,8 +366,10 @@ class _BlockingChatService(_FakeChatService):
session_id,
agent_id,
input_msg,
- queue_item_id,
- input_persisted,
+ queue_item_id=queue_item_id,
+ input_persisted=input_persisted,
+ client_external_tools=client_external_tools,
+ client_builtin_tools=client_builtin_tools,
)
if len(self.calls) == 1:
await self.release_first.wait()
@@ -990,6 +1009,145 @@ class TestWakeupDispatcherDispatch( # pylint: disable=too-many-public-methods
self.assertIsInstance(call["input_msg"], UserConfirmResultEvent)
self.assertEqual(call["input_msg"].reply_id, "r1")
+ async def test_resume_preserves_client_external_tools(self) -> None:
+ """Queued resume triggers retain active-client tool schemas."""
+ from agentscope.event import UserConfirmResultEvent
+
+ bus = _FakeBus()
+ chat = _FakeChatService()
+ event = UserConfirmResultEvent.model_construct(
+ reply_id="r1",
+ confirm_results=[],
+ )
+ definition = ClientExternalToolDefinition(
+ name="client__choose_option",
+ description="Ask the user to choose.",
+ input_schema={
+ "type": "object",
+ "properties": {
+ "question": {"type": "string"},
+ },
+ },
+ )
+
+ async with WakeupDispatcher(
+ message_bus=bus,
+ storage=_FakeStorage(),
+ chat_service=chat,
+ chat_run_registry=ChatRunRegistry(),
+ ):
+ await bus.queue_push(
+ MessageBusKeys.wakeup_queue(),
+ {
+ "user_id": "u",
+ "session_id": "w1",
+ "agent_id": "wa1",
+ "kind": MessageBusKeys.WAKEUP_KIND_RESUME,
+ "input": event.model_dump(mode="json"),
+ "client_external_tools": [
+ definition.model_dump(mode="json"),
+ ],
+ "client_builtin_tools": ["AskUser"],
+ },
+ )
+ await bus.publish(MessageBusKeys.wakeup_signal(), {})
+ await asyncio.wait_for(chat.notify.wait(), timeout=2.0)
+
+ self.assertEqual(len(chat.calls), 1)
+ self.assertEqual(
+ chat.calls[0]["client_external_tools"],
+ [definition],
+ )
+ self.assertEqual(chat.calls[0]["client_builtin_tools"], ["AskUser"])
+
+ async def test_invalid_client_tools_do_not_drop_resume(self) -> None:
+ """Invalid optional tools cannot strand an external result."""
+ from agentscope.event import ExternalExecutionResultEvent
+
+ bus = _FakeBus()
+ chat = _FakeChatService()
+ event = ExternalExecutionResultEvent(
+ reply_id="r1",
+ execution_results=[
+ ToolResultBlock(
+ id="tool-call-1",
+ name="client__choose_option",
+ output="Minimal change",
+ ),
+ ],
+ )
+
+ async with WakeupDispatcher(
+ message_bus=bus,
+ storage=_FakeStorage(),
+ chat_service=chat,
+ chat_run_registry=ChatRunRegistry(),
+ ):
+ await bus.queue_push(
+ MessageBusKeys.wakeup_queue(),
+ {
+ "user_id": "u",
+ "session_id": "w1",
+ "agent_id": "wa1",
+ "kind": MessageBusKeys.WAKEUP_KIND_RESUME,
+ "input": event.model_dump(mode="json"),
+ "client_external_tools": [{"name": "invalid"}],
+ "client_builtin_tools": ["unknown"],
+ },
+ )
+ await bus.publish(MessageBusKeys.wakeup_signal(), {})
+ await asyncio.wait_for(chat.notify.wait(), timeout=2.0)
+
+ self.assertEqual(
+ chat.calls,
+ [
+ {
+ "user_id": "u",
+ "session_id": "w1",
+ "agent_id": "wa1",
+ "input_msg": event,
+ },
+ ],
+ )
+
+ async def test_invalid_client_tools_do_not_drop_message(self) -> None:
+ """Invalid optional tools cannot discard a valid user message."""
+ bus = _FakeBus()
+ chat = _FakeChatService()
+ message = UserMsg(name="user", content="Keep this message.")
+
+ async with WakeupDispatcher(
+ message_bus=bus,
+ storage=_FakeStorage(),
+ chat_service=chat,
+ chat_run_registry=ChatRunRegistry(),
+ ):
+ await bus.queue_push(
+ MessageBusKeys.wakeup_queue(),
+ {
+ "user_id": "u",
+ "session_id": "w1",
+ "agent_id": "wa1",
+ "kind": MessageBusKeys.WAKEUP_KIND_MESSAGE,
+ "input": message.model_dump(mode="json"),
+ "client_external_tools": [{"name": "invalid"}],
+ },
+ )
+ await bus.publish(MessageBusKeys.wakeup_signal(), {})
+ await asyncio.wait_for(chat.notify.wait(), timeout=2.0)
+
+ self.assertEqual(
+ chat.calls,
+ [
+ {
+ "user_id": "u",
+ "session_id": "w1",
+ "agent_id": "wa1",
+ "input_msg": message,
+ },
+ ],
+ )
+
async def test_resume_running_session_requeues_until_free(self) -> None:
"""A ``resume`` whose target is still running is NOT dropped: it
is re-queued (with backoff) and dispatched once the session lock
@@ -1020,6 +1178,7 @@ class TestWakeupDispatcherDispatch( # pylint: disable=too-many-public-methods
"agent_id": "wa1",
"kind": MessageBusKeys.WAKEUP_KIND_RESUME,
"input": event.model_dump(mode="json"),
+ "client_builtin_tools": ["AskUser"],
},
)
await bus.publish(MessageBusKeys.wakeup_signal(), {})
@@ -1034,6 +1193,7 @@ class TestWakeupDispatcherDispatch( # pylint: disable=too-many-public-methods
self.assertEqual(len(chat.calls), 1)
self.assertEqual(chat.calls[0]["session_id"], "w1")
+ self.assertEqual(chat.calls[0]["client_builtin_tools"], ["AskUser"])
self.assertIsInstance(
chat.calls[0]["input_msg"],
UserConfirmResultEvent,