import { useState } from "react"; import { Card, Form, InputNumber, Select, Switch, Input, Button, Tabs, Tag, Modal, Dropdown, } from "@agentscope-ai/design"; import { Plus, Trash2, ChevronDown, ChevronRight, Repeat, Shield, CheckCircle, Target, Rocket, Gauge, Wallet, Lock, GripVertical, Wrench, ListChecks, Copy, Sparkles, Terminal, Clock3, } from "lucide-react"; import { DndContext, PointerSensor, useSensor, useSensors, type DragEndEvent, } from "@dnd-kit/core"; import { arrayMove, SortableContext, useSortable, verticalListSortingStrategy, } from "@dnd-kit/sortable"; import { CSS } from "@dnd-kit/utilities"; import { useTranslation } from "react-i18next"; import type { CustomGateType, CustomLoopModeConfig, GateInstanceConfig, } from "@/api/types"; import styles from "../index.module.less"; import loopStyles from "./AgentLoopCard.module.less"; function IterationSection() { const { t } = useTranslation(); const form = Form.useFormInstance(); const enabled = Form.useWatch(["loop", "iteration", "enabled"], form); return (
{enabled && ( )}
); } function DoomLoopSection() { const { t } = useTranslation(); const form = Form.useFormInstance(); const enabled = Form.useWatch(["loop", "doom_loop", "enabled"], form); const stages = Form.useWatch(["loop", "doom_loop", "stages"], form) || []; const actionOptions = [ { value: "modify_prompt", label: t("agentConfig.doomLoopWarnAction", "Send Reminder"), }, { value: "stop", label: t("agentConfig.doomLoopStopAction", "Pause & Ask for Help"), }, ]; return (
{enabled && ( <>
{t("agentConfig.doomLoopStages", "Intervention Rules")}
{(fields, { add, remove }) => (
{fields.map(({ key, name, ...rest }) => (
} placeholder={t( "agentConfig.loopMode.defaultVerifyCommandPlaceholder", "For example: pytest -q", )} />
); } type GateDefinition = { type: CustomGateType; title: string; titleKey: string; description: string; descriptionKey: string; icon: React.ReactNode; defaults: Record; exclusiveGroup?: string; }; function PerToolLimits({ value = {}, onChange, }: { value?: Record; onChange?: (value: Record) => void; }) { const { t } = useTranslation(); const entries = Object.entries(value); const updateName = (oldName: string, nextName: string) => { const normalized = nextName.trim(); if (!normalized || (normalized !== oldName && normalized in value)) { return false; } if (normalized === oldName) return true; const next = { ...value }; const limit = next[oldName]; delete next[oldName]; next[normalized] = limit; onChange?.(next); return true; }; const updateLimit = (name: string, limit: number | null) => onChange?.({ ...value, [name]: limit || 1 }); const addLimit = () => { let name = "tool-name"; let suffix = 2; while (name in value) { name = `tool-name-${suffix}`; suffix += 1; } onChange?.({ ...value, [name]: 3 }); }; return (
{entries.map(([name, limit]) => (
{ if (!updateName(name, event.target.value)) { event.target.value = name; } }} onPressEnter={(event) => event.currentTarget.blur()} /> updateLimit(name, next)} />
))}
); } const GATE_DEFINITIONS: GateDefinition[] = [ { type: "iteration", title: "Iteration limit", titleKey: "agentConfig.loopMode.iterationGateTitle", description: "Stop after a fixed number of loop iterations.", descriptionKey: "agentConfig.loopMode.iterationGateDescription", icon: , defaults: { max_iterations: 40 }, }, { type: "doom_loop", title: "Repetition protection", titleKey: "agentConfig.loopMode.doomGateTitle", description: "Detect repeated tool calls and change strategy.", descriptionKey: "agentConfig.loopMode.doomGateDescription", icon: , defaults: { window_size: 3, similarity_threshold: 1, stages: [ { after: 3, action: "modify_prompt", prompt: "Change strategy instead of repeating the same action.", }, { after: 5, action: "stop", prompt: "Stopped after repeated actions did not make progress.", }, ], }, }, { type: "token_budget", title: "Token budget", titleKey: "agentConfig.loopMode.tokenGateTitle", description: "Limit prompt and completion token usage.", descriptionKey: "agentConfig.loopMode.tokenGateDescription", icon: , defaults: { max_total_tokens: 120000 }, }, { type: "timeout", title: "Loop time limit", titleKey: "agentConfig.loopMode.timeoutGateTitle", description: "Stop at the next loop boundary after elapsed time.", descriptionKey: "agentConfig.loopMode.timeoutGateDescription", icon: , defaults: { max_seconds: 1800 }, }, { type: "tool_call_budget", title: "Tool-call budget", titleKey: "agentConfig.loopMode.toolBudgetGateTitle", description: "Limit all calls and selected tools.", descriptionKey: "agentConfig.loopMode.toolBudgetGateDescription", icon: , defaults: { max_calls: 30, per_tool: {} }, }, { type: "qualitative_rubric", title: "Qualitative completion check", titleKey: "agentConfig.loopMode.qualitativeRubricTitle", description: "Check text responses without tool calls before ending.", descriptionKey: "agentConfig.loopMode.qualitativeRubricDescription", icon: , defaults: { rubric: "Every explicit user requirement must be addressed.", max_evaluations: 1, }, exclusiveGroup: "completion_rubric", }, { type: "completion_rubric", title: "Completion signal check", titleKey: "agentConfig.loopMode.completionRubricTitle", description: "Check text responses without tool calls for a completion signal.", descriptionKey: "agentConfig.loopMode.completionRubricDescription", icon: , defaults: { prompt: "Treat the task as complete only when every explicit user requirement has been addressed. If any requirement remains, the task is incomplete and work must continue until it is addressed.", completion_signal: "COMPLETED", max_evaluations: 3, }, exclusiveGroup: "completion_rubric", }, ]; function gateDefinition(type: CustomGateType) { return GATE_DEFINITIONS.find((item) => item.type === type)!; } function GateParamsEditor({ modeIndex, gateIndex, type, }: { modeIndex: number; gateIndex: number; type: CustomGateType; }) { const { t } = useTranslation(); const form = Form.useFormInstance(); const base = [ "loop", "custom_modes", modeIndex, "gates", gateIndex, "params", ]; const stages = (Form.useWatch([...base, "stages"], { form, preserve: true, }) as Array<{ after?: number }> | undefined) || []; if (type === "iteration") { return ( ); } if (type === "doom_loop") { return ( <>
{t("agentConfig.doomLoopStages", "Intervention Rules")}
{(fields, { add, remove }) => (
{fields.map(({ key, name, ...rest }) => (

{t( "agentConfig.loopMode.completionRubricHelp", "Triggered after text responses without tool calls. The agent outputs the completion signal when done; otherwise it keeps working until the maximum evaluation rounds is reached.", )}

); } function SortableGateCard({ modeIndex, gateIndex, gate, onRemove, onMove, }: { modeIndex: number; gateIndex: number; gate: GateInstanceConfig; onRemove: () => void; onMove: (offset: number) => void; }) { const { t } = useTranslation(); const [expanded, setExpanded] = useState(gate.type === "completion_rubric"); const definition = gateDefinition(gate.type); const title = t(definition.titleKey, definition.title); const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: gate.id }); return (
{definition.icon}
{expanded && (
)}
); } function CustomModeEditor({ modeIndex, onDelete, onDuplicate, }: { modeIndex: number; onDelete: () => void; onDuplicate: () => void; }) { const { t } = useTranslation(); const form = Form.useFormInstance(); const gates = (Form.useWatch(["loop", "custom_modes", modeIndex, "gates"], { form, preserve: true, }) as GateInstanceConfig[]) || []; const sensors = useSensors(useSensor(PointerSensor)); const path = ["loop", "custom_modes", modeIndex, "gates"]; const updateGates = (next: GateInstanceConfig[]) => { form.setFieldValue(path, next); form.setFieldValue( ["loop", "custom_modes", modeIndex, "enabled"], next.some((gate) => gate.enabled), ); }; const usedTypes = new Set(gates.map((gate) => gate.type)); const claimedGroups = new Set( gates .map((gate) => gateDefinition(gate.type).exclusiveGroup) .filter((group): group is string => Boolean(group)), ); const available = GATE_DEFINITIONS.filter( (definition) => !usedTypes.has(definition.type) && !( definition.exclusiveGroup && claimedGroups.has(definition.exclusiveGroup) ), ); const addGate = (type: CustomGateType) => { const definition = gateDefinition(type); updateGates([ ...gates, { id: `${type}-${Date.now()}`, type, enabled: true, params: structuredClone(definition.defaults), }, ]); }; const moveGate = (index: number, offset: number) => { const target = index + offset; if (target < 0 || target >= gates.length) return; updateGates(reorderCustomGates(gates, index, target)); }; const removeGate = (index: number) => { const next = gates.filter((_, itemIndex) => itemIndex !== index); updateGates(next); }; const onDragEnd = ({ active, over }: DragEndEvent) => { if (!over || active.id === over.id) return; const from = gates.findIndex((gate) => gate.id === active.id); const to = gates.findIndex((gate) => gate.id === over.id); updateGates(reorderCustomGates(gates, from, to)); }; return (
{t("agentConfig.loopMode.custom", "Custom")}

{t( "agentConfig.loopMode.customDescription", "Build a saved pipeline from QwenPaw-owned gates.", )}

{ const modes = form.getFieldValue([ "loop", "custom_modes", ]) as CustomLoopModeConfig[]; if (hasDuplicateLoopModeName(modes || [], value, modeIndex)) { return Promise.reject( new Error( t( "agentConfig.loopMode.duplicateModeName", "A loop mode with this name already exists.", ), ), ); } return Promise.resolve(); }, }, ]} >
{t("agentConfig.loopMode.gatePipeline", "Gate pipeline")} {t( "agentConfig.loopMode.runsTopToBottom", "Runs from top to bottom", )}
({ key: definition.type, icon: definition.icon, label: t(definition.titleKey, definition.title), })), onClick: ({ key }: { key: string }) => addGate(key as CustomGateType), }} >
{!gates.length ? (
{t( "agentConfig.loopMode.emptyPipeline", "Add at least one gate before enabling this mode.", )}
) : ( gate.id)} strategy={verticalListSortingStrategy} >
{gates.map((gate, index) => ( removeGate(index)} onMove={(offset) => moveGate(index, offset)} /> ))}
)}
); } const TEMPLATES: Record = { safe: ["iteration", "token_budget", "doom_loop", "qualitative_rubric"], research: ["iteration", "timeout", "tool_call_budget", "doom_loop"], quality: ["iteration", "token_budget", "doom_loop", "completion_rubric"], blank: [], }; function makeGate( type: CustomGateType, nonce = `${Date.now()}-${Math.random().toString(36).slice(2, 6)}`, ): GateInstanceConfig { const definition = gateDefinition(type); return { id: `${type}-${nonce}`, type, enabled: true, params: structuredClone(definition.defaults), }; } export function buildCustomLoopMode( existing: CustomLoopModeConfig[], name: string, command: string, template: string, nonce = Date.now(), description = "A custom gate pipeline.", ): CustomLoopModeConfig { const baseCommand = command || "custom-mode"; const slashCommand = uniqueValue( baseCommand, new Set(existing.map((mode) => mode.slash_command)), 64, ); const id = uniqueValue( baseCommand, new Set(existing.map((mode) => mode.id)), 64, ); return { id, name, slash_command: slashCommand, description, enabled: template !== "blank", gates: TEMPLATES[template].map((type, index) => makeGate(type, `${nonce}-${index}`), ), }; } function uniqueValue( base: string, existing: Set, maxLength: number, normalize: (value: string) => string = (value) => value, ): string { let candidate = base.slice(0, maxLength); let suffix = 2; while (existing.has(normalize(candidate))) { const suffixText = `-${suffix}`; candidate = `${base.slice(0, maxLength - suffixText.length)}${suffixText}`; suffix += 1; } return candidate; } function normalizeLoopModeName(name: string | undefined): string { return (name || "").trim().toUpperCase().toLowerCase(); } export function hasDuplicateLoopModeName( modes: CustomLoopModeConfig[], name: string | undefined, ignoredIndex = -1, ): boolean { const normalized = normalizeLoopModeName(name); if (!normalized) return false; return modes.some( (mode, index) => index !== ignoredIndex && normalizeLoopModeName(mode.name) === normalized, ); } export function reorderCustomGates( gates: GateInstanceConfig[], from: number, to: number, ): GateInstanceConfig[] { if (from < 0 || to < 0 || from >= gates.length || to >= gates.length) { return gates; } return arrayMove(gates, from, to); } export function AgentLoopCard() { const { t } = useTranslation(); const form = Form.useFormInstance(); const customModes = (Form.useWatch(["loop", "custom_modes"], { form, preserve: true, }) as CustomLoopModeConfig[]) || []; const [activeKey, setActiveKey] = useState("default"); const [creating, setCreating] = useState(false); const [newName, setNewName] = useState(() => t("agentConfig.loopMode.newModeName", "New Loop Mode"), ); const [newCommand, setNewCommand] = useState("new-mode"); const [template, setTemplate] = useState("safe"); const duplicateNewName = hasDuplicateLoopModeName(customModes, newName); const setModes = (modes: CustomLoopModeConfig[]) => form.setFieldValue(["loop", "custom_modes"], modes); const createMode = () => { const mode = buildCustomLoopMode( customModes, newName.trim(), newCommand.trim(), template, Date.now(), t( "agentConfig.loopMode.defaultCustomDescription", "A custom gate pipeline.", ), ); setModes([...customModes, mode]); setActiveKey(`custom:${mode.id}`); setCreating(false); }; const duplicateMode = (index: number) => { const source = customModes[index]; const baseId = `${source.id}-copy`; const baseCommand = `${source.slash_command}-copy`; const copy: CustomLoopModeConfig = { ...structuredClone(source), id: uniqueValue(baseId, new Set(customModes.map((mode) => mode.id)), 64), name: uniqueValue( t("agentConfig.loopMode.copyName", "{{name}} Copy", { name: source.name, }), new Set(customModes.map((mode) => normalizeLoopModeName(mode.name))), 80, normalizeLoopModeName, ), slash_command: uniqueValue( baseCommand, new Set(customModes.map((mode) => mode.slash_command)), 64, ), enabled: source.gates.some((gate) => gate.enabled), }; setModes([...customModes, copy]); setActiveKey(`custom:${copy.id}`); }; const deleteMode = (index: number) => { setModes(customModes.filter((_, itemIndex) => itemIndex !== index)); setActiveKey("default"); }; const tabItems = [ { key: "default", label: ( {t("agentConfig.loopMode.defaultTab", "Default")} ), children: , }, { key: "goal", label: ( {t("agentConfig.loopMode.goalTab", "Goal")} ), children: , }, { key: "mission", label: ( {t("agentConfig.loopMode.missionTab", "Mission")} ), children: , }, ...customModes.map((mode, index) => ({ key: `custom:${mode.id}`, label: {mode.name}, children: ( deleteMode(index)} onDuplicate={() => duplicateMode(index)} /> ), })), { key: "add-mode", disabled: customModes.length >= 20, label: ( ), children: null, }, ]; const handleTabChange = (key: string) => { if (key === "add-mode") { setCreating(true); return; } setActiveKey(key); }; return (
{t("agentConfig.loopMode.templateSectionTitle", "Loop templates")} {t( "agentConfig.loopMode.templateSectionDescription", "Choose a built-in template or add your own.", )}
setCreating(false)} onOk={createMode} okButtonProps={{ disabled: !newName.trim() || !newCommand.trim() || duplicateNewName, }} >
setNewName(event.target.value)} /> {duplicateNewName && ( {t( "agentConfig.loopMode.duplicateModeName", "A loop mode with this name already exists.", )} )} setNewCommand( event.target.value.toLowerCase().replace(/[^a-z0-9_-]/g, ""), ) } />