Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

258 KB
Raw Blame
<template>
  <SettingsModalShell :visible="visible"
    :title="editorMode === 'create' ? $t('agent.editor.createTitle') : $t('agent.editor.editTitle')"
    v-model="currentSection" :nav-groups="navGroups" :loading="editorInitializing" :z-index="1000"
    nav-guide="agent-editor-sidebar" nav-item-guide-prefix="agent-editor-nav" @close="modalShell.requestClose">
    <div ref="contentWrapperRef" class="content-wrapper" :class="{ 'content-wrapper--prompts': currentSection === 'prompts' }">
      <!-- 基础设置 -->
      <div v-show="currentSection === 'basic'" class="section">
        <div class="section-header">
          <div class="section-header-title">
            <h2>{{ $t('agent.editor.basicInfo') }}</h2>
            <t-tooltip v-if="isBuiltinAgent" :content="$t('agentEditor.builtinHint')" placement="top">
              <span class="builtin-agent-hint" tabindex="0" role="img"
                :aria-label="$t('agentEditor.builtinHint')">
                <t-icon name="info-circle" />
              </span>
            </t-tooltip>
          </div>
          <p class="section-description">{{ $t('agent.editor.basicInfoDesc') }}</p>
        </div>

        <div class="settings-group">
          <!-- 智能体 ID(用于 API 集成) -->
          <div v-if="editorMode === 'edit' && editorAgent?.id" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.agentId') }}</label>
              <p class="desc">{{ $t('agent.editor.agentIdDesc') }}</p>
            </div>
            <div class="setting-control">
              <div class="agent-id-field">
                <code class="agent-id-value" :title="editorAgent.id">{{ editorAgent.id }}</code>
                <t-tooltip :content="$t('common.copy')" placement="top">
                  <t-button theme="default" size="small" variant="text" class="agent-id-copy"
                    @click="copyAgentId">
                    <t-icon name="file-copy" />
                  </t-button>
                </t-tooltip>
              </div>
            </div>
          </div>

          <!-- 集成渠道状态(编辑模式,配置在集成中心) -->
          <div v-if="editorMode === 'edit' && editorAgent?.id" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('integrations.agentEditor.label') }}</label>
              <p class="desc">{{ isPostCreateSession ? $t('agent.editor.postCreateHint.integrationDesc') : $t('integrations.agentEditor.desc') }}</p>
            </div>
            <div class="setting-control">
              <div class="integration-inline">
                <button type="button" class="integration-inline__stat integration-inline__link" @click="gotoIntegrations('im')">
                  <span>{{ $t('integrations.tabs.im') }} · {{ agentIMChannelCount }}</span>
                  <t-icon name="chevron-right" size="14px" />
                </button>
                <span class="integration-inline__sep" aria-hidden="true">|</span>
                <button type="button" class="integration-inline__stat integration-inline__link" @click="gotoIntegrations('embed')">
                  <span>{{ $t('integrations.tabs.embed') }} · {{ agentEmbedChannelCount }}</span>
                  <t-icon name="chevron-right" size="14px" />
                </button>
              </div>
            </div>
          </div>

          <!-- 运行模式(首先选择) -->
          <div class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.mode') }} <span class="required">*</span></label>
              <p class="desc">{{ agentMode === 'smart-reasoning' ? $t('agent.editor.agentDesc') :
                $t('agent.editor.normalDesc') }}</p>
            </div>
            <div class="setting-control">
              <t-radio-group v-model="agentMode" :disabled="isBuiltinAgent" data-guide="agent-create-mode">
                <t-radio-button value="quick-answer">
                  {{ $t('agent.type.normal') }}
                </t-radio-button>
                <t-radio-button value="smart-reasoning">
                  {{ $t('agent.type.agent') }}
                </t-radio-button>
              </t-radio-group>
            </div>
          </div>

          <!-- 智能体类型(仅智能推理模式下显示) -->
          <div v-if="isAgentMode && agentTypePresets.length > 0" class="setting-row setting-row--emphasize"
            data-guide="agent-create-agent-type">
            <div class="setting-info">
              <label>{{ $t('agentEditor.agentType.label') }}</label>
              <p class="desc">{{ $t('agentEditor.agentType.desc') }}</p>
              <p v-if="activeAgentTypePreset" class="desc agent-type-preset-desc">{{
                agentTypePresetDescription(activeAgentTypePreset) }}</p>
            </div>
            <div class="setting-control">
              <t-select :value="agentType" @change="onAgentTypeChange" :disabled="isBuiltinAgent"
                :placeholder="$t('agentEditor.agentType.label')" :options="agentTypeSelectOptions"
                :popup-props="{ overlayClassName: 'agent-type-popup' }" class="agent-type-select">
                <template #option="{ option }">
                  <div class="agent-type-option">
                    <span class="agent-type-option-label">{{ option.label }}</span>
                    <span v-if="option.desc" class="agent-type-option-desc">{{ option.desc }}</span>
                  </div>
                </template>
              </t-select>
            </div>
          </div>

          <!-- 名称 -->
          <div class="setting-row" data-guide="agent-create-name">
            <div class="setting-info">
              <label>{{ $t('agent.editor.name') }} <span v-if="!isBuiltinAgent"
                  class="required">*</span></label>
              <p class="desc">{{ $t('agentEditor.desc.name') }}</p>
            </div>
            <div class="setting-control">
              <div class="name-input-wrapper">
                <!-- 内置智能体使用简洁图标 -->
                <div v-if="isBuiltinAgent" class="builtin-avatar" :class="isAgentMode ? 'agent' : 'normal'">
                  <t-icon :name="isAgentMode ? 'control-platform' : 'chat'" size="24px" />
                </div>
                <!-- 自定义智能体使用 AgentAvatar -->
                <AgentAvatar v-else :name="formData.name || '?'" size="medium" />
                <t-input v-model="formData.name" :placeholder="$t('agent.editor.namePlaceholder')"
                  class="name-input" :disabled="isBuiltinAgent" />
              </div>
            </div>
          </div>

          <!-- 描述 -->
          <div class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.description') }}</label>
              <p class="desc">{{ $t('agentEditor.desc.description') }}</p>
            </div>
            <div class="setting-control">
              <t-textarea v-model="formData.description"
                :placeholder="$t('agent.editor.descriptionPlaceholder')"
                :autosize="{ minRows: 2, maxRows: 4 }" :disabled="isBuiltinAgent" />
            </div>
          </div>

          <!-- 长期记忆。留在基础信息这一组而不是「多轮对话」,是因为它与
               多轮历史窗口无关,且智能推理恰恰是最需要这个开关的模式。
               这个开关只能"关":空间或个人设置关闭时,这里打开也不生效。 -->
          <div class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.memoryEnabled') }}</label>
              <p class="desc">{{ $t('agentEditor.desc.memoryEnabled') }}</p>
            </div>
            <div class="setting-control">
              <t-switch v-model="formData.config.memory_enabled" />
            </div>
          </div>

        </div>
      </div>

      <!-- 提示词 -->
      <div v-show="currentSection === 'prompts'" class="section section--prompts">
        <div class="prompts-panel">
          <div class="prompts-panel__header">
            <div class="section-header section-header--compact">
              <h2>{{ $t('agent.editor.promptsConfig') }}</h2>
              <p class="section-description">{{ $t('agent.editor.promptsConfigDesc') }}</p>
            </div>

            <nav v-if="promptNavItems.length > 1" class="prompts-outline"
              :aria-label="$t('agentEditor.promptNav.ariaLabel')">
              <button v-for="item in promptNavItems" :key="item.key" type="button"
                class="prompts-outline__pill"
                :class="{ 'prompts-outline__pill--active': activePromptAnchor === item.key }"
                @click="activePromptAnchor = item.key">
                <span>{{ item.label }}</span>
                <span v-if="item.customized" class="prompts-outline__dot"
                  :title="$t('agentEditor.intentPrompts.customized')" />
              </button>
            </nav>
          </div>

          <div class="prompts-panel__body">
            <div class="settings-group">
              <!-- 系统提示词 -->
              <div v-show="activePromptAnchor === 'system'"
                class="setting-row setting-row-vertical prompts-panel__pane">
            <div class="setting-info">
              <label>{{ $t('agent.editor.systemPrompt') }} <span v-if="!isBuiltinAgent"
                  class="required">*</span></label>
              <p class="desc">{{ $t('agentEditor.desc.systemPrompt') }}{{ isBuiltinAgent ?
                $t('agentEditor.desc.leaveEmptyDefault') : '' }}</p>
              <p class="desc">{{ $t('agentEditor.desc.promptInheritance') }}</p>
              <div class="placeholder-tags">
                <span class="placeholder-label">{{ $t('agentEditor.placeholders.available') }}</span>
                <t-tooltip v-for="placeholder in availablePlaceholders" :key="placeholder.name"
                  :content="placeholder.description + $t('agentEditor.placeholders.clickToInsert')"
                  placement="top">
                  <span class="placeholder-tag" @click="handlePlaceholderClick('system', placeholder.name)"
                    v-text="'{{' + placeholder.name + '}}'"></span>
                </t-tooltip>
                <span class="placeholder-hint">{{ $t('agentEditor.placeholders.hint') }}</span>
              </div>
            </div>
            <div class="setting-control setting-control-full" style="position: relative;">
              <!-- Agent模式:统一提示词(使用 {{web_search_status}} 占位符动态控制行为) -->
              <div v-if="isAgentMode" class="textarea-with-template textarea-with-assistant">
                <t-textarea ref="promptTextareaRef" v-model="formData.config.system_prompt"
                  :placeholder="systemPromptPlaceholder" :autosize="{ minRows: 10, maxRows: 25 }"
                  @input="handlePromptInput" class="system-prompt-textarea" />
                <AssistantActionButton class="prompt-assistant-action"
                  :label="$t(formData.config.system_prompt?.trim() ? 'assistant.actions.refinePrompt' : 'assistant.actions.writePrompt')"
                  :query="$t(formData.config.system_prompt?.trim() ? 'assistant.prompts.refinePrompt' : 'assistant.prompts.writePrompt')"
                  :selection="{ field: $t('agent.editor.systemPrompt'), text: formData.config.system_prompt || '' }" />
                <PromptTemplateSelector type="agentSystemPrompt" position="corner"
                  :hasKnowledgeBase="hasKnowledgeBase" @select="handleSystemPromptTemplateSelect"
                  @reset-default="handleAgentSystemPromptResetDefault" />
              </div>
              <!-- 普通模式:单个提示词 -->
              <div v-else class="textarea-with-template textarea-with-assistant">
                <t-textarea ref="promptTextareaRef" v-model="formData.config.system_prompt"
                  :placeholder="systemPromptPlaceholder" :autosize="{ minRows: 10, maxRows: 25 }"
                  @input="handlePromptInput" class="system-prompt-textarea" />
                <AssistantActionButton class="prompt-assistant-action"
                  :label="$t(formData.config.system_prompt?.trim() ? 'assistant.actions.refinePrompt' : 'assistant.actions.writePrompt')"
                  :query="$t(formData.config.system_prompt?.trim() ? 'assistant.prompts.refinePrompt' : 'assistant.prompts.writePrompt')"
                  :selection="{ field: $t('agent.editor.systemPrompt'), text: formData.config.system_prompt || '' }" />
                <PromptTemplateSelector type="systemPrompt" position="corner"
                  :hasKnowledgeBase="hasKnowledgeBase" @select="handleSystemPromptTemplateSelect"
                  @reset-default="handleSystemPromptTemplateSelect" />
              </div>
              <!-- 占位符提示下拉框 -->
              <Teleport to="body">
                <div v-if="showPlaceholderPopup && filteredPlaceholders.length > 0"
                  class="placeholder-popup-wrapper" :style="popupStyle">
                  <div class="placeholder-popup">
                    <div v-for="(placeholder, index) in filteredPlaceholders" :key="placeholder.name"
                      class="placeholder-item" :class="{ active: selectedPlaceholderIndex === index }"
                      @mousedown.prevent="insertPlaceholder(placeholder.name, true)"
                      @mouseenter="selectedPlaceholderIndex = index">
                      <div class="placeholder-name">
                        <code v-html="`{{${placeholder.name}}}`"></code>
                      </div>
                      <div class="placeholder-desc">{{ placeholder.description }}</div>
                    </div>
                  </div>
                </div>
              </Teleport>
            </div>
          </div>

          <!-- 上下文模板(仅普通模式) -->
          <div v-if="!isAgentMode" v-show="activePromptAnchor === 'context'"
            class="setting-row setting-row-vertical prompts-panel__pane">
            <div class="setting-info">
              <label>{{ $t('agent.editor.contextTemplate') }} <span v-if="!isBuiltinAgent"
                  class="required">*</span></label>
              <p class="desc">{{ $t('agentEditor.desc.contextTemplate') }}{{ isBuiltinAgent ?
                $t('agentEditor.desc.leaveEmptyDefault') : '' }}</p>
              <div class="placeholder-tags">
                <span class="placeholder-label">{{ $t('agentEditor.placeholders.available') }}</span>
                <t-tooltip v-for="placeholder in contextTemplatePlaceholders" :key="placeholder.name"
                  :content="placeholder.description + $t('agentEditor.placeholders.clickToInsert')"
                  placement="top">
                  <span class="placeholder-tag" @click="handlePlaceholderClick('context', placeholder.name)"
                    v-text="'{{' + placeholder.name + '}}'"></span>
                </t-tooltip>
                <span class="placeholder-hint">{{ $t('agentEditor.placeholders.hint') }}</span>
              </div>
            </div>
            <div class="setting-control setting-control-full" style="position: relative;">
              <div class="textarea-with-template">
                <t-textarea ref="contextTemplateTextareaRef" v-model="formData.config.context_template"
                  :placeholder="contextTemplatePlaceholder" :autosize="{ minRows: 8, maxRows: 20 }"
                  @input="handleContextTemplateInput" class="system-prompt-textarea" />
                <PromptTemplateSelector type="contextTemplate" position="corner"
                  :hasKnowledgeBase="hasKnowledgeBase" @select="handleContextTemplateSelect"
                  @reset-default="handleContextTemplateSelect" />
              </div>
              <!-- 上下文模板占位符提示下拉框 -->
              <Teleport to="body">
                <div v-if="showContextPlaceholderPopup && filteredContextPlaceholders.length > 0"
                  class="placeholder-popup-wrapper" :style="contextPopupStyle">
                  <div class="placeholder-popup">
                    <div v-for="(placeholder, index) in filteredContextPlaceholders" :key="placeholder.name"
                      class="placeholder-item" :class="{ active: selectedContextPlaceholderIndex === index }"
                      @mousedown.prevent="insertContextPlaceholder(placeholder.name, true)"
                      @mouseenter="selectedContextPlaceholderIndex = index">
                      <div class="placeholder-name">
                        <code v-html="`{{${placeholder.name}}}`"></code>
                      </div>
                      <div class="placeholder-desc">{{ placeholder.description }}</div>
                    </div>
                  </div>
                </div>
              </Teleport>
            </div>
          </div>

          <!-- 意图提示词(仅普通模式) -->
          <div v-if="!isAgentMode" v-show="activePromptAnchor === 'intent'"
            class="setting-row setting-row-vertical prompts-panel__pane">
            <div class="setting-info">
              <label>{{ $t('agentEditor.intentPrompts.title') }}</label>
              <p class="desc">{{ $t('agentEditor.intentPrompts.sectionDesc') }}</p>
            </div>
            <div class="setting-control setting-control-full">
              <div class="intent-prompts-editor">
                <div v-if="intentPromptTemplates.length === 0" class="prompt-disabled-hint">
                  {{ $t('agentEditor.intentPrompts.empty') }}
                </div>
                <template v-else>
                  <div class="intent-toggle-group" role="tablist"
                    :aria-label="$t('agentEditor.intentPrompts.intentLabel')">
                    <t-button v-for="template in intentPromptTemplates" :key="template.id" theme="default"
                      variant="outline" size="small" class="intent-toggle-btn"
                      :class="{ 'intent-toggle-btn--active': selectedIntent === template.id }"
                      :disabled="props.readOnly" @click="selectedIntent = template.id">
                      <span class="intent-toggle-label">
                        {{ template.name || template.id }}
                        <t-tooltip v-if="isIntentCustomized(template.id)"
                          :content="$t('agentEditor.intentPrompts.customized')" placement="top">
                          <span class="intent-toggle-dot" />
                        </t-tooltip>
                      </span>
                    </t-button>
                  </div>
                  <p v-if="currentIntentTemplateDesc" class="intent-active-desc">{{ currentIntentTemplateDesc
                  }}</p>

                  <div v-if="placeholderData.system_prompt.length > 0" class="placeholder-tags">
                    <span class="placeholder-label">{{ $t('agentEditor.placeholders.available') }}</span>
                    <t-tooltip v-for="placeholder in placeholderData.system_prompt" :key="placeholder.name"
                      :content="placeholder.description + $t('agentEditor.placeholders.clickToInsert')"
                      placement="top">
                      <span class="placeholder-tag"
                        @click="handlePlaceholderClick('intent', placeholder.name)"
                        v-text="'{{' + placeholder.name + '}}'" />
                    </t-tooltip>
                    <span class="placeholder-hint">{{ $t('agentEditor.placeholders.hint') }}</span>
                  </div>

                  <div class="textarea-with-template">
                    <t-textarea ref="intentPromptTextareaRef" v-model="intentEditorValue"
                      class="system-prompt-textarea" :autosize="{ minRows: 10, maxRows: 25 }"
                      :disabled="props.readOnly || !selectedIntent"
                      :placeholder="currentIntentTemplate?.content || $t('agentEditor.intentPrompts.promptPlaceholder')"
                      @input="handleIntentPromptInput" />
                    <PromptTemplateSelector type="intentPrompt" position="corner" :intent-id="selectedIntent"
                      :show-template-picker="false" @reset-default="resetCurrentIntentPrompt" />
                  </div>

                  <Teleport to="body">
                    <div v-if="intentPromptPopup.show && filteredIntentPlaceholders.length > 0"
                      class="placeholder-popup-wrapper" :style="intentPromptPopup.style">
                      <div class="placeholder-popup">
                        <div v-for="(placeholder, index) in filteredIntentPlaceholders" :key="placeholder.name"
                          class="placeholder-item"
                          :class="{ active: intentPromptPopup.selectedIndex === index }"
                          @mousedown.prevent="insertGenericPlaceholder('intent', placeholder.name, true)"
                          @mouseenter="intentPromptPopup.selectedIndex = index">
                          <div class="placeholder-name">
                            <code v-html="`{{${placeholder.name}}}`" />
                          </div>
                          <div class="placeholder-desc">{{ placeholder.description }}</div>
                        </div>
                      </div>
                    </div>
                  </Teleport>
                </template>
              </div>
            </div>
          </div>

          <!-- 改写提示词(多轮对话 + 问题改写开启时) -->
          <template
            v-if="!isAgentMode && formData.config.multi_turn_enabled && formData.config.enable_rewrite">
            <div v-show="activePromptAnchor === 'rewrite-system'"
              class="setting-row setting-row-vertical prompts-panel__pane">
              <div class="setting-info">
                <label>{{ $t('agent.editor.rewritePromptSystem') }}</label>
                <p class="desc">{{ $t('agentEditor.desc.rewriteSystemPrompt') }}</p>
                <div class="placeholder-tags" v-if="rewriteSystemPlaceholders.length > 0">
                  <span class="placeholder-label">{{ $t('agentEditor.placeholders.available') }}</span>
                  <t-tooltip v-for="placeholder in rewriteSystemPlaceholders" :key="placeholder.name"
                    :content="placeholder.description + $t('agentEditor.placeholders.clickToInsert')"
                    placement="top">
                    <span class="placeholder-tag"
                      @click="handlePlaceholderClick('rewriteSystem', placeholder.name)"
                      v-text="'{{' + placeholder.name + '}}'"></span>
                  </t-tooltip>
                  <span class="placeholder-hint">{{ $t('agentEditor.placeholders.hint') }}</span>
                </div>
              </div>
              <div class="setting-control setting-control-full" style="position: relative;">
                <div class="textarea-with-template">
                  <t-textarea ref="rewriteSystemTextareaRef" v-model="formData.config.rewrite_prompt_system"
                    :placeholder="defaultRewritePromptSystem || $t('agent.editor.rewritePromptSystemPlaceholder')"
                    :autosize="{ minRows: 4, maxRows: 10 }" @input="handleRewriteSystemInput" />
                  <PromptTemplateSelector type="rewrite" position="corner" @select="handleRewriteTemplateSelect"
                    @reset-default="handleRewriteTemplateSelect" />
                </div>
                <Teleport to="body">
                  <div v-if="rewriteSystemPopup.show && filteredRewriteSystemPlaceholders.length > 0"
                    class="placeholder-popup-wrapper" :style="rewriteSystemPopup.style">
                    <div class="placeholder-popup">
                      <div v-for="(placeholder, index) in filteredRewriteSystemPlaceholders"
                        :key="placeholder.name" class="placeholder-item"
                        :class="{ active: rewriteSystemPopup.selectedIndex === index }"
                        @mousedown.prevent="insertGenericPlaceholder('rewriteSystem', placeholder.name, true)"
                        @mouseenter="rewriteSystemPopup.selectedIndex = index">
                        <div class="placeholder-name">
                          <code v-html="`{{${placeholder.name}}}`"></code>
                        </div>
                        <div class="placeholder-desc">{{ placeholder.description }}</div>
                      </div>
                    </div>
                  </div>
                </Teleport>
              </div>
            </div>

            <div v-show="activePromptAnchor === 'rewrite-user'"
              class="setting-row setting-row-vertical prompts-panel__pane">
              <div class="setting-info">
                <label>{{ $t('agent.editor.rewritePromptUser') }}</label>
                <p class="desc">{{ $t('agentEditor.desc.rewriteUserPrompt') }}</p>
                <div class="placeholder-tags" v-if="rewritePlaceholders.length > 0">
                  <span class="placeholder-label">{{ $t('agentEditor.placeholders.available') }}</span>
                  <t-tooltip v-for="placeholder in rewritePlaceholders" :key="placeholder.name"
                    :content="placeholder.description + $t('agentEditor.placeholders.clickToInsert')"
                    placement="top">
                    <span class="placeholder-tag"
                      @click="handlePlaceholderClick('rewriteUser', placeholder.name)"
                      v-text="'{{' + placeholder.name + '}}'"></span>
                  </t-tooltip>
                  <span class="placeholder-hint">{{ $t('agentEditor.placeholders.hint') }}</span>
                </div>
              </div>
              <div class="setting-control setting-control-full" style="position: relative;">
                <div class="textarea-with-template">
                  <t-textarea ref="rewriteUserTextareaRef" v-model="formData.config.rewrite_prompt_user"
                    :placeholder="defaultRewritePromptUser || $t('agent.editor.rewritePromptUserPlaceholder')"
                    :autosize="{ minRows: 4, maxRows: 10 }" @input="handleRewriteUserInput" />
                  <PromptTemplateSelector type="rewrite" position="corner" @select="handleRewriteTemplateSelect"
                    @reset-default="handleRewriteTemplateSelect" />
                </div>
                <Teleport to="body">
                  <div v-if="rewriteUserPopup.show && filteredRewriteUserPlaceholders.length > 0"
                    class="placeholder-popup-wrapper" :style="rewriteUserPopup.style">
                    <div class="placeholder-popup">
                      <div v-for="(placeholder, index) in filteredRewriteUserPlaceholders"
                        :key="placeholder.name" class="placeholder-item"
                        :class="{ active: rewriteUserPopup.selectedIndex === index }"
                        @mousedown.prevent="insertGenericPlaceholder('rewriteUser', placeholder.name, true)"
                        @mouseenter="rewriteUserPopup.selectedIndex = index">
                        <div class="placeholder-name">
                          <code v-html="`{{${placeholder.name}}}`"></code>
                        </div>
                        <div class="placeholder-desc">{{ placeholder.description }}</div>
                      </div>
                    </div>
                  </div>
                </Teleport>
              </div>
            </div>
          </template>

          <!-- 检索兜底(普通模式 + 启用知识库) -->
          <div v-if="!isAgentMode && hasKnowledgeBase" v-show="activePromptAnchor === 'fallback'"
            class="prompts-panel__pane prompts-panel__pane--stack">
            <div class="setting-row">
              <div class="setting-info">
                <label>{{ $t('agent.editor.fallbackStrategy') }}</label>
                <p class="desc">{{ $t('agentEditor.desc.fallbackStrategy') }}</p>
              </div>
              <div class="setting-control">
                <t-radio-group v-model="formData.config.fallback_strategy">
                  <t-radio-button value="fixed">{{ $t('agentEditor.fallback.fixed') }}</t-radio-button>
                  <t-radio-button value="model">{{ $t('agentEditor.fallback.model') }}</t-radio-button>
                </t-radio-group>
              </div>
            </div>

            <div v-if="formData.config.fallback_strategy === 'fixed'"
              class="setting-row setting-row-vertical">
              <div class="setting-info">
                <label>{{ $t('agent.editor.fallbackResponse') }}</label>
                <p class="desc">{{ $t('agentEditor.desc.fallbackResponse') }}</p>
              </div>
              <div class="setting-control setting-control-full">
                <div class="textarea-with-template">
                  <t-textarea v-model="formData.config.fallback_response"
                    :placeholder="defaultFallbackResponse || $t('agent.editor.fallbackResponsePlaceholder')"
                    :autosize="{ minRows: 2, maxRows: 6 }" />
                  <PromptTemplateSelector type="fallback" position="corner" fallbackMode="fixed"
                    @select="handleFallbackResponseTemplateSelect"
                    @reset-default="handleFallbackResponseTemplateSelect" />
                </div>
              </div>
            </div>

            <div v-if="formData.config.fallback_strategy === 'model'"
              class="setting-row setting-row-vertical">
              <div class="setting-info">
                <label>{{ $t('agent.editor.fallbackPrompt') }}</label>
                <p class="desc">{{ $t('agentEditor.desc.fallbackPrompt') }}</p>
                <div class="placeholder-tags" v-if="fallbackPlaceholders.length > 0">
                  <span class="placeholder-label">{{ $t('agentEditor.placeholders.available') }}</span>
                  <t-tooltip v-for="placeholder in fallbackPlaceholders" :key="placeholder.name"
                    :content="placeholder.description + $t('agentEditor.placeholders.clickToInsert')"
                    placement="top">
                    <span class="placeholder-tag"
                      @click="handlePlaceholderClick('fallback', placeholder.name)"
                      v-text="'{{' + placeholder.name + '}}'"></span>
                  </t-tooltip>
                  <span class="placeholder-hint">{{ $t('agentEditor.placeholders.hint') }}</span>
                </div>
              </div>
              <div class="setting-control setting-control-full" style="position: relative;">
                <div class="textarea-with-template">
                  <t-textarea ref="fallbackPromptTextareaRef" v-model="formData.config.fallback_prompt"
                    :placeholder="defaultFallbackPrompt || $t('agent.editor.fallbackPromptPlaceholder')"
                    :autosize="{ minRows: 4, maxRows: 10 }" @input="handleFallbackPromptInput" />
                  <PromptTemplateSelector type="fallback" position="corner" fallbackMode="model"
                    @select="handleFallbackPromptTemplateSelect"
                    @reset-default="handleFallbackPromptTemplateSelect" />
                </div>
                <Teleport to="body">
                  <div v-if="fallbackPromptPopup.show && filteredFallbackPlaceholders.length > 0"
                    class="placeholder-popup-wrapper" :style="fallbackPromptPopup.style">
                    <div class="placeholder-popup">
                      <div v-for="(placeholder, index) in filteredFallbackPlaceholders"
                        :key="placeholder.name" class="placeholder-item"
                        :class="{ active: fallbackPromptPopup.selectedIndex === index }"
                        @mousedown.prevent="insertGenericPlaceholder('fallback', placeholder.name, true)"
                        @mouseenter="fallbackPromptPopup.selectedIndex = index">
                        <div class="placeholder-name">
                          <code v-html="`{{${placeholder.name}}}`"></code>
                        </div>
                        <div class="placeholder-desc">{{ placeholder.description }}</div>
                      </div>
                    </div>
                  </div>
                </Teleport>
              </div>
            </div>
          </div>

            </div>
          </div>
        </div>
      </div>

      <!-- 模型配置 -->
      <div v-show="currentSection === 'model'" class="section">
        <div class="section-header">
          <h2>{{ $t('agent.editor.modelConfig') }}</h2>
          <p class="section-description">{{ $t('agent.editor.modelConfigDesc') }}</p>
        </div>

        <div class="settings-group">
          <!-- 模型选择 -->
          <div
            class="setting-row"
            data-guide="agent-create-model"
            data-agent-field="summary_model"
            :class="{ 'setting-row--field-highlight': highlightedField === 'summary_model' }"
          >
            <div class="setting-info">
              <label>{{ $t('agent.editor.model') }} <span class="required">*</span></label>
              <p class="desc">{{ $t('agentEditor.desc.model') }}</p>
            </div>
            <div class="setting-control">
              <ModelSelector model-type="KnowledgeQA" :selected-model-id="formData.config.model_id"
                :all-models="allModels"
                @update:selected-model-id="(val: string) => formData.config.model_id = val"
                @add-model="handleAddModel('llm')" :placeholder="$t('agent.editor.modelPlaceholder')" />
            </div>
          </div>

          <!-- 温度 -->
          <div class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.temperature') }}</label>
              <p class="desc">{{ $t('agentEditor.desc.temperature') }}</p>
            </div>
            <div class="setting-control">
              <div class="slider-wrapper">
                <t-slider v-model="formData.config.temperature" :min="0" :max="1" :step="0.1" />
                <span class="slider-value">{{ formData.config.temperature }}</span>
              </div>
            </div>
          </div>

          <!-- 最大生成Token数:0 表示跟随系统默认;自定义后按输入值保存 -->
          <div class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.maxCompletionTokens') }}</label>
              <p class="desc">{{ isAgentMode ? $t('agentEditor.desc.maxTokensAgent') :
                $t('agentEditor.desc.maxTokens') }}
              </p>
            </div>
            <div class="setting-control max-tokens-control">
              <t-radio-group v-model="maxCompletionTokensMode">
                <t-radio-button value="default">{{ $t('agent.editor.maxCompletionTokensDefault')
                  }}</t-radio-button>
                <t-radio-button value="custom">{{ $t('agent.editor.maxCompletionTokensCustom')
                  }}</t-radio-button>
              </t-radio-group>
              <span v-if="maxCompletionTokensMode === 'default'" class="max-tokens-value">
                {{ effectiveDefaultMaxCompletionTokens }}
              </span>
              <t-input-number v-else v-model="formData.config.max_completion_tokens" :min="100" :max="100000"
                :step="100" theme="column" />
            </div>
          </div>

          <!-- 思考强度:off / auto + 所选对话模型目录上报的等级 -->
          <div class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.thinking') }}</label>
              <p class="desc">{{ $t('agentEditor.desc.thinking') }}</p>
              <p v-if="selectedChatModel && !selectedChatModelCanThink" class="desc">
                {{ $t('agent.editor.reasoningEffortUnsupported') }}
              </p>
              <p v-else-if="selectedChatModelAlwaysThinks" class="desc">
                {{ $t('agent.editor.reasoningEffortAlwaysOn') }}
              </p>
            </div>
            <div class="setting-control">
              <t-select v-model="reasoningEffortLevel" class="reasoning-effort-select"
                :popup-props="{ overlayClassName: 'reasoning-level-select-popup' }">
                <t-option v-for="level in reasoningEffortOptions" :key="level" :value="level"
                  :label="$t(levelLabelKey(level))" :show-overflow-tooltip="false">
                  <div class="reasoning-level-option">
                    <span class="reasoning-level-option__title">{{ $t(levelLabelKey(level)) }}</span>
                    <span class="reasoning-level-option__hint">{{ $t(levelDescriptionKey(level)) }}</span>
                  </div>
                </t-option>
              </t-select>
            </div>
          </div>

          <!-- 来源引用 -->
          <div class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.citationEnabled') }}</label>
              <p class="desc">{{ $t('agent.editor.citationEnabledDesc') }}</p>
            </div>
            <div class="setting-control">
              <t-switch v-model="formData.config.citation_enabled" />
            </div>
          </div>

          <!-- ReRank 模型(启用知识库或 search_knowledge 工具时显示) -->
          <div
            v-if="showRerankModelField"
            class="setting-row"
            data-agent-field="rerank_model"
            :class="{ 'setting-row--field-highlight': highlightedField === 'rerank_model' }"
          >
            <div class="setting-info">
              <label>
                {{ $t('agent.editor.rerankModel') }}
                <span v-if="needsRerankModel" class="required">*</span>
              </label>
              <p class="desc">
                {{ $t('agent.editor.rerankModelDesc') }}
                <template v-if="!needsRerankModel">
                  <br />
                  <span class="hint">{{ $t('agent.editor.rerankModelOptionalHint') }}</span>
                </template>
              </p>
            </div>
            <div class="setting-control">
              <ModelSelector model-type="Rerank" :selected-model-id="formData.config.rerank_model_id"
                :all-models="allModels"
                :clearable="!needsRerankModel"
                @update:selected-model-id="(val: string) => formData.config.rerank_model_id = val"
                @add-model="handleAddModel('rerank')"
                :placeholder="$t('agent.editor.rerankModelPlaceholder')" />
            </div>
          </div>

          <!-- 问题理解模型(多轮改写时,留空则复用主对话模型) -->
          <div
            v-if="!isAgentMode && formData.config.multi_turn_enabled && formData.config.enable_rewrite"
            class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.queryUnderstandModel') }}</label>
              <p class="desc">{{ $t('agentEditor.desc.queryUnderstandModel') }}</p>
            </div>
            <div class="setting-control">
              <ModelSelector model-type="KnowledgeQA"
                :selected-model-id="formData.config.query_understand_model_id" :all-models="allModels"
                clearable
                @update:selected-model-id="(val: string) => formData.config.query_understand_model_id = val"
                @add-model="handleAddModel('llm')"
                :placeholder="$t('agent.editor.queryUnderstandModelPlaceholder')" />
            </div>
          </div>

          <!-- 最大迭代次数(Agent 模式):正数为上限,-1 为不限制 -->
          <div v-if="isAgentMode" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.maxIterations') }}</label>
              <p class="desc">{{ $t('agentEditor.desc.maxIterations') }}</p>
            </div>
            <div class="setting-control max-tokens-control">
              <t-radio-group v-model="maxIterationsMode">
                <t-radio-button value="limit">{{ $t('agent.editor.maxIterationsLimit') }}</t-radio-button>
                <t-radio-button value="unlimited">{{ $t('agent.editor.maxIterationsUnlimited') }}</t-radio-button>
              </t-radio-group>
              <t-input-number v-if="maxIterationsMode === 'limit'" v-model="formData.config.max_iterations"
                :min="2" :max="50" theme="column" />
            </div>
          </div>

          <!-- LLM 调用超时(Agent 模式) -->
          <div v-if="isAgentMode" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agentEditor.llmCallTimeout.label') }}</label>
              <p class="desc">{{ $t('agentEditor.llmCallTimeout.desc') }}</p>
              <p class="desc-hint">{{ $t('agentEditor.llmCallTimeout.hint') }}</p>
            </div>
            <div class="setting-control">
              <t-input-number v-model="formData.config.llm_call_timeout" :min="0" :max="3600" theme="column"
                :placeholder="$t('agentEditor.llmCallTimeout.placeholder')" clearable />
            </div>
          </div>

        </div>
      </div>

      <!-- 附件上传 -->
      <div v-show="currentSection === 'multimodal'" class="section">
        <div class="section-header">
          <h2>{{ $t('agentEditor.imageUpload.sectionTitle') }}</h2>
          <p class="section-description">{{ $t('agentEditor.imageUpload.sectionDesc') }}</p>
        </div>

        <div class="settings-group">
          <!-- 图片上传 -->
          <div class="setting-row" data-guide="agent-create-multimodal">
            <div class="setting-info">
              <label>{{ $t('agentEditor.imageUpload.label') }}</label>
              <p class="desc">{{ $t('agentEditor.imageUpload.desc') }}</p>
            </div>
            <div class="setting-control">
              <t-switch v-model="formData.config.image_upload_enabled" />
            </div>
          </div>

          <!-- VLM 模型(图片上传启用时) -->
          <div v-if="formData.config.image_upload_enabled" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agentEditor.imageUpload.vlmModel') }} <span class="required">*</span></label>
              <p class="desc">{{ $t('agentEditor.imageUpload.vlmModelDesc') }}</p>
            </div>
            <div class="setting-control">
              <ModelSelector model-type="VLLM" :selected-model-id="formData.config.vlm_model_id"
                :all-models="allModels"
                @update:selected-model-id="(val: string) => formData.config.vlm_model_id = val"
                @add-model="handleAddModel('vllm')"
                :placeholder="$t('agentEditor.imageUpload.vlmModelPlaceholder')" />
            </div>
          </div>

          <!-- 附件图片理解 / 扫描件 OCR(图片上传启用时) -->
          <div v-if="formData.config.image_upload_enabled" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agentEditor.imageUpload.imageUnderstandingLabel') }}</label>
              <p class="desc">{{ $t('agentEditor.imageUpload.imageUnderstandingDesc') }}</p>
            </div>
            <div class="setting-control">
              <t-switch v-model="formData.config.attachment_image_understanding" />
            </div>
          </div>

          <!-- 扫描件 OCR 最大页数(开启附件图片理解时) -->
          <div v-if="formData.config.image_upload_enabled && formData.config.attachment_image_understanding"
            class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agentEditor.imageUpload.ocrMaxPagesLabel') }}</label>
              <p class="desc">{{ $t('agentEditor.imageUpload.ocrMaxPagesDesc') }}</p>
            </div>
            <div class="setting-control">
              <t-input-number v-model="formData.config.attachment_ocr_max_pages" :min="0" :max="64"
                :step="1" theme="normal" style="width: 160px;"
                :placeholder="$t('agentEditor.imageUpload.useGlobalDefault')" />
            </div>
          </div>

          <!-- 图片存储 Provider(图片上传启用时) -->
          <div v-if="formData.config.image_upload_enabled" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agentEditor.imageUpload.storageProvider') }}</label>
              <p class="desc">{{ $t('agentEditor.imageUpload.storageProviderDesc') }}</p>
            </div>
            <div class="setting-control" style="flex-direction: column; align-items: flex-end;">
              <t-select v-model="formData.config.image_storage_provider" style="width: 280px;"
                :placeholder="$t('agentEditor.imageUpload.storageProviderPlaceholder')" clearable>
                <t-option value="" :label="$t('agentEditor.imageUpload.storageDefault')" />
                <t-option v-for="opt in imageStorageOptions" :key="opt.value" :value="opt.value"
                  :label="opt.label" :disabled="opt.disabled">
                  <span class="select-option-with-tag">
                    <span>{{ opt.label }}</span>
                    <t-tag v-if="opt.disabled" theme="warning" variant="light" size="small">{{
                      $t('agentEditor.imageUpload.notConfigured') }}</t-tag>
                  </span>
                </t-option>
              </t-select>
              <a href="javascript:void(0)" class="go-settings-link"
                @click.prevent="uiStore.openSettings('storage')">
                {{ $t('agentEditor.imageUpload.goStorageSettings') }}
              </a>
            </div>
          </div>

          <!-- 音频上传开关 -->
          <div class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agentEditor.audioUpload.label') }}</label>
              <p class="desc">{{ $t('agentEditor.audioUpload.desc') }}</p>
            </div>
            <div class="setting-control">
              <t-switch v-model="formData.config.audio_upload_enabled" />
            </div>
          </div>

          <!-- ASR 模型(音频上传启用时) -->
          <div v-if="formData.config.audio_upload_enabled" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agentEditor.audioUpload.asrModel') }}</label>
              <p class="desc">{{ $t('agentEditor.audioUpload.asrModelDesc') }}</p>
            </div>
            <div class="setting-control">
              <ModelSelector model-type="ASR" :selected-model-id="formData.config.asr_model_id"
                :all-models="allModels"
                clearable
                @update:selected-model-id="(val: string) => formData.config.asr_model_id = val"
                @add-model="handleAddModel('asr')"
                :placeholder="$t('agentEditor.audioUpload.asrModelPlaceholder')" />
            </div>
          </div>

          <!-- 单轮等待附件解析超时(秒) -->
          <div class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agentEditor.chatParser.waitTimeoutLabel') }}</label>
              <p class="desc">{{ $t('agentEditor.chatParser.waitTimeoutDesc') }}</p>
            </div>
            <div class="setting-control">
              <t-input-number v-model="formData.config.attachment_parse_wait_timeout_sec" :min="0" :max="600"
                :step="10" theme="normal" style="width: 160px;"
                :placeholder="$t('agentEditor.imageUpload.useGlobalDefault')" />
            </div>
          </div>

          <!-- 聊天附件解析策略 -->
          <div class="parser-policy-block">
            <div class="parser-policy-block__header">
              <label>{{ $t('agentEditor.chatParser.label') }}</label>
              <p class="desc">{{ $t('agentEditor.chatParser.desc') }}</p>
            </div>
            <KBParserSettings
              embedded
              :parser-engine-rules="formData.config.chat_parser_engine_rules"
              :relevant-extensions="CHAT_PARSER_EXTENSIONS"
              @update:parser-engine-rules="(val: any) => formData.config.chat_parser_engine_rules = val"
            />
          </div>

        </div>
      </div>

      <!-- 多轮对话。两种模式都保留本组:Agent 模式在这里说明历史按上下文窗口
           自动管理,并承载跨轮保留检索结果;开关由 EnsureDefaults 强制开启,
           故只在普通模式展示。 -->
      <div v-show="currentSection === 'conversation'" class="section">
        <div class="section-header">
          <h2>{{ $t('agent.editor.conversationSettings') }}</h2>
          <p class="section-description">{{ conversationSectionDesc }}</p>
        </div>

        <div class="settings-group">
          <!-- 多轮对话开关(仅普通模式:Agent 模式由 EnsureDefaults 强制开启,
               展示可关闭的开关只会被服务端改回去) -->
          <div v-if="!isAgentMode" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.multiTurn') }}</label>
              <p class="desc">{{ $t('agentEditor.desc.multiTurn') }}</p>
            </div>
            <div class="setting-control">
              <t-switch v-model="formData.config.multi_turn_enabled" />
            </div>
          </div>

          <!-- 保留轮数(仅普通模式:Agent 模式按上下文窗口加载历史、超出时压缩成
               摘要,见 session_agent_qa.go -> LoadAgentHistory,不读 history_turns) -->
          <div v-if="!isAgentMode && formData.config.multi_turn_enabled" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.historyTurns') }}</label>
              <p class="desc">{{ $t('agentEditor.desc.historyRounds') }}</p>
            </div>
            <div class="setting-control">
              <t-input-number v-model="formData.config.history_turns" :min="1" :max="100" theme="column" />
            </div>
          </div>

          <!-- 跨轮保留检索结果。只有 agent 链路读取该值(internal/agent/observe.go),
               且改写的只是 KB/Wiki 这八个工具的历史结果,所以没有知识库时不展示。 -->
          <div v-if="isAgentMode && hasKnowledgeBase" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.retainRetrievalHistory') }}</label>
              <p class="desc">{{ $t('agentEditor.desc.retainRetrievalHistory') }}</p>
            </div>
            <div class="setting-control">
              <t-switch v-model="formData.config.retain_retrieval_history" />
            </div>
          </div>

          <!-- 问题改写(仅多轮对话开启且普通模式时显示) -->
          <div v-if="formData.config.multi_turn_enabled && !isAgentMode" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.enableRewrite') }}</label>
              <p class="desc">{{ $t('agentEditor.desc.rewrite') }}</p>
            </div>
            <div class="setting-control">
              <t-switch v-model="formData.config.enable_rewrite" />
            </div>
          </div>
        </div>
      </div>

      <!-- 对话问题推荐 -->
      <div v-show="currentSection === 'suggestions'" class="section">
        <div class="section-header">
          <h2>{{ $t('agentEditor.questionSuggestions.title') }}</h2>
          <p class="section-description">{{ $t('agentEditor.questionSuggestions.description') }}</p>
        </div>

        <t-tabs v-model="suggestionTab" class="suggestion-tabs">
          <t-tab-panel value="starters"
            :label="$t('agentEditor.questionSuggestions.startersTitle')" />
          <t-tab-panel value="followUps"
            :label="$t('agentEditor.questionSuggestions.followUpsTitle')" />
        </t-tabs>

        <div v-show="suggestionTab === 'starters'" class="settings-group">
          <div class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agentEditor.questionSuggestions.enableStarters') }}</label>
              <p class="desc">{{ $t('agentEditor.questionSuggestions.enableStartersDesc') }}</p>
            </div>
            <div class="setting-control">
              <t-switch v-model="formData.config.question_suggestions.starters.enabled"
                :aria-label="$t('agentEditor.questionSuggestions.enableStarters')" />
            </div>
          </div>

          <div v-if="formData.config.question_suggestions.starters.enabled" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agentEditor.questionSuggestions.sourceMode') }}</label>
            </div>
            <div class="setting-control">
              <t-select v-model="formData.config.question_suggestions.starters.mode"
                :options="starterSuggestionModeOptions" />
            </div>
          </div>

          <div v-if="formData.config.question_suggestions.starters.enabled" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agentEditor.questionSuggestions.count') }}</label>
            </div>
            <div class="setting-control">
              <t-input-number v-model="formData.config.question_suggestions.starters.count"
                :min="1" :max="8" theme="column" />
            </div>
          </div>

          <div
            v-if="formData.config.question_suggestions.starters.enabled && ['curated', 'hybrid'].includes(formData.config.question_suggestions.starters.mode)"
            class="setting-row setting-row-vertical">
            <div class="setting-info">
              <div class="setting-info-header setting-info-header--inline">
                <label>{{ $t('agentEditor.questionSuggestions.curatedItems') }}</label>
                <span class="curated-items-count">
                  {{ formData.config.question_suggestions.starters.items.length }}/8
                </span>
              </div>
              <p class="desc">{{ $t('agentEditor.questionSuggestions.curatedItemsDesc') }}</p>
            </div>
            <div class="setting-control setting-control-full">
              <div class="suggested-prompts-list">
                <div v-for="(_prompt, index) in formData.config.question_suggestions.starters.items"
                  :key="index" class="prompt-item">
                  <t-input v-model="formData.config.question_suggestions.starters.items[index]"
                    :maxlength="200" />
                  <t-button variant="text" theme="danger" shape="square"
                    :aria-label="$t('common.delete')" @click="removeStarterSuggestion(Number(index))">
                    <t-icon name="delete" />
                  </t-button>
                </div>
                <t-button variant="dashed"
                  :disabled="formData.config.question_suggestions.starters.items.length >= 8"
                  @click="addStarterSuggestion">
                  <template #icon><t-icon name="add" /></template>
                  {{ $t('agentEditor.questionSuggestions.addItem') }}
                </t-button>
              </div>
            </div>
          </div>
        </div>

        <div v-show="suggestionTab === 'followUps'" class="settings-group">
          <div class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agentEditor.questionSuggestions.enableFollowUps') }}</label>
              <p class="desc">{{ $t('agentEditor.questionSuggestions.enableFollowUpsDesc') }}</p>
            </div>
            <div class="setting-control">
              <t-switch v-model="formData.config.question_suggestions.follow_ups.enabled"
                :aria-label="$t('agentEditor.questionSuggestions.enableFollowUps')" />
            </div>
          </div>

          <template v-if="formData.config.question_suggestions.follow_ups.enabled">
            <div class="setting-row">
              <div class="setting-info">
                <label>{{ $t('agentEditor.questionSuggestions.sourceMode') }}</label>
              </div>
              <div class="setting-control">
                <t-select v-model="formData.config.question_suggestions.follow_ups.mode"
                  :options="followUpSuggestionModeOptions" />
              </div>
            </div>

            <div class="setting-row">
              <div class="setting-info">
                <label>{{ $t('agentEditor.questionSuggestions.count') }}</label>
              </div>
              <div class="setting-control">
                <t-input-number v-model="formData.config.question_suggestions.follow_ups.count"
                  :min="1" :max="5" theme="column" />
              </div>
            </div>

            <div v-if="formData.config.question_suggestions.follow_ups.mode !== 'knowledge'"
              class="setting-row">
              <div class="setting-info">
                <label>{{ $t('agentEditor.questionSuggestions.model') }}</label>
                <p class="desc">{{ $t('agentEditor.questionSuggestions.modelDesc') }}</p>
              </div>
              <div class="setting-control">
                <ModelSelector model-type="KnowledgeQA"
                  :selected-model-id="formData.config.question_suggestions.follow_ups.model_id"
                  :all-models="allModels"
                  clearable
                  @update:selected-model-id="(val: string) => formData.config.question_suggestions.follow_ups.model_id = val"
                  @add-model="handleAddModel('summary')" />
              </div>
            </div>

            <div class="suggestion-advanced-divider">
              <span>{{ $t('agentEditor.questionSuggestions.advancedSettings') }}</span>
            </div>

            <div class="setting-row">
              <div class="setting-info">
                <label>{{ $t('agentEditor.questionSuggestions.contextTurns') }}</label>
              </div>
              <div class="setting-control">
                <t-input-number
                  v-model="formData.config.question_suggestions.follow_ups.max_context_turns"
                  :min="1" :max="5" theme="column" />
              </div>
            </div>

            <div class="setting-row setting-row-vertical">
              <div class="setting-info">
                <label>{{ $t('agentEditor.questionSuggestions.categories') }}</label>
              </div>
              <div class="setting-control setting-control-full">
                <t-checkbox-group v-model="formData.config.question_suggestions.follow_ups.categories"
                  :options="followUpCategoryOptions" />
              </div>
            </div>

            <div class="setting-row setting-row-vertical">
              <div class="setting-info">
                <label>{{ $t('agentEditor.questionSuggestions.instruction') }}</label>
              </div>
              <div class="setting-control setting-control-full">
                <t-textarea
                  v-model="formData.config.question_suggestions.follow_ups.additional_instruction"
                  :placeholder="$t('agentEditor.questionSuggestions.instructionPlaceholder')"
                  :maxlength="2000" :autosize="{ minRows: 3, maxRows: 8 }" />
              </div>
            </div>

            <div class="setting-row setting-row-vertical">
              <div class="setting-info">
                <label>{{ $t('agentEditor.questionSuggestions.displayRules') }}</label>
              </div>
              <div class="setting-control setting-control-full">
                <div class="suggestion-checkboxes">
                  <t-checkbox v-model="formData.config.question_suggestions.follow_ups.suppress_on_fallback">{{ $t('agentEditor.questionSuggestions.suppressFallback') }}</t-checkbox>
                  <t-checkbox v-model="formData.config.question_suggestions.follow_ups.suppress_when_answer_asks_question">{{ $t('agentEditor.questionSuggestions.suppressQuestion') }}</t-checkbox>
                  <t-checkbox v-model="formData.config.question_suggestions.follow_ups.knowledge_fallback">{{ $t('agentEditor.questionSuggestions.knowledgeFallback') }}</t-checkbox>
                  <t-checkbox v-model="formData.config.question_suggestions.follow_ups.allow_regenerate">{{ $t('agentEditor.questionSuggestions.allowRegenerate') }}</t-checkbox>
                </div>
              </div>
            </div>
          </template>
        </div>
      </div>

      <!-- 工具配置(仅 Agent 模式) -->
      <div v-show="currentSection === 'tools' && isAgentMode" class="section">
        <div class="section-header">
          <h2>{{ $t('agent.editor.toolsConfig') }}</h2>
          <p class="section-description">{{ $t('agent.editor.toolsConfigDesc') }}</p>
        </div>

        <!-- 合并面板:能力状态 + 预设切换 -->
        <div class="tools-overview">
          <div class="tools-overview-row">
            <div class="tools-status-chip">
              <t-icon name="folder" />
              <template v-if="kbSelectionMode === 'none'">
                <span>{{ $t('agentEditor.tools.statusNoKb') }}</span>
              </template>
              <template v-else>
                <span class="tools-status-metric">
                  <strong>{{ ragKbCount }}</strong> {{ $t('agentEditor.tools.kbMetricRag') }}
                </span>
                <span class="tools-status-sep">·</span>
                <span class="tools-status-metric">
                  <strong>{{ wikiKbCount }}</strong> {{ $t('agentEditor.tools.kbMetricWiki') }}
                </span>
              </template>
            </div>
            <div v-if="inactiveToolCount > 0" class="tools-status-chip tools-status-chip--warn">
              <t-icon name="error-circle" />
              <span>{{ $t('agentEditor.tools.statusInactive', { count: inactiveToolCount }) }}</span>
            </div>
          </div>
        </div>

        <div class="settings-group">
          <!-- 允许的工具(按组渲染,统一网格) -->
          <div
            class="setting-row setting-row-vertical"
            data-agent-field="allowed_tools"
            :class="{ 'setting-row--field-highlight': highlightedField === 'allowed_tools' }"
          >
            <div class="setting-info">
              <label>{{ $t('agent.editor.allowedTools') }}</label>
              <p class="desc">{{ $t('agentEditor.desc.selectTools') }}</p>
            </div>
            <div class="setting-control setting-control-full">
              <t-checkbox-group v-model="formData.config.allowed_tools" class="tool-groups">
                <section v-for="group in groupedAvailableTools" :key="group.key"
                  :class="['tool-group', `tool-group--${group.key}`]">
                  <header class="tool-group-header">
                    <span class="tool-group-bar" />
                    <span class="tool-group-title">{{ group.label }}</span>
                    <span class="tool-group-count">{{ group.tools.length }}</span>
                    <span v-if="group.key === 'wiki_edit'" class="tool-group-warning">
                      <t-icon name="error-circle" />
                      {{ $t('agentEditor.tools.writeWarning') }}
                    </span>
                  </header>
                  <div class="tool-grid">
                    <t-checkbox v-for="tool in group.tools" :key="tool.value" :value="tool.value"
                      :disabled="tool.disabled"
                      :class="['tool-card', { 'tool-card--disabled': tool.disabled, 'tool-card--danger': tool.danger }]">
                      <div class="tool-card-body">
                        <div class="tool-card-head">
                          <span class="tool-card-name">{{ tool.label }}</span>
                          <span v-if="tool.danger" class="tool-card-badge">
                            {{ $t('agentEditor.tools.dangerTag') }}
                          </span>
                        </div>
                        <span v-if="tool.description" class="tool-card-desc">{{ tool.description }}</span>
                        <span v-if="tool.unmet && tool.disabledReason" class="tool-card-hint">
                          {{ tool.disabledReason }}
                        </span>
                      </div>
                    </t-checkbox>
                  </div>
                </section>
                <section v-if="storedExtras.length > 0" class="tool-group tool-group--stored">
                  <header class="tool-group-header">
                    <span class="tool-group-bar" />
                    <span class="tool-group-title">{{ $t('agentEditor.tools.groupStored') }}</span>
                    <span class="tool-group-count">{{ storedExtras.length }}</span>
                  </header>
                  <div class="tool-grid">
                    <t-checkbox v-for="extra in storedExtras" :key="extra.value" :value="extra.value"
                      :disabled="extra.disabled"
                      :class="['tool-card', { 'tool-card--disabled': extra.disabled }]">
                      <div class="tool-card-body">
                        <div class="tool-card-head">
                          <span class="tool-card-name">{{ extra.value }}</span>
                        </div>
                        <span class="tool-card-desc">
                          {{ extra.kind === 'switch_managed'
                            ? $t('agentEditor.tools.switchManagedDesc')
                            : $t('agentEditor.tools.unrecognizedDesc') }}
                        </span>
                      </div>
                    </t-checkbox>
                  </div>
                </section>
              </t-checkbox-group>
            </div>
          </div>

          <!-- 有效工具预览:所见即所得 -->
          <div class="setting-row setting-row-vertical">
            <div class="setting-info">
              <label>{{ $t('agentEditor.tools.effectiveLabel') }}</label>
              <p class="desc">{{ $t('agentEditor.tools.effectiveDesc') }}</p>
            </div>
            <div class="setting-control setting-control-full">
              <div class="effective-tools">
                <template v-if="effectiveTools.length === 0">
                  <div class="effective-tools-empty">
                    {{ $t('agentEditor.tools.effectiveEmpty') }}
                  </div>
                </template>
                <template v-else>
                  <span v-for="item in effectiveTools" :key="item.value"
                    :class="['effective-chip', { 'effective-chip--inactive': !item.active }]"
                    :title="item.reason || ''">
                    <span class="effective-chip-label">{{ item.label }}</span>
                    <span v-if="!item.active" class="effective-chip-reason">{{ item.reason }}</span>
                  </span>
                </template>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- MCP 服务配置(仅 Agent 模式) -->
      <div v-show="currentSection === 'mcp' && isAgentMode" class="section">
        <div class="section-header">
          <h2>{{ $t('agentEditor.mcp.label') }}</h2>
          <p class="section-description">{{ $t('agentEditor.mcp.desc') }}</p>
        </div>

        <div class="settings-group">
          <!-- MCP 服务选择 -->
          <div class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agentEditor.mcp.label') }}</label>
              <p class="desc">{{ $t('agentEditor.mcp.desc') }}</p>
            </div>
            <div class="setting-control">
              <t-radio-group v-model="mcpSelectionMode">
                <t-radio-button value="all">{{ $t('agentEditor.selection.all') }}</t-radio-button>
                <t-radio-button value="selected">{{ $t('agentEditor.selection.selected') }}</t-radio-button>
                <t-radio-button value="none">{{ $t('agentEditor.selection.disabled') }}</t-radio-button>
              </t-radio-group>
            </div>
          </div>

          <!-- 选择指定 MCP 服务 -->
          <div v-if="mcpSelectionMode === 'selected' && showMcpServiceSelect" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agentEditor.mcp.selectLabel') }}</label>
              <p class="desc">{{ $t('agentEditor.mcp.selectDesc') }}</p>
            </div>
            <div class="setting-control">
              <t-select v-model="formData.config.mcp_services" multiple
                :placeholder="$t('agentEditor.mcp.selectPlaceholder')" filterable>
                <t-option v-for="mcp in mcpOptions" :key="mcp.value" :value="mcp.value" :label="mcp.label"
                  :disabled="mcp.disabled" />
              </t-select>
            </div>
          </div>

          <!-- 授权等待超时:对话中触发 OAuth 授权时的等待秒数 -->
          <div v-if="mcpSelectionMode !== 'none'" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agentEditor.mcp.authWaitTimeout') }}</label>
              <p class="desc">{{ $t('agentEditor.mcp.authWaitTimeoutDesc') }}</p>
            </div>
            <div class="setting-control">
              <t-input-number v-model="formData.config.mcp_auth_wait_timeout" :min="5" :max="3600"
                theme="column" :placeholder="$t('agentEditor.mcp.authWaitTimeoutPlaceholder')" />
            </div>
          </div>

          <!-- 执行权限上限:修改数据的工具(MCP、Wiki 写入)能否不经确认直接执行 -->
          <div class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agentEditor.mcp.accessLevel') }}</label>
              <p class="desc">{{ $t('agentEditor.mcp.accessLevelDesc') }}</p>
            </div>
            <div class="setting-control">
              <t-select v-model="formData.config.access_level">
                <t-option v-for="level in ASSISTANT_ACCESS_LEVELS" :key="level" :value="level"
                  :label="$t(`assistant.access.levels.${level}.label`)" />
              </t-select>
            </div>
          </div>
        </div>
      </div>

      <!-- 技能:脚本跑在所选沙箱里,可用列表也来自这份配置 -->
      <div v-show="currentSection === 'skills' && isAgentMode" class="section">
        <div class="section-header">
          <h2>{{ $t('agent.editor.skillsConfig') }}</h2>
          <p class="section-description">{{ hostOnly ? $t('agent.editor.hostSkillsConfigDesc') : $t('agent.editor.skillsConfigDesc') }}</p>
        </div>

        <div class="settings-group">
          <div v-if="!hostOnly" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.sandboxBackend') }}</label>
              <p class="desc">{{ $t('agent.editor.sandboxBackendHint') }}</p>
            </div>
            <div class="setting-control sandbox-select-control">
              <t-select
                v-model="formData.config.sandbox_config_id"
                :placeholder="$t('agent.editor.sandboxBackendDefault')"
                class="sandbox-config-select"
                filterable
                :popup-props="{ overlayClassName: 'sandbox-config-select-popup' }"
              >
                <t-option value="" :label="$t('agent.editor.sandboxBackendDefault')" />
                <t-option
                  v-for="cfg in sandboxConfigOptions"
                  :key="cfg.id"
                  :value="cfg.id"
                  :label="cfg.name"
                >
                  <div class="sandbox-option">
                    <div class="sandbox-option__row">
                      <span class="sandbox-option__name">{{ cfg.name }}</span>
                      <span v-if="cfg.sandbox_type" class="sandbox-option__type">{{ backendLabel(cfg.sandbox_type) }}</span>
                    </div>
                    <div v-if="sandboxTargetLine(cfg)" class="sandbox-option__target">{{ sandboxTargetLine(cfg) }}</div>
                  </div>
                </t-option>
              </t-select>
              <p v-if="selectedSandboxSummary" class="sandbox-selected-meta">{{ selectedSandboxSummary }}</p>
              <div class="sandbox-select-links">
                <a href="javascript:void(0)" class="go-settings-link"
                  @click.prevent="uiStore.openSettings('sandbox')">
                  {{ $t('agent.editor.goSandboxSettings') }}
                </a>
                <template v-if="hasSandboxSelected && canInstallSkills">
                  <span class="sandbox-select-links__sep" aria-hidden="true">·</span>
                  <a
                    href="javascript:void(0)"
                    class="go-settings-link"
                    @click.prevent="openSkillSettings"
                  >
                    {{ $t('agent.editor.goSkillSettings') }}
                  </a>
                </template>
              </div>
              <p v-if="sandboxConfigOptions.length === 0" class="desc empty-hint">
                {{ $t('agent.editor.sandboxNoConfigs') }}
              </p>
            </div>
          </div>

          <div class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.skillsSelection') }}</label>
              <p class="desc">{{ skillsSelectionHint }}</p>
            </div>
            <div class="setting-control sandbox-select-control">
              <t-radio-group v-model="skillsSelectionMode">
                <t-radio-button value="all" :disabled="!canEnableSkills">{{ $t('agent.editor.skillsAll') }}</t-radio-button>
                <t-radio-button value="selected" :disabled="!canEnableSkills">{{ $t('agent.editor.skillsSelected') }}</t-radio-button>
                <t-radio-button value="none">{{ $t('agent.editor.skillsNone') }}</t-radio-button>
              </t-radio-group>
              <p v-if="!hasSandboxSelected && sandboxConfigOptions.length > 1" class="desc empty-hint">
                {{ $t('agent.editor.skillsNeedSandbox') }}
              </p>
              <p v-else-if="hasSandboxSelected && skillCatalog.length === 0" class="desc empty-hint">
                <span>{{ $t('agent.editor.noSkillsAvailable') }}</span>
                <a
                  v-if="canInstallSkills"
                  href="javascript:void(0)"
                  class="go-settings-link"
                  @click.prevent="openSkillSettings"
                >
                  {{ $t('agent.editor.goSkillSettings') }}
                </a>
              </p>
            </div>
          </div>

          <div v-if="showCatalogSkillList" class="setting-row setting-row-vertical">
            <div class="setting-control setting-control-full">
              <t-checkbox-group
                v-model="formData.config.selected_skills"
                class="skill-pick-list"
              >
                <section
                  v-for="group in catalogSkillGroups"
                  :key="group.key"
                  class="skill-pick-group"
                  :class="`skill-pick-group--${group.key}`"
                >
                  <header class="skill-pick-group__header">
                    <span class="skill-pick-group__bar" />
                    <span class="skill-pick-group__title">{{ group.label }}</span>
                    <span class="skill-pick-group__count">{{ group.skills.length }}</span>
                  </header>
                  <article
                    v-for="skill in group.skills"
                    :key="skill.name"
                    class="skill-pick"
                    :class="{
                      'skill-pick--ready': skill.selectable,
                      'skill-pick--pending': !skill.selectable,
                      'skill-pick--busy': isSkillBusy(skill),
                    }"
                  >
                    <t-checkbox
                      v-if="skillsSelectionMode === 'selected'"
                      :value="skill.name"
                      :disabled="!skill.selectable"
                      class="skill-pick__check"
                    />
                    <div class="skill-pick__badge" aria-hidden="true">
                      <t-icon :name="SKILL_ICON" size="16px" />
                    </div>
                    <div class="skill-pick__body">
                      <div class="skill-pick__title-row">
                        <span class="skill-name" :title="skill.name">{{ skill.name }}</span>
                        <span
                          v-if="!skill.selectable"
                          class="skill-pick__hint"
                          :class="{ 'skill-pick__hint--busy': isSkillBusy(skill) }"
                        >
                          <t-icon :name="skillStatusIcon(skill)" size="14px" />
                          {{ skillStatusHint(skill) }}
                        </span>
                        <span
                          v-if="skill.selectable && skill.servedNote"
                          class="skill-pick__hint"
                          :class="{ 'skill-pick__hint--busy': isSkillBusy(skill) }"
                        >
                          <t-icon :name="isSkillBusy(skill) ? 'refresh' : 'error-circle'" size="14px" />
                          {{ skill.servedNote }}
                        </span>
                        <span
                          v-if="canUpgradeSkillRow(skill)"
                          class="skill-pick__hint skill-pick__hint--upgrade"
                        >
                          <t-icon name="arrow-up" size="14px" />
                          {{ skillUpgradeHint(skill) }}
                        </span>
                      </div>
                      <p
                        v-if="skill.description"
                        class="skill-desc"
                        :title="skill.description"
                      >{{ skill.description }}</p>
                    </div>
                    <t-button
                      v-if="canInstallSkillRow(skill)"
                      size="small"
                      variant="text"
                      theme="primary"
                      :loading="installingCatalogId === skill.id"
                      :title="installsAnUpgrade(skill) ? (hostOnly ? $t('agent.editor.hostUpgradeOnThisComputer') : $t('agent.editor.upgradeOnThisSandbox')) : (hostOnly ? $t('agent.editor.hostInstallToThisComputer') : $t('agent.editor.installToThisSandbox'))"
                      @click.stop="installCatalogToCurrent(skill)"
                    >
                      {{ installsAnUpgrade(skill) ? $t('settings.skills.upgrade') : $t('agent.editor.installShort') }}
                    </t-button>
                    <t-button
                      v-else-if="canUpgradeSkillRow(skill)"
                      size="small"
                      variant="text"
                      theme="primary"
                      :loading="installingCatalogId === skill.id"
                      :title="hostOnly ? $t('agent.editor.hostUpgradeOnThisComputer') : $t('agent.editor.upgradeOnThisSandbox')"
                      @click.stop="installCatalogToCurrent(skill)"
                    >
                      {{ $t('settings.skills.upgrade') }}
                    </t-button>
                    <t-button
                      v-else-if="canInstallSkills && isSkillBusy(skill)"
                      size="small"
                      variant="text"
                      theme="primary"
                      :title="$t('agent.editor.viewInstallProgress')"
                      @click.stop="openSkillInstallProgress(skill)"
                    >
                      {{ $t('agent.editor.viewInstallProgress') }}
                    </t-button>
                  </article>
                </section>
              </t-checkbox-group>
            </div>
          </div>
        </div>
      </div>

      <!-- 知识库配置 -->
      <div v-show="currentSection === 'knowledge'" class="section">
        <div class="section-header">
          <h2>{{ $t('agent.editor.knowledgeConfig') }}</h2>
          <p class="section-description">{{ $t('agent.editor.knowledgeConfigDesc') }}</p>
        </div>

        <div class="settings-group">
          <!-- 关联知识库 -->
          <div class="setting-row" data-guide="agent-create-knowledge">
            <div class="setting-info">
              <label>{{ $t('agent.editor.knowledgeBases') }}</label>
              <p class="desc">{{ $t('agentEditor.desc.kbScope') }}</p>
            </div>
            <div class="setting-control">
              <t-radio-group v-model="kbSelectionMode">
                <t-radio-button value="all">{{ $t('agent.editor.allKnowledgeBases') }}</t-radio-button>
                <t-radio-button value="selected">{{ $t('agent.editor.selectedKnowledgeBases')
                  }}</t-radio-button>
                <t-radio-button value="none">{{ $t('agent.editor.noKnowledgeBase') }}</t-radio-button>
              </t-radio-group>
            </div>
          </div>

          <!-- 选择指定知识库(仅在选择"指定知识库"时显示) -->
          <div v-if="kbSelectionMode === 'selected'" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.selectKnowledgeBases') }}</label>
              <p class="desc">{{ $t('agent.editor.selectKnowledgeBasesDesc') }}</p>
            </div>
            <div class="setting-control">
              <t-select v-model="formData.config.knowledge_bases" multiple
                :placeholder="$t('agent.editor.selectKnowledgeBases')" filterable :min-collapsed-num="3">
                <t-option-group v-if="filteredMyKbOptions.length"
                  :label="$t('agent.editor.myKnowledgeBases')">
                  <t-option v-for="kb in filteredMyKbOptions" :key="kb.value" :value="kb.value"
                    :label="kb.label" :disabled="kb.disabled">
                    <div class="kb-option-item" :title="kb.disabled ? kb.disabledReason : ''">
                      <span class="kb-option-icon" :class="kb.type === 'faq' ? 'faq-icon' : 'doc-icon'">
                        <t-icon :name="kb.type === 'faq' ? 'chat-bubble-help' : 'folder'" />
                      </span>
                      <span class="kb-option-label">{{ kb.label }}</span>
                      <span v-if="kb.ragEnabled" class="kb-option-tag tag-rag">RAG</span>
                      <span v-if="kb.wikiEnabled" class="kb-option-tag tag-wiki">Wiki</span>
                      <span class="kb-option-count">{{ kb.count || 0 }}</span>
                      <span v-if="kb.disabled" class="kb-option-disabled-hint">{{ kb.disabledReason }}</span>
                    </div>
                  </t-option>
                </t-option-group>
                <t-option-group v-if="filteredSharedKbOptions.length"
                  :label="$t('agent.editor.sharedKnowledgeBases')">
                  <t-option v-for="kb in filteredSharedKbOptions" :key="kb.value" :value="kb.value"
                    :label="kb.label" :disabled="kb.disabled">
                    <div class="kb-option-item" :title="kb.disabled ? kb.disabledReason : ''">
                      <span class="kb-option-icon" :class="kb.type === 'faq' ? 'faq-icon' : 'doc-icon'">
                        <t-icon :name="kb.type === 'faq' ? 'chat-bubble-help' : 'folder'" />
                      </span>
                      <span class="kb-option-label">{{ kb.label }}</span>
                      <span v-if="kb.ragEnabled" class="kb-option-tag tag-rag">RAG</span>
                      <span v-if="kb.wikiEnabled" class="kb-option-tag tag-wiki">Wiki</span>
                      <span v-if="kb.orgName" class="kb-option-org">{{ kb.orgName }}</span>
                      <span class="kb-option-count">{{ kb.count || 0 }}</span>
                      <span v-if="kb.disabled" class="kb-option-disabled-hint">{{ kb.disabledReason }}</span>
                    </div>
                  </t-option>
                </t-option-group>
              </t-select>
            </div>
          </div>

          <!-- 支持的文件类型(限制用户可选择的文件类型) -->
          <div v-if="hasKnowledgeBase" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agentEditor.fileTypes.label') }}</label>
              <p class="desc">{{ $t('agentEditor.fileTypes.desc') }}</p>
            </div>
            <div class="setting-control">
              <t-select v-model="formData.config.supported_file_types" multiple
                :placeholder="$t('agentEditor.fileTypes.allTypes')" :min-collapsed-num="3" clearable>
                <t-option v-for="ft in availableFileTypes" :key="ft.value" :value="ft.value"
                  :label="ft.label" />
              </t-select>
            </div>
          </div>

          <!-- 仅在提及时检索知识库(当配置了知识库时显示) -->
          <div v-if="hasKnowledgeBase" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.retrieveKBOnlyWhenMentioned') }}</label>
              <p class="desc">{{ $t('agent.editor.retrieveKBOnlyWhenMentionedDesc') }}</p>
            </div>
            <div class="setting-control">
              <t-switch v-model="formData.config.retrieve_kb_only_when_mentioned" />
            </div>
          </div>

        </div>
      </div>

      <!-- 网络搜索配置 -->
      <div v-show="currentSection === 'websearch'" class="section">
        <div class="section-header">
          <h2>{{ $t('agent.editor.webSearchConfig') }}</h2>
          <p class="section-description">{{ $t('agent.editor.webSearchConfigDesc') }}</p>
        </div>

        <div class="settings-group">
          <!-- 网络搜索 -->
          <div class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.webSearch') }}</label>
              <p class="desc">{{ $t('agentEditor.desc.webSearch') }}</p>
            </div>
            <div class="setting-control">
              <t-switch v-model="formData.config.web_search_enabled" />
            </div>
          </div>

          <!-- 网络搜索最大结果数 -->
          <div v-if="formData.config.web_search_enabled" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.webSearchProvider') }}</label>
              <p class="desc">{{ $t('agentEditor.desc.webSearchProvider') }}</p>
            </div>
            <div class="setting-control">
              <t-select v-model="formData.config.web_search_provider_id" clearable
                :placeholder="$t('agent.editor.webSearchProviderPlaceholder')" style="width: 240px;">
                <t-option v-for="p in webSearchProviderList" :key="p.id" :value="p.id" :label="p.name">
                  <span>{{ p.name }}</span>
                  <t-tag v-if="p.is_default" theme="primary" size="small" style="margin-left: 6px;">{{
                    $t('common.default')
                    }}</t-tag>
                </t-option>
              </t-select>
            </div>
          </div>

          <!-- 网络搜索最大结果数 -->
          <div v-if="formData.config.web_search_enabled" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.webSearchMaxResults') }}</label>
              <p class="desc">{{ $t('agentEditor.desc.webSearchMaxResults') }}</p>
            </div>
            <div class="setting-control">
              <div class="slider-wrapper">
                <t-slider v-model="formData.config.web_search_max_results" :min="1" :max="10" />
                <span class="slider-value">{{ formData.config.web_search_max_results }}</span>
              </div>
            </div>
          </div>

          <!-- 自动抓取页面内容 -->
          <div v-if="formData.config.web_search_enabled" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.webFetchEnabled') }}</label>
              <p class="desc">{{ $t('agentEditor.desc.webFetchEnabled') }}</p>
            </div>
            <div class="setting-control">
              <t-switch v-model="formData.config.web_fetch_enabled" />
            </div>
          </div>

          <!-- 抓取页面数 -->
          <div v-if="formData.config.web_search_enabled && formData.config.web_fetch_enabled"
            class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.webFetchTopN') }}</label>
              <p class="desc">{{ $t('agentEditor.desc.webFetchTopN') }}</p>
            </div>
            <div class="setting-control">
              <div class="slider-wrapper">
                <t-slider v-model="formData.config.web_fetch_top_n" :min="1" :max="10" />
                <span class="slider-value">{{ formData.config.web_fetch_top_n }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 检索策略(仅普通模式且有知识库能力时显示;Agent 模式的 search_knowledge
           使用全局检索配置,这里的设置对它不生效) -->
      <div v-show="currentSection === 'retrieval' && hasKnowledgeBase && !isAgentMode" class="section">
        <div class="section-header">
          <h2>{{ $t('agent.editor.retrievalStrategy') }}</h2>
          <p class="section-description">{{ $t('agentEditor.desc.retrievalSection') }}</p>
        </div>

        <div class="settings-group">
          <!-- 查询扩展(仅普通模式) -->
          <div v-if="!isAgentMode" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.enableQueryExpansion') }}</label>
              <p class="desc">{{ $t('agentEditor.desc.queryExpansion') }}</p>
            </div>
            <div class="setting-control">
              <t-switch v-model="formData.config.enable_query_expansion" />
            </div>
          </div>

          <!-- 向量召回TopK -->
          <div class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.embeddingTopK') }}</label>
              <p class="desc">{{ $t('agentEditor.desc.embeddingTopK') }}</p>
            </div>
            <div class="setting-control">
              <t-input-number v-model="formData.config.embedding_top_k" :min="1" :max="50" theme="column" />
            </div>
          </div>

          <!-- 关键词阈值 -->
          <div class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.keywordThreshold') }}</label>
              <p class="desc">{{ $t('agentEditor.desc.keywordThreshold') }}</p>
            </div>
            <div class="setting-control">
              <div class="slider-wrapper">
                <t-slider v-model="formData.config.keyword_threshold" :min="0" :max="1" :step="0.01" />
                <span class="slider-value">{{ formData.config.keyword_threshold?.toFixed(2) }}</span>
              </div>
            </div>
          </div>

          <!-- 向量阈值 -->
          <div class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.vectorThreshold') }}</label>
              <p class="desc">{{ $t('agentEditor.desc.vectorThreshold') }}</p>
            </div>
            <div class="setting-control">
              <div class="slider-wrapper">
                <t-slider v-model="formData.config.vector_threshold" :min="0" :max="1" :step="0.01" />
                <span class="slider-value">{{ formData.config.vector_threshold?.toFixed(2) }}</span>
              </div>
            </div>
          </div>

          <!-- 重排TopK(仅在配置了 Rerank 模型时展示) -->
          <div v-if="formData.config.rerank_model_id" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.rerankTopK') }}</label>
              <p class="desc">{{ $t('agentEditor.desc.rerankTopK') }}</p>
            </div>
            <div class="setting-control">
              <t-input-number v-model="formData.config.rerank_top_k" :min="1" :max="20" theme="column" />
            </div>
          </div>

          <!-- 重排阈值(仅在配置了 Rerank 模型时展示) -->
          <div v-if="formData.config.rerank_model_id" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agent.editor.rerankThreshold') }}</label>
              <p class="desc">{{ $t('agentEditor.desc.rerankThreshold') }}</p>
            </div>
            <div class="setting-control">
              <div class="slider-wrapper">
                <t-slider v-model="formData.config.rerank_threshold" :min="-10" :max="10" :step="0.01" />
                <span class="slider-value">{{ formData.config.rerank_threshold?.toFixed(1) }}</span>
              </div>
            </div>
          </div>

          <!-- FAQ 优先策略(关联 FAQ 类型知识库时显示) -->
          <div v-if="hasFaqKnowledgeBase" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agentEditor.faq.enableLabel') }}</label>
              <p class="desc">{{ $t('agentEditor.faq.enableDesc') }}</p>
            </div>
            <div class="setting-control">
              <t-switch v-model="formData.config.faq_priority_enabled" />
            </div>
          </div>

          <div v-if="hasFaqKnowledgeBase && formData.config.faq_priority_enabled" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agentEditor.faq.thresholdLabel') }}</label>
              <p class="desc">{{ $t('agentEditor.faq.thresholdDesc') }}</p>
            </div>
            <div class="setting-control">
              <div class="slider-wrapper">
                <t-slider v-model="formData.config.faq_direct_answer_threshold" :min="0.7" :max="1"
                  :step="0.05" />
                <span class="slider-value">{{ formData.config.faq_direct_answer_threshold?.toFixed(2)
                  }}</span>
              </div>
            </div>
          </div>

          <div v-if="hasFaqKnowledgeBase && formData.config.faq_priority_enabled" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agentEditor.faq.boostLabel') }}</label>
              <p class="desc">{{ $t('agentEditor.faq.boostDesc') }}</p>
            </div>
            <div class="setting-control">
              <div class="slider-wrapper">
                <t-slider v-model="formData.config.faq_score_boost" :min="1" :max="2" :step="0.1" />
                <span class="slider-value">{{ formData.config.faq_score_boost?.toFixed(1) }}x</span>
              </div>
            </div>
          </div>

          <!-- 表格数据分析(仅普通模式,命中 CSV/Excel 时会多一次 LLM 调用生成 SQL) -->
          <div v-if="!isAgentMode" class="setting-row">
            <div class="setting-info">
              <label>{{ $t('agentEditor.dataAnalysis.enableLabel') }}</label>
              <p class="desc">{{ $t('agentEditor.dataAnalysis.enableDesc') }}</p>
            </div>
            <div class="setting-control">
              <t-switch v-model="formData.config.data_analysis_enabled" />
            </div>
          </div>
        </div>
      </div>

      <!-- 共享管理(仅编辑模式且非内置智能体) -->
      <div v-if="editorMode === 'edit' && editorAgent?.id && !editorAgent?.is_builtin"
        v-show="currentSection === 'share'" class="section">
        <AgentShareSettings :agent-id="editorAgent.id" :agent="editorAgent" />
      </div>
    </div>

    <template #footer-note>
      <p v-if="isPostCreateSession" class="settings-footer-note">
        <t-icon name="check-circle-filled" class="settings-footer-note__icon" />
        <span>
          <strong>{{ $t('agent.editor.postCreateHint.title') }}</strong>
          {{ $t('agent.editor.postCreateHint.footer') }}
        </span>
      </p>
    </template>
    <template #footer>
      <t-button variant="outline" @click="modalShell.requestClose">
        {{ props.readOnly ? $t('common.close') : $t('common.cancel') }}
      </t-button>
      <t-button v-if="!props.readOnly" theme="primary" data-guide="agent-create-submit" :loading="saving"
        :disabled="editorInitializing" @click="handleSave">
        {{ saveButtonLabel }}
      </t-button>
    </template>
  </SettingsModalShell>

  <SettingDrawer
    v-model:visible="showSkillProgress"
    :title="skillProgressTitle"
    :description="skillProgressDesc"
    :icon="SKILL_ICON"
    width="680px"
    :min-width="560"
    :max-width="920"
    storage-key="setting-drawer:width:skill-catalog-manage"
    :hide-footer="true"
  >
    <SandboxSkillsPanel
      v-if="showSkillProgress && skillProgressRecord && skillProgressId"
      :record="skillProgressRecord"
      mode="list"
      hide-add
      :focus-skill-id="skillProgressId"
      @updated="onSkillProgressUpdated"
      @skills-changed="onSkillProgressChanged"
    />
  </SettingDrawer>

  <AgentCreateContextualGuide :when="visible && editorMode === 'create'" :is-agent-mode="isAgentMode" />
</template>

<script setup lang="ts">
import { useAssistantDataChange } from '@/utils/assistantDataChange';
import { ref, computed, watch, nextTick, onMounted, onBeforeUnmount } from 'vue';
import { useRouter } from 'vue-router';
import AgentCreateContextualGuide from '@/components/AgentCreateContextualGuide.vue';
import {
  AGENT_EDITOR_FOCUS_SECTION_EVENT,
  markContextualGuideDone,
} from '@/config/contextualGuides';
import { useI18n } from 'vue-i18n';
import { selectInitialModelId } from '@/utils/modelDefaults';
import { hydrateAgentPromptRefs, serializeAgentPrompts } from '@/utils/agentPromptTemplates';
import { copyWithToast } from '@/utils/clipboard';
import { MessagePlugin } from 'tdesign-vue-next';
import { useModalShell } from '@/composables/useModalShell'
import { useAssistantPageContext } from '@/composables/useAssistantPageContext'
import SettingsModalShell from '@/components/SettingsModalShell.vue'
import AssistantActionButton from '@/components/assistant/AssistantActionButton.vue'
import {
  createAgent,
  updateAgent,
  listIMChannels,
  type CustomAgent,
  type PlaceholderDefinition,
  type AgentTypePreset,
  type AgentToolCatalog,
  type AllowedToolsWarnings,
  type AgentType,
  type AgentTypeKBFilter,
  type KBCapabilities,
} from '@/api/agent';
import { type ModelConfig } from '@/api/model';
import { type AgentNotReadyReasonKey, agentRequiresRerankModel } from '@/utils/agent-readiness';
import { normalizeLegacyToolNames } from '@/utils/legacy-tool-names';
import { installSkillCatalog, type SkillCatalogItem } from '@/api/skill';
import { installUpgradable, servedPreviousText, upgradeVersions } from '@/utils/skillUpgrade';
import { type WebSearchProviderEntity } from '@/api/web-search-provider';
import {
  isNamedSandboxBackend,
  type SandboxConfigRecord,
  type StorageEngineStatusItem,
  type PromptTemplate,
  type PromptTemplatesConfig,
} from '@/api/system';
import { useUIStore } from '@/stores/ui';
import { useAuthStore } from '@/stores/auth';
import { useOrganizationStore } from '@/stores/organization';
import { useChatResourcesStore } from '@/stores/chatResources';
import { useDeploymentCapabilitiesStore } from '@/stores/deploymentCapabilities';
import { HOST_SKILL_TARGET_ID, hostSkillTargetRecord, hostSkillsOnly } from '@/utils/skillTarget';
import { useEditorResourcesStore } from '@/stores/editorResources';
import AgentAvatar from '@/components/AgentAvatar.vue';
import PromptTemplateSelector from '@/components/PromptTemplateSelector.vue';
import ModelSelector from '@/components/ModelSelector.vue';
import SandboxSkillsPanel from '@/components/SandboxSkillsPanel.vue';
import SettingDrawer from '@/components/settings/SettingDrawer.vue';
import KBParserSettings, { type ParserEngineRule } from '@/views/knowledge/settings/KBParserSettings.vue';
import AgentShareSettings from '@/components/AgentShareSettings.vue';
import { SKILL_ICON } from '@/types/mention';
import { listEmbedChannels } from '@/api/embed';
import { ASSISTANT_ACCESS_LEVELS, type AssistantAccessLevel } from '@/api/assistant';
import { getRootZoom, rectToCssPx } from '@/utils/zoom';
import { integrationSectionKey } from '@/config/settingsRoute';
import { toolboxLocation } from '@/config/toolbox';
import {
  deriveKbFilterFromTools,
  type RequirementMissKind,
  type ScopeCapabilities,
} from '@/utils/tool-capabilities';
import {
  allowedToolsToSave as allowedToolsForSave,
  buildToolOptions,
  effectiveToolSelection,
  resolveLoadedAllowedTools,
  storedExtraTools,
  type ToolText,
} from '@/utils/agent-tool-list';
import {
  clampLevel,
  levelDescriptionKey,
  levelEnablesThinking,
  levelFromLegacy,
  levelLabelKey,
  modelCanThink,
  modelCannotDisableThinking,
  optionsFor,
  type ReasoningLevel,
} from '@/utils/reasoningEffort';

// File extensions offered in the agent-level chat attachment parsing policy.
const CHAT_PARSER_EXTENSIONS = [
  'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'epub', 'mhtml',
  'txt', 'md', 'markdown', 'csv', 'json', 'xml', 'html', 'yaml', 'yml', 'log',
  'jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'webp',
];

const uiStore = useUIStore();
const authStore = useAuthStore();
const deploymentCapabilities = useDeploymentCapabilitiesStore();
const router = useRouter();
const orgStore = useOrganizationStore();
const chatResources = useChatResourcesStore();
const editorResources = useEditorResourcesStore();

const { t, locale: i18nLocale } = useI18n();

const props = defineProps<{
  visible: boolean;
  mode: 'create' | 'edit';
  agent?: CustomAgent | null;
  initialSection?: string;
  initialHighlightField?: string;
  // readOnly hides the save button so a Viewer who clicks an agent
  // card to inspect its config doesn't see a "确定" that 403s on the
  // backend update endpoint. Field-level disable is intentionally NOT
  // wired here yet (the modal has 3000+ lines of form inputs); instead
  // we just remove the only mutation surface — the footer button.
  readOnly?: boolean;
}>();

const emit = defineEmits<{
  (e: 'update:visible', visible: boolean): void;
  (e: 'success', agent?: CustomAgent): void;
}>();

/** 首次保存创建成功后留在弹窗内,用本地状态切换到编辑模式以展示 IM / 嵌入等入口 */
const savedAgent = ref<CustomAgent | null>(null);
const editorMode = computed(() => (savedAgent.value ? 'edit' : props.mode));
const editorAgent = computed(() => savedAgent.value ?? props.agent ?? null);
const isPostCreateSession = computed(() => !!savedAgent.value);

useAssistantDataChange((changes) => {
  const agentId = editorAgent.value?.id;
  if (!props.visible || !agentId) return;
  const relevant = changes.filter(change => change.ids.agentIds.includes(agentId)
    && change.operation !== 'agent.copy');
  if (!relevant.length) return;
  const deleted = relevant.some(change => change.operation === 'agent.delete');
  MessagePlugin.warning(t(deleted ? 'agent.editor.assistantDeleted' : 'agent.editor.assistantChanged'));
}, { areas: ['agent'] });

const saveButtonLabel = computed(() =>
  editorMode.value === 'create'
    ? t('agent.editor.buttons.create')
    : t('agent.editor.buttons.saveAndClose')
);

const copyAgentId = async () => {
  await copyWithToast(editorAgent.value?.id, 'common.copied');
};

// 旧入口把技能沙箱拆成独立 tab;合并后仍接受 section=sandbox。
const AGENT_EDITOR_SECTION_ALIASES: Record<string, string> = {
  sandbox: 'skills',
};

function resolveEditorSection(section?: string | null): string {
  const key = section || 'basic';
  return AGENT_EDITOR_SECTION_ALIASES[key] || key;
}

const currentSection = ref(resolveEditorSection(props.initialSection));
// Refines the agent AgentList publishes; on its own it names no page.
useAssistantPageContext(() => props.visible && props.mode === 'edit' ? { section: currentSection.value } : null);
const suggestionTab = ref<'starters' | 'followUps'>('starters');
const contentWrapperRef = ref<HTMLElement | null>(null);
const highlightedField = ref<AgentNotReadyReasonKey | null>(null);
let highlightClearTimer: ReturnType<typeof setTimeout> | null = null;

const VALID_HIGHLIGHT_FIELDS: AgentNotReadyReasonKey[] = ['summary_model', 'rerank_model', 'allowed_tools'];

const sectionForHighlightField = (field: AgentNotReadyReasonKey): string => {
  if (field === 'allowed_tools') return 'tools';
  return 'model';
};

const FIELD_FLASH_DURATION_MS = 2400;

const clearFieldHighlight = () => {
  if (highlightClearTimer) {
    clearTimeout(highlightClearTimer);
    highlightClearTimer = null;
  }
  highlightedField.value = null;
};

const applyInitialFieldHighlight = async (field: string) => {
  if (!VALID_HIGHLIGHT_FIELDS.includes(field as AgentNotReadyReasonKey)) return;

  const targetField = field as AgentNotReadyReasonKey;
  currentSection.value = sectionForHighlightField(targetField);

  await nextTick();
  await new Promise<void>((resolve) => {
    requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
  });

  clearFieldHighlight();
  highlightedField.value = null;

  const wrapper = contentWrapperRef.value;
  const row = wrapper?.querySelector(`[data-agent-field="${targetField}"]`) as HTMLElement | null;
  if (row && wrapper) {
    const rowTop = row.offsetTop;
    const scrollTarget = rowTop - wrapper.clientHeight / 2 + row.clientHeight / 2;
    wrapper.scrollTo({ top: Math.max(0, scrollTarget), behavior: 'auto' });

    await nextTick();
    await new Promise<void>((resolve) => {
      requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
    });
  }

  highlightedField.value = targetField;

  if (row) {
    const focusTarget = row.querySelector('.t-input, .t-select-input, input, .t-checkbox') as HTMLElement | null;
    focusTarget?.focus({ preventScroll: true });
  }

  highlightClearTimer = setTimeout(() => {
    if (highlightedField.value === targetField) {
      highlightedField.value = null;
    }
    highlightClearTimer = null;
  }, FIELD_FLASH_DURATION_MS);
};

const onAgentEditorFocusSection = (event: Event) => {
  const section = (event as CustomEvent<{ section?: string }>).detail?.section
  if (!section) return
  const resolved = resolveEditorSection(section)
  if (navItems.value.some((item) => item.key === resolved)) {
    currentSection.value = resolved
  }
}

onMounted(() => {
  window.addEventListener(AGENT_EDITOR_FOCUS_SECTION_EVENT, onAgentEditorFocusSection)
})

onBeforeUnmount(() => {
  window.removeEventListener(AGENT_EDITOR_FOCUS_SECTION_EVENT, onAgentEditorFocusSection)
})

const saving = ref(false);
const editorInitializing = ref(false);
const allModels = ref<ModelConfig[]>([]);
const kbOptions = ref<{ label: string; value: string; type?: 'document' | 'faq'; count?: number; shared?: boolean; orgName?: string; ragEnabled?: boolean; wikiEnabled?: boolean; capabilities?: KBCapabilities }[]>([]);

// 智能体类型预设(仅 smart-reasoning 模式下展示)
const agentTypePresets = ref<AgentTypePreset[]>([]);
// Agent 系统提示词模板缓存(用于切换智能体类型时根据 system_prompt_id 解析出实际文本填入)
const agentSystemPromptTemplates = ref<PromptTemplate[]>([]);
const promptTemplates = ref<PromptTemplatesConfig | null>(null);
const intentPromptTemplates = ref<PromptTemplate[]>([]);
type McpSelectOption = { label: string; value: string; disabled?: boolean };

const mcpOptions = computed<McpSelectOption[]>(() => {
  const services = editorResources.mcpServices || [];
  const selectedIds = new Set<string>(formData.value.config.mcp_services || []);
  const serviceById = new Map(services.map((mcp) => [mcp.id, mcp]));
  const options: McpSelectOption[] = [];

  for (const mcp of services) {
    if (mcp.enabled) {
      options.push({ label: mcp.name, value: mcp.id });
    }
  }

  for (const id of selectedIds) {
    const mcp = serviceById.get(id);
    if (mcp && !mcp.enabled) {
      options.push({
        label: `${mcp.name} (${t('mcpSettings.disabled')})`,
        value: mcp.id,
        disabled: true,
      });
    } else if (!mcp) {
      options.push({
        label: t('agentEditor.mcp.unavailableService'),
        value: id,
        disabled: true,
      });
    }
  }

  return options;
});

const showMcpServiceSelect = computed(() =>
  mcpOptions.value.length > 0 || (formData.value.config.mcp_services?.length ?? 0) > 0,
);
const webSearchProviderList = ref<WebSearchProviderEntity[]>([]);
const skillCatalog = ref<SkillCatalogItem[]>([]);
const catalogReady = ref(false);
const installingCatalogId = ref('');
const skillsSelectionMode = ref<'all' | 'selected' | 'none'>('none');
const hostOnly = computed(() => hostSkillsOnly(
  deploymentCapabilities.isSupported('settings.sandbox.remote'),
  deploymentCapabilities.isSupported('settings.sandbox.host'),
));
// Where this agent's skills install and run.
const skillTargetId = computed(() =>
  hostOnly.value ? HOST_SKILL_TARGET_ID : (formData.value.config.sandbox_config_id || ''),
);
const hasSandboxSelected = computed(() => !!skillTargetId.value);
const canEnableSkills = computed(() =>
  hostOnly.value || hasSandboxSelected.value || namedSandboxConfigs().length === 1,
);
const canInstallSkills = computed(() => authStore.hasRole('admin'));

type CatalogSkillRow = SkillCatalogItem & {
  installed: boolean
  selectable: boolean
  installStatus: string
  installEnabled: boolean
  // The install on this sandbox is still on an archive the catalog has moved past.
  upgradable: boolean
  installVersion: string
  // Set while a newer install runs or after it failed: the sandbox still runs
  // the previous version, so the skill stays usable.
  servedNote: string
}

const catalogSkillRows = computed<CatalogSkillRow[]>(() => {
  const sandboxId = skillTargetId.value
  return skillCatalog.value.map((item) => {
    const inst = sandboxId
      ? (item.installations || []).find((row) => row.sandbox_config_id === sandboxId)
      : undefined
    const installStatus = inst?.status || ''
    const installEnabled = Boolean(inst?.enabled)
    const installed = Boolean(inst) && installStatus !== 'removed'
    const servedNote = inst ? servedPreviousText(t, inst) : ''
    const selectable = installEnabled && (installStatus === 'ready' || Boolean(servedNote))
    const upgradable = Boolean(inst && installUpgradable(item, inst))
    return {
      ...item, installed, selectable, installStatus, installEnabled,
      upgradable, installVersion: inst?.version || '', servedNote,
    }
  })
})

const showCatalogSkillList = computed(() =>
  skillsSelectionMode.value !== 'none'
  && hasSandboxSelected.value
  && catalogSkillRows.value.length > 0,
)

const skillsSelectionHint = computed(() => {
  if (hostOnly.value) {
    if (skillsSelectionMode.value === 'all') return t('agent.editor.hostSkillsAllListHint')
    if (skillsSelectionMode.value === 'selected') return t('agent.editor.hostSelectSkillsDesc')
    return t('agent.editor.hostSkillsSelectionDesc')
  }
  if (skillsSelectionMode.value === 'all') return t('agent.editor.skillsAllListHint')
  if (skillsSelectionMode.value === 'selected') return t('agent.editor.selectSkillsDesc')
  return t('agent.editor.skillsSelectionDesc')
})

const catalogSkillGroups = computed(() => {
  const ready = catalogSkillRows.value.filter((skill) => skill.selectable)
  const pending = catalogSkillRows.value.filter((skill) => !skill.selectable)
  const groups: { key: 'ready' | 'pending'; label: string; skills: CatalogSkillRow[] }[] = []
  if (ready.length) {
    groups.push({
      key: 'ready',
      label: t('agent.editor.skillsGroupAvailable'),
      skills: ready,
    })
  }
  if (pending.length) {
    groups.push({
      key: 'pending',
      label: t('agent.editor.skillsGroupUnavailable'),
      skills: pending,
    })
  }
  return groups
})

function skillStatusHint(skill: CatalogSkillRow): string {
  if (!skill.installed) return t('agent.editor.skillNotInstalled')
  if (skill.installStatus === 'installing') return t('settings.sandbox.skillStatusInstalling')
  if (skill.installStatus === 'failed') return t('settings.sandbox.skillStatusFailed')
  if (skill.installStatus === 'removing') return t('settings.sandbox.skillStatusRemoving')
  if (skill.installStatus === 'ready' && !skill.installEnabled) {
    return hostOnly.value ? t('agent.editor.hostSkillDisabled') : t('agent.editor.skillDisabledOnSandbox')
  }
  return t('agent.editor.skillNotReady')
}

function skillStatusIcon(skill: CatalogSkillRow): string {
  if (!skill.installed || skill.installStatus === 'failed') return 'download'
  if (skill.installStatus === 'installing' || skill.installStatus === 'removing') return 'refresh'
  if (skill.installStatus === 'ready' && !skill.installEnabled) return 'close-circle'
  return 'time'
}

function isSkillBusy(skill: CatalogSkillRow): boolean {
  return skill.installStatus === 'installing' || skill.installStatus === 'removing'
}

function canInstallSkillRow(skill: CatalogSkillRow): boolean {
  if (!canInstallSkills.value || !hasSandboxSelected.value) return false
  return !skill.installed || skill.installStatus === 'failed'
}

// Upgrading writes the sandbox image through the same admin-only catalog
// install, so it is offered, and even mentioned, only to those who can run it.
function canUpgradeSkillRow(skill: CatalogSkillRow): boolean {
  return canInstallSkills.value && hasSandboxSelected.value && skill.upgradable
}

// Installing the catalog version over what this sandbox has is an upgrade:
// over an outdated install, or over a failed upgrade whose previous version
// still runs. Only a skill the sandbox has never carried is a plain install.
function installsAnUpgrade(skill: CatalogSkillRow): boolean {
  return skill.upgradable || Boolean(skill.servedNote)
}

function skillUpgradeHint(skill: CatalogSkillRow): string {
  const versions = upgradeVersions(skill, { version: skill.installVersion })
  return versions
    ? t('settings.skills.upgradeFromTo', versions)
    : t('settings.skills.upgradeAvailable')
}

function namedSandboxConfigs(): SandboxConfigRecord[] {
  return chatResources.sandboxConfigs.filter((cfg) => isNamedSandboxBackend(cfg.sandbox_type))
}

function autoBindSoleSandbox() {
  if (hostOnly.value) return
  if (skillsSelectionMode.value === 'none') return
  if (formData.value.config.sandbox_config_id) return
  const configs = namedSandboxConfigs()
  if (configs.length === 1) {
    formData.value.config.sandbox_config_id = configs[0].id
  }
}

function openSkillSettings() {
  const configId = skillTargetId.value
  modalShell.requestClose(() => {
    void router.push(toolboxLocation('skills', configId || undefined))
  })
}

const showSkillProgress = ref(false)
const skillProgressRecord = ref<SandboxConfigRecord | null>(null)
const skillProgressId = ref('')
const skillProgressTitle = ref('')
const skillProgressDesc = computed(() => {
  const record = skillProgressRecord.value
  if (!record) return ''
  return t('settings.skills.manageDrawerDesc', { name: record.name })
})

function sandboxRecordById(configId: string): SandboxConfigRecord | undefined {
  if (hostOnly.value && configId === HOST_SKILL_TARGET_ID) return hostSkillTargetRecord(t('settings.skills.hostTarget'))
  return chatResources.sandboxConfigs.find((cfg) => cfg.id === configId)
}

function installOnCurrentSandbox(skill: CatalogSkillRow, configId: string) {
  return (skill.installations || []).find((row) => row.sandbox_config_id === configId)
}

async function openSkillInstallProgress(skill: CatalogSkillRow) {
  const configId = skillTargetId.value
  const record = sandboxRecordById(configId)
  if (!record) {
    openSkillSettings()
    return
  }
  let inst = installOnCurrentSandbox(skill, configId)
  if (!inst?.skill_id) {
    await syncInstalledSkills(true)
    const latest = catalogSkillRows.value.find((row) => row.id === skill.id)
    inst = latest ? installOnCurrentSandbox(latest, configId) : undefined
  }
  if (!inst?.skill_id) {
    openSkillSettings()
    return
  }
  skillProgressRecord.value = record
  skillProgressId.value = inst.skill_id
  skillProgressTitle.value = skill.name
  showSkillProgress.value = true
}

function onSkillProgressUpdated() {
  void syncInstalledSkills(true)
}

function onSkillProgressChanged() {
  void syncInstalledSkills(true)
}

function pruneSelectedSkills() {
  if (!catalogReady.value) return
  // A skill being upgraded is briefly not ready, and dropping it here would
  // silently unselect it for good once the agent is saved.
  const names = new Set(catalogSkillRows.value
    .filter((skill) => skill.selectable || (skill.installed && isSkillBusy(skill)))
    .map((skill) => skill.name))
  const selected: string[] = formData.value.config.selected_skills || []
  const kept = selected.filter((name: string) => names.has(name))
  if (kept.length !== selected.length) {
    formData.value.config.selected_skills = kept
  }
}

async function syncInstalledSkills(force = false) {
  autoBindSoleSandbox()
  const configId = skillTargetId.value
  // The editor only edits this workspace's agents, so the sandbox config is
  // local and needs no source-workspace scope.
  await editorResources.ensureSkills(configId, undefined, force)
  try {
    await editorResources.ensureSkillCatalog(force)
    skillCatalog.value = [...editorResources.skillCatalog]
    catalogReady.value = true
  } catch {
    catalogReady.value = false
  }
  pruneSelectedSkills()
}

async function installCatalogToCurrent(skill: CatalogSkillRow) {
  const configId = skillTargetId.value
  if (!configId || installingCatalogId.value) return
  installingCatalogId.value = skill.id
  const upgrading = installsAnUpgrade(skill)
  try {
    const res = await installSkillCatalog(skill.id, [configId])
    const failed = Object.keys(res?.data?.errors || {}).length
    if (failed > 0) {
      MessagePlugin.warning(t('settings.skills.installPartial', { failed }))
    } else {
      MessagePlugin.success(t(upgrading ? 'settings.skills.upgradeAccepted' : 'settings.skills.installAccepted'))
    }
    await syncInstalledSkills(true)
  } catch (e: any) {
    MessagePlugin.error(e?.message || t('settings.sandbox.skillUploadFailed'))
  } finally {
    installingCatalogId.value = ''
  }
}
// 空间内的具名沙箱后端配置。始终包含当前已选中的那份,即使它已被删除——
// 否则下拉会静默显示为“不启用沙箱”,看不出该智能体其实指着一份不存在的配置。
const sandboxConfigOptions = computed(() => {
  const configs = chatResources.sandboxConfigs.filter((cfg) => isNamedSandboxBackend(cfg.sandbox_type));
  const selected = formData.value.config.sandbox_config_id;
  if (!selected || configs.some((cfg) => cfg.id === selected)) return configs;
  return [
    ...configs,
    { id: selected, name: t('agent.editor.sandboxBackendMissing'), sandbox_type: '' } as SandboxConfigRecord,
  ];
});
const backendLabel = (type: string) =>
  type ? t(`settings.sandbox.backends.${type}`) : t('common.error');

function sandboxTargetLine(cfg: SandboxConfigRecord): string {
  if (cfg.sandbox_type === 'docker') {
    return cfg.config?.docker?.image?.trim() || ''
  }
  const remote = cfg.config?.e2b || cfg.config?.cube
  const raw = remote?.api_url?.trim() || ''
  if (!raw) return ''
  try {
    return new URL(raw).host
  } catch {
    return raw
  }
}

const selectedSandboxSummary = computed(() => {
  const id = formData.value.config.sandbox_config_id
  const cfg = sandboxConfigOptions.value.find((item) => item.id === id)
  if (!cfg?.sandbox_type) return ''
  const parts = [backendLabel(cfg.sandbox_type), sandboxTargetLine(cfg)]
  const desc = cfg.description?.trim()
  if (desc) parts.push(desc)
  return parts.filter(Boolean).join(' · ')
})
// 存储引擎可用状态(用于图片存储 provider 选择)
const storageEngineStatus = ref<StorageEngineStatusItem[]>([]);
const imageStorageOptions = computed(() => {
  const statusMap: Record<string, boolean> = {};
  for (const e of storageEngineStatus.value) {
    statusMap[e.name] = e.available;
  }
  return [
    { value: 'local', label: t('settings.storage.engineLocal'), disabled: false },
    { value: 'minio', label: 'MinIO', disabled: statusMap.minio === false },
    { value: 'cos', label: t('settings.storage.engineCos'), disabled: statusMap.cos === false },
    { value: 'tos', label: t('settings.storage.engineTos'), disabled: statusMap.tos === false },
    { value: 's3', label: 'Amazon S3', disabled: statusMap.s3 === false },
    { value: 'oss', label: t('settings.storage.engineOss'), disabled: statusMap.oss === false },
  ];
});

// 系统默认配置(用于内置智能体显示默认提示词)
// Agent (smart-reasoning) 模式的默认系统提示词。直接从 prompt-templates
// 的 agent_system_prompt 数组里挑 mode==='rag' && default 的那条得到,
// 与后端 agent.GetProgressiveRAGSystemPrompt 是同一份数据源。
const defaultAgentSystemPrompt = ref('');
const defaultNormalSystemPrompt = ref('');  // 普通模式默认系统提示词(来自 prompt-templates 的 default 项)
const defaultContextTemplate = ref('');
const defaultRewritePromptSystem = ref('');
const defaultRewritePromptUser = ref('');
const defaultFallbackPrompt = ref('');
const defaultFallbackResponse = ref('');
// 默认检索参数
const defaultEmbeddingTopK = ref(10);
const defaultKeywordThreshold = ref(0.3);
const defaultVectorThreshold = ref(0.5);
const defaultRerankTopK = ref(5);
const defaultRerankThreshold = ref(0.5);
const defaultQuickAnswerMaxCompletionTokens = 2048;
const defaultSmartReasoningMaxCompletionTokens = 24576;
const defaultSandboxWriteMaxCompletionTokens = 24576;
const defaultTemperature = ref(0.7);

const defaultMaxCompletionTokensFor = (mode: string, sandboxConfigId?: string) => {
  if (mode === 'smart-reasoning') {
    return sandboxConfigId
      ? defaultSandboxWriteMaxCompletionTokens
      : defaultSmartReasoningMaxCompletionTokens;
  }
  return defaultQuickAnswerMaxCompletionTokens;
};

// 知识库相关工具列表(用于 watch(hasKnowledgeBase) 从"无"变"有"时 seed 默认工具)
const knowledgeBaseTools = ['search_knowledge', 'read_document', 'list_documents'];

// Wiki 读取类工具(用于 watch(agentMode) 切到 smart-reasoning 时 seed 默认工具)
const wikiReadTools = ['wiki_search', 'wiki_read_page', 'read_document', 'wiki_flag_issue'];

// 初始化标志,防止初始化时触发 watch 自动添加工具
const isInitializing = ref(false);

// 知识库选择模式:all=全部, selected=指定, none=不使用
const kbSelectionMode = ref<'all' | 'selected' | 'none'>('none');

// MCP 服务选择模式:all=全部, selected=指定, none=不使用
const mcpSelectionMode = ref<'all' | 'selected' | 'none'>('none');

// 可选工具来自后端工具目录(GET /api/v1/agents/tools):工具本身、分组、danger 标记
// 和知识库能力要求都以后端为准,前端不再维护工具清单。这里只提供翻译文案;
// 没有翻译的工具(例如后端新增的工具)直接使用目录里的名称和描述,不会被隐藏。
const agentToolCatalog = ref<AgentToolCatalog | null>(null);
// 打开编辑器时已保存的 allowed_tools,用来在取消勾选后继续展示目录之外的保存值。
const storedToolNames = ref<string[]>([]);
// allowed_tools 未设置(null)表示使用后端默认工具,空列表表示不使用内置工具。
// 加载时无法显式写入默认工具(工具目录不可用,或不是智能推理模式)时保持未设置,
// 列表未被修改则保存时原样发送 null。
const keepAllowedToolsUnset = ref(false);
const toolTexts = computed<Record<string, ToolText>>(() => ({
  thinking: { label: t('agentEditor.tools.thinking'), description: t('agentEditor.tools.thinkingDesc') },
  todo_write: { label: t('agentEditor.tools.todoWrite'), description: t('agentEditor.tools.todoWriteDesc') },
  ask_user: { label: t('agentEditor.tools.askUser'), description: t('agentEditor.tools.askUserDesc') },
  search_conversations: { label: t('agentEditor.tools.searchConversations'), description: t('agentEditor.tools.searchConversationsDesc') },
  search_knowledge: { label: t('agentEditor.tools.searchKnowledge'), description: t('agentEditor.tools.searchKnowledgeDesc') },
  read_document: { label: t('agentEditor.tools.readDocument'), description: t('agentEditor.tools.readDocumentDesc') },
  list_documents: { label: t('agentEditor.tools.listDocuments'), description: t('agentEditor.tools.listDocumentsDesc') },
  query_knowledge_graph: { label: t('agentEditor.tools.queryGraph'), description: t('agentEditor.tools.queryGraphDesc') },
  database_query: { label: t('agentEditor.tools.dbQuery'), description: t('agentEditor.tools.dbQueryDesc') },
  wiki_search: { label: t('agentEditor.tools.wikiSearch'), description: t('agentEditor.tools.wikiSearchDesc') },
  wiki_read_page: { label: t('agentEditor.tools.wikiReadPage'), description: t('agentEditor.tools.wikiReadPageDesc') },
  wiki_flag_issue: { label: t('agentEditor.tools.wikiFlagIssue'), description: t('agentEditor.tools.wikiFlagIssueDesc') },
  wiki_write_page: { label: t('agentEditor.tools.wikiWritePage'), description: t('agentEditor.tools.wikiWritePageDesc') },
  wiki_replace_text: { label: t('agentEditor.tools.wikiReplaceText'), description: t('agentEditor.tools.wikiReplaceTextDesc') },
  wiki_rename_page: { label: t('agentEditor.tools.wikiRenamePage'), description: t('agentEditor.tools.wikiRenamePageDesc') },
  wiki_delete_page: { label: t('agentEditor.tools.wikiDeletePage'), description: t('agentEditor.tools.wikiDeletePageDesc') },
  wiki_read_issue: { label: t('agentEditor.tools.wikiReadIssue'), description: t('agentEditor.tools.wikiReadIssueDesc') },
  wiki_update_issue: { label: t('agentEditor.tools.wikiUpdateIssue'), description: t('agentEditor.tools.wikiUpdateIssueDesc') },
  data_analysis: { label: t('agentEditor.tools.dataAnalysis'), description: t('agentEditor.tools.dataAnalysisDesc') },
  data_schema: { label: t('agentEditor.tools.dataSchema'), description: t('agentEditor.tools.dataSchemaDesc') },
}));

// 工具分组元信息
const toolGroups = computed(() => [
  { key: 'base', label: t('agentEditor.tools.groupBase') },
  { key: 'rag', label: t('agentEditor.tools.groupRag') },
  { key: 'wiki_read', label: t('agentEditor.tools.groupWikiRead') },
  { key: 'wiki_edit', label: t('agentEditor.tools.groupWikiEdit') },
  { key: 'wiki_issue', label: t('agentEditor.tools.groupWikiIssue') },
  { key: 'data', label: t('agentEditor.tools.groupData') },
]);

// 知识库分组:我的 vs 共享的
const myKbOptions = computed(() => kbOptions.value.filter(kb => !kb.shared));
const sharedKbOptions = computed(() => kbOptions.value.filter(kb => kb.shared));

// 根据知识库配置动态计算是否有知识库能力
const hasKnowledgeBase = computed(() => {
  return kbSelectionMode.value !== 'none';
});

const showRerankModelField = computed(() => {
  if (!isAgentMode.value) return hasKnowledgeBase.value;
  return hasKnowledgeBase.value || agentRequiresRerankModel(formData.value.config);
});

// 当前配置下进入到智能体作用域的知识库列表
// 注意:用户可能选了 knowledge_bases(按库级),也可能选了 knowledge_ids(按文档级)
// 这里仅用于 UI 上的工具可用性判定,按库级来计算
const kbsInScope = computed(() => {
  if (kbSelectionMode.value === 'none') return [];
  if (kbSelectionMode.value === 'all') return kbOptions.value;
  const selectedIds = formData.value.config.knowledge_bases || [];
  return kbOptions.value.filter(kb => selectedIds.includes(kb.value));
});

// 是否存在至少一个启用了 RAG 能力的知识库(向量 or 关键词)
const hasRagKnowledgeBase = computed(() => {
  return kbsInScope.value.some(kb => kb.ragEnabled);
});

// 是否存在至少一个启用了 Wiki 能力的知识库
const hasWikiKnowledgeBase = computed(() => {
  return kbsInScope.value.some(kb => kb.wikiEnabled);
});

// 作用域内 RAG/Wiki 知识库数量(用于顶部状态栏)
const ragKbCount = computed(() => kbsInScope.value.filter(kb => kb.ragEnabled).length);
const wikiKbCount = computed(() => kbsInScope.value.filter(kb => kb.wikiEnabled).length);

// 检测选择的知识库中是否包含 FAQ 类型
const hasFaqKnowledgeBase = computed(() => {
  if (kbSelectionMode.value === 'none') return false;
  if (kbSelectionMode.value === 'all') {
    // 全部知识库模式,检查是否有任何 FAQ 类型的知识库
    return kbOptions.value.some(kb => kb.type === 'faq');
  }
  // 指定知识库模式,检查选中的知识库中是否有 FAQ 类型
  const selectedKbIds = formData.value.config.knowledge_bases || [];
  return kbOptions.value.some(kb => selectedKbIds.includes(kb.value) && kb.type === 'faq');
});

// 把"作用域内 KB 能力"聚合成一个 ScopeCapabilities 对象,交给
// `evaluateToolRequirement` 统一判定;UI 上的所有可用性提示都应出自此处。
const scopeCapabilities = computed<ScopeCapabilities>(() => {
  const scope: ScopeCapabilities = { vector: false, keyword: false, wiki: false, graph: false, faq: false };
  for (const kb of kbsInScope.value) {
    const caps = kb.capabilities;
    if (caps) {
      if (caps.vector) scope.vector = true;
      if (caps.keyword) scope.keyword = true;
      if (caps.wiki) scope.wiki = true;
      if (caps.graph) scope.graph = true;
      if (caps.faq) scope.faq = true;
    } else {
      // 向后兼容:capabilities 尚未加载时,退回到 ragEnabled/wikiEnabled 推断
      if (kb.ragEnabled) { scope.vector = true; scope.keyword = true; }
      if (kb.wikiEnabled) scope.wiki = true;
      if (kb.type === 'faq') scope.faq = true;
    }
  }
  return scope;
});

// 把 evaluateToolRequirement 返回的 missKind 映射到 i18n 文案。
// 新增的 needsGraph / needsFaq 暂时复用 requiresRagKb 文案("需要 RAG 知识库"),
// 后续可按需增加独立的 i18n 键。
const missKindToReason = (kind: RequirementMissKind): string | undefined => {
  switch (kind) {
    case 'needsKb': return t('agentEditor.tools.requiresKb');
    case 'needsWiki': return t('agentEditor.tools.requiresWikiKb');
    case 'needsRag':
    case 'needsGraph':
    case 'needsFaq': return t('agentEditor.tools.requiresRagKb');
    case 'none':
    default: return undefined;
  }
};

// 保存时的 allowed_tools:保持未设置的列表在未被修改时以 null 发送。
const allowedToolsToSave = (): string[] | null =>
  allowedToolsForSave(formData.value.config.allowed_tools || [], keepAllowedToolsUnset.value);

// 能力不满足时只禁止新勾选;已勾选的工具保持可点击,以便取消勾选(并显示原因)。
const availableTools = computed(() => {
  const options = buildToolOptions(
    agentToolCatalog.value,
    formData.value.config.allowed_tools || [],
    scopeCapabilities.value,
    hasKnowledgeBase.value,
    (name) => toolTexts.value[name],
  );
  return options.map(tool => ({
    ...tool,
    disabledReason: tool.unmet ? missKindToReason(tool.missKind) : undefined,
  }));
});

// 已保存但目录未提供的工具:开关控制的工具或无法识别的名称。
// 勾选状态展示出来以便移除,取消勾选后不能再勾回。
const storedExtras = computed(() => storedExtraTools(
  agentToolCatalog.value,
  [...storedToolNames.value, ...(formData.value.config.allowed_tools || [])],
  formData.value.config.allowed_tools || [],
));

// 按分组切片后的工具列表,用于模板分组渲染
const groupedAvailableTools = computed(() => {
  const map: Record<string, typeof availableTools.value> = {};
  for (const tool of availableTools.value) {
    const g = tool.group || 'base';
    if (!map[g]) map[g] = [];
    map[g].push(tool);
  }
  // 后端新增的分组没有文案时以分组名显示,不隐藏其中的工具
  const known = new Set(toolGroups.value.map(g => g.key));
  const extraGroups = Object.keys(map)
    .filter(key => !known.has(key))
    .map(key => ({ key, label: key }));
  return [...toolGroups.value, ...extraGroups]
    .map(g => ({
      ...g,
      tools: map[g.key] || [],
    }))
    .filter(g => g.tools.length > 0);
});

// ==================== 有效工具预览 ====================
// 最终运行时智能体实际能使用的工具集合(仅做预览展示),与运行时注册规则一致:
//   1) allowed_tools 未设置(null)时,运行时使用目录中的默认工具(default_tools),
//      空列表则不注册任何内置工具;
//   2) 勾选但缺失对应能力(无 KB / 无 Wiki 能力 KB)的工具不会生效,灰显展示;
//   3) 目录之外的保存值(开关控制的工具、无法识别的名称)自身不会注册任何工具;
//   4) 无论是否勾选,web_search / web_fetch 随 web_search_enabled 出现。
const effectiveSelection = computed(() => effectiveToolSelection(
  agentToolCatalog.value,
  allowedToolsToSave(),
  scopeCapabilities.value,
  hasKnowledgeBase.value,
));
const effectiveTools = computed(() => {
  const active = new Set(effectiveSelection.value.names);
  const inactive = new Set(effectiveSelection.value.inactive);
  const items: Array<{ value: string; label: string; reason?: string; active: boolean }> = [];
  // 按工具目录顺序展示
  for (const tool of availableTools.value) {
    if (active.has(tool.value)) {
      items.push({ value: tool.value, label: tool.label, active: true });
    } else if (inactive.has(tool.value)) {
      items.push({ value: tool.value, label: tool.label, active: false, reason: tool.disabledReason });
    }
  }
  if (formData.value.config.web_search_enabled) {
    items.push({ value: 'web_search', label: t('agentEditor.tools.webSearch'), active: true });
    items.push({ value: 'web_fetch', label: t('agentEditor.tools.webFetch'), active: true });
  }
  return items;
});

// 勾选了但当前配置下无法生效的工具数量(用于顶部状态提示)
const inactiveToolCount = computed(() => effectiveTools.value.filter(i => !i.active).length);

// 可用文件类型列表
const availableFileTypes = [
  { value: 'pdf', label: 'PDF', description: t('agentEditor.fileTypes.pdf') },
  { value: 'docx', label: 'Word', description: t('agentEditor.fileTypes.word') },
  { value: 'txt', label: t('agentEditor.fileTypes.textLabel'), description: t('agentEditor.fileTypes.text') },
  { value: 'md', label: 'Markdown', description: t('agentEditor.fileTypes.markdown') },
  { value: 'csv', label: 'CSV', description: t('agentEditor.fileTypes.csv') },
  { value: 'xlsx', label: 'Excel', description: t('agentEditor.fileTypes.excel') },
  { value: 'jpg', label: t('agentEditor.fileTypes.imageLabel'), description: t('agentEditor.fileTypes.image') },
];

// 占位符相关 - 从 API 获取
const placeholderData = ref<{
  system_prompt: PlaceholderDefinition[];
  agent_system_prompt: PlaceholderDefinition[];
  context_template: PlaceholderDefinition[];
  rewrite_system_prompt: PlaceholderDefinition[];
  rewrite_prompt: PlaceholderDefinition[];
  fallback_prompt: PlaceholderDefinition[];
}>({
  system_prompt: [],
  agent_system_prompt: [],
  context_template: [],
  rewrite_system_prompt: [],
  rewrite_prompt: [],
  fallback_prompt: [],
});

// 系统提示词占位符(根据模式动态选择)
const availablePlaceholders = computed(() => {
  return isAgentMode.value ? placeholderData.value.agent_system_prompt : placeholderData.value.system_prompt;
});

// 上下文模板占位符
const contextTemplatePlaceholders = computed(() => placeholderData.value.context_template);

// 改写系统提示词占位符
const rewriteSystemPlaceholders = computed(() => placeholderData.value.rewrite_system_prompt);

// 改写用户提示词占位符
const rewritePlaceholders = computed(() => placeholderData.value.rewrite_prompt);

// 兜底提示词占位符
const fallbackPlaceholders = computed(() => placeholderData.value.fallback_prompt);

const promptTextareaRef = ref<any>(null);
const showPlaceholderPopup = ref(false);
const selectedPlaceholderIndex = ref(0);
const placeholderPrefix = ref('');
const popupStyle = ref({ top: '0px', left: '0px' });
let placeholderPopupTimer: any = null;

// 上下文模板占位符相关
const contextTemplateTextareaRef = ref<any>(null);
const showContextPlaceholderPopup = ref(false);
const selectedContextPlaceholderIndex = ref(0);
const contextPlaceholderPrefix = ref('');
const contextPopupStyle = ref({ top: '0px', left: '0px' });
let contextPlaceholderPopupTimer: any = null;

// 意图提示词编辑相关
const selectedIntent = ref('');
const intentEditorValue = ref('');
const intentPromptsSyncing = ref(false);
const intentPromptTextareaRef = ref<any>(null);

// 通用占位符弹出相关(用于改写提示词和兜底提示词)
interface PlaceholderPopupState {
  show: boolean;
  selectedIndex: number;
  prefix: string;
  style: { top: string; left: string };
  timer: any;
  fieldKey: string;
  placeholders: PlaceholderDefinition[];
}

const intentPromptPopup = ref<PlaceholderPopupState>({
  show: false, selectedIndex: 0, prefix: '', style: { top: '0px', left: '0px' }, timer: null, fieldKey: 'intent_prompt', placeholders: []
});

const rewriteSystemPopup = ref<PlaceholderPopupState>({
  show: false, selectedIndex: 0, prefix: '', style: { top: '0px', left: '0px' }, timer: null, fieldKey: 'rewrite_prompt_system', placeholders: []
});
const rewriteUserPopup = ref<PlaceholderPopupState>({
  show: false, selectedIndex: 0, prefix: '', style: { top: '0px', left: '0px' }, timer: null, fieldKey: 'rewrite_prompt_user', placeholders: []
});
const fallbackPromptPopup = ref<PlaceholderPopupState>({
  show: false, selectedIndex: 0, prefix: '', style: { top: '0px', left: '0px' }, timer: null, fieldKey: 'fallback_prompt', placeholders: []
});

const rewriteSystemTextareaRef = ref<any>(null);
const rewriteUserTextareaRef = ref<any>(null);
const fallbackPromptTextareaRef = ref<any>(null);

const navItems = computed(() => {
  const items: { key: string; icon: string; label: string; badge?: number }[] = [
    { key: 'basic', icon: 'info-circle', label: t('agent.editor.basicInfo') },
    { key: 'prompts', icon: 'file-paste', label: t('agent.editor.promptsConfig'), badge: promptNavItems.value.length > 1 ? promptNavItems.value.length : undefined },
    { key: 'model', icon: 'control-platform', label: t('agent.editor.modelConfig') },
    { key: 'suggestions', icon: 'help-circle', label: t('agentEditor.questionSuggestions.navLabel') },
  ];
  // 多轮对话(两种模式都需要:Agent 模式在这里说明历史自动管理、保留检索结果)
  items.push({ key: 'conversation', icon: 'chat', label: t('agent.editor.conversationSettings') });
  // 知识库与检索
  items.push({ key: 'knowledge', icon: 'folder', label: t('agent.editor.knowledgeConfig') });
  // 检索策略只作用于普通模式的问答流程;Agent 模式的检索工具不读这些设置,
  // 显示出来只会让用户调了参数却没有任何效果。
  if (hasKnowledgeBase.value && !isAgentMode.value) {
    items.push({ key: 'retrieval', icon: 'search', label: t('agent.editor.retrievalStrategy') });
  }
  items.push({ key: 'websearch', icon: 'internet', label: t('agent.editor.webSearchConfig') });
  items.push({ key: 'multimodal', icon: 'attach', label: t('agentEditor.imageUpload.navLabel') });
  // Agent 模式能力
  if (isAgentMode.value) {
    items.push({ key: 'tools', icon: 'tools', label: t('agent.editor.toolsConfig') });
    items.push({ key: 'mcp', icon: 'server', label: t('agentEditor.mcp.label') });
    items.push({ key: 'skills', icon: SKILL_ICON, label: t('agent.editor.skillsConfig') });
  }
  // 发布(仅编辑模式)
  if (editorMode.value === 'edit' && editorAgent.value?.id && !editorAgent.value?.is_builtin && !authStore.isLiteMode) {
    items.push({ key: 'share', icon: 'share', label: t('knowledgeEditor.sidebar.share') });
  }
  return items;
});

// 左侧导航分组(参考「头像-设置」的分组方式)
const navGroups = computed(() => {
  const itemMap = new Map(navItems.value.map((item) => [item.key, item]));
  const pickItems = (keys: string[]) =>
    keys.map((key) => itemMap.get(key)).filter(Boolean) as typeof navItems.value;
  return [
    {
      key: 'basic',
      label: t('agentEditor.navGroups.basic'),
      items: pickItems(['basic', 'prompts', 'model', 'conversation', 'suggestions']),
    },
    {
      key: 'knowledge',
      label: t('agentEditor.navGroups.knowledge'),
      items: pickItems(['knowledge', 'retrieval', 'websearch']),
    },
    {
      key: 'capability',
      label: t('agentEditor.navGroups.capability'),
      items: pickItems(['multimodal', 'tools', 'mcp', 'skills']),
    },
    {
      key: 'integration',
      label: t('agentEditor.navGroups.integration'),
      items: pickItems(['share']),
    },
  ].filter((group) => group.items.length > 0);
});

// 初始数据
const defaultFormData = {
  name: '',
  description: '',
  is_builtin: false,
  config: {
    // 基础设置
    agent_mode: 'smart-reasoning' as 'quick-answer' | 'smart-reasoning',
    system_prompt: '',
    context_template: '',
    // 模型设置
    model_id: '',
    rerank_model_id: '',
    temperature: 0.7,
    max_completion_tokens: 0,
    thinking: false, // 默认禁用思考模式
    reasoning_effort: 'off', // 思考强度;与 thinking 布尔保持同步
    citation_enabled: true, // 默认输出知识库/网页来源引用
    // Agent模式设置
    max_iterations: 10,
    llm_call_timeout: 120,  // 120 seconds
    allowed_tools: [] as string[],
    reflection_enabled: false,
    // MCP 服务设置
    mcp_selection_mode: 'none' as 'all' | 'selected' | 'none',
    mcp_services: [] as string[],
    // 对话中触发 OAuth 授权时的等待超时(秒),默认 600
    mcp_auth_wait_timeout: 600,
    // 执行权限上限,默认自动执行
    access_level: 'auto_write' as AssistantAccessLevel,
    // Skills 设置
    skills_selection_mode: 'none' as 'all' | 'selected' | 'none',
    selected_skills: [] as string[],
    // 技能脚本运行在哪份空间沙箱配置上。留空表示禁用脚本执行。
    sandbox_config_id: '' as string,
    // 知识库设置:新建智能体默认选择 "全部知识库",
    // 让用户无需先去勾选 KB 即可上手;如有需要可改为 "selected" / "none"。
    kb_selection_mode: 'all' as 'all' | 'selected' | 'none',
    knowledge_bases: [] as string[],
    retrieve_kb_only_when_mentioned: false,
    // 智能推理下的类型预设:新建 agent 时默认给 RAG 问答(最常用场景)。
    // 编辑既有 agent 时会被 agent 自己保存的 agent_type 覆盖。
    agent_type: 'rag-qa' as AgentType,
    system_prompt_id: '' as string,
    // 附件上传设置
    image_upload_enabled: false,
    vlm_model_id: '',
    image_storage_provider: '',
    // 附件图片理解 / 扫描件 OCR 开关(默认关闭,避免解析耗时增加)
    attachment_image_understanding: false,
    // 扫描件 OCR 最大页数(0 = 使用全局默认)
    attachment_ocr_max_pages: 0,
    // 单轮问答等待附件解析完成的最长时间(秒,0 = 使用全局默认)
    attachment_parse_wait_timeout_sec: 0,
    // 聊天附件解析引擎策略(按文件类型选引擎)
    chat_parser_engine_rules: [] as ParserEngineRule[],
    // 文件类型限制
    supported_file_types: [] as string[],
    // 数据分析阶段开关(默认关闭,避免在普通问答上多一次 LLM 调用生成 SQL)
    data_analysis_enabled: false,
    // FAQ 策略设置
    faq_priority_enabled: true, // 是否启用 FAQ 优先策略
    faq_direct_answer_threshold: 0.9, // FAQ 直接回答阈值(相似度高于此值直接使用 FAQ 答案)
    faq_score_boost: 1.2, // FAQ 分数加权系数
    // 网络搜索设置
    web_search_enabled: false,
    web_search_max_results: 5,
    // 多轮对话设置
    multi_turn_enabled: false,
    history_turns: 5,
    retain_retrieval_history: false,
    // 长期记忆:默认跟随空间设置。写 true 与不写等价,只有 false 才会
    // 让这个智能体单独不读记忆。
    memory_enabled: true,
    // 检索策略设置
    embedding_top_k: 10,
    keyword_threshold: 0.3,
    vector_threshold: 0.5,
    rerank_top_k: 5,
    rerank_threshold: 0.5,
    // 高级设置(普通模式)
    enable_query_expansion: true,
    enable_rewrite: true,
    query_understand_model_id: '',
    rewrite_prompt_system: '',
    rewrite_prompt_user: '',
    fallback_strategy: 'model' as 'fixed' | 'model',
    fallback_response: '',
    fallback_prompt: '',
    question_suggestions: {
      starters: {
        enabled: true,
        mode: 'hybrid' as 'curated' | 'knowledge' | 'hybrid',
        items: [] as string[],
        count: 6,
      },
      follow_ups: {
        enabled: false,
        mode: 'hybrid' as 'generated' | 'knowledge' | 'hybrid',
        count: 3,
        model_id: '',
        additional_instruction: '',
        categories: ['clarify', 'deepen', 'action'] as Array<'clarify' | 'deepen' | 'action'>,
        max_context_turns: 2,
        suppress_on_fallback: true,
        suppress_when_answer_asks_question: true,
        knowledge_fallback: true,
        allow_regenerate: false,
      },
    },
    // 已废弃字段(保留兼容)
    welcome_message: '',
  }
};

const formData = ref(JSON.parse(JSON.stringify(defaultFormData)));

const starterSuggestionModeOptions = computed(() => [
  { value: 'curated', label: t('agentEditor.questionSuggestions.modeCurated') },
  { value: 'knowledge', label: t('agentEditor.questionSuggestions.modeKnowledge') },
  { value: 'hybrid', label: t('agentEditor.questionSuggestions.modeHybrid') },
]);
const followUpSuggestionModeOptions = computed(() => [
  { value: 'generated', label: t('agentEditor.questionSuggestions.modeGenerated') },
  { value: 'knowledge', label: t('agentEditor.questionSuggestions.modeKnowledge') },
  { value: 'hybrid', label: t('agentEditor.questionSuggestions.modeHybrid') },
]);
const followUpCategoryOptions = computed(() => [
  { value: 'clarify', label: t('agentEditor.questionSuggestions.categoryClarify') },
  { value: 'deepen', label: t('agentEditor.questionSuggestions.categoryDeepen') },
  { value: 'action', label: t('agentEditor.questionSuggestions.categoryAction') },
]);

const addStarterSuggestion = () => {
  const items = formData.value.config.question_suggestions.starters.items;
  if (items.length < 8) items.push('');
};

const removeStarterSuggestion = (index: number) => {
  formData.value.config.question_suggestions.starters.items.splice(index, 1);
};

const applyDefaultModelsIfEmpty = () => {
  if (props.mode !== 'create' || !formData.value) return
  const chatModelId = selectInitialModelId(allModels.value, 'KnowledgeQA')
  const rerankModelId = selectInitialModelId(allModels.value, 'Rerank')
  const vlmModelId = selectInitialModelId(allModels.value, 'VLLM')
  const asrModelId = selectInitialModelId(allModels.value, 'ASR')
  if (!formData.value.config.model_id && chatModelId) {
    formData.value.config.model_id = chatModelId
  }
  if (!formData.value.config.rerank_model_id && rerankModelId) {
    formData.value.config.rerank_model_id = rerankModelId
  }
  if (!formData.value.config.vlm_model_id && vlmModelId) {
    formData.value.config.vlm_model_id = vlmModelId
  }
  if (!formData.value.config.asr_model_id && asrModelId) {
    formData.value.config.asr_model_id = asrModelId
  }
}

const agentMode = computed({
  get: () => formData.value.config.agent_mode,
  set: (val: 'quick-answer' | 'smart-reasoning') => { formData.value.config.agent_mode = val; }
});

const isAgentMode = computed(() => agentMode.value === 'smart-reasoning');

const effectiveDefaultMaxCompletionTokens = computed(() =>
  defaultMaxCompletionTokensFor(agentMode.value, formData.value.config.sandbox_config_id),
);

const maxCompletionTokensMode = computed({
  get: () => (formData.value.config.max_completion_tokens > 0 ? 'custom' : 'default'),
  set: (mode: 'default' | 'custom') => {
    if (mode === 'default') {
      formData.value.config.max_completion_tokens = 0;
      return;
    }
    if (!formData.value.config.max_completion_tokens) {
      formData.value.config.max_completion_tokens = effectiveDefaultMaxCompletionTokens.value;
    }
  },
});

const lastFiniteMaxIterations = ref(10);
const maxIterationsMode = computed({
  get: () => (formData.value.config.max_iterations < 0 ? 'unlimited' : 'limit'),
  set: (mode: 'limit' | 'unlimited') => {
    if (mode === 'unlimited') {
      if (formData.value.config.max_iterations > 1) {
        lastFiniteMaxIterations.value = formData.value.config.max_iterations;
      }
      formData.value.config.max_iterations = -1;
      return;
    }
    const restored = lastFiniteMaxIterations.value > 1 ? lastFiniteMaxIterations.value : 10;
    formData.value.config.max_iterations = restored;
  },
});

const currentIntentTemplate = computed(() =>
  intentPromptTemplates.value.find((template) => template.id === selectedIntent.value),
);

const currentIntentTemplateDesc = computed(() =>
  currentIntentTemplate.value?.description || '',
);

const isIntentCustomized = (intentId: string) => {
  const overrides = formData.value.config.intent_prompts || {};
  const override = overrides[intentId];
  if (!override?.trim()) return false;
  const template = intentPromptTemplates.value.find((item) => item.id === intentId);
  return override.trim() !== (template?.content || '').trim();
};

const activePromptAnchor = ref('system');

const hasAnyIntentCustomized = computed(() =>
  intentPromptTemplates.value.some((item) => isIntentCustomized(item.id)),
);

// Agent 模式下本组只剩「保留轮数」(以及有知识库时的检索保留),
// 默认文案里的「问题改写」并不展示,故按模式分开。
const conversationSectionDesc = computed(() =>
  isAgentMode.value
    ? t('agentEditor.desc.conversationSectionAgent')
    : t('agentEditor.desc.conversationSection'),
);

const showRewritePrompts = computed(() =>
  !isAgentMode.value
  && formData.value.config.multi_turn_enabled
  && formData.value.config.enable_rewrite,
);

const promptNavItems = computed(() => {
  type PromptNavItem = { key: string; label: string; customized?: boolean };
  const items: PromptNavItem[] = [
    {
      key: 'system',
      label: t('agentEditor.promptNav.system'),
      customized: !!formData.value.config.system_prompt?.trim(),
    },
  ];
  if (!isAgentMode.value) {
    items.push({
      key: 'context',
      label: t('agentEditor.promptNav.context'),
      customized: !!formData.value.config.context_template?.trim(),
    });
    items.push({
      key: 'intent',
      label: t('agentEditor.promptNav.intent'),
      customized: hasAnyIntentCustomized.value,
    });
    if (showRewritePrompts.value) {
      items.push(
        {
          key: 'rewrite-system',
          label: t('agentEditor.promptNav.rewriteSystem'),
          customized: !!formData.value.config.rewrite_prompt_system?.trim(),
        },
        {
          key: 'rewrite-user',
          label: t('agentEditor.promptNav.rewriteUser'),
          customized: !!formData.value.config.rewrite_prompt_user?.trim(),
        },
      );
    }
    if (hasKnowledgeBase.value) {
      items.push({
        key: 'fallback',
        label: t('agentEditor.promptNav.fallback'),
      });
    }
  }
  return items;
});

const syncActivePromptAnchor = () => {
  const items = promptNavItems.value;
  if (!items.length) return;
  if (!items.some((item) => item.key === activePromptAnchor.value)) {
    activePromptAnchor.value = items[0].key;
  }
};

watch(promptNavItems, syncActivePromptAnchor);

watch(currentSection, (section) => {
  if (section === 'prompts') {
    syncActivePromptAnchor();
  }
});

const agentIMChannelCount = ref(0);
const agentEmbedChannelCount = ref(0);

async function loadAgentIntegrationCounts(agentId: string) {
  try {
    const [imResp, embedResp] = await Promise.all([
      listIMChannels(agentId),
      listEmbedChannels(agentId),
    ]);
    agentIMChannelCount.value = imResp?.data?.length ?? 0;
    agentEmbedChannelCount.value = embedResp?.data?.length ?? 0;
  } catch {
    agentIMChannelCount.value = 0;
    agentEmbedChannelCount.value = 0;
  }
}

function gotoIntegrations(tab: 'im' | 'embed') {
  const agentId = editorAgent.value?.id;
  if (!agentId) return;
  handleClose();
  router.push({ path: '/platform/settings', query: { section: integrationSectionKey(tab), agentId } });
}

const filteredIntentPlaceholders = computed(() => {
  if (!intentPromptPopup.value.prefix) {
    return placeholderData.value.system_prompt;
  }
  const prefix = intentPromptPopup.value.prefix.toLowerCase();
  return placeholderData.value.system_prompt.filter(p => p.name.toLowerCase().startsWith(prefix));
});

const syncIntentEditorFromSelection = () => {
  const key = selectedIntent.value;
  if (!key) {
    intentEditorValue.value = '';
    return;
  }
  const overrides = formData.value.config.intent_prompts || {};
  intentEditorValue.value = overrides[key] ?? currentIntentTemplate.value?.content ?? '';
};

watch(selectedIntent, () => {
  intentPromptPopup.value.show = false;
  intentPromptPopup.value.prefix = '';
  syncIntentEditorFromSelection();
});

watch(
  () => intentPromptTemplates.value,
  (templates) => {
    if (!selectedIntent.value && templates.length > 0) {
      selectedIntent.value = templates[0].id;
    } else if (selectedIntent.value) {
      syncIntentEditorFromSelection();
    }
  },
  { immediate: true },
);

watch(intentEditorValue, (value) => {
  const key = selectedIntent.value;
  if (!key || intentPromptsSyncing.value) return;
  const defaultContent = currentIntentTemplate.value?.content || '';
  const next = value.trim();
  if (!next || next === defaultContent.trim()) {
    if (formData.value.config.intent_prompts) {
      const { [key]: _removed, ...rest } = formData.value.config.intent_prompts;
      if (Object.keys(rest).length === 0) {
        delete formData.value.config.intent_prompts;
      } else {
        formData.value.config.intent_prompts = rest;
      }
    }
    return;
  }
  formData.value.config.intent_prompts = {
    ...(formData.value.config.intent_prompts || {}),
    [key]: value,
  };
});

watch(
  () => formData.value.config.intent_prompts,
  () => {
    intentPromptsSyncing.value = true;
    syncIntentEditorFromSelection();
    intentPromptsSyncing.value = false;
  },
  { deep: true },
);

const resetCurrentIntentPrompt = () => {
  const key = selectedIntent.value;
  if (!key || !formData.value.config.intent_prompts) return;
  const { [key]: _removed, ...rest } = formData.value.config.intent_prompts;
  if (Object.keys(rest).length === 0) {
    delete formData.value.config.intent_prompts;
  } else {
    formData.value.config.intent_prompts = rest;
  }
  syncIntentEditorFromSelection();
};

// ============================================================================
// 智能体类型预设(仅 smart-reasoning 模式下可见)
// 选择类型后自动填充 system_prompt_id / allowed_tools 等;
// 选择 "custom" 或没有匹配预设时不做任何覆盖。
// ============================================================================

const agentType = computed({
  get: () => (formData.value.config.agent_type as AgentType) || 'custom',
  set: (val: AgentType) => { formData.value.config.agent_type = val; },
});

// 当前激活的预设对象(用于 KB 过滤 / UI 徽章)
const activeAgentTypePreset = computed<AgentTypePreset | null>(() => {
  if (!isAgentMode.value) return null;
  const id = agentType.value;
  if (!id || id === 'custom') return null;
  return agentTypePresets.value.find(p => p.id === id) || null;
});

// 根据当前 locale 挑选 i18n 标签
const agentTypePresetLabel = (p: AgentTypePreset): string => {
  const locale = i18nLocale.value || 'default';
  return p.i18n?.[locale]?.label || p.i18n?.default?.label || p.id;
};
const agentTypePresetDescription = (p: AgentTypePreset): string => {
  const locale = i18nLocale.value || 'default';
  return p.i18n?.[locale]?.description || p.i18n?.default?.description || '';
};

// t-select 的 options 数据:label 给 TDesign 自己(用于选中态显示),desc 走自定义 option slot
const agentTypeSelectOptions = computed(() => {
  return agentTypePresets.value.map(p => ({
    value: p.id,
    label: agentTypePresetLabel(p),
    desc: agentTypePresetDescription(p),
  }));
});

// 为每个预设生成"我的 <label>"的默认名称,让用户可以一键保存
// custom 类型默认名为空(让用户自己想)
const getPresetDefaultName = (preset: AgentTypePreset | null): string => {
  if (!preset || preset.id === 'custom') return '';
  return t('agentEditor.agentType.defaultNamePattern', { label: agentTypePresetLabel(preset) });
};
const getPresetDefaultDescription = (preset: AgentTypePreset | null): string => {
  if (!preset) return '';
  return agentTypePresetDescription(preset);
};

// 判断当前名称/描述是否由系统自动填入(任一预设的默认值 或 空)
// 用于在切换类型时只覆盖"未被用户手动编辑"的值,避免覆盖用户输入
const isNameSystemGenerated = (name: string): boolean => {
  if (!name) return true;
  return agentTypePresets.value.some(p => getPresetDefaultName(p) === name);
};
const isDescriptionSystemGenerated = (desc: string): boolean => {
  if (!desc) return true;
  return agentTypePresets.value.some(p => getPresetDefaultDescription(p) === desc);
};

// 按预设 id 返回面向用户的不兼容原因文案。
// 不要直接把 "vector / keyword / wiki" 这些底层 capability 名回传给用户 —
// 用户不关心技术实现,只想知道"为什么我这个知识库不能用"。
const presetKbMismatchKeyMap: Record<string, string> = {
  'rag-qa': 'ragQa',
  'wiki-qa': 'wikiQa',
  'hybrid-rag-wiki': 'hybridRagWiki',
  'data-analysis': 'dataAnalysis',
};
const presetKbMismatchReason = (preset: AgentTypePreset): string => {
  const subKey = presetKbMismatchKeyMap[preset.id];
  if (subKey) return t(`agentEditor.agentType.kbMismatch.${subKey}`);
  return t('agentEditor.agentType.kbMismatch.generic');
};

// 计算预设的"有效 KB 过滤器":工具推导 + YAML 增量叠加。
//
// 设计原则:
//   - 工具 → any_of("KB 至少要能被其中一个工具用得上")由
//     `deriveKbFilterFromTools` 自动算出;
//   - YAML 里的 `kb_filter` 只负责**工具推不出来**的业务规则(如
//     data-analysis 的 `none_of: ["faq"]`),作为增量合并,而不是整体覆盖;
//   - `all_of` / `none_of` 直接从 YAML 继承(工具不表达这类约束)。
//
// 这样 rag-qa / wiki-qa / hybrid 在 YAML 里彻底不写 `kb_filter`,
// data-analysis 只需声明额外的 `none_of`,"工具→能力"的映射只在
// `@/utils/tool-capabilities` 维护一份。
const effectiveKbFilter = (preset: AgentTypePreset | null): AgentTypeKBFilter | null => {
  if (!preset) return null;
  const derived = deriveKbFilterFromTools(preset.config?.allowed_tools || []);
  const yaml = preset.kb_filter;

  // YAML 提供 any_of 时整体覆盖推导(给显式控制留口子);否则用推导的
  const anyOf = (yaml?.any_of && yaml.any_of.length > 0) ? yaml.any_of : (derived?.any_of ?? []);
  const allOf = yaml?.all_of ?? [];
  const noneOf = yaml?.none_of ?? [];
  if (anyOf.length === 0 && allOf.length === 0 && noneOf.length === 0) return null;
  return { any_of: anyOf, all_of: allOf, none_of: noneOf };
};

// 评估单个 KB 是否满足给定预设的 kb_filter
const kbSatisfiesPresetFilter = (kb: { capabilities?: KBCapabilities; ragEnabled?: boolean; wikiEnabled?: boolean; type?: string }, preset: AgentTypePreset | null): { ok: boolean; reason: string } => {
  const filter = effectiveKbFilter(preset);
  if (!preset || !filter) return { ok: true, reason: '' };
  const caps = kb.capabilities || {
    vector: !!kb.ragEnabled,
    keyword: !!kb.ragEnabled,
    wiki: !!kb.wikiEnabled,
    graph: false,
    faq: kb.type === 'faq',
  };
  const has = (name: string): boolean => {
    switch (name) {
      case 'vector': return !!caps.vector;
      case 'keyword': return !!caps.keyword;
      case 'wiki': return !!caps.wiki;
      case 'graph': return !!caps.graph;
      case 'faq': return !!caps.faq;
      default: return false;
    }
  };
  const reason = presetKbMismatchReason(preset);
  if (filter.all_of && filter.all_of.length > 0) {
    for (const n of filter.all_of) {
      if (!has(n)) return { ok: false, reason };
    }
  }
  if (filter.any_of && filter.any_of.length > 0) {
    if (!filter.any_of.some(n => has(n))) {
      return { ok: false, reason };
    }
  }
  if (filter.none_of && filter.none_of.length > 0) {
    for (const n of filter.none_of) {
      if (has(n)) return { ok: false, reason };
    }
  }
  return { ok: true, reason: '' };
};

// "快速问答 / RAG 模式"对 KB 的隐式要求:必须有 vector 或 keyword 索引。
// 这里跟 `activeAgentTypePreset` 解耦——quick-answer 没有 agent_type,
// 所以预设链路恒为 null,但 wiki-only KB 在 RAG 模式下检索结果永远为空,
// 必须在 UI 上 disable + 提示,避免用户白选。
const kbSatisfiesQuickAnswerMode = (kb: { capabilities?: KBCapabilities; ragEnabled?: boolean }): { ok: boolean; reason: string } => {
  if (agentMode.value !== 'quick-answer') return { ok: true, reason: '' };
  const hasRag = kb.capabilities
    ? (!!kb.capabilities.vector || !!kb.capabilities.keyword)
    : !!kb.ragEnabled;
  if (hasRag) return { ok: true, reason: '' };
  return { ok: false, reason: t('agentEditor.agentType.kbMismatch.quickAnswer') };
};

// KB 过滤后的选项(用于"指定知识库"下拉)— 不满足的仍保留但标记 disabled + tooltip
const filteredKbOptionsForPreset = computed(() => {
  const preset = activeAgentTypePreset.value;
  return kbOptions.value.map(kb => {
    const presetResult = kbSatisfiesPresetFilter(kb, preset);
    const modeResult = kbSatisfiesQuickAnswerMode(kb);
    const ok = presetResult.ok && modeResult.ok;
    const reason = !presetResult.ok ? presetResult.reason : (!modeResult.ok ? modeResult.reason : '');
    return { ...kb, disabled: !ok, disabledReason: reason };
  });
});
const filteredMyKbOptions = computed(() => filteredKbOptionsForPreset.value.filter(kb => !kb.shared));
const filteredSharedKbOptions = computed(() => filteredKbOptionsForPreset.value.filter(kb => kb.shared));

// 当前选中的 KB 中,有多少个在新预设 / 模式下会被禁用(用于保存前提示)。
// quick-answer 模式下 preset 恒为 null,但 wiki-only KB 仍属"被禁用",
// 所以这里不再依赖 preset 是否存在,直接看是否有被 disable 的选中项。
const incompatibleSelectedKbCount = computed(() => {
  if (kbSelectionMode.value !== 'selected') return 0;
  const selected = new Set(formData.value.config.knowledge_bases || []);
  return filteredKbOptionsForPreset.value.filter(kb => selected.has(kb.value) && kb.disabled).length;
});

// 应用一个预设的 config 到 formData.config(仅覆盖预设里明确设置的字段,其他不动)
const applyAgentTypePreset = (preset: AgentTypePreset | null) => {
  if (!preset || !preset.config) return;
  const c = preset.config;
  const target = formData.value.config;
  if (c.system_prompt_id !== undefined) {
    target.system_prompt_id = c.system_prompt_id;
    // 根据 system_prompt_id 从已加载的模板列表里查出正文并回填到用户可见的 textarea
    const tmpl = agentSystemPromptTemplates.value.find(t => t.id === c.system_prompt_id);
    if (tmpl && typeof tmpl.content === 'string') {
      target.system_prompt = tmpl.content;
    } else {
      // 模板列表还没加载完 / 或预设引用了不存在的 id:清空让用户感知到变化
      target.system_prompt = '';
      if (c.system_prompt_id) {
        console.warn(`[AgentType] system_prompt_id "${c.system_prompt_id}" not found in agent_system_prompt templates`);
      }
    }
  }
  if (typeof c.temperature === 'number') target.temperature = c.temperature;
  if (typeof c.max_iterations === 'number') target.max_iterations = c.max_iterations;
  if (Array.isArray(c.allowed_tools)) target.allowed_tools = normalizeLegacyToolNames(c.allowed_tools);
  if (typeof c.retain_retrieval_history === 'boolean') target.retain_retrieval_history = c.retain_retrieval_history;
  if (typeof c.faq_priority_enabled === 'boolean') target.faq_priority_enabled = c.faq_priority_enabled;
  if (typeof c.web_search_enabled === 'boolean') target.web_search_enabled = c.web_search_enabled;
  // supported_file_types 采用"强同步"语义:只有 data-analysis 需要限定 csv/xlsx,
  // 其余类型切过来时必须清空,否则会从上一个类型带过来残留。
  if (Array.isArray(c.supported_file_types)) {
    target.supported_file_types = [...c.supported_file_types];
  } else {
    target.supported_file_types = [];
  }
  // kb_selection_mode 同步到 formData 以及 UI 状态(两处都要改,否则单选按钮不更新)
  if (c.kb_selection_mode) {
    target.kb_selection_mode = c.kb_selection_mode;
    kbSelectionMode.value = c.kb_selection_mode;
  }
};

// 用户手动切换类型 → 应用预设
const onAgentTypeChange = (val: AgentType) => {
  // 切换前捕获"名称/描述是否可安全覆盖"
  // 已编辑过的用户输入(不等于任何预设默认值)绝不覆盖
  const canOverrideName = isNameSystemGenerated(formData.value.name);
  const canOverrideDesc = isDescriptionSystemGenerated(formData.value.description);

  agentType.value = val;
  const preset = agentTypePresets.value.find(p => p.id === val) || null;
  if (val !== 'custom') {
    applyAgentTypePreset(preset);
  }

  // 用新预设的默认名/描述刷新自动填充字段
  if (canOverrideName) {
    formData.value.name = getPresetDefaultName(preset);
  }
  if (canOverrideDesc) {
    formData.value.description = getPresetDefaultDescription(preset);
  }

  // 如果新预设与当前已选 KB 冲突,软提示(不强制移除)
  if (incompatibleSelectedKbCount.value > 0) {
    MessagePlugin.warning(
      t('agentEditor.agentType.kbIncompatibleWarn', { count: incompatibleSelectedKbCount.value }),
      4000,
    );
  }
};

// 思考强度:reasoning_effort 为准,旧数据只有 thinking 布尔时按 true→auto / false→off 推导。
// 写入时同步维护 thinking 布尔,保证旧后端 / 旧读取路径继续工作。
const selectedChatModel = computed(() =>
  allModels.value.find(model => model.id === formData.value.config.model_id),
);
const selectedChatModelCanThink = computed(() => modelCanThink(selectedChatModel.value?.capabilities));
// 所选模型无法关闭思考(deepseek-reasoner / qwq-plus / gemini-3 等)时给出提示,
// 否则下拉里没有「关闭」看起来像 bug。
const selectedChatModelAlwaysThinks = computed(
  () => modelCannotDisableThinking(selectedChatModel.value?.capabilities),
);
// 目录上报 capabilities 时严格按 thinking_levels 出选项(含「没有 off」这一事实);
// 没有 capabilities 的模型(本地 / Ollama / 模型列表未加载)才退回通用梯度。
const reasoningEffortOptions = computed<ReasoningLevel[]>(() => optionsFor(selectedChatModel.value?.capabilities));
const reasoningEffortLevel = computed<ReasoningLevel>({
  get: () => levelFromLegacy(formData.value.config.thinking, formData.value.config.reasoning_effort),
  set: (level: ReasoningLevel) => {
    formData.value.config.reasoning_effort = level;
    formData.value.config.thinking = levelEnablesThinking(level);
  },
});
// 已存等级可能不在所选模型的可用集合里(换模型,或加载了一个旧智能体):
// 夹到可用集合上,并同步 thinking 布尔(由 setter 负责),避免界面显示「关闭」
// 而后端其实没下发任何开关、模型照样思考。
//
// 只在模型真正解析出来之后才夹:模型列表异步加载期间 capabilities 还是 undefined,
// 此时的通用梯度会把已保存的 max/xhigh 误降级成 auto。
const clampReasoningEffortToModel = () => {
  if (!selectedChatModel.value) return;
  const clamped = clampLevel(reasoningEffortLevel.value, reasoningEffortOptions.value);
  if (clamped !== reasoningEffortLevel.value) reasoningEffortLevel.value = clamped;
};
watch(
  () => [
    editorInitializing.value,
    formData.value.config.model_id,
    reasoningEffortOptions.value.join(','),
  ].join('|'),
  () => {
    if (!editorInitializing.value) clampReasoningEffortToModel();
  },
  { immediate: true },
);

// 是否为内置智能体
const isBuiltinAgent = computed(() => {
  return formData.value.is_builtin === true;
});

// 系统提示词的 placeholder
const systemPromptPlaceholder = computed(() => {
  return t('agent.editor.systemPromptPlaceholder');
});

// 上下文模板的 placeholder
const contextTemplatePlaceholder = computed(() => {
  return t('agent.editor.contextTemplatePlaceholder');
});

// 是否需要配置 ReRank 模型(仅当关联的知识库中有 RAG 类型时需要)
const needsRerankModel = computed(() => {
  if (!hasKnowledgeBase.value) return false;
  const mode = kbSelectionMode.value;
  if (mode === 'all') {
    // "全部"模式下,只要存在任何一个 RAG 知识库就需要
    return kbOptions.value.some(kb => kb.ragEnabled);
  }
  if (mode === 'selected') {
    const selectedIds = formData.value.config.knowledge_bases || [];
    return kbOptions.value.some(kb => selectedIds.includes(kb.value) && kb.ragEnabled);
  }
  return false;
});

let editorInitializationGeneration = 0;

// 监听可见性变化,重置表单
watch(() => props.visible, async (val) => {
  const generation = ++editorInitializationGeneration;
  if (val) {
    void deploymentCapabilities.ensureLoaded();
    editorInitializing.value = true;
    try {
    savedAgent.value = null;
    currentSection.value = resolveEditorSection(props.initialSection);
    // 先加载依赖数据(包括默认配置)
    await loadDependencies();
    if (generation !== editorInitializationGeneration || !props.visible) return;

    if (props.mode === 'edit' && props.agent) {
      // 深度复制对象以避免引用问题
      const agentData = JSON.parse(JSON.stringify(props.agent));

      // 确保 config 对象存在
      if (!agentData.config) {
        agentData.config = JSON.parse(JSON.stringify(defaultFormData.config));
      }

      // 补全可能缺失的字段
      agentData.config = { ...defaultFormData.config, ...agentData.config };
      if (agentData.config.thinking == null) {
        agentData.config.thinking = false;
      }
      // Legacy rows carry only the boolean: derive the graded level once so
      // the selector and the persisted config agree (true → auto, false → off).
      agentData.config.reasoning_effort = levelFromLegacy(agentData.config.thinking, agentData.config.reasoning_effort);
      agentData.config.thinking = levelEnablesThinking(agentData.config.reasoning_effort);

      agentData.config.question_suggestions = {
        starters: {
          ...defaultFormData.config.question_suggestions.starters,
          ...(agentData.config.question_suggestions?.starters || {}),
          items: agentData.config.question_suggestions?.starters?.items || [],
        },
        follow_ups: {
          ...defaultFormData.config.question_suggestions.follow_ups,
          ...(agentData.config.question_suggestions?.follow_ups || {}),
          categories: agentData.config.question_suggestions?.follow_ups?.categories
            || [...defaultFormData.config.question_suggestions.follow_ups.categories],
        },
      };
      // 确保数组字段存在
      if (!agentData.config.knowledge_bases) agentData.config.knowledge_bases = [];
      // 旧配置里可能还带着已合并的工具名(knowledge_search / grep_chunks /
      // list_knowledge_chunks / get_document_info / wiki_read_source_doc),
      // 映射到新名字并去重,否则复选框对不上工具目录。
      const storedAllowedTools = agentData.config.allowed_tools;
      agentData.config.allowed_tools = normalizeLegacyToolNames(storedAllowedTools);
      if (!agentData.config.mcp_services) agentData.config.mcp_services = [];
      // 授权等待超时:旧数据缺省时用默认 600 秒
      if (agentData.config.mcp_auth_wait_timeout == null || agentData.config.mcp_auth_wait_timeout <= 0) {
        agentData.config.mcp_auth_wait_timeout = 600;
      }
      if (!agentData.config.access_level) agentData.config.access_level = 'auto_write';
      if (!agentData.config.selected_skills) agentData.config.selected_skills = [];
      if (!agentData.config.supported_file_types) agentData.config.supported_file_types = [];
      if (!agentData.config.chat_parser_engine_rules) agentData.config.chat_parser_engine_rules = [];
      // 附件解析调优字段:旧数据缺省时置 0(表示使用全局默认)
      if (agentData.config.attachment_ocr_max_pages == null) agentData.config.attachment_ocr_max_pages = 0;
      if (agentData.config.attachment_parse_wait_timeout_sec == null) agentData.config.attachment_parse_wait_timeout_sec = 0;
      if (agentData.config.max_completion_tokens == null) agentData.config.max_completion_tokens = 0;
      // 长期记忆:后端用 omitempty,跟随空间设置的智能体不带这个字段。
      // 不补成 true 的话开关会显示为"关",用户随手一存就真的把记忆关了。
      if (agentData.config.memory_enabled == null) agentData.config.memory_enabled = true;

      // 兼容旧数据:如果没有 agent_mode 字段,根据 allowed_tools 推断
      if (!agentData.config.agent_mode) {
        const isAgent = agentData.config.max_iterations < 0 || agentData.config.max_iterations > 1 || (agentData.config.allowed_tools && agentData.config.allowed_tools.length > 0);
        agentData.config.agent_mode = isAgent ? 'smart-reasoning' : 'quick-answer';
      }
      // 从未设置工具列表(null)的智能推理智能体使用后端默认工具:把默认工具显式写入并勾选,
      // 否则空列表一经保存就变成"不使用内置工具",悄悄改变行为。无法写入时保持未设置。
      // 放在模式推断之后,旧数据推断出的智能推理模式同样适用。
      const loadedTools = resolveLoadedAllowedTools(
        storedAllowedTools == null ? null : agentData.config.allowed_tools,
        agentData.config.agent_mode,
        agentToolCatalog.value,
      );
      agentData.config.allowed_tools = loadedTools.tools;
      keepAllowedToolsUnset.value = loadedTools.keepUnset;
      storedToolNames.value = [...loadedTools.tools];

      // 设置初始化标志,防止 watch 自动添加工具
      isInitializing.value = true;
      agentData.config = hydrateAgentPromptRefs(agentData.config, promptTemplates.value);
      formData.value = agentData;
      if (agentData.config.max_iterations > 1) {
        lastFiniteMaxIterations.value = agentData.config.max_iterations;
      }
      // 初始化知识库选择模式
      initKbSelectionMode();
      initMcpSelectionMode();
      initSkillsSelectionMode();
      // 初始化完成后重置标志
      nextTick(() => {
        isInitializing.value = false;
      });
      // Display inherited defaults for all agents without persisting a copy.
      fillBuiltinAgentDefaults();
      void loadAgentIntegrationCounts(agentData.id);
    } else {
      // 创建新智能体,使用系统默认值
      storedToolNames.value = [];
      keepAllowedToolsUnset.value = false;
      const newFormData = JSON.parse(JSON.stringify(defaultFormData));
      // 应用系统默认检索参数
      newFormData.config.embedding_top_k = defaultEmbeddingTopK.value;
      newFormData.config.keyword_threshold = defaultKeywordThreshold.value;
      newFormData.config.vector_threshold = defaultVectorThreshold.value;
      newFormData.config.rerank_top_k = defaultRerankTopK.value;
      newFormData.config.rerank_threshold = defaultRerankThreshold.value;
      newFormData.config.max_completion_tokens = 0;
      newFormData.config.max_iterations = -1;
      newFormData.config.temperature = defaultTemperature.value;
      // 应用系统默认提示词(根据模式填充)
      const isAgent = newFormData.config.agent_mode === 'smart-reasoning';
      if (isAgent) {
        // Agent 模式使用 agent-config 的默认系统提示词
        if (defaultAgentSystemPrompt.value) {
          newFormData.config.system_prompt = defaultAgentSystemPrompt.value;
        }
      } else {
        // 快速问答模式:默认提示词来自 prompt-templates 的 default 项
        if (defaultNormalSystemPrompt.value) {
          newFormData.config.system_prompt = defaultNormalSystemPrompt.value;
        }
        if (defaultContextTemplate.value) {
          newFormData.config.context_template = defaultContextTemplate.value;
        }
        if (defaultRewritePromptSystem.value) {
          newFormData.config.rewrite_prompt_system = defaultRewritePromptSystem.value;
        }
        if (defaultRewritePromptUser.value) {
          newFormData.config.rewrite_prompt_user = defaultRewritePromptUser.value;
        }
        if (defaultFallbackPrompt.value) {
          newFormData.config.fallback_prompt = defaultFallbackPrompt.value;
        }
        if (defaultFallbackResponse.value) {
          newFormData.config.fallback_response = defaultFallbackResponse.value;
        }
      }
      formData.value = newFormData;
      // 新建智能体:知识库默认 "全部",MCP / Skills 仍默认 "不使用"。
      kbSelectionMode.value = 'all';
      mcpSelectionMode.value = 'none';
      skillsSelectionMode.value = 'none';

      // 新建智能推理 agent 时,立即应用默认的 agent_type 预设
      // (补齐 system_prompt / allowed_tools / kb_selection_mode 等),
      // 否则用户在 modal 打开瞬间看到的"默认表单"和类型下拉显示的类型不一致。
      if (newFormData.config.agent_mode === 'smart-reasoning') {
        const defaultTypeId = newFormData.config.agent_type as AgentType;
        const preset = agentTypePresets.value.find(p => p.id === defaultTypeId) || null;
        if (defaultTypeId && defaultTypeId !== 'custom') {
          applyAgentTypePreset(preset);
        }
        // 给新建表单补上"我的 XXX"默认名 + 预设描述,让用户可直接保存;
        // 用户输入过的值不会被覆盖(此处是新建场景,字段必定为空)。
        if (!formData.value.name) {
          formData.value.name = getPresetDefaultName(preset);
        }
        if (!formData.value.description) {
          formData.value.description = getPresetDefaultDescription(preset);
        }
      }
      applyDefaultModelsIfEmpty()
    }

    await syncInstalledSkills()
    if (generation !== editorInitializationGeneration || !props.visible) return;

    if (props.initialHighlightField) {
      await applyInitialFieldHighlight(props.initialHighlightField);
      if (generation !== editorInitializationGeneration || !props.visible) return;
    }
    } catch (error) {
      console.error('Failed to initialize agent editor', error);
    } finally {
      if (generation === editorInitializationGeneration && props.visible) {
        // Model normalization and queued form watchers belong to initialization,
        // so capture the baseline only after they have settled.
        clampReasoningEffortToModel();
        await nextTick();
        if (generation !== editorInitializationGeneration || !props.visible) return;
        modalShell.markClean();
        editorInitializing.value = false;
      }
    }
  } else {
    editorInitializing.value = false;
    clearFieldHighlight();
    agentIMChannelCount.value = 0;
    agentEmbedChannelCount.value = 0;
    showSkillProgress.value = false;
    skillProgressRecord.value = null;
    skillProgressId.value = '';
  }
});

// 初始化知识库选择模式
const initKbSelectionMode = () => {
  if (formData.value.config.kb_selection_mode) {
    // 如果有保存的模式,直接使用
    kbSelectionMode.value = formData.value.config.kb_selection_mode;
  } else if (formData.value.config.knowledge_bases?.length > 0) {
    // 有指定知识库
    kbSelectionMode.value = 'selected';
  } else {
    kbSelectionMode.value = 'none';
  }
};

// 初始化 MCP 选择模式
const initMcpSelectionMode = () => {
  if (formData.value.config.mcp_selection_mode) {
    // 如果有保存的模式,直接使用
    mcpSelectionMode.value = formData.value.config.mcp_selection_mode;
  } else if (formData.value.config.mcp_services?.length > 0) {
    // 有指定 MCP 服务
    mcpSelectionMode.value = 'selected';
  } else {
    // Legacy configs with no mode run with every enabled MCP service for the
    // owner (registerMCPTools treats "" as "all"). Show that actual runtime
    // behaviour so the editor matches what the agent can call.
    mcpSelectionMode.value = 'all';
  }
};

// 初始化 Skills 选择模式
const initSkillsSelectionMode = () => {
  if (formData.value.config.skills_selection_mode) {
    // 如果有保存的模式,直接使用
    skillsSelectionMode.value = formData.value.config.skills_selection_mode;
  } else if (formData.value.config.selected_skills?.length > 0) {
    // 有指定 Skills
    skillsSelectionMode.value = 'selected';
  } else {
    skillsSelectionMode.value = 'none';
  }
  autoBindSoleSandbox();
};

// 内置智能体:填入系统默认值
const fillBuiltinAgentDefaults = () => {
  const config = formData.value.config;
  const isAgent = config.agent_mode === 'smart-reasoning';

  if (isAgent) {
    // Agent 模式:使用 agent-config 的默认提示词
    if (!config.system_prompt && defaultAgentSystemPrompt.value) {
      config.system_prompt = defaultAgentSystemPrompt.value;
    }
  } else {
    // 普通模式:默认系统提示词、上下文模板等来自 prompt-templates 的 default 项
    if (!config.system_prompt && defaultNormalSystemPrompt.value) {
      config.system_prompt = defaultNormalSystemPrompt.value;
    }
    if (!config.context_template && defaultContextTemplate.value) {
      config.context_template = defaultContextTemplate.value;
    }
  }

  // 通用默认值
  if (!config.rewrite_prompt_system && defaultRewritePromptSystem.value) {
    config.rewrite_prompt_system = defaultRewritePromptSystem.value;
  }
  if (!config.rewrite_prompt_user && defaultRewritePromptUser.value) {
    config.rewrite_prompt_user = defaultRewritePromptUser.value;
  }
  if (!config.fallback_prompt && defaultFallbackPrompt.value) {
    config.fallback_prompt = defaultFallbackPrompt.value;
  }
  if (!config.fallback_response && defaultFallbackResponse.value) {
    config.fallback_response = defaultFallbackResponse.value;
  }
};

// 监听知识库选择模式变化
watch(kbSelectionMode, (mode) => {
  formData.value.config.kb_selection_mode = mode;
  if (mode === 'none') {
    // 不使用知识库,清空相关配置
    formData.value.config.knowledge_bases = [];
  } else if (mode === 'all') {
    // 全部知识库,清空指定列表
    formData.value.config.knowledge_bases = [];
  }
  // selected 模式保持 knowledge_bases 不变
});

// 监听 MCP 选择模式变化
watch(mcpSelectionMode, (mode) => {
  // Hydration may map a legacy empty mode to "all" for display only; do not
  // persist that translation or clear the stored service list until the user
  // actually edits the MCP selection.
  if (isInitializing.value) return;
  formData.value.config.mcp_selection_mode = mode;
  if (mode === 'none') {
    // 不使用 MCP,清空相关配置
    formData.value.config.mcp_services = [];
  } else if (mode === 'all') {
    // 全部 MCP,清空指定列表
    formData.value.config.mcp_services = [];
  }
  // selected 模式保持 mcp_services 不变
});

// Editing a legacy list is an explicit selection even if the radio was
// already displayed as "selected". An empty list must also stay selected,
// since an unset mode would allow every enabled service at runtime.
watch(() => formData.value.config.mcp_services, () => {
  if (isInitializing.value || mcpSelectionMode.value !== 'selected') return;
  formData.value.config.mcp_selection_mode = 'selected';
}, { deep: true });

watch(() => formData.value.config.sandbox_config_id, async () => {
  if (!props.visible) return
  await syncInstalledSkills()
})

let catalogPollTimer: number | null = null

function stopCatalogPoll() {
  if (catalogPollTimer != null) {
    window.clearInterval(catalogPollTimer)
    catalogPollTimer = null
  }
}

watch(
  [() => props.visible, catalogSkillRows],
  () => {
    const busy = catalogSkillRows.value.some((skill) =>
      skill.installStatus === 'installing' || skill.installStatus === 'removing',
    )
    if (!props.visible || !busy) {
      stopCatalogPoll()
      return
    }
    if (catalogPollTimer != null) return
    catalogPollTimer = window.setInterval(() => {
      void syncInstalledSkills(true)
    }, 2500)
  },
  { flush: 'post' },
)

// 监听 Skills 选择模式变化
watch(skillsSelectionMode, (mode) => {
  formData.value.config.skills_selection_mode = mode;
  if (mode === 'none') {
    // 不使用 Skills,清空相关配置
    formData.value.config.selected_skills = [];
  } else if (mode === 'all') {
    // 全部 Skills,清空指定列表
    formData.value.config.selected_skills = [];
    autoBindSoleSandbox()
  } else {
    autoBindSoleSandbox()
  }
  // selected 模式保持 selected_skills 不变
});

// 监听模式变化,自动调整配置
watch(agentMode, (val, _oldVal) => {
  if (val === 'smart-reasoning') {
    // 切换到 Agent 模式,根据知识库配置启用工具。
    // 注意:默认不注入 thinking / todo_write —— 它们用于显式反思或多步计划,
    // 会显著增加 token 消耗,用户按需手动勾选。
    // 加载智能体时不补工具:空列表表示"不使用内置工具",是保存的值而不是待填的空白。
    // 用户主动切换模式后列表即为显式选择,不再保持未设置。
    if (!isInitializing.value) keepAllowedToolsUnset.value = false;
    if (!isInitializing.value && formData.value.config.allowed_tools.length === 0) {
      const tools: string[] = ['ask_user'];
      if (hasRagKnowledgeBase.value) {
        tools.push(...knowledgeBaseTools);
      }
      if (hasWikiKnowledgeBase.value) {
        tools.push(...wikiReadTools);
      }
      formData.value.config.allowed_tools = tools;
    }
    if (formData.value.config.max_iterations >= 0 && formData.value.config.max_iterations <= 1) {
      formData.value.config.max_iterations = -1;
    }
    // 切换到 Agent 模式时,如果系统提示词是快速问答的默认值或为空,替换为 Agent 默认提示词
    if (defaultAgentSystemPrompt.value) {
      const isDefaultNormalPrompt = formData.value.config.system_prompt === defaultNormalSystemPrompt.value;
      if (!formData.value.config.system_prompt || isDefaultNormalPrompt) {
        formData.value.config.system_prompt = defaultAgentSystemPrompt.value;
      }
    }
  } else {
    // 切换到普通模式,清空工具
    formData.value.config.allowed_tools = [];
    formData.value.config.max_iterations = 1; // 设置为1表示单轮 RAG
    // 切换到快速问答模式时,如果系统提示词是 Agent 的默认值或为空,替换为快速问答默认提示词
    if (defaultNormalSystemPrompt.value) {
      const isDefaultAgentPrompt = formData.value.config.system_prompt === defaultAgentSystemPrompt.value;
      if (!formData.value.config.system_prompt || isDefaultAgentPrompt) {
        formData.value.config.system_prompt = defaultNormalSystemPrompt.value;
      }
    }
    // 其他提示词只在为空时填充
    if (!formData.value.config.context_template && defaultContextTemplate.value) {
      formData.value.config.context_template = defaultContextTemplate.value;
    }
    if (!formData.value.config.rewrite_prompt_system && defaultRewritePromptSystem.value) {
      formData.value.config.rewrite_prompt_system = defaultRewritePromptSystem.value;
    }
    if (!formData.value.config.rewrite_prompt_user && defaultRewritePromptUser.value) {
      formData.value.config.rewrite_prompt_user = defaultRewritePromptUser.value;
    }
    if (!formData.value.config.fallback_prompt && defaultFallbackPrompt.value) {
      formData.value.config.fallback_prompt = defaultFallbackPrompt.value;
    }
    if (!formData.value.config.fallback_response && defaultFallbackResponse.value) {
      formData.value.config.fallback_response = defaultFallbackResponse.value;
    }
  }
});

// 监听知识库启用状态变化:
//   - 从"无"变"有":自动补齐 RAG 基础工具,方便用户开箱即用(仅 seed 行为);
//   - 从"有"变"无":**不再**自动擦工具,依赖不满足时由 `availableTools` 标注原因
//     (未勾选的工具禁止勾选)+ 运行时工具注册器过滤。`allowed_tools` 代表用户意图,只应在用户显式操作
//     (切 agent_type / 切 agent_mode / 手勾工具)时变更。
// 历史背景:旧版本在 KB 能力消失时会擦除 KB/Wiki 工具,导致用户切换
// `kb_selection_mode` 到 "selected"、但尚未勾具体 KB 的过渡期里静默丢失工具,
// 对默认工具全是 wiki_* 的内置"维基问答"智能体尤为致命。
watch(hasKnowledgeBase, (hasKB, oldHasKB) => {
  // 如果当前在检索策略页面但没有知识库能力了,切换到基础设置
  if (!hasKB && currentSection.value === 'retrieval') {
    currentSection.value = 'basic';
  }

  // 初始化期间或非 Agent 模式下不自动调整工具
  if (isInitializing.value || !isAgentMode.value) return;

  // 保持未设置(使用默认工具)时不补工具,否则保存后会丢掉默认工具。
  if (hasKB && !oldHasKB && !keepAllowedToolsUnset.value) {
    // 从无知识库变为有知识库,seed 默认的 RAG 工具(仅补齐未勾的)
    const currentTools = formData.value.config.allowed_tools || [];
    const toolsToAdd = knowledgeBaseTools.filter((tool: string) => !currentTools.includes(tool));
    formData.value.config.allowed_tools = [...currentTools, ...toolsToAdd];
  }
});

// 监听运行模式变化,自动切换页面
watch(isAgentMode, (isAgent) => {
  // 如果当前在高级设置或检索策略页面但切换到了Agent模式,切换到基础设置
  if (isAgent && (currentSection.value === 'advanced' || currentSection.value === 'retrieval')) {
    currentSection.value = 'basic';
  }
  if (!isAgent && (currentSection.value === 'skills' || currentSection.value === 'sandbox')) {
    currentSection.value = 'basic';
  }
});

// 监听设置弹窗关闭,刷新模型列表
watch(() => uiStore.showSettingsModal, async (visible, prevVisible) => {
  if (prevVisible && !visible && props.visible) {
    try {
      await Promise.all([
        chatResources.ensureModels(true),
        editorResources.ensureStorageEngine(true),
        chatResources.ensureSandboxConfigs(true),
      ]);
      if (chatResources.allModels.length > 0) {
        allModels.value = chatResources.allModels;
      }
      if (editorResources.storageStatus.length > 0) {
        storageEngineStatus.value = editorResources.storageStatus;
      }
      await syncInstalledSkills(true);
    } catch (e) {
      console.warn('Failed to refresh data after settings closed', e);
    }
  }
});

watch(() => chatResources.allModels, (list) => {
  if (props.visible) {
    allModels.value = list;
  }
});

const mapKbToOption = (kb: any, shared: boolean, orgName?: string) => {
  const strategy = kb.indexing_strategy;
  const caps: KBCapabilities | undefined = kb.capabilities;
  return {
    label: kb.name,
    value: kb.id,
    type: kb.type || 'document',
    count: kb.type === 'faq' ? (kb.chunk_count || 0) : (kb.knowledge_count || 0),
    shared,
    orgName,
    ragEnabled: caps ? (caps.vector || caps.keyword) : (!strategy || strategy.vector_enabled || strategy.keyword_enabled),
    wikiEnabled: caps ? caps.wiki : (strategy?.wiki_enabled || false),
    capabilities: caps,
  };
};

const applyPromptTemplateDefaults = (cfg: PromptTemplatesConfig | null) => {
  promptTemplates.value = cfg;
  if (!cfg) return;
  if (cfg.agent_system_prompt && Array.isArray(cfg.agent_system_prompt)) {
    agentSystemPromptTemplates.value = cfg.agent_system_prompt;
    const ragDefault =
      cfg.agent_system_prompt.find(t => t.mode === 'rag' && t.default) ||
      cfg.agent_system_prompt.find(t => t.mode === 'rag');
    if (ragDefault?.content) {
      defaultAgentSystemPrompt.value = ragDefault.content;
    }
  }
  const pickDefault = (arr?: PromptTemplate[]): PromptTemplate | undefined =>
    Array.isArray(arr) ? arr.find(t => t.default) : undefined;
  const sysPrompt = pickDefault(cfg.system_prompt);
  if (sysPrompt?.content) defaultNormalSystemPrompt.value = sysPrompt.content;
  const ctxTmpl = pickDefault(cfg.context_template);
  if (ctxTmpl?.content) defaultContextTemplate.value = ctxTmpl.content;
  const rewriteTmpl = pickDefault(cfg.rewrite);
  if (rewriteTmpl?.content) defaultRewritePromptSystem.value = rewriteTmpl.content;
  if (rewriteTmpl?.user) defaultRewritePromptUser.value = rewriteTmpl.user;
  const fallbackList = Array.isArray(cfg.fallback) ? cfg.fallback : [];
  const fixedFallback = fallbackList.find(t => t.default && t.mode !== 'model');
  if (fixedFallback?.content) defaultFallbackResponse.value = fixedFallback.content;
  const modelFallback = fallbackList.find(t => t.mode === 'model' && t.default) || fallbackList.find(t => t.mode === 'model');
  if (modelFallback?.content) defaultFallbackPrompt.value = modelFallback.content;
  if (Array.isArray(cfg.intent_prompts)) {
    intentPromptTemplates.value = cfg.intent_prompts;
  }
};

// 保存成功但后端调整了工具列表时提示用户(保留了无法识别的名称,或移除了由其他设置控制的工具)
const notifyAllowedToolsWarnings = (warnings?: AllowedToolsWarnings) => {
  if (warnings?.kept_unknown?.length) {
    MessagePlugin.warning(t('agentEditor.tools.keptUnknownWarning', { names: warnings.kept_unknown.join(', ') }));
  }
  if (warnings?.dropped?.length) {
    MessagePlugin.warning(t('agentEditor.tools.droppedWarning', { names: warnings.dropped.join(', ') }));
  }
};

// 加载依赖数据(复用空间级缓存,避免重复请求)
const loadDependencies = async () => {
  try {
    await Promise.all([
      chatResources.ensureModels(),
      chatResources.ensureKnowledgeBases(),
      chatResources.ensureWebSearchProviders(),
      chatResources.ensureSandboxConfigs(),
      editorResources.prefetchAgentEditorDeps(),
    ]);

    if (chatResources.allModels.length > 0) {
      allModels.value = chatResources.allModels;
    }

    const myKbs = chatResources.rawKnowledgeBases.map((kb: any) => mapKbToOption(kb, false));
    const myKbIds = new Set(myKbs.map(kb => kb.value));
    const sharedKbs = (orgStore.sharedKnowledgeBases || [])
      .filter((shared: any) => shared.knowledge_base && !myKbIds.has(shared.knowledge_base.id))
      .map((shared: any) => mapKbToOption(shared.knowledge_base, true, shared.org_name));
    kbOptions.value = [...myKbs, ...sharedKbs];

    agentTypePresets.value = editorResources.agentTypePresets as AgentTypePreset[];
    agentToolCatalog.value = editorResources.agentTools as AgentToolCatalog | null;
    applyPromptTemplateDefaults(editorResources.promptTemplates);

    storageEngineStatus.value = editorResources.storageStatus;

    webSearchProviderList.value = chatResources.webSearchProviders as WebSearchProviderEntity[];

    if (editorResources.placeholders) {
      placeholderData.value = editorResources.placeholders;
    }

    const rc = editorResources.tenantRetrievalConfig as Record<string, number> | null;
    if (rc?.embedding_top_k) defaultEmbeddingTopK.value = rc.embedding_top_k;
    if (rc?.keyword_threshold !== undefined) defaultKeywordThreshold.value = rc.keyword_threshold;
    if (rc?.vector_threshold !== undefined) defaultVectorThreshold.value = rc.vector_threshold;
    if (rc?.rerank_top_k) defaultRerankTopK.value = rc.rerank_top_k;
    if (rc?.rerank_threshold !== undefined) defaultRerankThreshold.value = rc.rerank_threshold;
  } catch (e) {
    console.error('Failed to load dependencies', e);
  }
};

// 跳转到模型管理页面添加模型
const handleAddModel = (subSection: string) => {
  uiStore.openSettings('models', subSection);
};

const handleClose = () => {
  showPlaceholderPopup.value = false;
  showContextPlaceholderPopup.value = false;
  intentPromptPopup.value.show = false;
  rewriteSystemPopup.value.show = false;
  rewriteUserPopup.value.show = false;
  fallbackPromptPopup.value.show = false;
  emit('update:visible', false);
};

const modalShell = useModalShell({
  visible: () => props.visible,
  loading: () => editorInitializing.value,
  close: handleClose,
  snapshot: () => formData.value,
  ignoreEscape: () =>
    showPlaceholderPopup.value ||
    showContextPlaceholderPopup.value ||
    intentPromptPopup.value.show ||
    rewriteSystemPopup.value.show ||
    rewriteUserPopup.value.show ||
    fallbackPromptPopup.value.show,
});

// 过滤后的占位符列表
const filteredPlaceholders = computed(() => {
  if (!placeholderPrefix.value) {
    return availablePlaceholders.value;
  }
  const prefix = placeholderPrefix.value.toLowerCase();
  return availablePlaceholders.value.filter(p =>
    p.name.toLowerCase().startsWith(prefix)
  );
});

// 过滤后的上下文模板占位符列表
const filteredContextPlaceholders = computed(() => {
  if (!contextPlaceholderPrefix.value) {
    return contextTemplatePlaceholders.value;
  }
  const prefix = contextPlaceholderPrefix.value.toLowerCase();
  return contextTemplatePlaceholders.value.filter(p =>
    p.name.toLowerCase().startsWith(prefix)
  );
});

// 过滤后的改写系统提示词占位符列表
const filteredRewriteSystemPlaceholders = computed(() => {
  if (!rewriteSystemPopup.value.prefix) {
    return rewriteSystemPlaceholders.value;
  }
  const prefix = rewriteSystemPopup.value.prefix.toLowerCase();
  return rewriteSystemPlaceholders.value.filter(p =>
    p.name.toLowerCase().startsWith(prefix)
  );
});

// 过滤后的改写用户提示词占位符列表
const filteredRewriteUserPlaceholders = computed(() => {
  if (!rewriteUserPopup.value.prefix) {
    return rewritePlaceholders.value;
  }
  const prefix = rewriteUserPopup.value.prefix.toLowerCase();
  return rewritePlaceholders.value.filter(p =>
    p.name.toLowerCase().startsWith(prefix)
  );
});

// 过滤后的兜底提示词占位符列表
const filteredFallbackPlaceholders = computed(() => {
  if (!fallbackPromptPopup.value.prefix) {
    return fallbackPlaceholders.value;
  }
  const prefix = fallbackPromptPopup.value.prefix.toLowerCase();
  return fallbackPlaceholders.value.filter(p =>
    p.name.toLowerCase().startsWith(prefix)
  );
});

// 获取 textarea 元素
const getTextareaElement = (): HTMLTextAreaElement | null => {
  if (promptTextareaRef.value) {
    if (promptTextareaRef.value.$el) {
      return promptTextareaRef.value.$el.querySelector('textarea');
    }
    if (promptTextareaRef.value instanceof HTMLTextAreaElement) {
      return promptTextareaRef.value;
    }
  }
  return null;
};

// 计算光标位置
const calculateCursorPosition = (textarea: HTMLTextAreaElement) => {
  const cursorPos = textarea.selectionStart;
  const textBeforeCursor = formData.value.config.system_prompt.substring(0, cursorPos);

  const style = window.getComputedStyle(textarea);
  // Placeholder popup is `position: fixed` under the root zoom; normalize the
  // visual-pixel rect to CSS pixels so the popup actually lands on the caret.
  const textareaRect = rectToCssPx(textarea.getBoundingClientRect(), getRootZoom());

  const lineHeight = parseFloat(style.lineHeight) || 20;
  const paddingTop = parseFloat(style.paddingTop) || 0;
  const paddingLeft = parseFloat(style.paddingLeft) || 0;

  // 计算当前行号
  const lines = textBeforeCursor.split('\n');
  const currentLine = lines.length - 1;
  const currentLineText = lines[currentLine];

  // 创建临时 span 计算文本宽度
  const span = document.createElement('span');
  span.style.font = style.font;
  span.style.visibility = 'hidden';
  span.style.position = 'absolute';
  span.style.whiteSpace = 'pre';
  span.textContent = currentLineText;
  document.body.appendChild(span);
  const textWidth = span.offsetWidth;
  document.body.removeChild(span);

  const scrollTop = textarea.scrollTop;
  const top = textareaRect.top + paddingTop + (currentLine * lineHeight) - scrollTop + lineHeight + 4;
  const scrollLeft = textarea.scrollLeft;
  const left = textareaRect.left + paddingLeft + textWidth - scrollLeft;

  return { top, left };
};

// 检查并显示占位符提示
const checkAndShowPlaceholderPopup = () => {
  const textarea = getTextareaElement();
  if (!textarea) return;

  const cursorPos = textarea.selectionStart;
  const textBeforeCursor = formData.value.config.system_prompt.substring(0, cursorPos);

  // 查找最近的 {{ 位置
  let lastOpenPos = -1;
  for (let i = textBeforeCursor.length - 1; i >= 1; i--) {
    if (textBeforeCursor[i] === '{' && textBeforeCursor[i - 1] === '{') {
      const textAfterOpen = textBeforeCursor.substring(i + 1);
      if (!textAfterOpen.includes('}}')) {
        lastOpenPos = i - 1;
        break;
      }
    }
  }

  if (lastOpenPos === -1) {
    showPlaceholderPopup.value = false;
    placeholderPrefix.value = '';
    return;
  }

  const textAfterOpen = textBeforeCursor.substring(lastOpenPos + 2);
  placeholderPrefix.value = textAfterOpen;

  const filtered = filteredPlaceholders.value;
  if (filtered.length > 0) {
    nextTick(() => {
      const position = calculateCursorPosition(textarea);
      popupStyle.value = {
        top: `${position.top}px`,
        left: `${position.left}px`
      };
      showPlaceholderPopup.value = true;
      selectedPlaceholderIndex.value = 0;
    });
  } else {
    showPlaceholderPopup.value = false;
  }
};

// 处理输入
const handlePromptInput = () => {
  if (placeholderPopupTimer) {
    clearTimeout(placeholderPopupTimer);
  }
  placeholderPopupTimer = setTimeout(() => {
    checkAndShowPlaceholderPopup();
  }, 50);
};

// 插入占位符
const insertPlaceholder = (placeholderName: string, fromPopup: boolean = false) => {
  const textarea = getTextareaElement();
  if (!textarea) return;

  showPlaceholderPopup.value = false;
  placeholderPrefix.value = '';
  selectedPlaceholderIndex.value = 0;

  nextTick(() => {
    const cursorPos = textarea.selectionStart;
    const currentValue = formData.value.config.system_prompt || '';
    const textBeforeCursor = currentValue.substring(0, cursorPos);
    const textAfterCursor = currentValue.substring(cursorPos);

    // 只有从下拉列表选择时才查找 {{ 并替换
    if (fromPopup) {
      let lastOpenPos = -1;
      for (let i = textBeforeCursor.length - 1; i >= 1; i--) {
        if (textBeforeCursor[i] === '{' && textBeforeCursor[i - 1] === '{') {
          lastOpenPos = i - 1;
          break;
        }
      }

      if (lastOpenPos !== -1) {
        const textBeforeOpen = currentValue.substring(0, lastOpenPos);
        const newValue = textBeforeOpen + `{{${placeholderName}}}` + textAfterCursor;
        formData.value.config.system_prompt = newValue;

        nextTick(() => {
          const newCursorPos = textBeforeOpen.length + placeholderName.length + 4;
          textarea.setSelectionRange(newCursorPos, newCursorPos);
          textarea.focus();
        });
        return;
      }
    }

    // 直接在光标位置插入完整占位符
    const newValue = textBeforeCursor + `{{${placeholderName}}}` + textAfterCursor;
    formData.value.config.system_prompt = newValue;

    nextTick(() => {
      const newCursorPos = cursorPos + placeholderName.length + 4;
      textarea.setSelectionRange(newCursorPos, newCursorPos);
      textarea.focus();
    });
  });
};

// 获取上下文模板 textarea 元素
const getContextTemplateTextareaElement = (): HTMLTextAreaElement | null => {
  if (contextTemplateTextareaRef.value) {
    if (contextTemplateTextareaRef.value.$el) {
      return contextTemplateTextareaRef.value.$el.querySelector('textarea');
    }
    if (contextTemplateTextareaRef.value instanceof HTMLTextAreaElement) {
      return contextTemplateTextareaRef.value;
    }
  }
  return null;
};

// 计算上下文模板光标位置
const calculateContextCursorPosition = (textarea: HTMLTextAreaElement) => {
  const cursorPos = textarea.selectionStart;
  const textBeforeCursor = formData.value.config.context_template.substring(0, cursorPos);

  const style = window.getComputedStyle(textarea);
  // See `calculateCursorPosition` for the zoom rationale.
  const textareaRect = rectToCssPx(textarea.getBoundingClientRect(), getRootZoom());

  const lineHeight = parseFloat(style.lineHeight) || 20;
  const paddingTop = parseFloat(style.paddingTop) || 0;
  const paddingLeft = parseFloat(style.paddingLeft) || 0;

  const lines = textBeforeCursor.split('\n');
  const currentLine = lines.length - 1;
  const currentLineText = lines[currentLine];

  const span = document.createElement('span');
  span.style.font = style.font;
  span.style.visibility = 'hidden';
  span.style.position = 'absolute';
  span.style.whiteSpace = 'pre';
  span.textContent = currentLineText;
  document.body.appendChild(span);
  const textWidth = span.offsetWidth;
  document.body.removeChild(span);

  const scrollTop = textarea.scrollTop;
  const top = textareaRect.top + paddingTop + (currentLine * lineHeight) - scrollTop + lineHeight + 4;
  const scrollLeft = textarea.scrollLeft;
  const left = textareaRect.left + paddingLeft + textWidth - scrollLeft;

  return { top, left };
};

// 检查并显示上下文模板占位符提示
const checkAndShowContextPlaceholderPopup = () => {
  const textarea = getContextTemplateTextareaElement();
  if (!textarea) return;

  const cursorPos = textarea.selectionStart;
  const textBeforeCursor = formData.value.config.context_template.substring(0, cursorPos);

  let lastOpenPos = -1;
  for (let i = textBeforeCursor.length - 1; i >= 1; i--) {
    if (textBeforeCursor[i] === '{' && textBeforeCursor[i - 1] === '{') {
      const textAfterOpen = textBeforeCursor.substring(i + 1);
      if (!textAfterOpen.includes('}}')) {
        lastOpenPos = i - 1;
        break;
      }
    }
  }

  if (lastOpenPos === -1) {
    showContextPlaceholderPopup.value = false;
    contextPlaceholderPrefix.value = '';
    return;
  }

  const textAfterOpen = textBeforeCursor.substring(lastOpenPos + 2);
  contextPlaceholderPrefix.value = textAfterOpen;

  const filtered = filteredContextPlaceholders.value;
  if (filtered.length > 0) {
    nextTick(() => {
      const position = calculateContextCursorPosition(textarea);
      contextPopupStyle.value = {
        top: `${position.top}px`,
        left: `${position.left}px`
      };
      showContextPlaceholderPopup.value = true;
      selectedContextPlaceholderIndex.value = 0;
    });
  } else {
    showContextPlaceholderPopup.value = false;
  }
};

// 处理上下文模板输入
const handleContextTemplateInput = () => {
  if (contextPlaceholderPopupTimer) {
    clearTimeout(contextPlaceholderPopupTimer);
  }
  contextPlaceholderPopupTimer = setTimeout(() => {
    checkAndShowContextPlaceholderPopup();
  }, 50);
};

// 插入上下文模板占位符
const insertContextPlaceholder = (placeholderName: string, fromPopup: boolean = false) => {
  const textarea = getContextTemplateTextareaElement();
  if (!textarea) return;

  showContextPlaceholderPopup.value = false;
  contextPlaceholderPrefix.value = '';
  selectedContextPlaceholderIndex.value = 0;

  nextTick(() => {
    const cursorPos = textarea.selectionStart;
    const currentValue = formData.value.config.context_template || '';
    const textBeforeCursor = currentValue.substring(0, cursorPos);
    const textAfterCursor = currentValue.substring(cursorPos);

    // 只有从下拉列表选择时才查找 {{ 并替换
    if (fromPopup) {
      let lastOpenPos = -1;
      for (let i = textBeforeCursor.length - 1; i >= 1; i--) {
        if (textBeforeCursor[i] === '{' && textBeforeCursor[i - 1] === '{') {
          lastOpenPos = i - 1;
          break;
        }
      }

      if (lastOpenPos !== -1) {
        const textBeforeOpen = currentValue.substring(0, lastOpenPos);
        const newValue = textBeforeOpen + `{{${placeholderName}}}` + textAfterCursor;
        formData.value.config.context_template = newValue;

        nextTick(() => {
          const newCursorPos = textBeforeOpen.length + placeholderName.length + 4;
          textarea.setSelectionRange(newCursorPos, newCursorPos);
          textarea.focus();
        });
        return;
      }
    }

    // 直接在光标位置插入完整占位符
    const newValue = textBeforeCursor + `{{${placeholderName}}}` + textAfterCursor;
    formData.value.config.context_template = newValue;

    nextTick(() => {
      const newCursorPos = cursorPos + placeholderName.length + 4;
      textarea.setSelectionRange(newCursorPos, newCursorPos);
      textarea.focus();
    });
  });
};

type GenericPlaceholderType = 'rewriteSystem' | 'rewriteUser' | 'fallback' | 'intent';

const genericPlaceholderFieldKeyMap: Record<Exclude<GenericPlaceholderType, 'intent'>, keyof typeof formData.value.config> = {
  rewriteSystem: 'rewrite_prompt_system',
  rewriteUser: 'rewrite_prompt_user',
  fallback: 'fallback_prompt',
};

const getGenericPlaceholderFieldValue = (type: GenericPlaceholderType): string => {
  if (type === 'intent') return intentEditorValue.value || '';
  return String(formData.value.config[genericPlaceholderFieldKeyMap[type]] || '');
};

const setGenericPlaceholderFieldValue = (type: GenericPlaceholderType, value: string) => {
  if (type === 'intent') {
    intentEditorValue.value = value;
    return;
  }
  (formData.value.config as any)[genericPlaceholderFieldKeyMap[type]] = value;
};

// 通用获取 textarea 元素
const getGenericTextareaElement = (type: GenericPlaceholderType): HTMLTextAreaElement | null => {
  const refMap = {
    rewriteSystem: rewriteSystemTextareaRef,
    rewriteUser: rewriteUserTextareaRef,
    fallback: fallbackPromptTextareaRef,
    intent: intentPromptTextareaRef,
  };
  const ref = refMap[type];
  if (ref.value) {
    if (ref.value.$el) {
      return ref.value.$el.querySelector('textarea');
    }
    if (ref.value instanceof HTMLTextAreaElement) {
      return ref.value;
    }
  }
  return null;
};

// 通用计算光标位置
const calculateGenericCursorPosition = (textarea: HTMLTextAreaElement, fieldValue: string) => {
  const cursorPos = textarea.selectionStart;
  const textBeforeCursor = fieldValue.substring(0, cursorPos);
  const lines = textBeforeCursor.split('\n');
  const currentLine = lines.length - 1;
  const currentLineText = lines[currentLine];

  // See `calculateCursorPosition` for the zoom rationale.
  const textareaRect = rectToCssPx(textarea.getBoundingClientRect(), getRootZoom());
  const style = window.getComputedStyle(textarea);
  const lineHeight = parseFloat(style.lineHeight) || 20;
  const paddingTop = parseFloat(style.paddingTop) || 0;
  const paddingLeft = parseFloat(style.paddingLeft) || 0;

  const span = document.createElement('span');
  span.style.font = style.font;
  span.style.visibility = 'hidden';
  span.style.position = 'absolute';
  span.style.whiteSpace = 'pre';
  span.textContent = currentLineText;
  document.body.appendChild(span);
  const textWidth = span.offsetWidth;
  document.body.removeChild(span);

  const scrollTop = textarea.scrollTop;
  const top = textareaRect.top + paddingTop + (currentLine * lineHeight) - scrollTop + lineHeight + 4;
  const scrollLeft = textarea.scrollLeft;
  const left = textareaRect.left + paddingLeft + textWidth - scrollLeft;

  return { top, left };
};

// 通用检查并显示占位符弹出
const checkAndShowGenericPlaceholderPopup = (
  type: GenericPlaceholderType,
  popup: typeof rewriteSystemPopup,
  filteredPlaceholders: PlaceholderDefinition[]
) => {
  const textarea = getGenericTextareaElement(type);
  if (!textarea) return;

  const cursorPos = textarea.selectionStart;
  const fieldValue = getGenericPlaceholderFieldValue(type);
  const textBeforeCursor = fieldValue.substring(0, cursorPos);

  let lastOpenPos = -1;
  for (let i = textBeforeCursor.length - 1; i >= 1; i--) {
    if (textBeforeCursor[i] === '{' && textBeforeCursor[i - 1] === '{') {
      const textAfterOpen = textBeforeCursor.substring(i + 1);
      if (!textAfterOpen.includes('}}')) {
        lastOpenPos = i - 1;
        break;
      }
    }
  }

  if (lastOpenPos === -1) {
    popup.value.show = false;
    popup.value.prefix = '';
    return;
  }

  const textAfterOpen = textBeforeCursor.substring(lastOpenPos + 2);
  popup.value.prefix = textAfterOpen;

  if (filteredPlaceholders.length > 0) {
    nextTick(() => {
      const position = calculateGenericCursorPosition(textarea, fieldValue);
      popup.value.style = {
        top: `${position.top}px`,
        left: `${position.left}px`
      };
      popup.value.show = true;
      popup.value.selectedIndex = 0;
    });
  } else {
    popup.value.show = false;
  }
};

// 处理改写系统提示词输入
const handleRewriteSystemInput = () => {
  if (rewriteSystemPopup.value.timer) {
    clearTimeout(rewriteSystemPopup.value.timer);
  }
  rewriteSystemPopup.value.timer = setTimeout(() => {
    checkAndShowGenericPlaceholderPopup('rewriteSystem', rewriteSystemPopup, filteredRewriteSystemPlaceholders.value);
  }, 50);
};

// 处理改写用户提示词输入
const handleRewriteUserInput = () => {
  if (rewriteUserPopup.value.timer) {
    clearTimeout(rewriteUserPopup.value.timer);
  }
  rewriteUserPopup.value.timer = setTimeout(() => {
    checkAndShowGenericPlaceholderPopup('rewriteUser', rewriteUserPopup, filteredRewriteUserPlaceholders.value);
  }, 50);
};

// 处理兜底提示词输入
const handleFallbackPromptInput = () => {
  if (fallbackPromptPopup.value.timer) {
    clearTimeout(fallbackPromptPopup.value.timer);
  }
  fallbackPromptPopup.value.timer = setTimeout(() => {
    checkAndShowGenericPlaceholderPopup('fallback', fallbackPromptPopup, filteredFallbackPlaceholders.value);
  }, 50);
};

// 处理意图提示词输入
const handleIntentPromptInput = () => {
  if (intentPromptPopup.value.timer) {
    clearTimeout(intentPromptPopup.value.timer);
  }
  intentPromptPopup.value.timer = setTimeout(() => {
    checkAndShowGenericPlaceholderPopup('intent', intentPromptPopup, filteredIntentPlaceholders.value);
  }, 50);
};

// 通用插入占位符
const insertGenericPlaceholder = (type: GenericPlaceholderType, placeholderName: string, fromPopup: boolean = false) => {
  const textarea = getGenericTextareaElement(type);
  if (!textarea) return;

  const popupMap = {
    rewriteSystem: rewriteSystemPopup,
    rewriteUser: rewriteUserPopup,
    fallback: fallbackPromptPopup,
    intent: intentPromptPopup,
  };

  const popup = popupMap[type];

  popup.value.show = false;
  popup.value.prefix = '';
  popup.value.selectedIndex = 0;

  nextTick(() => {
    const cursorPos = textarea.selectionStart;
    const currentValue = getGenericPlaceholderFieldValue(type);
    const textBeforeCursor = currentValue.substring(0, cursorPos);
    const textAfterCursor = currentValue.substring(cursorPos);

    // 只有从下拉列表选择时才查找 {{ 并替换
    if (fromPopup) {
      let lastOpenPos = -1;
      for (let i = textBeforeCursor.length - 1; i >= 1; i--) {
        if (textBeforeCursor[i] === '{' && textBeforeCursor[i - 1] === '{') {
          lastOpenPos = i - 1;
          break;
        }
      }

      if (lastOpenPos !== -1) {
        const textBeforeOpen = currentValue.substring(0, lastOpenPos);
        const newValue = textBeforeOpen + `{{${placeholderName}}}` + textAfterCursor;
        setGenericPlaceholderFieldValue(type, newValue);

        nextTick(() => {
          const newCursorPos = textBeforeOpen.length + placeholderName.length + 4;
          textarea.setSelectionRange(newCursorPos, newCursorPos);
          textarea.focus();
        });
        return;
      }
    }

    // 直接在光标位置插入完整占位符
    const newValue = textBeforeCursor + `{{${placeholderName}}}` + textAfterCursor;
    setGenericPlaceholderFieldValue(type, newValue);

    nextTick(() => {
      const newCursorPos = cursorPos + placeholderName.length + 4;
      textarea.setSelectionRange(newCursorPos, newCursorPos);
      textarea.focus();
    });
  });
};

// 设置上下文模板 textarea 事件监听
const setupContextTemplateEventListeners = () => {
  nextTick(() => {
    const textarea = getContextTemplateTextareaElement();
    if (textarea) {
      textarea.addEventListener('keydown', (e: KeyboardEvent) => {
        if (showContextPlaceholderPopup.value && filteredContextPlaceholders.value.length > 0) {
          if (e.key === 'ArrowDown') {
            e.preventDefault();
            e.stopPropagation();
            if (selectedContextPlaceholderIndex.value < filteredContextPlaceholders.value.length - 1) {
              selectedContextPlaceholderIndex.value++;
            } else {
              selectedContextPlaceholderIndex.value = 0;
            }
          } else if (e.key === 'ArrowUp') {
            e.preventDefault();
            e.stopPropagation();
            if (selectedContextPlaceholderIndex.value > 0) {
              selectedContextPlaceholderIndex.value--;
            } else {
              selectedContextPlaceholderIndex.value = filteredContextPlaceholders.value.length - 1;
            }
          } else if (e.key === 'Enter' || e.key === 'Tab') {
            e.preventDefault();
            e.stopPropagation();
            const selected = filteredContextPlaceholders.value[selectedContextPlaceholderIndex.value];
            if (selected) {
              insertContextPlaceholder(selected.name, true);
            }
          } else if (e.key === 'Escape') {
            e.preventDefault();
            e.stopPropagation();
            showContextPlaceholderPopup.value = false;
            contextPlaceholderPrefix.value = '';
          }
        }
      }, true);
    }
  });
};

// 设置 textarea 事件监听
const setupTextareaEventListeners = () => {
  nextTick(() => {
    const textarea = getTextareaElement();
    if (textarea) {
      textarea.addEventListener('keydown', (e: KeyboardEvent) => {
        if (showPlaceholderPopup.value && filteredPlaceholders.value.length > 0) {
          if (e.key === 'ArrowDown') {
            e.preventDefault();
            e.stopPropagation();
            if (selectedPlaceholderIndex.value < filteredPlaceholders.value.length - 1) {
              selectedPlaceholderIndex.value++;
            } else {
              selectedPlaceholderIndex.value = 0;
            }
          } else if (e.key === 'ArrowUp') {
            e.preventDefault();
            e.stopPropagation();
            if (selectedPlaceholderIndex.value > 0) {
              selectedPlaceholderIndex.value--;
            } else {
              selectedPlaceholderIndex.value = filteredPlaceholders.value.length - 1;
            }
          } else if (e.key === 'Enter' || e.key === 'Tab') {
            e.preventDefault();
            e.stopPropagation();
            const selected = filteredPlaceholders.value[selectedPlaceholderIndex.value];
            if (selected) {
              insertPlaceholder(selected.name, true);
            }
          } else if (e.key === 'Escape') {
            e.preventDefault();
            e.stopPropagation();
            showPlaceholderPopup.value = false;
            placeholderPrefix.value = '';
          }
        }
      }, true);
    }
  });
};

// 通用设置 textarea 事件监听
const setupGenericTextareaEventListeners = (
  type: GenericPlaceholderType,
  popup: typeof rewriteSystemPopup,
  filteredPlaceholders: () => PlaceholderDefinition[]
) => {
  nextTick(() => {
    const textarea = getGenericTextareaElement(type);
    if (textarea) {
      textarea.addEventListener('keydown', (e: KeyboardEvent) => {
        const filtered = filteredPlaceholders();
        if (popup.value.show && filtered.length > 0) {
          if (e.key === 'ArrowDown') {
            e.preventDefault();
            e.stopPropagation();
            if (popup.value.selectedIndex < filtered.length - 1) {
              popup.value.selectedIndex++;
            } else {
              popup.value.selectedIndex = 0;
            }
          } else if (e.key === 'ArrowUp') {
            e.preventDefault();
            e.stopPropagation();
            if (popup.value.selectedIndex > 0) {
              popup.value.selectedIndex--;
            } else {
              popup.value.selectedIndex = filtered.length - 1;
            }
          } else if (e.key === 'Enter' || e.key === 'Tab') {
            e.preventDefault();
            e.stopPropagation();
            const selected = filtered[popup.value.selectedIndex];
            if (selected) {
              insertGenericPlaceholder(type, selected.name, true);
            }
          } else if (e.key === 'Escape') {
            e.preventDefault();
            e.stopPropagation();
            popup.value.show = false;
            popup.value.prefix = '';
          }
        }
      }, true);
    }
  });
};

// 处理点击占位符标签
const handlePlaceholderClick = (type: 'system' | 'context' | 'rewriteSystem' | 'rewriteUser' | 'fallback' | 'intent', placeholderName: string) => {
  if (type === 'system') {
    insertPlaceholder(placeholderName);
  } else if (type === 'context') {
    insertContextPlaceholder(placeholderName);
  } else {
    insertGenericPlaceholder(type, placeholderName);
  }
};

// 监听 visible 变化设置事件监听
watch(() => props.visible, (val) => {
  if (val) {
    nextTick(() => {
      setupTextareaEventListeners();
      setupContextTemplateEventListeners();
      setupGenericTextareaEventListeners('intent', intentPromptPopup, () => filteredIntentPlaceholders.value);
      setupGenericTextareaEventListeners('rewriteSystem', rewriteSystemPopup, () => filteredRewriteSystemPlaceholders.value);
      setupGenericTextareaEventListeners('rewriteUser', rewriteUserPopup, () => filteredRewriteUserPlaceholders.value);
      setupGenericTextareaEventListeners('fallback', fallbackPromptPopup, () => filteredFallbackPlaceholders.value);
    });
  }
});

// 模板选择处理函数
const handleSystemPromptTemplateSelect = (template: PromptTemplate) => {
  formData.value.config.system_prompt = template.content;
  formData.value.config.system_prompt_id = template.id;
};

// Agent 系统提示词的"恢复默认":
// 当前选中了非 custom 的智能体类型时,"默认"应当是该类型预设绑定的提示词
// (比如 Wiki 问答 → wiki_researcher),而不是 agent_system_prompt 模板表里
// 全局 default: true 的那一条。只有当类型为 custom 或找不到预设绑定的模板时,
// 才回退到 PromptTemplateSelector 传来的全局默认模板。
const handleAgentSystemPromptResetDefault = (fallback: PromptTemplate) => {
  const typeId = agentType.value;
  if (typeId && typeId !== 'custom') {
    const preset = agentTypePresets.value.find(p => p.id === typeId);
    const presetPromptId = preset?.config?.system_prompt_id;
    if (presetPromptId) {
      const tmpl = agentSystemPromptTemplates.value.find(t => t.id === presetPromptId);
      if (tmpl && typeof tmpl.content === 'string') {
        formData.value.config.system_prompt = tmpl.content;
        formData.value.config.system_prompt_id = tmpl.id;
        return;
      }
    }
  }
  // Fallback:没有合适的类型预设,用 PromptTemplateSelector 找到的全局默认
  formData.value.config.system_prompt = fallback.content;
  formData.value.config.system_prompt_id = fallback.id;
};

const handleContextTemplateSelect = (template: PromptTemplate) => {
  formData.value.config.context_template = template.content;
  formData.value.config.context_template_id = template.id;
};

const handleRewriteTemplateSelect = (template: PromptTemplate) => {
  // Rewrite templates contain both content (system) and user fields
  formData.value.config.rewrite_prompt_system = template.content;
  if (template.user) {
    formData.value.config.rewrite_prompt_user = template.user;
  }
};

const handleFallbackResponseTemplateSelect = (template: PromptTemplate) => {
  formData.value.config.fallback_response = template.content;
};

const handleFallbackPromptTemplateSelect = (template: PromptTemplate) => {
  formData.value.config.fallback_prompt = template.content;
};

// 辅助函数:检查提示词是否包含指定占位符
const hasPlaceholder = (text: string | undefined, placeholder: string): boolean => {
  if (!text) return false;
  return text.includes(`{{${placeholder}}}`);
};

const handleSave = async () => {
  // 验证必填项(内置智能体不验证名称和系统提示词)
  if (!isBuiltinAgent.value) {
    if (!formData.value.name || !formData.value.name.trim()) {
      MessagePlugin.error(t('agent.editor.nameRequired'));
      currentSection.value = 'basic';
      return;
    }

    // 自定义智能体必须填写系统提示词
    if (!formData.value.config.system_prompt || !formData.value.config.system_prompt.trim()) {
      MessagePlugin.error(t('agent.editor.systemPromptRequired'));
      currentSection.value = 'prompts';
      return;
    }

    // 自定义智能体普通模式必须填写上下文模板
    if (!isAgentMode.value && (!formData.value.config.context_template || !formData.value.config.context_template.trim())) {
      MessagePlugin.error(t('agent.editor.contextTemplateRequired'));
      currentSection.value = 'prompts';
      return;
    }
  }

  // 校验占位符(普通模式 + 开启多轮对话改写)
  if (!isAgentMode.value && formData.value.config.multi_turn_enabled && formData.value.config.enable_rewrite) {
    const rewritePrompt = formData.value.config.rewrite_prompt_user || '';
    // 只有用户自定义了改写提示词时才校验
    if (rewritePrompt.trim()) {
      if (!hasPlaceholder(rewritePrompt, 'query')) {
        MessagePlugin.error(t('agent.editor.queryMissingInRewrite'));
        currentSection.value = 'prompts';
        return;
      }
    }
  }

  // 校验占位符(兜底策略为模型生成时)
  if (!isAgentMode.value && formData.value.config.fallback_strategy === 'model') {
    const fallbackPrompt = formData.value.config.fallback_prompt || '';
    // 只有用户自定义了兜底提示词时才校验
    if (fallbackPrompt.trim() && !hasPlaceholder(fallbackPrompt, 'query')) {
      MessagePlugin.error(t('agent.editor.queryMissingInFallback'));
      currentSection.value = 'prompts';
      return;
    }
  }

  if (!formData.value.config.model_id) {
    MessagePlugin.error(t('agent.editor.modelRequired'));
    currentSection.value = 'model';
    return;
  }

  // 校验 VLM 模型(当图片上传启用时必填)
  if (formData.value.config.image_upload_enabled && !formData.value.config.vlm_model_id) {
    MessagePlugin.error(t('agentEditor.imageUpload.vlmModelRequired'));
    currentSection.value = 'multimodal';
    return;
  }

  // ReRank 模型按运行范围按需使用:知识库范围为 none,或未启用
  // search_knowledge 时不需要;其余情况由对话入口在使用前给出明确提示。

  formData.value.config.question_suggestions.starters.items =
    formData.value.config.question_suggestions.starters.items
      .map((p: string) => p.trim())
      .filter(Boolean);

  if (!formData.value.config.intent_prompts || Object.keys(formData.value.config.intent_prompts).length === 0) {
    delete formData.value.config.intent_prompts;
  }

  pruneSelectedSkills()

  if (hostOnly.value) formData.value.config.sandbox_config_id = ''

  const payload = { ...formData.value, config: serializeAgentPrompts({ ...formData.value.config, allowed_tools: allowedToolsToSave() }, promptTemplates.value) };
  saving.value = true;
  try {
    if (editorMode.value === 'create') {
      const result: any = await createAgent(payload);
      const created = result?.data as CustomAgent | undefined;
      if (!created?.id) {
        throw new Error(result?.message || t('agent.messages.saveFailed'));
      }
      savedAgent.value = created;
      formData.value.id = created.id;
      // 后端可能改写了工具列表(旧名称映射、移除由其他设置控制的工具),与之同步,
      // 避免再次保存时重复提示。
      if (Array.isArray(created.config?.allowed_tools)) {
        formData.value.config.allowed_tools = normalizeLegacyToolNames(created.config.allowed_tools);
        storedToolNames.value = [...formData.value.config.allowed_tools];
        keepAllowedToolsUnset.value = false;
      }
      modalShell.markClean();
      markContextualGuideDone('agentCreate')
      currentSection.value = 'basic';
      void loadAgentIntegrationCounts(created.id);
      MessagePlugin.success(t('agent.messages.created'));
      notifyAllowedToolsWarnings(result?.allowed_tools_warnings);
      emit('success', created);
    } else {
      const updated: any = await updateAgent(formData.value.id, payload);
      MessagePlugin.success(t('agent.messages.updated'));
      emit('success');
      handleClose();
      notifyAllowedToolsWarnings(updated?.allowed_tools_warnings);
    }
  } catch (e: any) {
    MessagePlugin.error(e?.message || t('agent.messages.saveFailed'));
  } finally {
    saving.value = false;
  }
};
</script>

<style scoped lang="less">
// 复用创建知识库的样式
/* 左侧导航:与「头像-设置」弹窗对齐 */
.section--prompts {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
}

.prompts-panel {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
}

.prompts-panel__header {
  flex-shrink: 0;
  margin: 0 0 0;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--td-component-stroke);
  background: var(--td-bg-color-container);
}

.prompts-panel__body {
  flex: 1;
  min-height: 0;
  overflow-y: auto;
  margin: 0 -4px;
  padding: 4px 4px 8px;
}

.prompts-panel__pane {
  &.setting-row:last-child {
    border-bottom: none;
  }
}

.prompts-panel__pane--stack {
  .setting-row:last-child {
    border-bottom: none;
  }
}

.section-header--compact {
  margin-bottom: 0;

  h2 {
    margin-bottom: 4px;
  }

  .section-description {
    font-size: var(--app-text-md);
  }
}

.prompts-outline {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 14px;
  min-width: 0;

  &__pill {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 5px 12px;
    border: none;
    border-radius: var(--app-radius-sm);
    background: var(--td-bg-color-secondarycontainer);
    font: inherit;
    font-size: var(--app-text-md);
    line-height: 1.4;
    color: var(--td-text-color-secondary);
    cursor: pointer;
    transition: color var(--app-motion-fast) ease, background var(--app-motion-fast) ease;

    &:hover,
    &:focus-visible {
      color: var(--td-brand-color);
      background: color-mix(in srgb, var(--td-brand-color) 8%, var(--td-bg-color-secondarycontainer));
      outline: none;
    }

    &--active {
      background: color-mix(in srgb, var(--td-brand-color) 12%, transparent);
      color: var(--td-brand-color);
      font-weight: 500;
    }
  }

  &__dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background: var(--td-brand-color);
    flex-shrink: 0;
  }
}

.content-wrapper {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
  padding: 28px 40px 48px;
  box-sizing: border-box;
  scroll-padding-bottom: 24px;

  &--prompts {
    display: flex;
    flex-direction: column;
    overflow: hidden;
    padding-bottom: 28px;
  }
}

.section {
  width: 100%;
  animation: sectionFadeIn 0.25s ease;
}

@keyframes sectionFadeIn {
  from {
    opacity: 0;
    transform: translateY(6px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.section-header {
  margin-bottom: 20px;

  .section-header-title {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 6px;

    h2 {
      margin: 0;
    }
  }

  h2 {
    font-size: var(--app-text-3xl);
    font-weight: 600;
    color: var(--td-text-color-primary);
    margin: 0 0 6px 0;
  }

  .section-description {
    font-size: var(--app-text-base);
    color: var(--td-text-color-secondary);
    margin: 0;
    line-height: 1.5;

    .doc-link {
      margin-left: 8px;
    }
  }
}

// 与知识库设置一致的 settings-group 样式
.settings-group {
  display: flex;
  flex-direction: column;
  gap: 0;
}

.parser-policy-block {
  padding: 16px 0;
  border-bottom: 1px solid var(--td-component-stroke);

  &__header {
    margin-bottom: 12px;

    label {
      display: block;
      font-size: var(--app-text-lg);
      font-weight: 500;
      color: var(--td-text-color-primary);
      margin-bottom: 4px;
    }

    .desc {
      margin: 0;
      font-size: var(--app-text-md);
      color: var(--td-text-color-secondary);
      line-height: 1.5;
    }
  }
}

.setting-row {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 24px;
  padding: 16px 0;
  border-bottom: 1px solid var(--td-component-stroke);
  min-width: 0;

  &:last-child {
    border-bottom: none;
  }

  &.setting-row-vertical {
    flex-direction: column;
    gap: 12px;

    .setting-info {
      max-width: 100%;
      padding-right: 0;
    }
  }

  // 强调行:用于"智能体类型"这类对用户影响最大、需要突出的关键配置。
  // 视觉上只做极轻度强调 —— 左侧 3px 品牌色竖条 + label 加粗。
  &.setting-row--emphasize {
    position: relative;
    padding-left: 14px;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 18px;
      bottom: 18px;
      width: 3px;
      border-radius: 2px;
      background: var(--td-brand-color);
    }

    .setting-info label {
      font-weight: 600;
    }
  }

  &.setting-row--field-highlight {
    border-radius: var(--app-radius-sm);
    animation: agent-field-flash 0.8s ease-in-out 3;
  }
}

@keyframes agent-field-flash {
  0%,
  100% {
    background-color: transparent;
    box-shadow: none;
  }

  50% {
    background-color: var(--td-warning-color-light);
    box-shadow: inset 0 0 0 1px rgba(237, 123, 47, 0.35);
  }
}

.setting-info {
  flex: 0 0 42%;
  max-width: 42%;
  min-width: 0;
  padding-right: 0;

  &.full-width {
    max-width: 100%;
    padding-right: 0;
  }

  .setting-info-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 4px;

    label {
      margin-bottom: 0;
    }
  }

  label {
    font-size: var(--app-text-lg);
    font-weight: 500;
    color: var(--td-text-color-primary);
    display: block;
    margin-bottom: 4px;

    .required {
      color: var(--td-error-color);
      margin-left: 2px;
    }
  }

  .desc {
    font-size: var(--app-text-md);
    color: var(--td-text-color-secondary);
    margin: 0;
    line-height: 1.5;

    .hint {
      color: var(--td-warning-color);
    }
  }
}

.setting-control {
  flex: 1 1 58%;
  min-width: 0;
  max-width: 58%;
  display: flex;
  justify-content: flex-end;
  align-items: flex-start;
  overflow: hidden;

  .reasoning-effort-select {
    width: 100%;
    max-width: 220px;
  }

  &.setting-control-full {
    width: 100%;
    min-width: 100%;
    max-width: 100%;
    justify-content: flex-start;
  }

  &.max-tokens-control {
    flex-direction: column;
    align-items: flex-end;
    gap: 8px;

    :deep(.t-input-number) {
      width: 140px;
    }
  }

  // 让 select 和 input 占满控件区域
  :deep(.t-select),
  :deep(.t-input),
  :deep(.t-textarea) {
    width: 100%;
    min-width: 0;
  }

  :deep(.t-select-input) {
    min-width: 0;
  }

  :deep(.t-select .t-tag) {
    max-width: 160px;
  }

  :deep(.t-select .t-tag__text) {
    display: block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  :deep(.t-input-number) {
    width: 120px;
  }
}

.integration-inline {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
  justify-content: flex-end;

  &__stat {
    font-size: var(--app-text-md);
    color: var(--td-text-color-secondary);

    &.integration-inline__link {
      display: inline-flex;
      align-items: center;
      gap: 2px;
      padding: 0;
      border: none;
      background: transparent;
      line-height: 1;
      color: var(--td-brand-color);
      cursor: pointer;

      &:hover {
        opacity: 0.85;
      }
    }
  }

  &__sep {
    color: var(--td-component-stroke);
    font-size: var(--app-text-sm);
  }

  &__link {
    display: inline-flex;
    align-items: center;
    gap: 2px;
    margin-left: 4px;
    padding: 0;
    border: none;
    background: transparent;
    font-size: var(--app-text-md);
    line-height: 1;
    color: var(--td-brand-color);
    cursor: pointer;

    &:hover {
      opacity: 0.85;
    }

    :deep(.t-icon) {
      display: block;
    }
  }
}

.select-option-with-tag {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  gap: 8px;
}

.go-settings-link {
  font-size: var(--app-text-sm);
  color: var(--td-brand-color);
  margin-top: 0;
  text-decoration: none;

  &:hover {
    text-decoration: underline;
  }
}

.sandbox-select-links {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  flex-wrap: wrap;
  gap: 6px;
  margin-top: 4px;
}

.sandbox-select-links__sep {
  color: var(--td-text-color-placeholder);
  font-size: var(--app-text-sm);
}

.sandbox-select-control {
  flex-direction: column;
  align-items: flex-end;
}

.sandbox-config-select {
  width: 280px;
}

.sandbox-option {
  display: flex;
  flex-direction: column;
  gap: 2px;
  width: 100%;
  min-width: 0;
}

.sandbox-option__row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  min-width: 0;
}

.sandbox-option__name {
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.sandbox-option__type {
  flex-shrink: 0;
  color: var(--td-text-color-placeholder);
  font-size: var(--app-text-sm);
}

.sandbox-option__target {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: var(--td-text-color-placeholder);
  font-size: var(--app-text-sm);
  line-height: 1.35;
}

.sandbox-selected-meta {
  margin: 6px 0 0;
  max-width: 280px;
  font-size: var(--app-text-sm);
  line-height: 1.45;
  color: var(--td-text-color-secondary);
  word-break: break-word;
}

// 名称输入框带头像预览
.name-input-wrapper {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;

  .name-input {
    flex: 1;
  }
}

.agent-id-field {
  display: flex;
  align-items: center;
  gap: 4px;
  width: 100%;
  padding: 6px 8px 6px 12px;
  background: var(--td-bg-color-secondarycontainer);
  border: 1px solid var(--td-component-stroke);
  border-radius: var(--app-radius-sm);

  .agent-id-value {
    flex: 1;
    min-width: 0;
    margin: 0;
    padding: 0;
    background: none;
    border: none;
    font-family: var(--app-font-family-mono);
    font-size: var(--app-text-md);
    line-height: 1.5;
    color: var(--td-text-color-primary);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .agent-id-copy {
    flex-shrink: 0;
    color: var(--td-text-color-secondary);

    &:hover {
      color: var(--td-brand-color);
    }
  }
}

/* 滚动条:与设置弹窗一致 */
.content-wrapper::-webkit-scrollbar {
  width: 6px;
}

.content-wrapper::-webkit-scrollbar-track {
  background: var(--td-bg-color-container);
}

.content-wrapper::-webkit-scrollbar-thumb {
  background: var(--td-gray-color-5);
  border-radius: 3px;
}

.content-wrapper::-webkit-scrollbar-thumb:hover {
  background: var(--td-gray-color-6);
}

// 模式提示样式
.mode-hint {
  display: flex;
  align-items: center;
  padding: 10px 14px;
  background: var(--td-success-color-light);
  border-radius: var(--app-radius-sm);
  border: 1px solid var(--td-success-color-focus);
  color: var(--td-brand-color);
  font-size: var(--app-text-md);
  line-height: 1.5;
}

// 过渡动画
// Slider 样式
.slider-wrapper {
  display: flex;
  align-items: center;
  gap: 16px;
  width: 100%;

  :deep(.t-slider) {
    flex: 1;
  }
}

.slider-value {
  width: 40px;
  text-align: right;
  font-family: var(--app-font-family-mono);
  font-size: var(--app-text-base);
  color: var(--td-text-color-primary);
}

.max-tokens-value {
  font-family: var(--app-font-family-mono);
  font-variant-numeric: tabular-nums;
  font-size: var(--app-text-sm);
  color: var(--td-text-color-placeholder);
}

// 推荐问题列表
.suggested-prompts-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  width: 100%;
}

.prompt-item {
  display: flex;
  align-items: center;
  gap: 8px;

  :deep(.t-input) {
    flex: 1;
  }
}

// 开场 / 回答后推荐用顶部 tab 区分(参照模型管理),避免整块包围框
.suggestion-tabs {
  margin-bottom: 4px;

  :deep(.t-tabs__nav-item) {
    font-size: var(--app-text-base);
  }

  :deep(.t-tabs__operations) {
    display: none;
  }

  // 只用 tab 作导航,内容自行渲染在下方
  :deep(.t-tabs__content) {
    display: none;
  }
}

.suggestion-advanced-divider {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 4px 0 2px;
  color: var(--td-text-color-placeholder);
  font-size: var(--app-text-sm);
  line-height: 18px;

  &::before,
  &::after {
    content: '';
    flex: 1;
    height: 1px;
    background: var(--td-component-stroke);
  }

  span {
    flex-shrink: 0;
    color: var(--td-text-color-secondary);
    font-weight: 500;
  }
}

// 计数徽标紧贴标签,避免在整宽行里被 space-between 甩开
// 需与基础 `.setting-info .setting-info-header`(space-between)同等特异性才能覆盖
.setting-info-header.setting-info-header--inline {
  justify-content: flex-start;
  gap: 8px;
}

.curated-items-count {
  flex-shrink: 0;
  padding: 0 8px;
  height: 20px;
  display: inline-flex;
  align-items: center;
  border-radius: var(--app-radius-lg);
  background: var(--td-bg-color-secondarycontainer);
  font-size: var(--app-text-sm);
  font-variant-numeric: tabular-nums;
  color: var(--td-text-color-secondary);
}

.suggestion-checkboxes {
  display: flex;
  flex-direction: column;
  gap: 10px;
  width: 100%;
}

// ===== 工具配置:overview 面板 =====
.tools-overview {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 12px;
  padding: 12px 14px;
  background: var(--td-bg-color-secondarycontainer);
  border-radius: var(--app-radius-lg);
  border: 1px solid var(--td-component-stroke);
}

.tools-overview-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 10px 12px;

  &--preset {
    border-top: 1px dashed var(--td-component-stroke);
    padding-top: 10px;
    justify-content: space-between;
  }
}

.tools-status-chip {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 4px 10px;
  font-size: var(--app-text-md);
  color: var(--td-text-color-secondary);
  background: var(--td-bg-color-container);
  border-radius: var(--app-radius-pill);
  border: 1px solid var(--td-component-stroke);

  .t-icon {
    color: var(--td-text-color-secondary);
    font-size: var(--app-text-base);
  }

  .tools-status-metric {
    display: inline-flex;
    align-items: baseline;
    gap: 4px;

    strong {
      font-size: var(--app-text-base);
      font-weight: 600;
      color: var(--td-text-color-primary);
    }
  }

  .tools-status-sep {
    color: var(--td-text-color-placeholder);
  }

  &--warn {
    color: var(--td-warning-color);
    background: var(--td-warning-color-1);
    border-color: var(--td-warning-color-light);

    .t-icon {
      color: var(--td-warning-color);
    }
  }
}

// ===== 按组的卡片网格 =====
.tool-groups {
  display: flex;
  flex-direction: column;
  gap: 22px;
  width: 100%;
}

.tool-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.tool-group-header {
  display: flex;
  align-items: center;
  gap: 8px;
  padding-bottom: 2px;

  .tool-group-bar {
    display: inline-block;
    width: 3px;
    height: 14px;
    border-radius: 2px;
    background: var(--td-brand-color);
  }

  .tool-group-title {
    font-size: var(--app-text-md);
    font-weight: 600;
    color: var(--td-text-color-primary);
    letter-spacing: 0.2px;
  }

  .tool-group-count {
    min-width: 20px;
    padding: 0 6px;
    font-size: var(--app-text-xs);
    color: var(--td-text-color-secondary);
    background: var(--td-bg-color-secondarycontainer);
    border-radius: var(--app-radius-pill);
    text-align: center;
    line-height: 18px;
  }

  .tool-group-warning {
    margin-left: auto;
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 2px 8px;
    font-size: var(--app-text-sm);
    color: var(--td-warning-color);
    background: var(--td-warning-color-1);
    border: 1px solid var(--td-warning-color-light);
    border-radius: var(--app-radius-pill);

    .t-icon {
      font-size: var(--app-text-md);
    }
  }
}

// 不同分组的左侧色条
.tool-group--base .tool-group-bar {
  background: var(--td-gray-color-6);
}

.tool-group--rag .tool-group-bar {
  background: var(--td-brand-color);
}

.tool-group--wiki_read .tool-group-bar {
  background: var(--td-success-color);
}

.tool-group--wiki_edit .tool-group-bar {
  background: var(--td-warning-color);
}

.tool-group--wiki_issue .tool-group-bar {
  background: var(--td-purple-5, #8e56dd);
}

.tool-group--data .tool-group-bar {
  background: var(--td-cyan-6, #09a3b7);
}

// 统一两列网格;小屏退化单列
.tool-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 10px;
  width: 100%;

  @media (max-width: 720px) {
    grid-template-columns: 1fr;
  }
}

// ===== 工具卡片(基于 t-checkbox 的 label 结构) =====
.tool-card {
  margin: 0; // 清掉 TDesign checkbox 默认外边距
  padding: 12px 14px;
  background: var(--td-bg-color-container);
  border-radius: var(--app-radius-md);
  border: 1px solid var(--td-component-stroke);
  transition: border-color var(--app-motion-base), background var(--app-motion-base);
  cursor: pointer;
  overflow: hidden;

  &:hover:not(.tool-card--disabled) {
    border-color: var(--td-brand-color);
    background: var(--td-brand-color-1);
  }

  // checkbox 的勾选框 + label 改造
  :deep(.t-checkbox__input) {
    margin-top: 2px;
    flex-shrink: 0;
  }

  :deep(.t-checkbox__label) {
    flex: 1;
    min-width: 0;
    padding-left: 10px;
  }

  &.t-is-checked {
    border-color: var(--td-brand-color);
    background: var(--td-brand-color-1);
  }

  &--disabled {
    cursor: not-allowed;
    opacity: 0.6;
  }

  &--danger {
    border-color: var(--td-warning-color-light);

    &:hover:not(.tool-card--disabled) {
      border-color: var(--td-warning-color);
      background: var(--td-warning-color-1);
    }

    &.t-is-checked {
      border-color: var(--td-warning-color);
      background: var(--td-warning-color-1);
    }
  }
}

.tool-card-body {
  display: flex;
  flex-direction: column;
  gap: 4px;
  min-width: 0;
}

.tool-card-head {
  display: flex;
  align-items: center;
  gap: 6px;
  min-width: 0;
}

.tool-card-name {
  font-size: 13.5px;
  font-weight: 500;
  color: var(--td-text-color-primary);
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 0 1 auto;
  min-width: 0;
}

.tool-card-badge {
  flex: 0 0 auto;
  font-size: 10.5px;
  line-height: 1;
  padding: 3px 6px;
  color: var(--td-warning-color);
  background: transparent;
  border: 1px solid var(--td-warning-color-light);
  border-radius: var(--app-radius-xs);
  letter-spacing: 0.3px;
}

.tool-card-desc {
  font-size: var(--app-text-sm);
  color: var(--td-text-color-secondary);
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.tool-card-hint {
  font-size: var(--app-text-xs);
  color: var(--td-warning-color);
  font-style: italic;
  line-height: 1.4;
}

.tool-card--disabled {

  .tool-card-name,
  .tool-card-desc {
    color: var(--td-text-color-placeholder);
  }
}

// ===== 有效工具预览(芯片组)=====
.effective-tools {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  padding: 12px;
  background: var(--td-bg-color-container);
  border-radius: var(--app-radius-md);
  border: 1px dashed var(--td-component-stroke);
  min-height: 52px;
  align-items: flex-start;
}

.effective-chip {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 3px 10px;
  font-size: var(--app-text-sm);
  line-height: 18px;
  color: var(--td-brand-color);
  background: color-mix(in srgb, var(--td-brand-color) 10%, transparent);
  border: 1px solid color-mix(in srgb, var(--td-brand-color) 22%, transparent);
  border-radius: var(--app-radius-pill);
  max-width: 100%;
}

.effective-chip-label {
  font-weight: 500;
}

.effective-chip-reason {
  font-size: var(--app-text-xs);
  color: var(--td-warning-color);
  font-style: normal;

  &::before {
    content: "· ";
    color: var(--td-text-color-placeholder);
    margin-right: 2px;
  }
}

.effective-chip--inactive {
  color: var(--td-text-color-placeholder);
  background: var(--td-bg-color-secondarycontainer);
  border-color: var(--td-component-stroke);

  .effective-chip-label {
    text-decoration: line-through;
  }
}

.effective-tools-empty {
  font-size: var(--app-text-sm);
  color: var(--td-text-color-placeholder);
  font-style: italic;
}

.skill-pick-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  width: 100%;
}

.skill-pick-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.skill-pick-group__header {
  display: flex;
  align-items: center;
  gap: 8px;
  padding-bottom: 2px;
}

.skill-pick-group__bar {
  display: inline-block;
  width: 3px;
  height: 14px;
  border-radius: 2px;
  background: var(--td-brand-color);
}

.skill-pick-group--pending .skill-pick-group__bar {
  background: var(--td-text-color-placeholder);
}

.skill-pick-group__title {
  font-size: var(--app-text-md);
  font-weight: 600;
  color: var(--td-text-color-primary);
  letter-spacing: 0.2px;
}

.skill-pick-group__count {
  min-width: 20px;
  padding: 0 6px;
  font-size: var(--app-text-xs);
  color: var(--td-text-color-secondary);
  background: var(--td-bg-color-secondarycontainer);
  border-radius: var(--app-radius-pill);
  text-align: center;
  line-height: 18px;
}

.skill-pick {
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 0;
  padding: 8px 10px;
  background: var(--td-bg-color-container);
  border: 1px solid var(--td-component-stroke);
  border-radius: var(--app-radius-md);
}

.skill-pick--pending {
  background: var(--td-bg-color-secondarycontainer);
}

.skill-pick__check {
  flex-shrink: 0;
}

.skill-pick__badge {
  flex-shrink: 0;
  width: 28px;
  height: 28px;
  border-radius: 7px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--td-bg-color-secondarycontainer);
  color: var(--td-text-color-secondary);
}

.skill-pick--ready .skill-pick__badge {
  background: color-mix(in srgb, var(--td-brand-color) 12%, transparent);
  color: var(--td-brand-color);
}

.skill-pick--pending .skill-pick__badge {
  background: var(--td-bg-color-container);
  color: var(--td-text-color-placeholder);
}

.skill-pick__body {
  flex: 1;
  min-width: 0;
}

.skill-pick__title-row {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 0;
}

.skill-name {
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: var(--app-text-md);
  font-weight: 500;
  color: var(--td-text-color-primary);
}

.skill-pick__hint {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  flex-shrink: 0;
  font-size: var(--app-text-sm);
  color: var(--td-text-color-placeholder);

  .t-icon {
    flex-shrink: 0;
  }
}

.skill-pick__hint--upgrade {
  color: var(--td-warning-color);
}

.skill-pick__hint--busy {
  color: var(--td-brand-color);

  .t-icon {
    animation: wk-spin 1s linear infinite;
  }
}

.skill-desc {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  margin: 2px 0 0;
  overflow: hidden;
  font-size: var(--app-text-sm);
  color: var(--td-text-color-secondary);
  line-height: 1.45;
  white-space: pre-line;
  word-break: break-word;
}

.hint-trigger {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 2px;
  border: none;
  border-radius: var(--app-radius-xs);
  background: transparent;
  color: var(--td-text-color-placeholder);
  cursor: help;
  line-height: 1;

  &:hover,
  &:focus-visible {
    color: var(--td-brand-color);
    outline: none;
  }
}

.hint-popover {
  display: flex;
  flex-direction: column;
  gap: 4px;
  max-width: 340px;
}

.hint-popover__title {
  margin: 0;
  color: var(--td-text-color-primary);
  font-size: var(--app-text-md);
  font-weight: 600;
}

.hint-popover__text {
  margin: 0;
  color: var(--td-text-color-secondary);
  font-size: var(--app-text-sm);
  line-height: 1.55;
}

.empty-hint {
  color: var(--td-text-color-placeholder);
  font-style: italic;

  .go-settings-link {
    display: inline-block;
    font-style: normal;
  }
}

// textarea 与模板选择器容器
.textarea-with-template {
  position: relative;
  width: 100%;
}

.textarea-with-assistant {
  .prompt-assistant-action {
    position: absolute;
    left: 8px;
    bottom: 8px;
  }

  :deep(.t-textarea__inner) {
    padding-bottom: 44px;
  }
}

.intent-prompts-editor {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.intent-toggle-group {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.intent-toggle-group :deep(.intent-toggle-btn--active) {
  background-color: color-mix(in srgb, var(--td-brand-color) 10%, transparent);
  border-color: var(--td-brand-color);
  color: var(--td-brand-color);
  font-weight: 500;

  &:hover,
  &:focus-visible {
    background-color: color-mix(in srgb, var(--td-brand-color) 14%, transparent);
    border-color: var(--td-brand-color);
    color: var(--td-brand-color);
  }
}

.intent-toggle-btn {
  max-width: 100%;
}

.intent-toggle-label {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  white-space: nowrap;
}

.intent-toggle-dot {
  flex-shrink: 0;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background: currentColor;
}

.intent-active-desc {
  margin: 0;
  font-size: var(--app-text-sm);
  color: var(--td-text-color-placeholder);
  line-height: 1.5;
}

// 系统提示词输入框样式
.system-prompt-textarea {
  width: 100%;
  font-family: var(--app-font-family-mono);
  font-size: var(--app-text-md);

  :deep(textarea) {
    resize: vertical !important;
    min-height: 200px;
  }
}

// 占位符标签组样式
.placeholder-tags {
  margin-top: 6px;
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: var(--app-text-sm);
  line-height: 1.4;
  overflow-x: auto;
  white-space: nowrap;
  padding-bottom: 4px;

  // 隐藏滚动条但保持可滚动
  scrollbar-width: thin;

  &::-webkit-scrollbar {
    height: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(0, 0, 0, 0.1);
    border-radius: 2px;
  }

  .placeholder-label {
    color: var(--td-text-color-secondary);
    flex-shrink: 0;
  }

  .placeholder-hint {
    color: var(--td-text-color-placeholder);
    font-size: var(--app-text-xs);
    user-select: none;
    flex-shrink: 0;
  }

  .placeholder-tag {
    display: inline-flex;
    align-items: center;
    padding: 1px 5px;
    border-radius: 3px;
    font-family: var(--app-font-family-mono);
    font-size: var(--app-text-xs);
    color: var(--td-text-color-primary);
    background-color: var(--td-bg-color-secondarycontainer);
    cursor: pointer;
    transition: all var(--app-motion-base);
    user-select: none;
    border: 1px solid transparent;
    flex-shrink: 0;

    &:hover {
      color: var(--td-brand-color);
      background-color: var(--td-brand-color-light);
      border-color: var(--td-brand-color-focus);
    }

    &:active {
      background-color: var(--td-brand-color-focus);
    }
  }
}

.placeholder-popup-wrapper {
  position: fixed;
  z-index: 10001;
  pointer-events: auto;
}

.placeholder-popup {
  background: var(--td-bg-color-container);
  border: 1px solid var(--td-component-stroke);
  border-radius: var(--app-radius-sm);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
  max-width: 320px;
  max-height: 240px;
  overflow-y: auto;
  padding: 4px;
}

.placeholder-item {
  padding: 6px 10px;
  cursor: pointer;
  transition: background-color var(--app-motion-fast);
  border-radius: var(--app-radius-xs);

  &:hover,
  &.active {
    background-color: var(--td-bg-color-container-hover);
  }

  .placeholder-name {
    margin-bottom: 2px;

    code {
      background: var(--td-bg-color-container-hover);
      padding: 2px 5px;
      border-radius: 3px;
      font-family: var(--app-font-family-mono);
      font-size: var(--app-text-xs);
      color: var(--td-brand-color);
    }
  }

  .placeholder-desc {
    font-size: var(--app-text-xs);
    color: var(--td-text-color-secondary);
  }
}

.builtin-agent-hint {
  display: inline-flex;
  align-items: center;
  color: var(--td-text-color-placeholder);
  font-size: var(--app-text-2xl);
  line-height: 1;
  cursor: help;
  transition: color var(--app-motion-base);

  &:hover,
  &:focus-visible {
    color: var(--td-warning-color);
    outline: none;
  }

  &:focus-visible {
    border-radius: 2px;
    box-shadow: 0 0 0 2px var(--td-warning-color-focus);
  }
}

// 内置智能体头像
.builtin-avatar {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  border-radius: var(--app-radius-xl);
  flex-shrink: 0;

  &.normal {
    background: linear-gradient(135deg, color-mix(in srgb, var(--td-brand-color) 15%, transparent) 0%, color-mix(in srgb, var(--td-brand-color) 8%, transparent) 100%);
    color: var(--td-brand-color-active);
  }

  &.agent {
    background: linear-gradient(135deg, rgba(124, 77, 255, 0.15) 0%, rgba(124, 77, 255, 0.08) 100%);
    color: var(--td-brand-color);
  }
}

// 提示词开关
.prompt-toggle {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 12px;

  .prompt-toggle-label {
    font-size: var(--app-text-md);
    color: var(--td-text-color-secondary);
  }
}

// 提示词禁用提示
.prompt-disabled-hint {
  color: var(--td-text-color-placeholder);
  font-size: var(--app-text-md);
  font-style: italic;
  padding: 12px 16px;
  background: var(--td-bg-color-secondarycontainer);
  border-radius: var(--app-radius-sm);
}

// 系统提示词Tabs
.system-prompt-tabs {
  width: 100%;

  .prompt-variant-tabs {
    :deep(.t-tabs__nav) {
      margin-bottom: 12px;
    }
  }
}

// 知识库选项样式
.kb-option-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 2px 0;
}

.kb-option-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  width: 24px;
  height: 24px;
  border-radius: var(--app-radius-sm);
  font-size: var(--app-text-base);

  // Document KB
  &.doc-icon {
    background: rgba(16, 185, 129, 0.1);
    color: var(--td-success-color);
  }

  // FAQ KB
  &.faq-icon {
    background: rgba(0, 82, 217, 0.1);
    color: var(--td-brand-color);
  }
}

.kb-option-label {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: var(--app-text-md);
  color: var(--td-text-color-primary);
}

.kb-option-org {
  flex-shrink: 0;
  font-size: var(--app-text-xs);
  color: var(--td-text-color-placeholder);
  background: var(--td-bg-color-secondarycontainer);
  padding: 1px 6px;
  border-radius: var(--app-radius-xs);
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.kb-option-disabled-hint {
  flex-shrink: 0;
  font-size: var(--app-text-xs);
  color: var(--td-warning-color-6);
  background: var(--td-warning-color-1);
  padding: 1px 6px;
  border-radius: var(--app-radius-xs);
  max-width: 240px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.agent-type-preset-desc {
  margin-top: 4px;
  color: var(--td-text-color-secondary);
  font-size: var(--app-text-sm);
  line-height: 1.5;
}

.agent-type-select {
  width: 100%;
  min-width: 240px;
  max-width: 360px;
}

.kb-option-count {
  flex-shrink: 0;
  font-size: var(--app-text-xs);
  color: var(--td-text-color-placeholder);
  background: var(--td-bg-color-secondarycontainer);
  padding: 1px 6px;
  border-radius: var(--app-radius-xs);
}

.kb-option-tag {
  flex-shrink: 0;
  font-size: var(--app-text-2xs);
  font-weight: 500;
  padding: 0 5px;
  border-radius: 3px;
  line-height: 18px;
}

.tag-rag {
  color: #165dff;
  background: rgba(22, 93, 255, 0.1);
}

.tag-wiki {
  color: #00b42a;
  background: rgba(0, 180, 42, 0.1);
}

</style>

<!-- Non-scoped styles: TDesign teleports the popup outside this component, so
     scoped selectors can't reach .agent-type-popup .t-select-option. -->
<style lang="less">
.reasoning-level-select-popup {
  padding: 4px;

  .t-select-option {
    height: auto !important;
    padding: 6px 10px;
    border-radius: 6px;
    margin: 2px 0;
    white-space: normal;
  }
}

.reasoning-level-option {
  display: flex;
  flex-direction: column;
  gap: 2px;
  line-height: 1.35;
  min-width: 0;

  &__title {
    font-size: var(--app-text-md);
    color: var(--td-text-color-primary);
  }

  &__hint {
    font-size: var(--app-text-sm);
    color: var(--td-text-color-placeholder);
    word-break: break-word;
  }
}

.agent-type-popup {
  .t-select-option {
    // 默认 option 是 32px 单行;我们要双行显示,取消固定高度并放宽 padding
    height: auto !important;
    min-height: 48px;
    line-height: 1.4;
    padding: 8px 12px;
    white-space: normal;
  }
}

.sandbox-config-select-popup {
  .t-select-option {
    height: auto;
    padding: 6px 10px;
  }
}

.agent-type-option {
  display: flex;
  flex-direction: column;
  gap: 2px;
  min-width: 0;
  width: 100%;
}

.agent-type-option-label {
  font-size: var(--app-text-md);
  font-weight: 500;
  color: var(--td-text-color-primary);
  line-height: 1.4;
}

.agent-type-option-desc {
  font-size: var(--app-text-sm);
  color: var(--td-text-color-secondary);
  line-height: 1.4;
  white-space: normal;
  overflow-wrap: break-word;
}
</style>