Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(agent-team): support to invite the existing agents within the agent service (#1977)
DavdGao426e660a47dc
diff --git a/.gitignore b/.gitignoreindex a84acd686..730e6c8f8 100644--- a/.gitignore+++ b/.gitignore@@ -16,6 +16,11 @@ eggs/.eggs/lib/lib64/+# JS/Node frontend uses lib/ as a source directory (shadcn convention).+# Re-include it so newly added files under examples/web_ui/frontend/src/lib/+# aren't silently swallowed by the Python-oriented lib/ rule above.+!examples/web_ui/frontend/src/lib/+!examples/web_ui/frontend/src/lib/**parts/sdist/var/diff --git a/examples/web_ui/frontend/src/api/agent.ts b/examples/web_ui/frontend/src/api/agent.tsindex 30a6f6faf..264793e4d 100644--- a/examples/web_ui/frontend/src/api/agent.ts+++ b/examples/web_ui/frontend/src/api/agent.ts@@ -2,7 +2,7 @@ import { client } from './client';import type {AgentListResponse,AgentRecord,- AgentSchemaResponse,+ AgentSchemaV2Response,CreateAgentRequest,CreateAgentResponse,UpdateAgentRequest,@@ -11,12 +11,13 @@ import type {export const agentApi = {list: () => client.get<AgentListResponse>('/agent/'),- getSchema: () => client.get<AgentSchemaResponse>('/agent/schema'),+ getSchema: () => client.get<AgentSchemaV2Response>('/agent/schema/v2'),- create: (body: CreateAgentRequest) => client.post<CreateAgentResponse>('/agent/', body),+ create: (body: CreateAgentRequest, options?: { silent?: boolean }) =>+ client.post<CreateAgentResponse>('/agent/', body, undefined, options),- update: (agentId: string, body: UpdateAgentRequest) =>- client.patch<AgentRecord>(`/agent/${agentId}`, body),+ update: (agentId: string, body: UpdateAgentRequest, options?: { silent?: boolean }) =>+ client.patch<AgentRecord>(`/agent/${agentId}`, body, undefined, options),delete: (agentId: string) => client.delete(`/agent/${agentId}`),};diff --git a/examples/web_ui/frontend/src/api/client.ts b/examples/web_ui/frontend/src/api/client.tsindex e8d071472..2ba6e6fd2 100644--- a/examples/web_ui/frontend/src/api/client.ts+++ b/examples/web_ui/frontend/src/api/client.ts@@ -100,10 +100,18 @@ async function streamRequest(export const client = {get: <T>(path: string, params?: Record<string, string>) =>request<T>(path, { method: 'GET', params }),- post: <T>(path: string, body?: unknown, params?: Record<string, string>) =>- request<T>(path, { method: 'POST', body, params }),- patch: <T>(path: string, body?: unknown, params?: Record<string, string>) =>- request<T>(path, { method: 'PATCH', body, params }),+ post: <T>(+ path: string,+ body?: unknown,+ params?: Record<string, string>,+ options?: { silent?: boolean },+ ) => request<T>(path, { method: 'POST', body, params, silent: options?.silent }),+ patch: <T>(+ path: string,+ body?: unknown,+ params?: Record<string, string>,+ options?: { silent?: boolean },+ ) => request<T>(path, { method: 'PATCH', body, params, silent: options?.silent }),delete: <T = void>(path: string, params?: Record<string, string>) =>request<T>(path, { method: 'DELETE', params }),stream: (path: string, options?: RequestOptions & { signal?: AbortSignal }) =>diff --git a/examples/web_ui/frontend/src/api/types.ts b/examples/web_ui/frontend/src/api/types.tsindex 7a5950487..2d66f6100 100644--- a/examples/web_ui/frontend/src/api/types.ts+++ b/examples/web_ui/frontend/src/api/types.ts@@ -33,6 +33,11 @@ export interface ReActConfig {stop_on_reject?: boolean;}+export interface InviteConfig {+ invitable?: boolean;+ invite_description?: string | null;+}+// ─── Agent ────────────────────────────────────────────────────────────────────export interface AgentData {@@ -41,6 +46,7 @@ export interface AgentData {system_prompt: string;context_config: ContextConfig;react_config: ReActConfig;+ invite_config: InviteConfig;}export interface AgentRecord extends RecordBase {@@ -53,6 +59,7 @@ export interface CreateAgentRequest {system_prompt?: string;context_config?: ContextConfig;react_config?: ReActConfig;+ invite_config?: InviteConfig;}export interface CreateAgentResponse {@@ -64,6 +71,7 @@ export interface UpdateAgentRequest {system_prompt?: string;context_config?: ContextConfig;react_config?: ReActConfig;+ invite_config?: InviteConfig;}export interface AgentListResponse {@@ -72,9 +80,10 @@ export interface AgentListResponse {}/**- * JSON Schema fragments returned by `GET /agent/schema`. Each fragment is a- * self-contained JSON Schema object (no `$ref`s across fragments) covering- * one section of the agent create / edit form.+ * @deprecated Superseded by {@link AgentSchemaV2Response}. Kept only for+ * legacy consumers still calling `GET /agent/schema`. The new form flow+ * uses `GET /agent/schema/v2`, which returns the full `AgentData` JSON+ * Schema in a single `schema` field.*/export interface AgentSchemaResponse {identity: JSONSchema;@@ -82,6 +91,19 @@ export interface AgentSchemaResponse {react_config: JSONSchema;}+/**+ * Response of `GET /agent/schema/v2`. `schema` is the full `AgentData`+ * JSON Schema (with `$ref`s inlined, `id` filtered out, and+ * `context_config.summary_schema` filtered out). The frontend derives+ * its section grouping directly from `schema.properties`:+ * - top-level scalar/textarea/boolean properties → "identity" section+ * - top-level `object`-typed properties (currently `context_config`,+ * `react_config`, and `invite_config`) → one section each+ */+export interface AgentSchemaV2Response {+ schema: JSONSchema;+}+// ─── Session ──────────────────────────────────────────────────────────────────export type SessionSource = 'user' | 'schedule';diff --git a/examples/web_ui/frontend/src/components/dialog/AgentDialog.tsx b/examples/web_ui/frontend/src/components/dialog/AgentDialog.tsxindex de77fdddc..e217af608 100644--- a/examples/web_ui/frontend/src/components/dialog/AgentDialog.tsx+++ b/examples/web_ui/frontend/src/components/dialog/AgentDialog.tsx@@ -2,7 +2,7 @@ import { CircleAlert, Loader2, PlusCircle } from 'lucide-react';import { useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';-import type { ContextConfig, ReActConfig } from '@/api';+import type { ContextConfig, InviteConfig, ReActConfig } from '@/api';import {AgentFormFields,defaultAgentFormValues,@@ -10,6 +10,7 @@ import {type AgentSection,} from '@/components/form/AgentFormFields';import type { SchemaFormValue } from '@/components/form/SchemaForm';+import { Alert, AlertDescription } from '@/components/ui/alert.tsx';import { Button } from '@/components/ui/button';import {Dialog,@@ -22,6 +23,7 @@ import {} from '@/components/ui/dialog';import { useAgents } from '@/hooks/useAgents';import { useAgentSchema } from '@/hooks/useAgentSchema';+import { formatApiErrorForAlert } from '@/lib/api-error';interface Props {onCreated?: () => void;@@ -35,15 +37,20 @@ export function AgentDialog({ onCreated, triggerId }: Props) {const [open, setOpen] = useState(false);const [submitting, setSubmitting] = useState(false);const [values, setValues] = useState<AgentFormValues | null>(null);+ const [errorMsg, setErrorMsg] = useState('');useEffect(() => {if (open && schema && !values) {setValues(defaultAgentFormValues(schema));}- if (!open) setValues(null);+ if (!open) {+ setValues(null);+ setErrorMsg('');+ }}, [open, schema, values]);const handleChange = (section: AgentSection, key: string, value: SchemaFormValue) => {+ setErrorMsg('');setValues((prev) =>prev ? { ...prev, [section]: { ...prev[section], [key]: value } } : prev,);@@ -53,16 +60,23 @@ export function AgentDialog({ onCreated, triggerId }: Props) {if (!values) return;const name = (values.identity.name as string | undefined)?.trim();if (!name) return;+ setErrorMsg('');setSubmitting(true);try {- await create({- name,- system_prompt: values.identity.system_prompt as string | undefined,- context_config: values.context_config as unknown as ContextConfig,- react_config: values.react_config as unknown as ReActConfig,- });+ await create(+ {+ name,+ system_prompt: values.identity.system_prompt as string | undefined,+ context_config: values.context_config as unknown as ContextConfig,+ react_config: values.react_config as unknown as ReActConfig,+ invite_config: values.invite_config as unknown as InviteConfig,+ },+ { silent: true },+ );setOpen(false);onCreated?.();+ } catch (e) {+ setErrorMsg(formatApiErrorForAlert(e));} finally {setSubmitting(false);}@@ -92,6 +106,14 @@ export function AgentDialog({ onCreated, triggerId }: Props) {<p className="text-muted-foreground text-sm">{t('common.loading')}</p>)}</div>+ {errorMsg && (+ <Alert variant="destructive">+ <CircleAlert />+ <AlertDescription className="whitespace-pre-wrap">+ {errorMsg}+ </AlertDescription>+ </Alert>+ )}<DialogFooter><Button variant="ghost" onClick={() => setOpen(false)} disabled={submitting}><CircleAlert className="size-3.5" />diff --git a/examples/web_ui/frontend/src/components/dialog/EditAgentDialog.tsx b/examples/web_ui/frontend/src/components/dialog/EditAgentDialog.tsxindex 48b9e52c6..4400936b3 100644--- a/examples/web_ui/frontend/src/components/dialog/EditAgentDialog.tsx+++ b/examples/web_ui/frontend/src/components/dialog/EditAgentDialog.tsx@@ -2,7 +2,7 @@ import { CircleAlert, Loader2, Save } from 'lucide-react';import { useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';-import type { AgentRecord, ContextConfig, ReActConfig } from '@/api';+import type { AgentRecord, ContextConfig, InviteConfig, ReActConfig } from '@/api';import {AgentFormFields,defaultAgentFormValues,@@ -10,6 +10,7 @@ import {type AgentSection,} from '@/components/form/AgentFormFields';import type { SchemaFormValue } from '@/components/form/SchemaForm';+import { Alert, AlertDescription } from '@/components/ui/alert.tsx';import { Button } from '@/components/ui/button';import {Dialog,@@ -21,6 +22,7 @@ import {} from '@/components/ui/dialog';import { useAgents } from '@/hooks/useAgents';import { useAgentSchema } from '@/hooks/useAgentSchema';+import { formatApiErrorForAlert } from '@/lib/api-error';interface Props {open: boolean;@@ -35,10 +37,14 @@ export function EditAgentDialog({ open, onOpenChange, agent, onUpdated }: Props)const { schema } = useAgentSchema();const [submitting, setSubmitting] = useState(false);const [values, setValues] = useState<AgentFormValues | null>(null);+ const [errorMsg, setErrorMsg] = useState('');useEffect(() => {if (!open || !schema) {- if (!open) setValues(null);+ if (!open) {+ setValues(null);+ setErrorMsg('');+ }return;}// Start from schema defaults, then overlay the existing agent's data so@@ -53,10 +59,13 @@ export function EditAgentDialog({ open, onOpenChange, agent, onUpdated }: Props)},context_config: { ...base.context_config, ...(d.context_config ?? {}) },react_config: { ...base.react_config, ...(d.react_config ?? {}) },+ invite_config: { ...base.invite_config, ...(d.invite_config ?? {}) },});+ setErrorMsg('');}, [open, schema, agent]);const handleChange = (section: AgentSection, key: string, value: SchemaFormValue) => {+ setErrorMsg('');setValues((prev) =>prev ? { ...prev, [section]: { ...prev[section], [key]: value } } : prev,);@@ -66,16 +75,24 @@ export function EditAgentDialog({ open, onOpenChange, agent, onUpdated }: Props)if (!values) return;const name = (values.identity.name as string | undefined)?.trim();if (!name) return;+ setErrorMsg('');setSubmitting(true);try {- await update(agent.id, {- name,- system_prompt: values.identity.system_prompt as string | undefined,- context_config: values.context_config as unknown as ContextConfig,- react_config: values.react_config as unknown as ReActConfig,- });+ await update(+ agent.id,+ {+ name,+ system_prompt: values.identity.system_prompt as string | undefined,+ context_config: values.context_config as unknown as ContextConfig,+ react_config: values.react_config as unknown as ReActConfig,+ invite_config: values.invite_config as unknown as InviteConfig,+ },+ { silent: true },+ );onOpenChange(false);onUpdated?.();+ } catch (e) {+ setErrorMsg(formatApiErrorForAlert(e));} finally {setSubmitting(false);}@@ -99,6 +116,14 @@ export function EditAgentDialog({ open, onOpenChange, agent, onUpdated }: Props)<p className="text-muted-foreground text-sm">{t('common.loading')}</p>)}</div>+ {errorMsg && (+ <Alert variant="destructive">+ <CircleAlert />+ <AlertDescription className="whitespace-pre-wrap">+ {errorMsg}+ </AlertDescription>+ </Alert>+ )}<DialogFooter><Buttonvariant="ghost"diff --git a/examples/web_ui/frontend/src/components/form/AgentFormFields.tsx b/examples/web_ui/frontend/src/components/form/AgentFormFields.tsxindex a3769f349..1099c6759 100644--- a/examples/web_ui/frontend/src/components/form/AgentFormFields.tsx+++ b/examples/web_ui/frontend/src/components/form/AgentFormFields.tsx@@ -1,6 +1,6 @@import { useTranslation } from 'react-i18next';-import type { AgentSchemaResponse } from '@/api';+import type { AgentSchemaV2Response, JSONSchema, JSONSchemaProperty } from '@/api';import { SchemaForm, type SchemaFormValue } from '@/components/form/SchemaForm';import {FieldDescription,@@ -10,33 +10,89 @@ import {FieldSet,} from '@/components/ui/field';-export type AgentSection = 'identity' | 'context_config' | 'react_config';+export type AgentSection = 'identity' | 'context_config' | 'react_config' | 'invite_config';export type AgentFormValues = {[K in AgentSection]: Record<string, SchemaFormValue>;};interface Props {- schema: AgentSchemaResponse;+ schema: AgentSchemaV2Response;values: AgentFormValues;onChange: (section: AgentSection, key: string, value: SchemaFormValue) => void;}-const SECTIONS: { key: AgentSection; i18n: string }[] = [- { key: 'identity', i18n: 'identity' },+/**+ * Section derivation from the flat `AgentData` schema. Ordered — controls+ * the visual order of the fieldsets. "identity" carries every top-level+ * property that is NOT one of the nested-object sections below, so any+ * newly added scalar / boolean / textarea field on `AgentData` shows up+ * in the identity fieldset automatically.+ */+const NESTED_SECTIONS: Array<{ key: Exclude<AgentSection, 'identity'>; i18n: string }> = [{ key: 'context_config', i18n: 'context-config' },{ key: 'react_config', i18n: 'react-config' },+ { key: 'invite_config', i18n: 'invite-config' },];+const IDENTITY_I18N = 'identity';+const toKebab = (s: string) => s.replace(/_/g, '-');+/** Split the flat `AgentData` schema into the sections the form renders+ * (currently four: `identity` + one per `NESTED_SECTIONS` entry). */+function sliceSchema(root: JSONSchema): Record<AgentSection, JSONSchema> {+ const props = root.properties ?? {};+ const nestedKeys = new Set(NESTED_SECTIONS.map((s) => s.key));++ const identityProps: Record<string, JSONSchemaProperty> = {};+ for (const [k, prop] of Object.entries(props)) {+ if (nestedKeys.has(k as Exclude<AgentSection, 'identity'>)) continue;+ identityProps[k] = prop;+ }++ const identity: JSONSchema = {+ type: 'object',+ title: 'Identity',+ properties: identityProps,+ required: (root.required ?? []).filter(+ (r) => !nestedKeys.has(r as Exclude<AgentSection, 'identity'>),+ ),+ };++ return {+ identity,+ context_config: (props.context_config as JSONSchema) ?? {+ type: 'object',+ properties: {},+ },+ react_config: (props.react_config as JSONSchema) ?? {+ type: 'object',+ properties: {},+ },+ invite_config: (props.invite_config as JSONSchema) ?? {+ type: 'object',+ properties: {},+ },+ };+}+export function AgentFormFields({ schema, values, onChange }: Props) {const { t } = useTranslation();+ const sections = sliceSchema(schema.schema);++ const rows: Array<{ key: AgentSection; i18n: string; sectionSchema: JSONSchema }> = [+ { key: 'identity', i18n: IDENTITY_I18N, sectionSchema: sections.identity },+ ...NESTED_SECTIONS.map((s) => ({+ key: s.key as AgentSection,+ i18n: s.i18n,+ sectionSchema: sections[s.key],+ })),+ ];return (<FieldGroup>- {SECTIONS.map(({ key: sectionKey, i18n: sectionI18n }, idx) => {- const sectionSchema = schema[sectionKey];+ {rows.map(({ key: sectionKey, i18n: sectionI18n, sectionSchema }, idx) => {const legend = t(`agent-form.${sectionI18n}.legend`, {defaultValue: sectionSchema.title ?? sectionKey,});@@ -74,10 +130,9 @@ export function AgentFormFields({ schema, values, onChange }: Props) {}/** Build a fresh `AgentFormValues` populated from each section schema's defaults. */-export function defaultAgentFormValues(schema: AgentSchemaResponse): AgentFormValues {- const fromDefaults = (- section: AgentSchemaResponse[AgentSection],- ): Record<string, SchemaFormValue> => {+export function defaultAgentFormValues(schema: AgentSchemaV2Response): AgentFormValues {+ const sections = sliceSchema(schema.schema);+ const fromDefaults = (section: JSONSchema): Record<string, SchemaFormValue> => {const out: Record<string, SchemaFormValue> = {};for (const [k, prop] of Object.entries(section.properties ?? {})) {if (prop.const !== undefined) continue;@@ -86,8 +141,9 @@ export function defaultAgentFormValues(schema: AgentSchemaResponse): AgentFormVareturn out;};return {- identity: fromDefaults(schema.identity),- context_config: fromDefaults(schema.context_config),- react_config: fromDefaults(schema.react_config),+ identity: fromDefaults(sections.identity),+ context_config: fromDefaults(sections.context_config),+ react_config: fromDefaults(sections.react_config),+ invite_config: fromDefaults(sections.invite_config),};}diff --git a/examples/web_ui/frontend/src/hooks/useAgentSchema.ts b/examples/web_ui/frontend/src/hooks/useAgentSchema.tsindex 9e25ca0f2..4a20bb9df 100644--- a/examples/web_ui/frontend/src/hooks/useAgentSchema.ts+++ b/examples/web_ui/frontend/src/hooks/useAgentSchema.ts@@ -1,17 +1,17 @@import { useEffect, useState } from 'react';import { agentApi } from '@/api';-import type { AgentSchemaResponse } from '@/api';+import type { AgentSchemaV2Response } from '@/api';/*** Module-level cache. The agent schema is derived from Pydantic models* on the backend and never changes at runtime, so a single in-flight fetch* is enough for the whole session.*/-let cached: AgentSchemaResponse | null = null;-let inflight: Promise<AgentSchemaResponse> | null = null;+let cached: AgentSchemaV2Response | null = null;+let inflight: Promise<AgentSchemaV2Response> | null = null;-async function loadSchema(): Promise<AgentSchemaResponse> {+async function loadSchema(): Promise<AgentSchemaV2Response> {if (cached) return cached;if (!inflight) {inflight = agentApi.getSchema().then((res) => {@@ -22,9 +22,9 @@ async function loadSchema(): Promise<AgentSchemaResponse> {return inflight;}-/** Fetch (and cache) the JSON Schema fragments for the agent form. */+/** Fetch (and cache) the full `AgentData` JSON Schema for the agent form. */export function useAgentSchema() {- const [schema, setSchema] = useState<AgentSchemaResponse | null>(cached);+ const [schema, setSchema] = useState<AgentSchemaV2Response | null>(cached);const [error, setError] = useState<Error | null>(null);useEffect(() => {diff --git a/examples/web_ui/frontend/src/hooks/useAgents.ts b/examples/web_ui/frontend/src/hooks/useAgents.tsindex 11aae7161..b690cf971 100644--- a/examples/web_ui/frontend/src/hooks/useAgents.ts+++ b/examples/web_ui/frontend/src/hooks/useAgents.ts@@ -31,8 +31,8 @@ export function useAgents() {/** Creates a new agent and refreshes the list. */const create = useCallback(- async (body: CreateAgentRequest) => {- const res = await agentApi.create(body);+ async (body: CreateAgentRequest, options?: { silent?: boolean }) => {+ const res = await agentApi.create(body, options);await refetch();return res;},@@ -41,8 +41,8 @@ export function useAgents() {/** Partially updates an agent and refreshes the list. */const update = useCallback(- async (agentId: string, body: UpdateAgentRequest) => {- const res = await agentApi.update(agentId, body);+ async (agentId: string, body: UpdateAgentRequest, options?: { silent?: boolean }) => {+ const res = await agentApi.update(agentId, body, options);await refetch();return res;},diff --git a/examples/web_ui/frontend/src/i18n/locales/en.json b/examples/web_ui/frontend/src/i18n/locales/en.jsonindex 64144acfc..f9fa2cf26 100644--- a/examples/web_ui/frontend/src/i18n/locales/en.json+++ b/examples/web_ui/frontend/src/i18n/locales/en.json@@ -140,6 +140,15 @@"description": "Controls the reasoning and action loop behaviour.","max-iters": { "label": "Max iterations" },"stop-on-reject": { "label": "Stop on reject" }+ },+ "invite-config": {+ "legend": "Invite Config",+ "description": "Controls whether other agents can borrow this one via AgentInvite.",+ "invitable": { "label": "Invitable" },+ "invite-description": {+ "label": "Invite description",+ "placeholder": "Briefly describe this agent's expertise; required when invitable is on."+ }}},"dialog-agent-edit": {diff --git a/examples/web_ui/frontend/src/i18n/locales/zh.json b/examples/web_ui/frontend/src/i18n/locales/zh.jsonindex a858578a9..8a77fe958 100644--- a/examples/web_ui/frontend/src/i18n/locales/zh.json+++ b/examples/web_ui/frontend/src/i18n/locales/zh.json@@ -140,6 +140,15 @@"description": "控制推理和行动循环的行为。","max-iters": { "label": "最大迭代次数" },"stop-on-reject": { "label": "拒绝时停止" }+ },+ "invite-config": {+ "legend": "邀请配置",+ "description": "控制此 Agent 是否可被其他 Agent 通过 AgentInvite 邀请。",+ "invitable": { "label": "允许被邀请" },+ "invite-description": {+ "label": "邀请说明",+ "placeholder": "简要描述此 Agent 的专长;允许被邀请时必填。"+ }}},"dialog-agent-edit": {diff --git a/examples/web_ui/frontend/src/lib/api-error.ts b/examples/web_ui/frontend/src/lib/api-error.tsnew file mode 100644index 000000000..ed2b3e36b--- /dev/null+++ b/examples/web_ui/frontend/src/lib/api-error.ts@@ -0,0 +1,32 @@+import { ApiError } from '@/api/client';++/**+ * FastAPI 422 responses put a pydantic ``.errors()`` array in ``detail``.+ * `client.ts` stringifies that array, so what we get here is a JSON string+ * like ``[{"type":"value_error","loc":[...],"msg":"..."}]``. Show only the+ * ``msg`` fields — that's the human-readable part; ``type`` / ``loc`` /+ * ``input`` are noise for end users.+ */+export function formatApiErrorForAlert(err: unknown): string {+ if (err instanceof ApiError) {+ const { detail } = err;+ try {+ const parsed = JSON.parse(detail) as unknown;+ if (Array.isArray(parsed)) {+ const msgs = parsed+ .map((item) =>+ item && typeof item === 'object' && 'msg' in item+ ? String((item as { msg: unknown }).msg)+ : null,+ )+ .filter((m): m is string => !!m);+ if (msgs.length > 0) return msgs.join('\n');+ }+ } catch {+ // not JSON — fall through to raw detail+ }+ return detail;+ }+ if (err instanceof Error) return err.message;+ return String(err);+}diff --git a/src/agentscope/app/_router/_agent.py b/src/agentscope/app/_router/_agent.pyindex 6f3135c4d..a3574199f 100644--- a/src/agentscope/app/_router/_agent.py+++ b/src/agentscope/app/_router/_agent.py@@ -3,11 +3,14 @@from datetime import datetimefrom fastapi import APIRouter, Depends, HTTPException, status+from pydantic import ValidationErrorfrom ...agent import ContextConfig, ReActConfig+from ..._utils._common import _flatten_json_schemafrom ..deps import get_current_user_id, get_session_service, get_storagefrom ._schema import (AgentSchemaResponse,+ AgentSchemaV2Response,ListAgentsResponse,CreateAgentRequest,CreateAgentResponse,@@ -26,15 +29,22 @@ agent_router = APIRouter(@agent_router.get("/schema",response_model=AgentSchemaResponse,- summary="Get JSON Schema fragments for the agent form",+ deprecated=True,+ summary="[Deprecated] Legacy sectioned schema — use /schema/v2",)async def get_agent_schema() -> AgentSchemaResponse:- """Return the JSON Schema fragments used by the frontend to render- the agent create / edit forms.+ """Return the legacy sectioned JSON Schema fragments.- The frontend uses three sections — identity, context config, and- react config — so we return them as separate self-contained schemas- rather than a single ``AgentData`` schema with ``$ref``s.+ .. deprecated::+ Superseded by :func:`get_agent_schema_v2`, which returns the+ full :class:`AgentData` schema in a single ``schema`` field.+ Kept for backwards compatibility with existing API consumers.+ New consumers should call ``GET /agent/schema/v2``.++ The frontend previously used three sections — identity, context+ config, and react config — so we return them as separate+ self-contained schemas rather than a single :class:`AgentData`+ schema with ``$ref`` s.Returns:`AgentSchemaResponse`:@@ -72,6 +82,50 @@ async def get_agent_schema() -> AgentSchemaResponse:)+@agent_router.get(+ "/schema/v2",+ response_model=AgentSchemaV2Response,+ summary="Full AgentData JSON Schema for the agent form",+)+async def get_agent_schema_v2() -> AgentSchemaV2Response:+ """Return the full :class:`AgentData` JSON Schema.++ Superset of the legacy sectioned endpoint. The response body is a+ single ``schema`` field carrying the whole Pydantic-generated+ schema of :class:`AgentData`, with two curated exclusions handled+ at the model layer (so no post-processing is needed here):++ - ``id``: server-assigned, marked :class:`SkipJsonSchema` on+ :attr:`AgentData.id`.+ - ``context_config.summary_schema``: internal structured-output+ spec for the compression model, dropped below since it is not+ user-editable and there is no equivalent hook on the Pydantic+ side.++ ``$ref`` inlining is delegated to+ :func:`~agentscope._utils._common._flatten_json_schema` so the+ frontend can render every property from the response body alone.++ The frontend derives its section grouping (identity / context /+ react / invite) directly from this schema — top-level scalar+ properties are the "identity" section, and top-level nested-object+ properties each become their own section. Adding a new+ user-editable field to :class:`AgentData` is thus enough to have it+ appear in the create / edit form without a router change.++ Returns:+ `AgentSchemaV2Response`:+ ``schema`` = the full :class:`AgentData` JSON Schema.+ """+ schema = _flatten_json_schema(AgentData.model_json_schema())+ # ``summary_schema`` is Pydantic's structured-output spec fed to the+ # compression model — internal, not user-editable. No pydantic-side+ # hook covers this deep nested field, so drop it after inlining.+ context_config = schema.get("properties", {}).get("context_config", {})+ context_config.get("properties", {}).pop("summary_schema", None)+ return AgentSchemaV2Response(schema=schema)++@agent_router.get("/",response_model=ListAgentsResponse,@@ -121,16 +175,29 @@ async def create_agent(Returns:`CreateAgentResponse`:The server-assigned agent identifier.++ Raises:+ `HTTPException`: 422 if the request body passes+ :class:`CreateAgentRequest` validation but the resulting+ :class:`AgentData` fails its cross-field invariants (e.g.+ ``invite_config.invitable=True`` without a non-empty+ ``invite_description``). Symmetrical with+ :func:`update_agent`."""- record = AgentRecord(- user_id=user_id,- data=AgentData(+ try:+ data = AgentData(name=body.name,system_prompt=body.system_prompt,context_config=body.context_config,react_config=body.react_config,- ),- )+ invite_config=body.invite_config,+ )+ except ValidationError as exc:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail=exc.errors(),+ ) from exc+ record = AgentRecord(user_id=user_id, data=data)agent_id = await storage.upsert_agent(user_id, record)return CreateAgentResponse(agent_id=agent_id)@@ -173,7 +240,20 @@ async def update_agent()updates = body.model_dump(exclude_none=True)- updated_data = existing.data.model_copy(update=updates)+ # ``model_copy(update=...)`` skips validators; re-run+ # ``AgentData.model_validate`` on the merged shape so the+ # ``invite_config`` sub-model's ``invitable ⇒ non-empty description``+ # invariant enforced by ``@model_validator(mode="after")`` produces+ # an HTTP 422 instead of a stored-but-invalid record.+ try:+ updated_data = AgentData.model_validate(+ {**existing.data.model_dump(), **updates},+ )+ except ValidationError as exc:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail=exc.errors(),+ ) from excupdated_agent = existing.model_copy(update={"data": updated_data, "updated_at": datetime.now()},)diff --git a/src/agentscope/app/_router/_schema/__init__.py b/src/agentscope/app/_router/_schema/__init__.pyindex 8c25125a6..810ccd6bf 100644--- a/src/agentscope/app/_router/_schema/__init__.py+++ b/src/agentscope/app/_router/_schema/__init__.py@@ -13,6 +13,7 @@ from ._schedule import ()from ._agent import (AgentSchemaResponse,+ AgentSchemaV2Response,ListAgentsResponse,CreateAgentRequest,CreateAgentResponse,@@ -56,6 +57,7 @@ from ._session import (__all__ = [# Agent"AgentSchemaResponse",+ "AgentSchemaV2Response","ListAgentsResponse","CreateAgentRequest","CreateAgentResponse",diff --git a/src/agentscope/app/_router/_schema/_agent.py b/src/agentscope/app/_router/_schema/_agent.pyindex 4dc396cef..1949d6364 100644--- a/src/agentscope/app/_router/_schema/_agent.py+++ b/src/agentscope/app/_router/_schema/_agent.py@@ -1,9 +1,11 @@# -*- coding: utf-8 -*-"""Request / response schemas for the agent router."""+import warnings+from pydantic import BaseModel, Fieldfrom ....agent import ContextConfig, ReActConfig-from ...storage import AgentRecord+from ...storage import AgentRecord, InviteConfigclass CreateAgentRequest(BaseModel):@@ -22,6 +24,14 @@ class CreateAgentRequest(BaseModel):default_factory=ReActConfig,description="ReAct loop configuration.",)+ invite_config: InviteConfig = Field(+ default_factory=InviteConfig,+ description=(+ "Invite-pool settings for this agent. See "+ ":class:`InviteConfig` — enforces the "+ "``invitable ⇒ non-empty description`` invariant."+ ),+ )class CreateAgentResponse(BaseModel):@@ -49,6 +59,14 @@ class UpdateAgentRequest(BaseModel):default=None,description="New ReAct loop configuration.",)+ invite_config: InviteConfig | None = Field(+ default=None,+ description=(+ "New invite-pool settings. Pass the full :class:`InviteConfig` "+ "object to update; omit to leave both invitable-related "+ "fields unchanged."+ ),+ )class ListAgentsResponse(BaseModel):@@ -59,13 +77,19 @@ class ListAgentsResponse(BaseModel):class AgentSchemaResponse(BaseModel):- """JSON Schema fragments used by the frontend to render the agent- create / edit forms.-- Each fragment is a self-contained JSON Schema object so the frontend- doesn't need to follow ``$ref`` links across fragments. The frontend- pairs each property with an i18n key derived from its path, so labels- and descriptions remain localizable independently of the backend.+ """**Deprecated.** JSON Schema fragments used by the frontend to+ render the agent create / edit forms.++ Superseded by :class:`AgentSchemaV2Response`, which returns the full+ :class:`AgentData` JSON Schema in a single ``schema`` field so newly+ added agent fields (like the ``invite_config`` sub-model) reach the+ frontend automatically without the router having to know about them.++ The frontend previously split :class:`AgentData` into three+ hand-picked sections (``identity``, ``context_config``,+ ``react_config``) here, which required a router edit every time a+ new user-editable field landed on :class:`AgentData`. Kept for+ backwards compatibility with pre-v2 API consumers."""identity: dict = Field(@@ -80,3 +104,35 @@ class AgentSchemaResponse(BaseModel):react_config: dict = Field(description="Schema for ``ReActConfig``.",)+++# The ``schema`` field name below is intentional — the wire contract for+# ``GET /agent/schema/v2`` is ``{"schema": ...}`` so the response is+# self-documenting. Pydantic v2's :meth:`BaseModel.schema` is a+# deprecated legacy classmethod (superseded by ``model_json_schema``);+# a like-named instance field triggers a cosmetic "shadows an attribute+# in parent BaseModel" warning that is irrelevant here because we never+# call the legacy classmethod. Suppress it locally instead of adding an+# alias that would obscure the wire contract at every call site.+with warnings.catch_warnings():+ warnings.filterwarnings(+ "ignore",+ message=r'Field name "schema" in "AgentSchemaV2Response"',+ )++ class AgentSchemaV2Response(BaseModel):+ """Response for ``GET /agent/schema/v2``.++ Wraps the full :class:`AgentData` JSON Schema in a single+ ``schema`` field so the frontend can render every user-editable+ property without the router having to enumerate them.+ """++ schema: dict = Field(+ description=(+ "Full :class:`AgentData` JSON Schema. All user-editable "+ "fields appear as top-level entries in ``properties`` — "+ "the frontend derives its section grouping from this "+ "single schema."+ ),+ )diff --git a/src/agentscope/app/_router/_session.py b/src/agentscope/app/_router/_session.pyindex b9e60352a..cfa15ec36 100644--- a/src/agentscope/app/_router/_session.py+++ b/src/agentscope/app/_router/_session.py@@ -37,6 +37,7 @@ from ..storage import (TeamRecord,)from ...message import ToolCallState+from ..storage._utils import _ensure_team_membersfrom ...event import CustomEvent@@ -71,13 +72,16 @@ async def _build_team_detail()members: list[TeamMemberView] = []- for member_id in team.data.member_ids:- agent = await storage.get_agent(user_id, member_id)+ for member in await _ensure_team_members(storage, user_id, team):+ agent = await storage.get_agent(member.owner_id, member.agent_id)if agent is None:continue- sessions = await storage.list_sessions(user_id, member_id)- session_id = sessions[0].id if sessions else None- members.append(TeamMemberView(agent=agent, session_id=session_id))+ # Use the member's team-scoped session id directly; an invited+ # agent has multiple sessions and only ``member.session_id``+ # belongs to this team.+ members.append(+ TeamMemberView(agent=agent, session_id=member.session_id),+ )return TeamDetailResponse(team=team,diff --git a/src/agentscope/app/_service/_projectors/_subagent_hitl.py b/src/agentscope/app/_service/_projectors/_subagent_hitl.pyindex cc5e03b86..fccacfd47 100644--- a/src/agentscope/app/_service/_projectors/_subagent_hitl.py+++ b/src/agentscope/app/_service/_projectors/_subagent_hitl.py@@ -112,17 +112,22 @@ class SubagentHitlProjector:session_record (`SessionRecord`):The currently-running session's record.agent_record (`AgentRecord`):- The currently-running agent's record. Only- ``source == "team"`` agents forward.+ The currently-running agent's record. Whether this+ session forwards is decided by ``session_record.team_id``+ (and the leader check below), NOT by+ ``agent_record.source`` — an ``AgentInvite`` borrowed+ session runs on a ``source='user'`` record but is still+ a team worker, so its HITL must project onto the leader.event (`AgentEvent`):The event just published to this session's channel.projection (`SessionProjection`):Shared primitive used to write the durable entry and thelive notification."""- # Fast path: only team-member sessions forward anything, and- # only for the event kinds we care about.- if agent_record.source != "team" or not session_record.team_id:+ # Fast path: only sessions that participate in a team forward+ # anything, and only for the event kinds we care about. The+ # leader/worker distinction is made below via ``team.session_id``.+ if not session_record.team_id:returnif not isinstance(event,diff --git a/src/agentscope/app/_service/_session.py b/src/agentscope/app/_service/_session.pyindex 1044c3b2a..d364a48d5 100644--- a/src/agentscope/app/_service/_session.py+++ b/src/agentscope/app/_service/_session.py@@ -49,6 +49,7 @@ import asynciofrom ..message_bus import MessageBus, MessageBusKeysfrom ..storage import StorageBase+from ..storage._utils import _ensure_team_membersfrom ._session_projection import SessionProjectionfrom ._projectors import SubagentHitlProjectorfrom ..._logging import logger@@ -230,11 +231,27 @@ class SessionService:async def delete_team(self, user_id: str, team_id: str) -> bool:"""Cancel, delete and bus-purge a team.- Delegates worker dissolution to :meth:`delete_agent` (one call- per ``member_id``) so the per-session cancel + bus purge runs- for each worker. The leader's own session is **not** deleted —- teams dissolve, leaders survive (and have their ``team_id``- cleared by ``storage.delete_team``).+ With :meth:`StorageBase.delete_team` now role-aware, the service+ method's sole responsibility is to run per-member+ ``cancel + bus purge`` (storage cannot touch the bus) via the+ role-appropriate ``delete_agent`` / ``delete_session`` call, and+ then delegate to storage for the remaining leader-detach ++ team-record cleanup.++ Branches per member role:++ - ``role == "created"``: the member was spawned by ``AgentCreate``+ and lives only as long as the team — delegate to+ :meth:`delete_agent` so its record, session, and bus state+ are fully removed.+ - ``role == "invited"``: the member is a pre-existing user-owned+ agent borrowed via ``AgentInvite``. Only the borrowed+ team-scoped session is removed; the underlying+ :class:`AgentRecord` and its other sessions survive.++ The leader's own session is **not** deleted — teams dissolve,+ leaders survive (and have their ``team_id`` cleared by+ ``storage.delete_team``).Args:user_id (`str`): The owner user id.@@ -250,13 +267,21 @@ class SessionService:# residue, but the return value will be False.return await self._storage.delete_team(user_id, team_id)- for member_id in team.data.member_ids:- await self.delete_agent(user_id, member_id)+ members = await _ensure_team_members(self._storage, user_id, team)+ for member in members:+ if member.role == "created":+ await self.delete_agent(member.owner_id, member.agent_id)+ else: # invited+ await self.delete_session(+ member.owner_id,+ member.agent_id,+ member.session_id,+ )- # storage.delete_team will iterate member_ids again to delete- # each worker agent — those calls are now no-ops because the- # agents are already gone, leaving only the leader-detach and- # team-record cleanup work.+ # storage.delete_team walks the same members again to run its+ # own role-aware cascade — those calls are now idempotent+ # no-ops (records already removed above). What remains for+ # storage is leader-detach + team-record + index cleanup.return await self._storage.delete_team(user_id, team_id)async def delete_agent(self, user_id: str, agent_id: str) -> bool:@@ -268,6 +293,20 @@ class SessionService:storage to clean the remaining agent-scoped state (the agentrecord, the agent index entry, and any team back-references).+ **Reverse-cascade for invited members.** When an agent is+ borrowed into a team (``AgentInvite``), it has a session with+ ``team_id`` set that it does not lead. Deleting the agent while+ such a borrowed session exists would leave a stale+ :class:`TeamMember` entry behind, and — worse — trigger the+ storage cascade in that team's next ``delete_team``, which+ iterates the team roster (via ``_ensure_team_members``) and+ would try to re-delete this already-gone agent. So before+ deleting each session, this method extracts the corresponding+ entry from the borrowing team's roster (matched by+ ``session_id``, not ``agent_id``, so a leader session that+ happens to share the agent id — impossible today but cheap to+ be careful about — is not touched).+Args:user_id (`str`): The owner user id.agent_id (`str`): The agent to delete.@@ -277,6 +316,31 @@ class SessionService:``True`` if the agent record existed and was deleted."""for session in await self._storage.list_sessions(user_id, agent_id):+ if session.team_id is not None:+ team = await self._storage.get_team(+ user_id,+ session.team_id,+ )+ # Only worker sessions require the extraction — a leader+ # session dropping its team is handled by+ # ``storage.delete_session -> delete_team`` further down.+ if team is not None and team.session_id != session.id:+ members = await _ensure_team_members(+ self._storage,+ user_id,+ team,+ )+ filtered = [+ m for m in members if m.session_id != session.id+ ]+ if len(filtered) != len(members):+ team.data.members = filtered+ team.data.member_ids = [+ mid+ for mid in team.data.member_ids+ if mid != agent_id+ ]+ await self._storage.upsert_team(user_id, team)await self.delete_session(user_id, agent_id, session.id)for schedule in await self._storage.list_schedules(user_id):@@ -336,6 +400,13 @@ class SessionService:Mirrors :meth:`StorageBase.delete_session`'s own team-leadercascade so the bus side can purge the same sessions.+ Uses :func:`ensure_team_members` — which carries the exact+ session id per member (including invited members whose agent+ can have multiple sessions of its own, only one of which+ belongs to this team). Falling back to+ ``list_sessions(agent_id)[0]`` here would pick the wrong+ session for invited agents.+Args:user_id (`str`): The owner user id.agent_id (`str`):@@ -359,14 +430,8 @@ class SessionService:team = await self._storage.get_team(user_id, session.team_id)if team is None or team.session_id != session_id:return []- sids: list[str] = []- for member_id in team.data.member_ids:- worker_sessions = await self._storage.list_sessions(- user_id,- member_id,- )- sids.extend(s.id for s in worker_sessions)- return sids+ members = await _ensure_team_members(self._storage, user_id, team)+ return [m.session_id for m in members]async def _cancel_runs(self, session_ids: list[str]) -> None:"""Cancel every in-flight run in ``session_ids`` concurrently.diff --git a/src/agentscope/app/_service/_toolkit.py b/src/agentscope/app/_service/_toolkit.pyindex fa86e68f8..a518be9e4 100644--- a/src/agentscope/app/_service/_toolkit.py+++ b/src/agentscope/app/_service/_toolkit.py@@ -6,11 +6,17 @@ workspace builtins, MCPs, skills, planning tools (Task*), background-taskcontrol (ToolStop), schedule control (Schedule*), team participationtools, and caller-supplied extras — into one :class:`Toolkit`."""-from typing import Any+from typing import Any, Literalfrom .._manager import BackgroundTaskManager, SchedulerManagerfrom ..message_bus import MessageBus-from .._tool import AgentCreate, TeamCreate, TeamDelete, TeamSay+from .._tool import (+ AgentCreate,+ AgentInvite,+ TeamCreate,+ TeamDelete,+ TeamSay,+)from .._types import AgentToolFactory, SubAgentTemplatefrom ..storage import AgentRecord, SessionRecord, StorageBasefrom ...middleware import MiddlewareBase@@ -53,10 +59,15 @@ async def get_toolkit(:meth:`SchedulerManager.list_tools`). Only attached when thesession has a model configured (Schedule tools need a model tofire new chats with).- 5. Team tools — selected inline by ``agent_record.source``:- worker (``"team"``) gets only ``TeamSay``; everyone else gets- the full leader-side toolset- (``TeamCreate / AgentCreate / TeamSay / TeamDelete``)+ 5. Team tools — variant based on the *session's* team role, not+ the agent's ``source``. This matters because a borrowed+ ("invited") agent's session must see worker-only tools even+ though its underlying :class:`AgentRecord` still has+ ``source='user'``. A session that is a worker in some team+ gets only ``TeamSay``. A session that is not in any team OR+ that is its team's leader gets the full leader-side toolset+ (``TeamCreate / AgentCreate / TeamSay / TeamDelete``, plus+ ``AgentInvite`` when the user has at least one invitable agent).6. Caller-supplied extras (``extra_factory``)Plus the workspace's skills and MCPs, which become the toolkit's@@ -87,11 +98,16 @@ async def get_toolkit(user_id (`str`):Caller user id.agent_record (`AgentRecord`):- Pre-loaded agent record (loaded once by the caller). Its- ``source`` field determines which team tools are attached.+ Pre-loaded agent record (loaded once by the caller). Still+ used for its identity (``id``) and for pipeline consumers+ downstream; the ``source`` field is no longer the team-tool+ gate — see :attr:`session_record.team_id` below.session_record (`SessionRecord`):Pre-loaded session record (loaded once by the caller).- Used for the schedule-tool model configuration.+ Used for the schedule-tool model configuration and — via+ :attr:`SessionRecord.team_id` and the resolved team's+ leader session id — for deciding which team tools to+ attach.extra_factory (`AgentToolFactory | None`, optional):Async factory invoked once per assembly to produceuser/session-specific extra tools.@@ -146,12 +162,14 @@ time or interval"),)- # Team tools — variant based on ``agent_record.source``. A worker- # only gets TeamSay (to report back); a user-owned agent always- # gets the full leader-side toolset. Each tool checks its own- # preconditions (am I in a team? am I the leader?) at call time- # against fresh storage, which is why the full set can be attached- # unconditionally without needing a stale snapshot of team_id.+ # Team tools — variant based on the session's team role rather+ # than the agent's ``source`` field. A borrowed ("invited") agent+ # runs with ``source='user'`` on its underlying AgentRecord but+ # its session must behave as a worker; the session-level check+ # captures both created and invited workers uniformly. Sessions+ # not in a team fall through to the leader-side toolset — each+ # leader tool has a runtime precondition check anyway (am I in a+ # team? am I the leader?), so attaching the full set is safe.team_tool_kwargs: dict[str, Any] = {"storage": storage,"message_bus": message_bus,@@ -159,7 +177,14 @@ time or interval""session_id": session_record.id,"agent_id": agent_record.id,}- if agent_record.source == "team":+ team_role: Literal["leader", "worker"] | None = None+ if session_record.team_id is not None:+ team = await storage.get_team(user_id, session_record.team_id)+ if team is not None:+ team_role = (+ "leader" if team.session_id == session_record.id else "worker"+ )+ if team_role == "worker":tools.append(TeamSay(**team_tool_kwargs, role="worker"))else:tools += [@@ -171,6 +196,26 @@ time or interval"TeamSay(**team_tool_kwargs, role="leader"),TeamDelete(**team_tool_kwargs),]+ # Conditionally attach AgentInvite. Skipping construction when+ # the user has no invitable agents keeps the input_schema enum+ # non-empty (an empty enum would break tool-schema validators+ # and confuse the LLM into calling a tool with no valid+ # targets). Team-tool base is safe to call for either team or+ # non-team sessions — AgentInvite rechecks the leader+ # precondition at call time.+ invitable_pool = [+ a+ for a in await storage.list_agents(user_id)+ if a.data.invite_config.invitable+ and (a.data.invite_config.invite_description or "").strip()+ ]+ if invitable_pool:+ tools.append(+ AgentInvite(+ **team_tool_kwargs,+ invitable_pool=invitable_pool,+ ),+ )# Caller-supplied extras.if extra_factory is not None:diff --git a/src/agentscope/app/_tool/__init__.py b/src/agentscope/app/_tool/__init__.pyindex a90dc0156..1585fd3d9 100644--- a/src/agentscope/app/_tool/__init__.py+++ b/src/agentscope/app/_tool/__init__.py@@ -10,28 +10,35 @@ Task series, …) in two ways:assembly time, and call storage / bus directly in their``__call__`` — except ``TeamDelete``, which delegates to:class:`SessionService` for cascade deletion.-2. **Visibility depends only on the agent's source field** —- ``source='user'`` agents always see the full leader-side toolset- (``TeamCreate / AgentCreate / TeamSay / TeamDelete``) regardless of- whether they currently lead a team. Each tool checks the storage- state at ``__call__`` time and fails clearly if its precondition- is not met. ``source='team'`` workers only see ``TeamSay``.+2. **Visibility depends on the session's team role, not the agent's+ source field** — a session that is not in any team OR that is its+ team's leader gets the full leader-side toolset (``TeamCreate /+ AgentCreate / TeamSay / TeamDelete``, plus ``AgentInvite`` when the+ user has any invitable agents). A session that is a worker in some+ team gets only ``TeamSay``. This session-level distinction is what+ lets a borrowed ("invited") agent's session see worker-only tools+ even though the underlying ``AgentRecord`` still has+ ``source='user'``. Each tool re-reads the current session + team+ from storage at ``__call__`` time and fails clearly if its+ precondition is not met.The benefit is that a single chat run can ``TeamCreate`` and then``AgentCreate`` immediately afterward — there is no toolkitrefresh point because the toolkit never changed; only theunderlying storage state did, which the next tool reads fresh.-Selection of the right subset by ``agent.source`` happens inline in-:func:`get_toolkit`; there is no separate "team tool factory" helper.+Selection of the right subset happens inline in :func:`get_toolkit`;+there is no separate "team tool factory" helper."""from ._agent_create import AgentCreate, DEFAULT_SUB_AGENT_TEMPLATE+from ._agent_invite import AgentInvitefrom ._team_create import TeamCreatefrom ._team_delete import TeamDeletefrom ._team_say import TeamSay__all__ = ["AgentCreate",+ "AgentInvite","DEFAULT_SUB_AGENT_TEMPLATE","TeamCreate","TeamDelete",diff --git a/src/agentscope/app/_tool/_agent_create.py b/src/agentscope/app/_tool/_agent_create.pyindex 93caf7eec..144416b1b 100644--- a/src/agentscope/app/_tool/_agent_create.py+++ b/src/agentscope/app/_tool/_agent_create.py@@ -12,7 +12,8 @@ from ._team_tool_base import _TeamToolBasefrom .._types import SubAgentTemplatefrom ..message_bus import MessageBusKeysfrom .._bus_ops import enqueue_run_trigger-from ..storage import AgentData, AgentRecord, SessionConfig+from ..storage import AgentData, AgentRecord, SessionConfig, TeamMember+from ..storage._utils import _ensure_team_membersfrom ...message import HintBlock, TextBlock, ToolResultStatefrom ...permission import PermissionContextfrom ...state import AgentState@@ -375,6 +376,24 @@ optional):# ``name`` (not agent_id), so duplicates would be ambiguous# and unaddressable. The leader's name participates too —# workers must not collide with it.+ #+ # Also reject ``@`` in the name: invited members display as+ # ``"<name>@<agent_id[:8]>"`` in TeamSay, and letting a+ # created member sneak an ``@`` into its name would make+ # the two routing forms visually collide.+ if "@" in name:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ f"AgentCreate: member name {name!r} cannot "+ f"contain the character '@'."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )+leader_agent_record = await self._storage.get_agent(self._user_id,leader_session.agent_id,@@ -382,10 +401,15 @@ optional):existing_names: set[str] = set()if leader_agent_record is not None:existing_names.add(leader_agent_record.data.name)- for member_id in team.data.member_ids:+ members = await _ensure_team_members(+ self._storage,+ self._user_id,+ team,+ )+ for member in members:member_record = await self._storage.get_agent(- self._user_id,- member_id,+ member.owner_id,+ member.agent_id,)if member_record is not None:existing_names.add(member_record.data.name)@@ -480,11 +504,26 @@ optional):team.id,)- # 3. Append worker to team.member_ids.+ # 3. Append worker to the team roster. Write both the+ # legacy ``member_ids`` (for backwards-compatible+ # readers) and the new ``members`` entry with+ # ``role="created"`` — the two must stay in sync so+ # ``ensure_team_members`` and any legacy reader agree+ # on membership. ``members`` above was materialised via+ # the same helper, so it includes any prior migration.team.data.member_ids = [*team.data.member_ids,worker_agent.id,]+ team.data.members = [+ *members,+ TeamMember(+ owner_id=self._user_id,+ agent_id=worker_agent.id,+ session_id=worker_session.id,+ role="created",+ ),+ ]await self._storage.upsert_team(self._user_id, team)# 4. Deliver the initial task to the worker's inbox + wakeup.diff --git a/src/agentscope/app/_tool/_agent_invite.py b/src/agentscope/app/_tool/_agent_invite.pynew file mode 100644index 000000000..bdb6d4267--- /dev/null+++ b/src/agentscope/app/_tool/_agent_invite.py@@ -0,0 +1,550 @@+# -*- coding: utf-8 -*-+"""The AgentInvite tool — borrows an existing agent into the leader's team.++Unlike :class:`AgentCreate`, which spawns a brand-new worker+(``source='team'``) from a :class:`SubAgentTemplate`, this tool+**borrows** a pre-existing user-owned agent by minting a fresh+team-scoped :class:`SessionRecord` on top of the *existing*+:class:`AgentRecord`. The borrowed agent keeps its system prompt,+context/react configs, workspace, MCP, skills, and model choice; only+a new session is created so it can hold a parallel conversation for+the team.++When the team is dissolved or the leader is deleted, only the borrowed+session is cleaned up — the underlying :class:`AgentRecord` survives+so the user can still use the agent stand-alone.+"""+from __future__ import annotations++import copy+import json+from typing import TYPE_CHECKING++from pydantic import Field++from ._constants import HANDLE_LEN+from ._team_tool_base import _TeamToolBase+from ..message_bus import MessageBusKeys+from .._bus_ops import enqueue_run_trigger+from ..storage import SessionConfig, TeamMember+from ..storage._utils import _ensure_team_members+from ...message import HintBlock, TextBlock, ToolResultState+from ...state import AgentState+from ...tool import ToolChunk, ParamsBase+from ..._utils._common import _generate_id++if TYPE_CHECKING:+ from ..message_bus import MessageBus+ from ..storage import AgentRecord, StorageBase+++def _display_handle(agent_id: str) -> str:+ """Return the derived routing handle for ``agent_id``.++ Kept as a tiny helper (rather than inlining ``agent_id[:HANDLE_LEN]``+ at every call site) so a future change to how a handle is derived+ (widening the prefix, hashing, etc.) has exactly one place to touch.+ The length itself lives in :mod:`_constants` so ``TeamSay``'s+ parser agrees byte-for-byte with what this producer emits.+ """+ return agent_id[:HANDLE_LEN]+++def _display_name(agent_name: str, agent_id: str) -> str:+ """Format the leader-facing display / routing string.++ Example: ``"Monday@9f3c1a20"``. Used by both :class:`AgentInvite`+ (as the ``target`` enum values) and :func:`TeamSay` (as the+ directory keys for invited members).+ """+ return f"{agent_name}@{_display_handle(agent_id)}"+++class _AgentInviteParams(ParamsBase):+ """Parameters for :class:`AgentInvite`.++ ``target`` and ``prompt`` are the only inputs — the borrowed+ agent's name, system prompt, and configuration all come from its+ existing :class:`AgentRecord`, so there is nothing else for the+ leader LLM to override.+ """++ target: str = Field(+ description=(+ "The invitable agent to borrow, formatted "+ '``"<name>@<handle>"`` (e.g. ``"Monday@9f3c1a20"``). Choose '+ "from the enum values — each was populated from the "+ "user's currently-invitable agents at the moment the tool "+ "list was assembled."+ ),+ )+ prompt: str = Field(+ description=(+ "The first task delivered to the invited agent as a user "+ "message. It begins executing immediately upon joining — "+ "do NOT tell it to wait for further instructions. Include "+ "context, constraints, deliverables, and deadlines the "+ "agent needs to work autonomously."+ ),+ )+++_DESCRIPTION_HEADER = """Borrow an existing user-owned agent into the \+team you lead.++<If ``AgentCreate`` is not available in your toolset, ignore all \+references to it below.>++## Difference From ``AgentCreate``+- ``AgentCreate`` spins up a brand-new agent that **shares your \+workspace**, so you and it can collaborate on files inside the same \+working directory. ``AgentInvite`` borrows a pre-existing agent that has \+its **own workspace** — depending on how the user has configured it, the \+two workspaces MAY or MAY NOT expose the same filesystem, so paths you \+hand over cannot be assumed to resolve on the invited agent's side.+- The invited agent already has a name; you cannot rename it.++## When to Use This Tool+- A user-owned agent already exists whose stated purpose matches a role \+you need — reuse it instead of spawning a fresh worker with \+``AgentCreate``.+- You want to notify or delegate to an existing agent that specialises \+in a specific domain.++## When NOT to Use This Tool+- No suitable invitable agent exists — use ``AgentCreate`` instead.+- You need to customise the member's system prompt or role for this \+team specifically — invited members' configs are frozen; use \+``AgentCreate`` if you need per-team customisation.+- You are not currently leading a team. Call ``TeamCreate`` first.++## Important+- Do NOT assume the invited agent shares your filesystem. Prefer \+self-contained messages; do not embed working-directory or file paths \+unless you have first verified the two sides can see them.+- If (and only if) the task genuinely requires jointly operating on the \+same large file or complex project directory, first use ``TeamSay`` to \+check whether the invited agent can actually see the same files (e.g. \+by asking it to list or stat a specific path). Skip this handshake for \+tasks where only message content matters.+- ``TeamSay`` is the primary communication channel between you and the \+invited agent.+- ``TeamDelete`` does NOT delete the invited agent — only the \+team-scoped session is cleaned up. If you invite the same agent into \+multiple teams over time, it may retain long-term memory or files from \+earlier collaborations with you.++## Available invitable agents"""+++class AgentInvite(_TeamToolBase):+ """Borrow one of the user's invitable agents into the current team.++ The tool is only attached to the leader's toolkit when the calling+ user has at least one agent with ``invitable=True`` and a non-empty+ ``invite_description`` — see the toolkit assembly logic in+ :func:`get_toolkit`. The invitable pool is captured as a **snapshot**+ at attachment time so the tool's ``input_schema`` can enumerate+ concrete targets; ``__call__`` re-fetches the target's record and+ re-checks invitability before minting the session, so a race+ between snapshot and call (e.g. the user just turned off the toggle)+ is caught cleanly.+ """++ name: str = "AgentInvite"+ # No leader state needed — the borrowed session starts from a+ # fresh PermissionContext(); nothing carries over from the leader.+ is_state_injected: bool = False++ description: str+ input_schema: dict++ def __init__(+ self,+ storage: "StorageBase",+ message_bus: "MessageBus",+ user_id: str,+ session_id: str,+ agent_id: str,+ invitable_pool: list["AgentRecord"],+ ) -> None:+ """Bind request-scoped identifiers plus the invitable pool snapshot.++ Args:+ storage (`StorageBase`):+ Application storage backend.+ message_bus (`MessageBus`):+ Application message bus for inter-session delivery.+ user_id (`str`):+ The owner user id of the calling agent.+ session_id (`str`):+ The current session id of the calling agent.+ agent_id (`str`):+ The id of the agent invoking the tool.+ invitable_pool (`list[AgentRecord]`):+ Snapshot of the user's currently-invitable agents,+ resolved at toolkit assembly time. Non-empty — the+ caller is responsible for skipping construction when+ there is nothing to invite.+ """+ super().__init__(storage, message_bus, user_id, session_id, agent_id)++ self._pool_by_id: dict[str, "AgentRecord"] = {+ a.id: a for a in invitable_pool+ }++ # Build enum + a human-readable per-target rundown for the LLM.+ enum_values = [+ _display_name(a.data.name, a.id) for a in invitable_pool+ ]+ target_lines = [+ f"- ``{_display_name(a.data.name, a.id)!r}`` — "+ f"{a.data.invite_config.invite_description}"+ for a in invitable_pool+ ]+ self.description = (+ _DESCRIPTION_HEADER + "\n" + "\n".join(target_lines) + "\n"+ )++ schema = copy.deepcopy(_AgentInviteParams.model_json_schema())+ schema["properties"]["target"]["enum"] = enum_values+ self.input_schema = schema++ async def __call__(+ self,+ target: str,+ prompt: str,+ ) -> ToolChunk:+ """Mint a team-scoped session on top of an existing agent record.++ Preconditions (all rechecked at call time against fresh storage+ reads):+ - Caller's session is in a team AND is that team's leader.+ - ``target`` is a well-formed ``"<name>@<handle>"`` string whose+ handle prefix-matches an agent id in the current invitable+ pool.+ - The matched agent is still ``invitable=True`` with a+ non-empty ``invite_description`` (guards against a+ toggle-off race between attachment and invocation).+ - The team does not already have this agent as a member (one+ borrow per agent per team).+ - The invited agent has at least one existing session to+ inherit ``workspace_id`` / ``chat_model_config`` from — a+ brand-new never-opened agent record is not invitable in+ practice because it has no runtime state to reuse.++ Args:+ target (`str`):+ The ``"<name>@<handle>"`` display string chosen from+ the enum.+ prompt (`str`):+ First task delivered as a user message to the invited+ agent.++ Returns:+ `ToolChunk`:+ A success message containing the invited agent's+ display name, or an error chunk on failure.+ """+ try:+ invited, resolve_err = _resolve_target(+ self._pool_by_id,+ target,+ )+ if resolve_err is not None:+ return _error(resolve_err)+ assert invited is not None # narrows for mypy++ session = await self._storage.get_session(+ self._user_id,+ self._agent_id,+ self._session_id,+ )+ if session is None or session.team_id is None:+ return _error(+ "AgentInvite: this session is not in any team — "+ "call TeamCreate first.",+ )+ team = await self._storage.get_team(+ self._user_id,+ session.team_id,+ )+ if team is None:+ return _error(+ f"AgentInvite: team {session.team_id} no longer "+ f"exists.",+ )+ if team.session_id != self._session_id:+ return _error(+ "AgentInvite: only the team leader can invite "+ "members; this session is a worker.",+ )++ # Re-fetch fresh — the snapshot could be stale if the user+ # just toggled the invite off.+ fresh = await self._storage.get_agent(+ self._user_id,+ invited.id,+ )+ if (+ fresh is None+ or not fresh.data.invite_config.invitable+ or not (+ fresh.data.invite_config.invite_description or ""+ ).strip()+ ):+ return _error(+ f"AgentInvite: agent {invited.data.name!r} is no "+ f"longer invitable.",+ )+ invited = fresh++ # Duplicate-borrow guard — one team, one borrow per agent.+ existing_members = await _ensure_team_members(+ self._storage,+ self._user_id,+ team,+ )+ if any(m.agent_id == invited.id for m in existing_members):+ return _error(+ f"AgentInvite: agent {invited.data.name!r} is "+ f"already a member of team "+ f"{team.data.name!r}.",+ )++ # Leader session — needed for chat-model / workspace fallback+ # when the invited agent has no existing session, and for the+ # sender-name in the initial team-message hint.+ leader_session = await self._storage.get_session(+ self._user_id,+ "",+ team.session_id,+ )+ if leader_session is None:+ return _error(+ f"AgentInvite: leader session {team.session_id} "+ f"for team {team.id} is missing — team is in an "+ f"inconsistent state.",+ )+ leader_agent = await self._storage.get_agent(+ self._user_id,+ leader_session.agent_id,+ )+ leader_name = (+ leader_agent.data.name+ if leader_agent is not None+ else leader_session.agent_id+ )++ # Prefer the invited agent's own primary session for+ # workspace + chat-model reuse: it already has any MCP /+ # skills / cache set up. Fall back to a freshly-generated+ # workspace id + the leader's chat model when the agent has+ # never been opened — the underlying workspace is created+ # lazily by the workspace manager on first chat, so a bare+ # id is enough.+ invited_sessions = await self._storage.list_sessions(+ self._user_id,+ invited.id,+ )+ if invited_sessions:+ primary = invited_sessions[0]+ borrowed_workspace_id = primary.config.workspace_id+ borrowed_chat_model = (+ primary.config.chat_model_config+ or leader_session.config.chat_model_config+ )+ borrowed_fallback_model = (+ primary.config.fallback_chat_model_config+ or leader_session.config.fallback_chat_model_config+ )+ else:+ borrowed_workspace_id = _generate_id()+ borrowed_chat_model = leader_session.config.chat_model_config+ borrowed_fallback_model = (+ leader_session.config.fallback_chat_model_config+ )++ # Permission context is NOT inherited from the leader.+ # PermissionContext.working_directories and allow/deny/ask+ # rules are anchored to the leader's workspace, which the+ # invited agent may not share (it has its own workspace_id).+ # Merging leader dirs / rules would advertise paths the+ # invited agent cannot reach and pull in user confirmations+ # granted against a different filesystem. Nor do we inherit+ # from the invited agent's own primary session — the+ # team-scoped conversation is a separate context; prior+ # "user approved X" state should not silently cross over.+ # HITL prompts in this team will re-confirm any sensitive+ # tool call.+ worker_state = AgentState(+ # permission_context defaults to a fresh+ # ``PermissionContext()``; tasks_context defaults to+ # empty. Both are the intended reset for the borrowed+ # session — the invited agent's main-session state+ # stays with its own session.+ )++ invited_display = _display_name(+ invited.data.name,+ invited.id,+ )+ invited_handle = _display_handle(invited.id)+ borrowed = await self._storage.upsert_session(+ user_id=self._user_id,+ agent_id=invited.id,+ config=SessionConfig(+ workspace_id=borrowed_workspace_id,+ name=f"team:{team.id}/invited:{invited_handle}",+ chat_model_config=borrowed_chat_model,+ fallback_chat_model_config=borrowed_fallback_model,+ ),+ state=worker_state,+ )+ await self._storage.set_session_team_id(+ self._user_id,+ borrowed.id,+ team.id,+ )++ team.data.members = [+ *existing_members,+ TeamMember(+ owner_id=self._user_id,+ agent_id=invited.id,+ session_id=borrowed.id,+ role="invited",+ ),+ ]+ await self._storage.upsert_team(self._user_id, team)++ hint = HintBlock(+ hint=(+ "<system-reminder>You're now invited into a team named "+ f"'{team.data.name}' led by an agent named "+ f"'{leader_name}' in this session. All team members "+ f"can **ONLY** communicate through the `TeamSay` tool. "+ f"Once you finished the given tasks, or want to "+ f"communicate with the leader or team members, "+ f"use `TeamSay`.</system-reminder>\n"+ f'<team-message from="{leader_name}">\n'+ f"{prompt}\n"+ f"</team-message>"+ ),+ source=json.dumps(+ {+ "label": "team_message",+ "sublabel": leader_name,+ },+ ensure_ascii=False,+ ),+ )+ await self._message_bus.queue_push(+ MessageBusKeys.inbox(borrowed.id),+ hint.model_dump(mode="json"),+ )+ await enqueue_run_trigger(+ self._message_bus,+ user_id=self._user_id,+ session_id=borrowed.id,+ agent_id=invited.id,+ )++ return ToolChunk(+ content=[+ TextBlock(+ text=(+ f"Invited {invited_display!r} into team "+ f"{team.data.name!r}."+ ),+ ),+ ],+ )+ except Exception as e: # pylint: disable=broad-except+ return ToolChunk(+ content=[TextBlock(text=f"AgentInvite failed: {e}")],+ state=ToolResultState.ERROR,+ )+++def _resolve_target(+ pool_by_id: dict[str, "AgentRecord"],+ target: str,+) -> tuple["AgentRecord | None", str | None]:+ """Parse a ``"<name>@<handle>"`` string and look up the pool entry.++ Matches on **both** the name part and the handle so that two+ invitable agents sharing an 8-char UUID4 prefix are still+ disambiguated by the LLM-supplied name. Falls back to a+ handle-only lookup when exactly one pool entry matches the handle,+ which keeps the common single-agent case working. If two or more+ entries share the handle AND the name does not narrow the match,+ an ``ambiguous`` error is returned so the caller can retry.++ Returns ``(record, None)`` on success or ``(None, error_message)``+ on any parse or resolution failure.+ """+ if "@" not in target:+ return None, (+ f"AgentInvite: malformed target {target!r} — expected "+ f'"<name>@<handle>", got no ``@`` separator.'+ )+ name_part, handle = target.rsplit("@", 1)+ name_part = name_part.strip()+ handle = handle.strip()+ if not handle:+ return None, (+ f"AgentInvite: malformed target {target!r} — empty handle "+ f"after ``@``."+ )+ handle_matches = [+ record+ for agent_id, record in pool_by_id.items()+ if _display_handle(agent_id) == handle+ ]+ # Preferred: unique (name, handle) match. Guards against the rare+ # 8-char-prefix collision on distinct agents with distinct names.+ named_matches = [r for r in handle_matches if r.data.name == name_part]+ if len(named_matches) == 1:+ return named_matches[0], None+ if len(named_matches) > 1:+ # Same name AND same handle prefix on multiple pool entries —+ # the display strings are indistinguishable, so no client+ # input could disambiguate. Surface the ids so the caller can+ # see what collided.+ ids = sorted(r.id for r in named_matches)+ return None, (+ f"AgentInvite: target {target!r} is ambiguous — multiple "+ f"invitable agents share this display string: {ids}."+ )+ # Fallback: no name match, but exactly one handle match — accept it.+ if len(handle_matches) == 1:+ return handle_matches[0], None+ if len(handle_matches) > 1:+ colliding = sorted(+ _display_name(r.data.name, r.id) for r in handle_matches+ )+ return None, (+ f"AgentInvite: handle {handle!r} matches multiple invitable "+ f"agents: {colliding}. Retry with the exact display string."+ )+ available = sorted(+ _display_name(a.data.name, a.id) for a in pool_by_id.values()+ )+ return None, (+ f"AgentInvite: no invitable agent matches target {target!r}. "+ f"Available: {available}."+ )+++def _error(text: str) -> ToolChunk:+ """Build an ``ERROR``-state :class:`ToolChunk` with a text block.++ Not moved to :mod:`_team_tool_base` because that shape is specific+ to :class:`AgentInvite`'s branchy validation path — the other team+ tools currently inline the same pattern.+ """+ return ToolChunk(+ content=[TextBlock(text=text)],+ state=ToolResultState.ERROR,+ )diff --git a/src/agentscope/app/_tool/_constants.py b/src/agentscope/app/_tool/_constants.pynew file mode 100644index 000000000..65a493868--- /dev/null+++ b/src/agentscope/app/_tool/_constants.py@@ -0,0 +1,19 @@+# -*- coding: utf-8 -*-+"""Shared constants for the framework-builtin team tools.++Centralised here (rather than duplicated per-module) so contracts that+must agree across tools have exactly one source of truth. Adding a new+tool that touches the same invariant should import from here, not+redeclare the value.+"""++HANDLE_LEN: int = 8+# Length of the ``agent_id`` prefix used to disambiguate invited+# members in the ``"<name>@<handle>"`` display string.+#+# Must be the same value at every producer (``AgentInvite``, which+# builds the enum and the display string) and every consumer+# (``TeamSay``, which parses the display string back into a routing+# key). Widening this in the future is a coordinated change — leaders+# that already routed via the old length would target the wrong member+# otherwise.diff --git a/src/agentscope/app/_tool/_team_say.py b/src/agentscope/app/_tool/_team_say.pyindex d020ae742..eaf7d5aa0 100644--- a/src/agentscope/app/_tool/_team_say.py+++ b/src/agentscope/app/_tool/_team_say.py@@ -4,9 +4,11 @@ from typing import Anyfrom pydantic import Field+from ._constants import HANDLE_LENfrom ._team_tool_base import _TeamToolBasefrom ..message_bus import MessageBusKeysfrom .._bus_ops import enqueue_run_trigger+from ..storage._utils import _ensure_team_membersfrom ...message import HintBlock, TextBlock, ToolResultStatefrom ...tool import ToolChunk, ParamsBase@@ -200,12 +202,19 @@ class TeamSay(_TeamToolBase):state=ToolResultState.ERROR,)- # Build a (name -> (session_id, agent_id)) directory in one- # pass over the team. Routing is by **name** rather than- # agent_id so workers can address the leader (they receive- # the leader's name in the <team-message from="..."> hint- # but never see the leader's agent_id). Uniqueness of names- # within the team is enforced at AgentCreate time.+ # Build a (name -> (session_id, agent_id)) directory. The+ # leader is always in the directory under its plain agent+ # name; workers come from the team's members roster via+ # ``ensure_team_members`` (which migrates legacy+ # ``member_ids``-only records on first read). Invited+ # members display as ``"<name>@<agent_id[:8]>"`` so a+ # borrowed agent whose name collides with an already-created+ # member (or the leader) remains addressable.+ #+ # Uniqueness of the resulting display strings within a team+ # is preserved by the AgentCreate name check (which rejects+ # ``@``) and by AgentInvite's one-borrow-per-agent-per-team+ # rule.leader_agent = await self._storage.get_agent(self._user_id,leader_session.agent_id,@@ -218,22 +227,26 @@ class TeamSay(_TeamToolBase):directory: dict[str, tuple[str, str]] = {leader_name: (leader_session.id, leader_session.agent_id),}- for worker_agent_id in team.data.member_ids:- worker_agent = await self._storage.get_agent(- self._user_id,- worker_agent_id,+ members = await _ensure_team_members(+ self._storage,+ self._user_id,+ team,+ )+ for member in members:+ member_agent = await self._storage.get_agent(+ member.owner_id,+ member.agent_id,)- if worker_agent is None:+ if member_agent is None:continue- sessions = await self._storage.list_sessions(- self._user_id,- worker_agent_id,- )- if sessions:- directory[worker_agent.data.name] = (- sessions[0].id,- worker_agent_id,+ if member.role == "invited":+ display = (+ f"{member_agent.data.name}"+ f"@{member.agent_id[:HANDLE_LEN]}")+ else:+ display = member_agent.data.name+ directory[display] = (member.session_id, member.agent_id)own_session_ids = {sid for sid, _aid in directory.values()}if self._session_id not in own_session_ids:diff --git a/src/agentscope/app/middleware/_state_change_middleware.py b/src/agentscope/app/middleware/_state_change_middleware.pyindex 372244e11..7e5669559 100644--- a/src/agentscope/app/middleware/_state_change_middleware.py+++ b/src/agentscope/app/middleware/_state_change_middleware.py@@ -13,10 +13,11 @@ Two kinds of change are detected:while handling a user confirmation). Pushes``CustomEvent(name="state_updated", value={...})``.- **Team change** — the tool that just ran is one of the team tools- (``TeamCreate``, ``AgentCreate``, ``TeamDelete``). These tools- directly mutate storage (``TeamRecord``, ``SessionRecord.team_id``),- so we don't need to check storage; the fact that the tool ran is- the trigger. Pushes ``CustomEvent(name="team_updated", value={})``.+ (``TeamCreate``, ``AgentCreate``, ``AgentInvite``, ``TeamDelete``).+ These tools directly mutate storage (``TeamRecord``,+ ``SessionRecord.team_id``), so we don't need to check storage; the+ fact that the tool ran is the trigger. Pushes+ ``CustomEvent(name="team_updated", value={})``.Both events are published directly to the bus (via``session_publish_event``) instead of being yielded through the agent's@@ -32,7 +33,9 @@ from .._bus_ops import publish_session_eventfrom ...event import CustomEventfrom ...middleware import MiddlewareBase-_TEAM_TOOL_NAMES = frozenset({"TeamCreate", "AgentCreate", "TeamDelete"})+_TEAM_TOOL_NAMES = frozenset(+ {"TeamCreate", "AgentCreate", "AgentInvite", "TeamDelete"},+)# Tool names whose execution implies a team membership change.diff --git a/src/agentscope/app/storage/__init__.py b/src/agentscope/app/storage/__init__.pyindex 0c0f4ab14..661203f8e 100644--- a/src/agentscope/app/storage/__init__.py+++ b/src/agentscope/app/storage/__init__.py@@ -24,12 +24,15 @@ from ._model import (TeamData,TeamRecord,UserRecord,+ TeamMember,+ InviteConfig,)__all__ = ["StorageBase","RedisStorage",# The ORM models+ "InviteConfig","AgentData","AgentRecord","CredentialRecord",@@ -44,6 +47,7 @@ __all__ = ["ChatModelConfig","TTSModelConfig","EmbeddingModelConfig",+ "TeamMember","TeamData","TeamRecord","UserRecord",diff --git a/src/agentscope/app/storage/_base.py b/src/agentscope/app/storage/_base.pyindex 7731bf7ba..6c5b944aa 100644--- a/src/agentscope/app/storage/_base.py+++ b/src/agentscope/app/storage/_base.py@@ -505,16 +505,28 @@ class StorageBase(ABC):@abstractmethodasync def delete_team(self, user_id: str, team_id: str) -> bool:- """Delete a team record and cascade-delete all of its workers.-- The cascade mirrors SQL's ``ON DELETE CASCADE`` semantics:-- 1. For each ``member_id`` in :attr:`TeamData.member_ids`, call- :meth:`delete_agent` (which cascades that worker's session).+ """Delete a team record and cascade-clean its members by role.++ The cascade is role-aware — the two team-membership modes+ (created vs invited, see :class:`TeamMember`) must be handled+ differently:++ 1. For each :class:`TeamMember` in the team's roster (resolved+ via the ``ensure_team_members`` helper so legacy+ ``member_ids``-only records are migrated on first read):++ - ``role == "created"`` — call :meth:`delete_agent`+ (which cascades that worker's session). The agent record+ is fully removed because it was spawned solely for this+ team.+ - ``role == "invited"`` — call :meth:`delete_session` for+ the borrowed team-scoped session only. The invited+ agent's :class:`AgentRecord` and any other sessions it+ owns survive the team's dissolution.2. Clear ``team_id`` on the leader session referenced by- :attr:`TeamRecord.session_id` (``ON DELETE SET NULL`` for the- leader's back-reference to the team). Idempotent if the- session has already been deleted.+ :attr:`TeamRecord.session_id` (``ON DELETE SET NULL`` for+ the leader's back-reference). Idempotent if the session has+ already been deleted.3. Delete the :class:`TeamRecord` key and the per-user teamindex entry.diff --git a/src/agentscope/app/storage/_model/__init__.py b/src/agentscope/app/storage/_model/__init__.pyindex 3cbc86a2d..14f25814a 100644--- a/src/agentscope/app/storage/_model/__init__.py+++ b/src/agentscope/app/storage/_model/__init__.py@@ -1,7 +1,7 @@# -*- coding: utf-8 -*-"""Storage models for persisted resources."""-from ._agent import AgentRecord, AgentData+from ._agent import AgentRecord, AgentData, InviteConfigfrom ._credential import CredentialRecordfrom ._knowledge_base import KnowledgeBaseRecordfrom ._knowledge_document import (@@ -19,7 +19,7 @@ from ._session import (EmbeddingModelConfig,SessionSource,)-from ._team import TeamRecord, TeamData+from ._team import TeamRecord, TeamData, TeamMemberfrom ._user import UserRecord__all__ = [@@ -42,5 +42,7 @@ __all__ = ["EmbeddingModelConfig","TeamData","TeamRecord",+ "TeamMember","UserRecord",+ "InviteConfig",]diff --git a/src/agentscope/app/storage/_model/_agent.py b/src/agentscope/app/storage/_model/_agent.pyindex 6b1ed3bf9..412c046d0 100644--- a/src/agentscope/app/storage/_model/_agent.py+++ b/src/agentscope/app/storage/_model/_agent.py@@ -1,22 +1,82 @@# -*- coding: utf-8 -*-"""The agent storage class."""-from typing import Literal+from typing import Literal, Self-from pydantic import Field, BaseModel+from pydantic import Field, BaseModel, model_validator+from pydantic.json_schema import SkipJsonSchemafrom ...._utils._common import _generate_idfrom ._base import _RecordBasefrom ....agent import ContextConfig, ReActConfig+class InviteConfig(BaseModel):+ """User-editable invite settings for :class:`AgentData`.++ Kept in its own sub-model so the frontend's schema-driven form —+ which renders any nested-object property as its own fieldset —+ picks it up as a dedicated section without a per-field allowlist.+ Also keeps the cross-field ``invitable ⇒ non-empty description``+ invariant local to this model.+ """++ invitable: bool = Field(+ default=False,+ description=(+ "Whether this agent may be borrowed into another agent's team "+ "via the ``AgentInvite`` tool. Independent from "+ ":attr:`invite_description` so the user can preserve an "+ "authored blurb while temporarily disabling the toggle. "+ "``invitable=True`` requires a non-empty "+ ":attr:`invite_description` (enforced by validator)."+ ),+ title="Invitable",+ )++ invite_description: str | None = Field(+ default=None,+ description=(+ "Free-text blurb shown to a leader LLM in the ``AgentInvite`` "+ "tool description — used by the leader to decide whether to "+ "borrow this agent. Persisted across toggle off/on so the "+ "user's authored draft is not lost when :attr:`invitable` "+ "is temporarily disabled."+ ),+ title="Invite Description",+ json_schema_extra={"format": "textarea"},+ )++ @model_validator(mode="after")+ def _check_invitable_has_description(self) -> Self:+ """Reject ``invitable=True`` without a non-empty description.++ The blurb is what the leader LLM sees when it inspects the+ ``AgentInvite`` tool; without it, the LLM cannot make a sensible+ choice. Rejecting at the model boundary (rather than in the+ service layer) means PATCH / POST return HTTP 422 automatically.+ """+ if self.invitable and not (self.invite_description or "").strip():+ raise ValueError(+ "invite_description must be non-empty when invitable=True",+ )+ return self++class AgentData(BaseModel):"""The agent data model."""- id: str = Field(+ id: SkipJsonSchema[str] = Field(description="Unique agent id",default_factory=_generate_id,)- """The agent id."""+ """The agent id.++ Server-assigned; never edited via the create / update form.+ Annotated with :class:`SkipJsonSchema` so it is dropped from+ ``AgentData.model_json_schema()`` (the frontend renders the form+ off that schema) while still being serialised in normal JSON+ dumps (so persisted records keep the id).+ """name: str = Field(description="The name of the agent.",@@ -42,6 +102,12 @@ class AgentData(BaseModel):title="React Config",)+ invite_config: InviteConfig = Field(+ default_factory=InviteConfig,+ description="The invite config for the agent.",+ title="Invite Config",+ )+class AgentRecord(_RecordBase):"""The agent ORM model."""diff --git a/src/agentscope/app/storage/_model/_team.py b/src/agentscope/app/storage/_model/_team.pyindex af1b39c1e..48fd32ba0 100644--- a/src/agentscope/app/storage/_model/_team.py+++ b/src/agentscope/app/storage/_model/_team.py@@ -1,10 +1,62 @@# -*- coding: utf-8 -*-"""The team storage class."""+from typing import Literal+from pydantic import BaseModel, Fieldfrom ._base import _RecordBase+class TeamMember(BaseModel):+ """An entry in a team's member roster.++ Unlike the legacy :attr:`TeamData.member_ids`, this carries both the+ agent id AND the session id — required because an *invited* member's+ agent (e.g. Monday) can have multiple sessions of its own; the team+ only wants the one it created when the leader called ``AgentInvite``.+ The ``role`` tag then drives cascade behavior (see+ :meth:`SessionService.delete_team`): ``created`` members are fully+ deleted with the team, ``invited`` members only lose the borrowed+ session while their :class:`AgentRecord` survives.+ """++ owner_id: str = Field(+ description=(+ "Owner of the member's agent. Always equals the team owner "+ "in today's user-only invite pool, but is stored explicitly "+ "so a future admin-share layer (agents borrowed across users) "+ "can slot in without a schema migration. Distinct name from "+ ":attr:`TeamRecord.user_id` on purpose — the surrounding "+ "team already carries the team owner in context, so calling "+ "this field ``user_id`` too would be ambiguous."+ ),+ )++ agent_id: str = Field(+ description="The member agent's id.",+ )++ session_id: str = Field(+ description=(+ "The team-scoped session id for this member. For ``created`` "+ "members this is the sole session (1:1 with the agent). For "+ "``invited`` members this is the freshly-minted session that "+ "``AgentInvite`` created — the agent's other sessions are "+ "unrelated to this team."+ ),+ )++ role: Literal["created", "invited"] = Field(+ description=(+ "How this member joined the team. ``created`` — spawned "+ "from a :class:`SubAgentTemplate` via ``AgentCreate``, "+ "deleted with the team. ``invited`` — a pre-existing "+ "user-owned agent borrowed via ``AgentInvite``, retains its "+ ":class:`AgentRecord` when the team is dissolved."+ ),+ )++class TeamData(BaseModel):"""The team data model."""@@ -26,12 +78,26 @@ class TeamData(BaseModel):member_ids: list[str] = Field(default_factory=list,description=(- "Worker agent ids that belong to this team. Each worker has "- "``source='team'`` and exactly one session, so the agent id "- "uniquely identifies the member; the session can be looked up "- "via :meth:`StorageBase.list_sessions`."+ "**Deprecated** — legacy roster of worker agent ids from "+ "before the ``AgentInvite`` era, when every member was "+ "team-spawned (``source='team'``) with a 1:1 agent-session "+ "mapping. New code should read :attr:`members` via the "+ "``ensure_team_members`` helper, which migrates any records "+ "still using this field to the richer schema on first read."),title="Member Ids",+ deprecated=True,+ )++ members: list[TeamMember] = Field(+ default_factory=list,+ description=(+ "Explicit member roster with role + session id per entry. "+ "Read this via the ``ensure_team_members`` helper so legacy "+ "records with only :attr:`member_ids` populated are migrated "+ "transparently."+ ),+ title="Members",)@@ -40,9 +106,10 @@ class TeamRecord(_RecordBase):Team membership is session-level: the leader is identified by its``session_id`` (since a user agent can lead multiple teams across- different sessions). Workers are identified by their agent id in- :attr:`TeamData.member_ids` (since workers have a 1:1 mapping between- agent and session).+ different sessions). Workers are identified by+ :class:`TeamMember` entries in :attr:`TeamData.members`, accessed+ via the ``ensure_team_members`` helper which handles migration from+ the legacy :attr:`TeamData.member_ids` shape."""user_id: strdiff --git a/src/agentscope/app/storage/_redis_storage.py b/src/agentscope/app/storage/_redis_storage.pyindex 57a31e308..57e43bde3 100644--- a/src/agentscope/app/storage/_redis_storage.py+++ b/src/agentscope/app/storage/_redis_storage.py@@ -492,14 +492,17 @@ class RedisStorage(StorageBase):a team — the team).2. **Schedules** — every schedule whose ``data.agent_id`` matchesis deleted via :meth:`delete_schedule`.- 3. **Team back-references (defensive)** — if the agent is a team- worker (``source='team'``) but the caller chose to delete it- directly instead of going through :meth:`delete_team`, scan- the user's teams and remove the agent id from every- :attr:`TeamData.member_ids` list it appears in. The normal- path (``delete_team`` iterates ``member_ids`` and calls- ``delete_agent`` for each) does not need this scan, but it- keeps the team record consistent if a caller bypasses it.+ 3. **Team back-references (defensive)** — if the caller chose to+ delete the agent directly instead of going through+ :meth:`delete_team`, scan the user's teams and remove the+ agent id from both the legacy :attr:`TeamData.member_ids`+ list *and* the current :attr:`TeamData.members` list. The+ normal path (``delete_team`` iterates members and calls+ ``delete_agent`` / ``delete_session`` for each) does not+ need this scan, but it keeps team records consistent if a+ caller bypasses it. Applies to invited members too — a stale+ entry pointing at a removed agent would otherwise poison+ ``TeamSay`` routing.4. **Agent record + index** — finally delete the agent key andremove from the per-user agent index.@@ -525,16 +528,26 @@ class RedisStorage(StorageBase):if schedule.agent_id == agent_id:await self.delete_schedule(user_id, schedule.id)- # Defensive: scrub agent_id from any team's member_ids list.- # The common path (delete_team -> delete_agent) is unaffected- # because the team is being torn down anyway and removed from- # the index in step 4 of delete_team.+ # Defensive: scrub agent_id from any team's member roster.+ # Covers both the legacy ``member_ids`` field and the current+ # ``members`` list (which additionally holds invited entries).+ # The common path (delete_team -> delete_agent / delete_session)+ # is unaffected because the team is being torn down anyway.teams = await self.list_teams(user_id)for team in teams:+ dirty = Falseif agent_id in team.data.member_ids:team.data.member_ids = [mid for mid in team.data.member_ids if mid != agent_id]+ dirty = True+ filtered_members = [+ m for m in team.data.members if m.agent_id != agent_id+ ]+ if len(filtered_members) != len(team.data.members):+ team.data.members = filtered_members+ dirty = True+ if dirty:await self.upsert_team(user_id, team)key = self._key(@@ -1122,14 +1135,26 @@ class RedisStorage(StorageBase):await self._set_with_ttl(key, record.model_dump_json())async def delete_team(self, user_id: str, team_id: str) -> bool:- """Delete a team record and cascade-delete all of its workers.+ """Delete a team record and cascade-clean its members by role.Cascade order (mirrors what SQL's ``ON DELETE CASCADE`` would do- for the same set of foreign keys):+ for the same set of foreign keys, but role-aware to honour the+ ``AgentInvite`` semantics — see :class:`TeamMember`):++ 1. Materialise the member roster via+ :func:`ensure_team_members` (which migrates legacy+ ``member_ids``-only records on first read). For each entry:++ - ``role == "created"`` — the member was spawned by+ ``AgentCreate`` and lives only for this team. Delete it in+ full via :meth:`delete_agent`, which cascades that+ worker's session.+ - ``role == "invited"`` — the member is a pre-existing+ user-owned agent that was borrowed via ``AgentInvite``.+ Only remove the team-scoped session via+ :meth:`delete_session`; the underlying+ :class:`AgentRecord` and its other sessions must survive.- 1. For each ``member_id`` in :attr:`TeamData.member_ids`, call- :meth:`delete_agent`. Each call cascades the worker's single- session via the existing agent-cascade logic.2. Clear ``team_id`` on the leader session (referenced by:attr:`TeamRecord.session_id`) — semantically equivalent to``ON DELETE SET NULL`` for that direction of the relationship.@@ -1153,6 +1178,11 @@ class RedisStorage(StorageBase):``False`` if no record was found at the``(user_id, team_id)`` key."""+ # Local import to avoid a top-level cycle between _utils (which+ # imports TeamMember from _model) and _base (which imports the+ # abstract StorageBase from this module hierarchy).+ from ._utils import _ensure_team_members+team = await self.get_team(user_id, team_id)if team is None:# Make sure the index is also clean if the record vanished@@ -1161,9 +1191,17 @@ class RedisStorage(StorageBase):await self._client.srem(index_key, team_id)return False- # Cascade: delete each worker agent (which cascades its session)- for member_id in team.data.member_ids:- await self.delete_agent(user_id, member_id)+ # Role-aware member cleanup — see docstring above.+ members = await _ensure_team_members(self, user_id, team)+ for member in members:+ if member.role == "created":+ await self.delete_agent(member.owner_id, member.agent_id)+ else: # invited+ await self.delete_session(+ member.owner_id,+ member.agent_id,+ member.session_id,+ )# Clear team_id on the leader session (idempotent)await self.set_session_team_id(user_id, team.session_id, None)diff --git a/src/agentscope/app/storage/_utils.py b/src/agentscope/app/storage/_utils.pyindex 6d08fe6d1..40bf22f63 100644--- a/src/agentscope/app/storage/_utils.py+++ b/src/agentscope/app/storage/_utils.py@@ -1,8 +1,15 @@# -*- coding: utf-8 -*-"""The utils for storage."""+from typing import TYPE_CHECKINGfrom pydantic import BaseModel, SecretStr+from ._model import TeamMember++if TYPE_CHECKING:+ from ._base import StorageBase+ from ._model import TeamRecord+def _dump_with_secrets(model: BaseModel) -> dict:"""Dump the BaseModel instance with SecretStr fields. Used for@@ -27,3 +34,74 @@ def _dump_with_secrets(model: BaseModel) -> dict:result[field_name] = value.get_secret_value()return result+++async def _ensure_team_members(+ storage: "StorageBase",+ user_id: str,+ team: "TeamRecord",+) -> list[TeamMember]:+ """Return the team's members, lazily migrating legacy ``member_ids``.++ Before ``AgentInvite`` existed, ``TeamData`` only stored a flat list+ of worker agent ids in :attr:`~TeamData.member_ids`; each such worker+ was ``source='team'`` with a 1:1 agent-to-session mapping, so the+ session could be recovered on demand via ``list_sessions``. With+ invited members the shape no longer fits: an invited agent has+ multiple sessions of its own, only one of which belongs to the team.++ This helper is the single read path. If :attr:`TeamData.members` is+ already populated it is returned verbatim (idempotent fast path).+ Otherwise, it rebuilds the roster from ``member_ids`` — each legacy+ entry is tagged ``role="created"`` — persists it back via+ :meth:`StorageBase.upsert_team`, and returns the new list. A+ ``member_id`` whose sole session has been deleted out from under+ the team is dropped from the migrated roster (nothing to route to+ anyway).++ Args:+ storage (`StorageBase`):+ Storage backend used for the session lookups and the+ optional writeback.+ user_id (`str`):+ The team owner.+ team (`TeamRecord`):+ The team record to inspect (and mutate in place on migration).++ Returns:+ `list[TeamMember]`:+ The team's current roster.+ """+ if team.data.members:+ return team.data.members++ if not team.data.member_ids:+ return []++ migrated: list[TeamMember] = []+ for agent_id in team.data.member_ids:+ sessions = await storage.list_sessions(user_id, agent_id)+ if not sessions:+ # Session already deleted — nothing sensible to route to.+ continue+ migrated.append(+ TeamMember(+ owner_id=user_id,+ agent_id=agent_id,+ session_id=sessions[0].id,+ role="created",+ ),+ )++ team.data.members = migrated+ # Sync the legacy list to match. Dropping entries with no surviving+ # session from ``members`` without also removing them from+ # ``member_ids`` would leave the two disagreeing, and would cause+ # this migration to re-run on every future read whenever the+ # migrated result is empty (empty ``members`` fails the fast-path+ # truthiness check, so we would fall through here again). Writing+ # ``member_ids`` to match ``migrated`` keeps the record consistent+ # and terminates the migration.+ team.data.member_ids = [m.agent_id for m in migrated]+ await storage.upsert_team(user_id, team)+ return migrateddiff --git a/tests/service_subagent_hitl_projector_test.py b/tests/service_subagent_hitl_projector_test.pyindex e7b751102..267b3b045 100644--- a/tests/service_subagent_hitl_projector_test.py+++ b/tests/service_subagent_hitl_projector_test.py@@ -183,6 +183,25 @@ class TestSubagentHitlProjectorRequire(IsolatedAsyncioTestCase):"require_external_execution",)+ async def test_invited_agent_source_user_still_projects(self) -> None:+ """An ``AgentInvite``-borrowed session runs on a+ ``source='user'`` agent record but is still a team worker — its+ HITL request must project onto the leader like any other+ team-member session."""+ projection = _FakeProjection()+ await _projector().maybe_project(+ "u",+ _session(_WORKER_SID),+ _agent(source="user"), # invited agents keep source='user'+ RequireUserConfirmEvent.model_construct(+ reply_id="r1",+ tool_calls=[],+ ),+ projection,+ )+ card = projection.store[(_LEADER_SID, SubagentHitlProjector.KIND)]+ self.assertIn(_entry_id(), card)+class TestSubagentHitlProjectorClear(IsolatedAsyncioTestCase):"""The result / reply-end → delete + publish path."""@@ -288,10 +307,6 @@ class TestSubagentHitlProjectorNoOp(IsolatedAsyncioTestCase):self.assertEqual(projection.store, {})self.assertEqual(projection.published, [])- async def test_non_team_agent_is_noop(self) -> None:- """A ``source="user"`` agent never projects."""- await self._assert_noop(agent_source="user")-async def test_session_without_team_id_is_noop(self) -> None:"""A session with no ``team_id`` never projects."""await self._assert_noop(team_id=None)diff --git a/tests/service_team_tools_test.py b/tests/service_team_tools_test.pyindex 86b460684..e69a46971 100644--- a/tests/service_team_tools_test.py+++ b/tests/service_team_tools_test.py@@ -24,6 +24,7 @@ from utils import AnyStringfrom agentscope.agent import ContextConfig, ReActConfigfrom agentscope.app._tool import (AgentCreate,+ AgentInvite,DEFAULT_SUB_AGENT_TEMPLATE,TeamCreate,TeamDelete,@@ -1179,3 +1180,482 @@ class TestTeamDelete(_TeamToolsTestBase):"id": AnyString(),},)+++# ----------------------------------------------------------------------+# AgentInvite tests+# ----------------------------------------------------------------------+++class TestAgentDataInvitableValidator(IsolatedAsyncioTestCase):+ """:class:`InviteConfig`'s cross-field validator rejects+ ``invitable=True`` without a non-empty ``invite_description`` at+ model boundary so PATCH / POST return HTTP 422 automatically."""++ async def test_invitable_requires_description(self) -> None:+ """``invitable=True`` with empty description fails validation."""+ from pydantic import ValidationError+ from agentscope.app.storage._model._agent import InviteConfig++ with self.assertRaises(ValidationError):+ AgentData(+ name="x",+ context_config=ContextConfig(),+ react_config=ReActConfig(),+ invite_config=InviteConfig(+ invitable=True,+ invite_description=None,+ ),+ )+ with self.assertRaises(ValidationError):+ AgentData(+ name="x",+ context_config=ContextConfig(),+ react_config=ReActConfig(),+ invite_config=InviteConfig(+ invitable=True,+ invite_description=" ",+ ),+ )++ async def test_invitable_off_keeps_description(self) -> None:+ """Draft description is preserved when ``invitable=False``."""+ from agentscope.app.storage._model._agent import InviteConfig++ data = AgentData(+ name="x",+ context_config=ContextConfig(),+ react_config=ReActConfig(),+ invite_config=InviteConfig(+ invitable=False,+ invite_description="draft",+ ),+ )+ self.assertEqual(data.invite_config.invite_description, "draft")+ self.assertFalse(data.invite_config.invitable)+++class _AgentInviteTestBase(_TeamToolsTestBase):+ """Fixture: leader in a team + one invitable "Monday" agent with+ a primary session so ``AgentInvite`` has something to borrow."""++ async def asyncSetUp(self) -> None:+ await super().asyncSetUp()+ # Leader creates a team.+ await TeamCreate(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ )(name="team", description="d")++ # A pre-existing invitable user-owned agent.+ from agentscope.app.storage._model._agent import InviteConfig++ self.monday_agent = AgentRecord(+ user_id=self.user_id,+ source="user",+ data=AgentData(+ name="Monday",+ system_prompt="I am Monday.",+ context_config=ContextConfig(),+ react_config=ReActConfig(),+ invite_config=InviteConfig(+ invitable=True,+ invite_description="Expert on X.",+ ),+ ),+ )+ await self.storage.upsert_agent(self.user_id, self.monday_agent)+ self.monday_session = await self.storage.upsert_session(+ user_id=self.user_id,+ agent_id=self.monday_agent.id,+ config=SessionConfig(workspace_id="ws-monday"),+ )+++class TestAgentInviteSuccess(_AgentInviteTestBase):+ """Happy-path: leader borrows Monday; borrowed session is minted+ on top of Monday's existing AgentRecord and joins the team as an+ invited member."""++ async def test_invites_existing_agent(self) -> None:+ """A successful ``AgentInvite`` mints a fresh session on the+ invited agent, tags it invited in the team roster, and delivers+ the initial prompt via inbox + wakeup."""+ pool = [self.monday_agent]+ tool = AgentInvite(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ invitable_pool=pool,+ )+ target = f"Monday@{self.monday_agent.id[:8]}"+ chunk = await tool(target=target, prompt="please look up X")+ self.assertDictEqual(+ chunk.model_dump(),+ {+ "content": [+ {"type": "text", "text": AnyString(), "id": AnyString()},+ ],+ "state": "running",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ },+ )++ # No new AgentRecord — the invited agent's id is reused.+ agents = await self.storage.list_agents(self.user_id)+ agent_ids = {a.id for a in agents}+ self.assertIn(self.monday_agent.id, agent_ids)+ # Only leader + Monday exist (no team-spawned worker record).+ self.assertEqual(len(agents), 2)++ # Team now has exactly one invited member pointing at Monday.+ sess = await self.storage.get_session(+ self.user_id,+ self.leader_agent.id,+ self.leader_session.id,+ )+ team = await self.storage.get_team(self.user_id, sess.team_id)+ self.assertEqual(len(team.data.members), 1)+ member = team.data.members[0]+ self.assertEqual(member.role, "invited")+ self.assertEqual(member.agent_id, self.monday_agent.id)+ self.assertEqual(member.owner_id, self.user_id)++ # The borrowed session is distinct from Monday's primary+ # session but inherits its workspace_id.+ self.assertNotEqual(member.session_id, self.monday_session.id)+ borrowed = await self.storage.get_session(+ self.user_id,+ self.monday_agent.id,+ member.session_id,+ )+ self.assertEqual(borrowed.config.workspace_id, "ws-monday")+ self.assertEqual(borrowed.team_id, team.id)++ # Borrowed session starts with a fresh PermissionContext —+ # no leader / Monday state carried over.+ self.assertEqual(+ borrowed.state.permission_context,+ PermissionContext(),+ )++ # Initial prompt was delivered to the borrowed session only.+ inbox = await self.bus.inbox_drain(member.session_id, max_count=10)+ self.assertEqual(len(inbox), 1)+ self.assertIn("please look up X", inbox[0][1]["hint"])+ # Monday's primary session inbox is untouched.+ primary_inbox = await self.bus.inbox_drain(+ self.monday_session.id,+ max_count=10,+ )+ self.assertEqual(primary_inbox, [])+++class TestAgentInviteRejections(_AgentInviteTestBase):+ """``AgentInvite`` rejects the obvious bad inputs / states."""++ _EXPECTED_ERROR_CHUNK = {+ "content": [+ {"type": "text", "text": AnyString(), "id": AnyString()},+ ],+ "state": "error",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ }++ def _tool(self, pool: list | None = None) -> AgentInvite:+ """Build an :class:`AgentInvite` bound to the leader session."""+ return AgentInvite(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ invitable_pool=pool or [self.monday_agent],+ )++ async def test_rejects_malformed_target(self) -> None:+ """A ``target`` without an ``@`` separator is rejected."""+ chunk = await self._tool()(target="just-a-name", prompt="hi")+ self.assertDictEqual(chunk.model_dump(), self._EXPECTED_ERROR_CHUNK)++ async def test_rejects_unknown_handle(self) -> None:+ """A syntactically-valid ``target`` whose handle prefix does+ not match any agent in the pool is rejected."""+ chunk = await self._tool()(+ target="Monday@deadbeef",+ prompt="hi",+ )+ self.assertDictEqual(chunk.model_dump(), self._EXPECTED_ERROR_CHUNK)++ async def test_rejects_when_no_longer_invitable(self) -> None:+ """Snapshot said invitable but fresh read shows the toggle off."""+ # Flip the toggle off in storage while pool snapshot still has it.+ stale = self.monday_agent+ stale.data.invite_config.invitable = False+ stale.data.invite_config.invite_description = None+ await self.storage.upsert_agent(self.user_id, stale)++ chunk = await self._tool(pool=[stale])(+ target=f"Monday@{stale.id[:8]}",+ prompt="hi",+ )+ self.assertDictEqual(chunk.model_dump(), self._EXPECTED_ERROR_CHUNK)++ async def test_rejects_when_not_leader(self) -> None:+ """A session that has no team can't invite."""+ loner = await self.storage.upsert_session(+ user_id=self.user_id,+ agent_id=self.leader_agent.id,+ config=SessionConfig(workspace_id="ws-lone"),+ )+ tool = AgentInvite(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=loner.id,+ agent_id=self.leader_agent.id,+ invitable_pool=[self.monday_agent],+ )+ chunk = await tool(+ target=f"Monday@{self.monday_agent.id[:8]}",+ prompt="hi",+ )+ self.assertDictEqual(chunk.model_dump(), self._EXPECTED_ERROR_CHUNK)++ async def test_rejects_duplicate_borrow(self) -> None:+ """One team, one borrow per agent."""+ tool = self._tool()+ await tool(+ target=f"Monday@{self.monday_agent.id[:8]}",+ prompt="task 1",+ )+ chunk = await tool(+ target=f"Monday@{self.monday_agent.id[:8]}",+ prompt="task 2",+ )+ self.assertDictEqual(chunk.model_dump(), self._EXPECTED_ERROR_CHUNK)+++class TestTeamSayInvitedRouting(_AgentInviteTestBase):+ """``TeamSay`` reaches the borrowed session using the ``@handle``+ display string, and the invited agent can reply back."""++ async def asyncSetUp(self) -> None:+ await super().asyncSetUp()+ # Borrow Monday.+ await AgentInvite(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ invitable_pool=[self.monday_agent],+ )(target=f"Monday@{self.monday_agent.id[:8]}", prompt="join")++ sess = await self.storage.get_session(+ self.user_id,+ self.leader_agent.id,+ self.leader_session.id,+ )+ team = await self.storage.get_team(self.user_id, sess.team_id)+ self.borrowed_sid = next(+ m.session_id for m in team.data.members if m.role == "invited"+ )+ # Drain the initial "join" prompt so later inbox checks see+ # only the subsequent TeamSay delivery.+ await self.bus.inbox_drain(self.borrowed_sid, max_count=10)+ await self.bus.dequeue_wakeups(max_count=10)++ async def test_leader_addresses_invited_by_display(self) -> None:+ """Leader's ``TeamSay(to="Monday@<prefix>")`` reaches the+ borrowed session — not Monday's primary session."""+ display = f"Monday@{self.monday_agent.id[:8]}"+ tool = TeamSay(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ role="leader",+ )+ chunk = await tool(content="hey", to=display)+ self.assertEqual(chunk.state.value, "running")++ borrowed_inbox = await self.bus.inbox_drain(+ self.borrowed_sid,+ max_count=10,+ )+ self.assertEqual(len(borrowed_inbox), 1)+ primary_inbox = await self.bus.inbox_drain(+ self.monday_session.id,+ max_count=10,+ )+ self.assertEqual(primary_inbox, [])+++class TestTeamDeletePreservesInvited(_AgentInviteTestBase):+ """``TeamDelete`` removes the borrowed session but preserves the+ invited agent's :class:`AgentRecord` and other sessions."""++ async def test_borrowed_session_dies_agent_survives(self) -> None:+ """After ``TeamDelete``, the invited agent's ``AgentRecord``+ and primary session survive; only the team-scoped borrowed+ session is removed."""+ await AgentInvite(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ invitable_pool=[self.monday_agent],+ )(target=f"Monday@{self.monday_agent.id[:8]}", prompt="join")++ sess = await self.storage.get_session(+ self.user_id,+ self.leader_agent.id,+ self.leader_session.id,+ )+ team = await self.storage.get_team(self.user_id, sess.team_id)+ borrowed_sid = next(+ m.session_id for m in team.data.members if m.role == "invited"+ )++ await TeamDelete(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ )()++ # Monday's AgentRecord survives.+ monday = await self.storage.get_agent(+ self.user_id,+ self.monday_agent.id,+ )+ self.assertIsNotNone(monday)+ # Monday's primary session survives.+ primary = await self.storage.get_session(+ self.user_id,+ self.monday_agent.id,+ self.monday_session.id,+ )+ self.assertIsNotNone(primary)+ # Borrowed session is gone.+ gone = await self.storage.get_session(+ self.user_id,+ self.monday_agent.id,+ borrowed_sid,+ )+ self.assertIsNone(gone)+++class TestDeleteInvitedAgentReverseCascade(_AgentInviteTestBase):+ """Deleting an invited agent while it is borrowed extracts the+ stale entry from the borrowing team's roster."""++ async def test_reverse_cascade(self) -> None:+ """Deleting an invited agent while it is borrowed also strips+ the stale entry from the borrowing team's ``members`` /+ ``member_ids`` — the leader's later ``TeamSay`` will hit a+ clean "no such member" instead of dangling routing."""+ from agentscope.app._service import SessionService++ await AgentInvite(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ invitable_pool=[self.monday_agent],+ )(target=f"Monday@{self.monday_agent.id[:8]}", prompt="join")++ service = SessionService(+ storage=self.storage,+ message_bus=self.bus,+ )+ await service.delete_agent(self.user_id, self.monday_agent.id)++ sess = await self.storage.get_session(+ self.user_id,+ self.leader_agent.id,+ self.leader_session.id,+ )+ team = await self.storage.get_team(self.user_id, sess.team_id)+ # No stale invited entry remains.+ self.assertEqual(+ [+ m+ for m in team.data.members+ if m.agent_id == self.monday_agent.id+ ],+ [],+ )+ # Legacy member_ids scrubbed too.+ self.assertNotIn(self.monday_agent.id, team.data.member_ids)+++class TestEnsureTeamMembersMigration(_TeamToolsTestBase):+ """Legacy ``TeamRecord`` with only ``member_ids`` populated is+ migrated to the new ``members`` shape on first read via+ ``ensure_team_members``."""++ async def test_legacy_member_ids_migrate_to_created_role(self) -> None:+ """A ``TeamRecord`` whose stored shape only carries the legacy+ ``member_ids`` list is migrated in place on first read via+ ``ensure_team_members``: each id becomes a+ ``TeamMember(role="created", ...)`` entry, and the writeback+ means later reads hit the fast path."""+ from agentscope.app.storage._model import TeamData, TeamRecord+ from agentscope.app.storage._utils import _ensure_team_members++ # Fabricate a legacy worker agent + session (no ``members``+ # entry on the team, just ``member_ids``).+ worker = _make_agent_record(+ self.user_id,+ "legacy-worker",+ source="team",+ )+ await self.storage.upsert_agent(self.user_id, worker)+ worker_sess = await self.storage.upsert_session(+ user_id=self.user_id,+ agent_id=worker.id,+ config=SessionConfig(workspace_id="ws-w"),+ )++ team = TeamRecord(+ user_id=self.user_id,+ session_id=self.leader_session.id,+ data=TeamData(+ name="legacy",+ description="",+ member_ids=[worker.id],+ # members deliberately left empty+ ),+ )+ await self.storage.upsert_team(self.user_id, team)++ members = await _ensure_team_members(+ self.storage,+ self.user_id,+ team,+ )+ self.assertEqual(len(members), 1)+ self.assertEqual(members[0].role, "created")+ self.assertEqual(members[0].agent_id, worker.id)+ self.assertEqual(members[0].session_id, worker_sess.id)+ self.assertEqual(members[0].owner_id, self.user_id)++ # And the writeback happened — subsequent reads take the fast+ # path.+ stored = await self.storage.get_team(self.user_id, team.id)+ self.assertEqual(len(stored.data.members), 1)diff --git a/tests/service_toolkit_test.py b/tests/service_toolkit_test.pyindex 61bcb2d18..15b8b9966 100644--- a/tests/service_toolkit_test.py+++ b/tests/service_toolkit_test.py@@ -31,6 +31,8 @@ from agentscope.app.storage import (ChatModelConfig,SessionConfig,SessionRecord,+ TeamData,+ TeamRecord,)from agentscope.tool import ToolBase@@ -86,6 +88,7 @@ def _make_session(user_id: str,agent_id: str,with_model: bool,+ team_id: str | None = None,) -> SessionRecord:"""Build a minimal :class:`SessionRecord`, optionally with a chatmodel config."""@@ -102,12 +105,47 @@ def _make_session(else None),)- return SessionRecord(user_id=user_id, agent_id=agent_id, config=cfg)+ return SessionRecord(+ user_id=user_id,+ agent_id=agent_id,+ config=cfg,+ team_id=team_id,+ )class _NoOpStorage:"""Storage placeholder. ``get_toolkit`` itself does not call any- storage method — the team tools bind a reference for later use."""+ storage method — the team tools bind a reference for later use.++ Exceptions: since :class:`AgentInvite` landed, ``get_toolkit`` calls+ ``list_agents(user_id)`` at assembly time to build the invitable+ pool. Return an empty list — the toolkit tests care about which+ team tools are attached, not about the pool contents; the non-empty+ case is covered by the ``AgentInvite`` tests in+ ``service_team_tools_test.py``. Additionally, when the session has+ a ``team_id`` set, ``get_toolkit`` calls ``get_team`` to decide+ leader-vs-worker; the ``team_id_map`` constructor arg lets a test+ inject a lookup so the worker branch can be exercised.+ """++ def __init__(+ self,+ team_id_map: dict[str, TeamRecord] | None = None,+ ) -> None:+ """Initialize the storage placeholder."""+ self._teams = team_id_map or {}++ async def list_agents(self, _user_id: str) -> list:+ """List agents for a team."""+ return []++ async def get_team(+ self,+ _user_id: str,+ team_id: str,+ ) -> TeamRecord | None:+ """Return the team record for ``team_id``."""+ return self._teams.get(team_id)def _tool_names(toolkit: Any) -> list[str]:@@ -207,19 +245,33 @@ class TestGetToolkitBaseAssembly(IsolatedAsyncioTestCase):class TestGetToolkitWorkerVariant(IsolatedAsyncioTestCase):- """Worker agent (``source="team"``) only gets ``TeamSay``."""+ """A session whose team role is worker only gets ``TeamSay``.++ The worker/leader distinction is now session-level: a session with+ ``team_id`` set and ``team.session_id != session.id`` is a worker+ regardless of the agent record's ``source`` (an ``AgentInvite``+ borrowed session runs on ``source='user'`` but is still a worker)."""async def test_worker_only_gets_team_say(self) -> None:- """A worker agent (``source="team"``) receives only ``TeamSay``- from the team toolset."""+ """A worker session receives only ``TeamSay`` from the team+ toolset."""agent = _make_agent(source="team", name="worker")session = _make_session(user_id="u",agent_id=agent.id,with_model=True,+ team_id="t1",+ )+ # Team exists and its leader session is NOT this one → worker.+ team = TeamRecord(+ user_id="u",+ session_id="leader-sid",+ data=TeamData(name="team", description="d"),)toolkit = await get_toolkit(- storage=_NoOpStorage(), # type: ignore[arg-type]+ storage=_NoOpStorage(+ team_id_map={"t1": team},+ ), # type: ignore[arg-type]workspace=_FakeWorkspace(), # type: ignore[arg-type]scheduler_manager=SchedulerManager(storage=_NoOpStorage(), # type: ignore[arg-type]@@ -238,7 +290,12 @@ class TestGetToolkitWorkerVariant(IsolatedAsyncioTestCase):names = set(_tool_names(toolkit))# Only TeamSay from the team toolset.self.assertIn("TeamSay", names)- for missing in ("TeamCreate", "AgentCreate", "TeamDelete"):+ for missing in (+ "TeamCreate",+ "AgentCreate",+ "TeamDelete",+ "AgentInvite",+ ):self.assertNotIn(missing, names)