chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动

演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-11-18 13:59:25 +08:00
1 parent 60158935f4
commit 6519682885
15831 files changed
+3063428

No files matched your search

@@ -0,0 +1,51 @@
import type { ThoughtItem } from '@/app/components/base/chat/chat/type'
import type { FileEntity } from '@/app/components/base/file-uploader/types'
import { describe, expect, it } from 'vite-plus/test'
import { addFileInfos, sortAgentSorts } from '../index'
describe('tools/utils', () => {
describe('sortAgentSorts', () => {
it('returns unsorted when some items lack position', () => {
const items = [{ id: '1', position: 2 }, { id: '2' }] as unknown as ThoughtItem[]
const result = sortAgentSorts(items)
expect(result[0]).toEqual(expect.objectContaining({ id: '1' }))
expect(result[1]).toEqual(expect.objectContaining({ id: '2' }))
})
it('sorts items by position ascending', () => {
const items = [
{ id: 'c', position: 3 },
{ id: 'a', position: 1 },
{ id: 'b', position: 2 },
] as unknown as ThoughtItem[]
const result = sortAgentSorts(items)
expect(result.map((item) => item.id)).toEqual(['a', 'b', 'c'])
expect(items.map((item) => item.id)).toEqual(['c', 'a', 'b'])
})
})
describe('addFileInfos', () => {
it('adds message_files by matching file IDs', () => {
const file1 = { id: 'file-1', name: 'doc.pdf' } as FileEntity
const file2 = { id: 'file-2', name: 'img.png' } as FileEntity
const items = [
{ id: '1', files: ['file-2', 'file-1'] },
{ id: '2', files: [] },
] as unknown as ThoughtItem[]
const result = addFileInfos(items, [file1, file2])
expect((result[0] as ThoughtItem & { message_files: FileEntity[] }).message_files).toEqual([
file2,
file1,
])
expect(result[1]).toEqual(items[1])
expect(items[0]).not.toHaveProperty('message_files')
})
it('returns items without files unchanged', () => {
const items = [{ id: '1' }, { id: '2', files: [] }] as unknown as ThoughtItem[]
const result = addFileInfos(items, [])
expect(result).toEqual(items)
})
})
})
@@ -0,0 +1,215 @@
import type {
ApiProviderDetailResponse,
ToolProviderApiEntityResponse,
} from '@dify/contracts/api/console/workspaces/types.gen'
import { describe, expect, it } from 'vite-plus/test'
import {
selectApiSchemaParameters,
selectCustomCollection,
selectMCPServerDetail,
selectRAGRecommendedPlugins,
selectToolsWithProvider,
selectWorkflowToolDetail,
} from '../query-select'
const createProvider = (
overrides: Partial<ToolProviderApiEntityResponse> = {},
): ToolProviderApiEntityResponse => ({
id: 'provider-1',
name: 'provider',
author: 'dify',
label: { en_US: 'Provider', zh_Hans: null },
description: { en_US: 'Description', zh_Hans: '描述' },
icon: '/icon.svg',
type: 'builtin',
...overrides,
})
describe('tool query selectors', () => {
it('should fill untranslated labels and defaulted provider flags', () => {
const [provider] = selectToolsWithProvider([createProvider()])
expect(provider).toMatchObject({
label: { en_US: 'Provider', zh_Hans: 'Provider' },
description: { en_US: 'Description', zh_Hans: '描述' },
is_team_authorization: false,
allow_delete: false,
labels: [],
team_credentials: {},
tools: [],
})
expect(provider!.label).not.toHaveProperty('ja_JP')
})
it('should keep emoji icons and drop unknown identity modes', () => {
const [provider] = selectToolsWithProvider([
createProvider({
icon: { background: '#fff', content: '🔧' },
identity_mode: 'legacy',
plugin_id: null,
}),
])
expect(provider!.icon).toEqual({ background: '#fff', content: '🔧' })
expect(provider!.identity_mode).toBeUndefined()
expect(provider!.plugin_id).toBeUndefined()
})
it('should map tool parameters and keep non-string defaults', () => {
const [provider] = selectToolsWithProvider([
createProvider({
tools: [
{
name: 'search',
author: 'dify',
label: { en_US: 'Search' },
description: { en_US: 'Search the web' },
parameters: [
{
name: 'limit',
label: { en_US: 'Limit' },
form: 'form',
type: 'number',
default: 10,
human_description: null,
options: [{ label: { en_US: 'Ten' }, value: '10' }],
},
],
},
],
}),
])
const parameter = provider!.tools[0]!.parameters[0]!
expect(parameter).toMatchObject({
default: 10,
required: false,
multiple: false,
llm_description: '',
human_description: { en_US: '', zh_Hans: '' },
options: [{ label: { en_US: 'Ten', zh_Hans: 'Ten' }, value: '10' }],
})
})
it('should keep only string MCP server parameters', () => {
expect(
selectMCPServerDetail({
id: 'server-1',
name: 'server',
server_code: 'code',
description: '',
status: 'active',
parameters: { query: 'Question', count: 3 },
}).parameters,
).toEqual({ query: 'Question' })
expect(
selectMCPServerDetail({
id: 'server-1',
name: 'server',
server_code: 'code',
description: '',
status: 'active',
parameters: [],
}).parameters,
).toBeUndefined()
})
it('should narrow the workflow tool output schema', () => {
const detail = selectWorkflowToolDetail({
name: 'tool',
label: 'Tool',
description: '',
icon: { background: '#fff', content: '🔧' },
parameters: [],
synced: true,
workflow_app_id: 'app-1',
workflow_tool_id: 'tool-1',
tool: {
name: 'tool',
author: 'dify',
label: { en_US: 'Tool' },
description: { en_US: '' },
output_schema: {
type: 'object',
properties: { text: { type: 'string', description: 'Text' }, broken: 'x' },
},
},
})
expect(detail.privacy_policy).toBe('')
expect(detail.tool.output_schema).toEqual({
type: 'object',
properties: { text: { type: 'string', description: 'Text' } },
})
})
it('should keep installable marketplace recommendations', () => {
const plugin = {
type: 'plugin',
org: 'langgenius',
name: 'notion',
plugin_id: 'langgenius/notion',
latest_package_identifier: 'langgenius/notion:1.0.0@hash',
}
const recommendations = selectRAGRecommendedPlugins({
installed_recommended_plugins: [createProvider()],
uninstalled_recommended_plugins: [plugin, { plugin_id: 'broken' }],
})
expect(recommendations.installed_recommended_plugins[0]!.tools).toEqual([])
expect(recommendations.uninstalled_recommended_plugins).toEqual([plugin])
})
it('should label parsed operations without an id or summary as empty', () => {
expect(
selectApiSchemaParameters({
schema_type: 'openapi',
credentials_schema: [],
warning: {},
parameters_schema: [
{ author: 'dify', method: 'get', openapi: {}, server_url: 'https://api.example.com' },
],
}).parameters_schema,
).toEqual([
{
operation_id: '',
summary: '',
server_url: 'https://api.example.com',
method: 'get',
parameters: [],
},
])
})
it('should read stored API provider credentials by their auth type', () => {
const detail: ApiProviderDetailResponse = {
schema_type: 'openapi',
schema: '{}',
tools: [],
icon: { background: '#FFF', content: '🔧' },
}
expect(
selectCustomCollection({
...detail,
credentials: {
auth_type: 'api_key_header',
api_key_header: 'Authorization',
api_key_header_prefix: 'bearer',
api_key_value: '[__HIDDEN__]',
},
}).credentials,
).toEqual({
auth_type: 'api_key_header',
api_key_header: 'Authorization',
api_key_header_prefix: 'bearer',
api_key_value: '[__HIDDEN__]',
api_key_query_param: undefined,
})
expect(selectCustomCollection(detail)).toMatchObject({
credentials: { auth_type: 'none' },
privacy_policy: '',
custom_disclaimer: '',
})
})
})
@@ -0,0 +1,359 @@
import type { TriggerEventParameter } from '../../../plugins/types'
import type { ToolCredential, ToolParameter } from '../../types'
import { describe, expect, it } from 'vite-plus/test'
import {
addDefaultValue,
generateAgentToolValue,
generateFormValue,
getConfiguredValue,
getPlainValue,
getStructureValue,
toolCredentialToFormSchemas,
toolParametersToFormSchemas,
toType,
triggerEventParametersToFormSchemas,
} from '../to-form-schema'
describe('to-form-schema utilities', () => {
describe('toType', () => {
it('converts "string" to "text-input"', () => {
expect(toType('string')).toBe('text-input')
})
it('converts "number" to "number-input"', () => {
expect(toType('number')).toBe('number-input')
})
it('converts "boolean" to "checkbox"', () => {
expect(toType('boolean')).toBe('checkbox')
})
it('returns the original type for unknown types', () => {
expect(toType('select')).toBe('select')
expect(toType('secret-input')).toBe('secret-input')
expect(toType('file')).toBe('file')
})
})
describe('triggerEventParametersToFormSchemas', () => {
it('maps parameters with type conversion and tooltip from description', () => {
const params = [
{
name: 'query',
type: 'string',
description: { en_US: 'Search query', zh_Hans: '搜索查询' },
label: { en_US: 'Query', zh_Hans: '查询' },
required: true,
form: 'llm',
},
] as unknown as TriggerEventParameter[]
const result = triggerEventParametersToFormSchemas(params)
expect(result).toHaveLength(1)
expect(result[0]!.type).toBe('text-input')
expect(result[0]!._type).toBe('string')
expect(result[0]).toMatchObject({
name: 'query',
label: { en_US: 'Query', zh_Hans: '查询' },
required: true,
tooltip: { en_US: 'Search query', zh_Hans: '搜索查询' },
})
})
})
describe('toolParametersToFormSchemas', () => {
it('converts parameters with variable = name and type conversion', () => {
const params: ToolParameter[] = [
{
name: 'input_text',
label: { en_US: 'Input', zh_Hans: '输入' },
human_description: { en_US: 'Enter text', zh_Hans: '输入文本' },
type: 'string',
form: 'llm',
llm_description: 'The input text',
required: true,
multiple: false,
default: 'hello',
},
]
const result = toolParametersToFormSchemas(params)
expect(result).toHaveLength(1)
expect(result[0]!.variable).toBe('input_text')
expect(result[0]!.type).toBe('text-input')
expect(result[0]!._type).toBe('string')
expect(result[0]!.show_on).toEqual([])
expect(result[0]!.tooltip).toEqual({ en_US: 'Enter text', zh_Hans: '输入文本' })
})
it('maps options with show_on = []', () => {
const params: ToolParameter[] = [
{
name: 'mode',
label: { en_US: 'Mode', zh_Hans: '模式' },
human_description: { en_US: 'Select mode', zh_Hans: '选择模式' },
type: 'select',
form: 'form',
llm_description: '',
required: false,
multiple: false,
default: 'fast',
options: [
{ label: { en_US: 'Fast', zh_Hans: '快速' }, value: 'fast' },
{ label: { en_US: 'Accurate', zh_Hans: '精确' }, value: 'accurate' },
],
},
]
const result = toolParametersToFormSchemas(params)
expect(result[0]!.options).toHaveLength(2)
expect(result[0]!.options![0]!.show_on).toEqual([])
expect(result[0]!.options![1]!.show_on).toEqual([])
})
})
describe('toolCredentialToFormSchemas', () => {
it('converts credentials with variable = name and tooltip from help', () => {
const creds: ToolCredential[] = [
{
name: 'api_key',
label: { en_US: 'API Key', zh_Hans: 'API 密钥' },
help: { en_US: 'Enter your API key', zh_Hans: '输入你的 API 密钥' },
placeholder: { en_US: 'sk-xxx', zh_Hans: 'sk-xxx' },
type: 'secret-input',
required: true,
default: '',
},
]
const result = toolCredentialToFormSchemas(creds)
expect(result).toHaveLength(1)
expect(result[0]!.variable).toBe('api_key')
expect(result[0]!.type).toBe('secret-input')
expect(result[0]!.tooltip).toEqual({
en_US: 'Enter your API key',
zh_Hans: '输入你的 API 密钥',
})
expect(result[0]!.show_on).toEqual([])
})
it('handles null help field → tooltip becomes undefined', () => {
const creds: ToolCredential[] = [
{
name: 'token',
label: { en_US: 'Token', zh_Hans: '令牌' },
help: null,
placeholder: { en_US: '', zh_Hans: '' },
type: 'string',
required: false,
default: '',
},
]
const result = toolCredentialToFormSchemas(creds)
expect(result[0]!.tooltip).toBeUndefined()
})
it('maps credential options with show_on = []', () => {
const creds: ToolCredential[] = [
{
name: 'auth_method',
label: { en_US: 'Auth', zh_Hans: '认证' },
help: null,
placeholder: { en_US: '', zh_Hans: '' },
type: 'select',
required: true,
default: 'bearer',
options: [
{ label: { en_US: 'Bearer', zh_Hans: 'Bearer' }, value: 'bearer' },
{ label: { en_US: 'Basic', zh_Hans: 'Basic' }, value: 'basic' },
],
},
]
const result = toolCredentialToFormSchemas(creds)
expect(result[0]!.options).toHaveLength(2)
result[0]!.options!.forEach((opt) => expect(opt.show_on).toEqual([]))
})
})
describe('addDefaultValue', () => {
it('fills in default when value is empty/null/undefined', () => {
const schemas = [
{ variable: 'name', type: 'text-input', default: 'default-name' },
{ variable: 'count', type: 'number-input', default: 10 },
]
const result = addDefaultValue({}, schemas)
expect(result.name).toBe('default-name')
expect(result.count).toBe(10)
})
it('does not override existing values', () => {
const schemas = [{ variable: 'name', type: 'text-input', default: 'default' }]
const result = addDefaultValue({ name: 'existing' }, schemas)
expect(result.name).toBe('existing')
})
it('fills default for empty string value', () => {
const schemas = [{ variable: 'name', type: 'text-input', default: 'default' }]
const result = addDefaultValue({ name: '' }, schemas)
expect(result.name).toBe('default')
})
it('converts string boolean values to proper boolean type', () => {
const schemas = [{ variable: 'flag', type: 'boolean' }]
expect(addDefaultValue({ flag: 'true' }, schemas).flag).toBe(true)
expect(addDefaultValue({ flag: 'false' }, schemas).flag).toBe(false)
expect(addDefaultValue({ flag: '1' }, schemas).flag).toBe(true)
expect(addDefaultValue({ flag: 'True' }, schemas).flag).toBe(true)
expect(addDefaultValue({ flag: '0' }, schemas).flag).toBe(false)
})
it('converts number boolean values to proper boolean type', () => {
const schemas = [{ variable: 'flag', type: 'boolean' }]
expect(addDefaultValue({ flag: 1 }, schemas).flag).toBe(true)
expect(addDefaultValue({ flag: 0 }, schemas).flag).toBe(false)
})
it('preserves actual boolean values', () => {
const schemas = [{ variable: 'flag', type: 'boolean' }]
expect(addDefaultValue({ flag: true }, schemas).flag).toBe(true)
expect(addDefaultValue({ flag: false }, schemas).flag).toBe(false)
})
})
describe('generateFormValue', () => {
it('generates constant-type value wrapper for defaults', () => {
const schemas = [{ variable: 'name', type: 'text-input', default: 'hello' }]
const result = generateFormValue({}, schemas)
const wrapper = result.name as { value: { type: string; value: unknown } }
// correctInitialData sets type to 'mixed' for text-input but preserves default value
expect(wrapper.value.type).toBe('mixed')
expect(wrapper.value.value).toBe('hello')
})
it('skips values that already exist', () => {
const schemas = [{ variable: 'name', type: 'text-input', default: 'hello' }]
const result = generateFormValue({ name: 'existing' }, schemas)
expect(result.name).toBeUndefined()
})
it('generates auto:1 for reasoning mode', () => {
const schemas = [{ variable: 'name', type: 'text-input', default: 'hello' }]
const result = generateFormValue({}, schemas, true)
expect(result.name).toEqual({ auto: 1, value: null })
})
it('handles boolean default conversion in non-reasoning mode', () => {
const schemas = [{ variable: 'flag', type: 'boolean', default: 'true' }]
const result = generateFormValue({}, schemas)
const wrapper = result.flag as { value: { type: string; value: unknown } }
expect(wrapper.value.value).toBe(true)
})
it('handles number-input default conversion', () => {
const schemas = [{ variable: 'count', type: 'number-input', default: '42' }]
const result = generateFormValue({}, schemas)
const wrapper = result.count as { value: { type: string; value: unknown } }
expect(wrapper.value.value).toBe(42)
})
})
describe('getPlainValue', () => {
it('unwraps { value: ... } structure to plain values', () => {
const input = {
a: { value: { type: 'constant', val: 1 } },
b: { value: { type: 'mixed', val: 'text' } },
}
const result = getPlainValue(input)
expect(result.a).toEqual({ type: 'constant', val: 1 })
expect(result.b).toEqual({ type: 'mixed', val: 'text' })
})
it('returns empty object for empty input', () => {
expect(getPlainValue({})).toEqual({})
})
})
describe('getStructureValue', () => {
it('wraps plain values into { value: ... } structure', () => {
const input = { a: 'hello', b: 42 }
const result = getStructureValue(input)
expect(result).toEqual({ a: { value: 'hello' }, b: { value: 42 } })
})
it('returns empty object for empty input', () => {
expect(getStructureValue({})).toEqual({})
})
})
describe('getConfiguredValue', () => {
it('fills defaults with correctInitialData for missing values', () => {
const schemas = [{ variable: 'name', type: 'text-input', default: 'hello' }]
const result = getConfiguredValue({}, schemas)
const val = result.name as { type: string; value: unknown }
expect(val.type).toBe('mixed')
})
it('does not override existing values', () => {
const schemas = [{ variable: 'name', type: 'text-input', default: 'hello' }]
const result = getConfiguredValue({ name: 'existing' }, schemas)
expect(result.name).toBe('existing')
})
it('escapes newlines in string defaults', () => {
const schemas = [{ variable: 'prompt', type: 'text-input', default: 'line1\nline2' }]
const result = getConfiguredValue({}, schemas)
const val = result.prompt as { type: string; value: unknown }
expect(val.type).toBe('mixed')
expect(val.value).toBe('line1\\nline2')
})
it('handles boolean default conversion', () => {
const schemas = [{ variable: 'flag', type: 'boolean', default: 'true' }]
const result = getConfiguredValue({}, schemas)
const val = result.flag as { type: string; value: unknown }
expect(val.value).toBe(true)
})
it('handles app-selector type', () => {
const schemas = [{ variable: 'app', type: 'app-selector', default: 'app-id-123' }]
const result = getConfiguredValue({}, schemas)
const val = result.app as { type: string; value: unknown }
expect(val.value).toBe('app-id-123')
})
})
describe('generateAgentToolValue', () => {
it('generates constant-type values in non-reasoning mode', () => {
const schemas = [{ variable: 'name', type: 'text-input', default: 'hello' }]
const value = { name: { value: 'world' } }
const result = generateAgentToolValue(value, schemas)
expect(result.name!.value).toEqual({ type: 'mixed', value: 'world' })
})
it('generates auto:1 for auto-mode parameters in reasoning mode', () => {
const schemas = [{ variable: 'name', type: 'text-input' }]
const value = { name: { auto: 1 as const, value: undefined } }
const result = generateAgentToolValue(value, schemas, true)
expect(result.name).toEqual({ auto: 1, value: null })
})
it('generates auto:0 with value for manual parameters in reasoning mode', () => {
const schemas = [{ variable: 'name', type: 'text-input' }]
const value = { name: { auto: 0 as const, value: { type: 'constant', value: 'manual' } } }
const result = generateAgentToolValue(value, schemas, true)
expect(result.name!.auto).toBe(0)
expect(result.name!.value).toEqual({ type: 'constant', value: 'manual' })
})
it('handles undefined value in reasoning mode with fallback', () => {
const schemas = [{ variable: 'name', type: 'select' }]
const value = { name: { auto: 0 as const, value: undefined } }
const result = generateAgentToolValue(value, schemas, true)
expect(result.name!.auto).toBe(0)
expect(result.name!.value).toEqual({ type: 'constant', value: null })
})
it('applies correctInitialData for boolean type conversion', () => {
const schemas = [{ variable: 'flag', type: 'boolean' }]
const value = { flag: { value: 'true' } }
const result = generateAgentToolValue(value, schemas)
expect(result.flag!.value!.value).toBe(true)
})
})
})
@@ -0,0 +1,42 @@
import type { ThoughtItem } from '@/app/components/base/chat/chat/type'
import type { FileEntity } from '@/app/components/base/file-uploader/types'
import type { VisionFile } from '@/types/app'
import { ToolType } from '../../workflow/block-selector/types'
export const getToolType = (type: string) => {
switch (type) {
case 'builtin':
return ToolType.BuiltIn
case 'api':
return ToolType.Custom
case 'workflow':
return ToolType.Workflow
case 'mcp':
return ToolType.MCP
default:
return ToolType.BuiltIn
}
}
export const sortAgentSorts = (list: ThoughtItem[]) => {
if (!list) return list
if (list.some((item) => item.position === undefined)) return list
const temp = [...list]
temp.sort((a, b) => a.position - b.position)
return temp
}
export const addFileInfos = (list: ThoughtItem[], messageFiles: (FileEntity | VisionFile)[]) => {
if (!list || !messageFiles) return list
return list.map((item) => {
if (item.files && item.files?.length > 0) {
return {
...item,
message_files: item.files.map((fileId) =>
messageFiles.find((file) => file.id === fileId),
) as FileEntity[],
}
}
return item
})
}
@@ -0,0 +1,233 @@
import type { AppMcpServerResponse } from '@dify/contracts/api/console/apps/types.gen'
import type { RagPipelineRecommendedPluginsResponse } from '@dify/contracts/api/console/rag/types.gen'
import type {
ApiProviderDetailResponse,
ApiSchemaParseResponse,
ApiToolBundle,
ToolParameter as ContractToolParameter,
I18nObject,
ToolApiEntity,
ToolApiListResponse,
ToolProviderApiEntityResponse,
ToolProviderListResponse,
WorkflowToolDetailResponse,
} from '@dify/contracts/api/console/workspaces/types.gen'
import type { MarketplacePlugin } from '@dify/contracts/marketplace'
import type {
Collection,
Credential,
CustomParamSchema,
Emoji,
MCPServerDetail,
Tool,
ToolParameter,
WorkflowToolProviderOutputSchema,
WorkflowToolProviderResponse,
} from '../types'
import type { RAGRecommendedPlugins, ToolWithProvider } from '@/app/components/workflow/types'
import { AuthHeaderPrefix, AuthType } from '../types'
type LocalizedText = Collection['label']
type ProviderIcon = ToolProviderApiEntityResponse['icon']
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null && !Array.isArray(value)
const isOneOf = <T extends string>(values: Record<string, T>, value: unknown): value is T =>
typeof value === 'string' && Object.values<string>(values).includes(value)
const getString = (record: Record<string, unknown>, key: string) => {
const value = record[key]
return typeof value === 'string' ? value : undefined
}
// Untranslated locales fall back to en_US, matching renderI18nObject.
const toLocalizedText = ({ en_US, ja_JP, pt_BR, zh_Hans }: I18nObject): LocalizedText => ({
en_US,
zh_Hans: zh_Hans ?? en_US,
...(ja_JP != null && { ja_JP }),
...(pt_BR != null && { pt_BR }),
})
const EMPTY_TEXT: LocalizedText = { en_US: '', zh_Hans: '' }
// Providers return an icon URL, or an emoji record for API and workflow tools.
const toIcon = (icon: ProviderIcon): string | Emoji =>
typeof icon === 'string'
? icon
: { background: icon.background ?? '', content: icon.content ?? '' }
const toIdentityMode = (mode: string | undefined) =>
mode === 'off' || mode === 'idp_token' ? mode : undefined
const toToolParameter = (parameter: ContractToolParameter): ToolParameter => ({
...parameter,
label: toLocalizedText(parameter.label),
human_description: parameter.human_description
? toLocalizedText(parameter.human_description)
: EMPTY_TEXT,
llm_description: parameter.llm_description ?? '',
required: parameter.required ?? false,
multiple: parameter.multiple ?? false,
min: parameter.min ?? undefined,
max: parameter.max ?? undefined,
options: parameter.options?.map((option) => ({
...option,
label: toLocalizedText(option.label),
})),
})
const toTool = (tool: ToolApiEntity): Tool => ({
...tool,
label: toLocalizedText(tool.label),
description: toLocalizedText(tool.description),
labels: tool.labels ?? [],
output_schema: tool.output_schema ?? {},
parameters: (tool.parameters ?? []).map(toToolParameter),
})
const toCollection = (provider: ToolProviderApiEntityResponse): Collection => ({
...provider,
label: toLocalizedText(provider.label),
description: toLocalizedText(provider.description),
icon: toIcon(provider.icon),
icon_dark: provider.icon_dark === undefined ? undefined : toIcon(provider.icon_dark),
team_credentials: provider.team_credentials ?? {},
is_team_authorization: provider.is_team_authorization ?? false,
allow_delete: provider.allow_delete ?? false,
labels: provider.labels ?? [],
tools: provider.tools?.map(toTool),
plugin_id: provider.plugin_id ?? undefined,
server_url: provider.server_url ?? undefined,
server_identifier: provider.server_identifier ?? undefined,
masked_headers: provider.masked_headers ?? undefined,
authentication: provider.authentication
? {
client_id: provider.authentication.client_id,
client_secret: provider.authentication.client_secret ?? undefined,
}
: undefined,
configuration: provider.configuration ?? undefined,
identity_mode: toIdentityMode(provider.identity_mode),
workflow_app_id: provider.workflow_app_id ?? undefined,
})
export const selectToolProvider = (provider: ToolProviderApiEntityResponse): ToolWithProvider => ({
...toCollection(provider),
tools: (provider.tools ?? []).map(toTool),
plugin_unique_identifier: provider.plugin_unique_identifier ?? undefined,
})
export const selectToolCollections = (data: ToolProviderListResponse) => data.map(toCollection)
export const selectToolsWithProvider = (data: ToolProviderListResponse) =>
data.map(selectToolProvider)
export const selectToolProviderTools = (provider: ToolProviderApiEntityResponse) => ({
tools: (provider.tools ?? []).map(toTool),
})
export const selectBuiltinProviderTools = (data: ToolApiListResponse) => data.map(toTool)
export const selectMCPServerDetail = (detail: AppMcpServerResponse): MCPServerDetail => ({
...detail,
parameters: isRecord(detail.parameters)
? Object.fromEntries(
Object.entries(detail.parameters).filter(
(entry): entry is [string, string] => typeof entry[1] === 'string',
),
)
: undefined,
})
const toOutputSchema = (
schema: Record<string, unknown> = {},
): WorkflowToolProviderOutputSchema => ({
type: typeof schema.type === 'string' ? schema.type : 'object',
properties: isRecord(schema.properties)
? Object.fromEntries(
Object.entries(schema.properties).flatMap(([name, property]) =>
isRecord(property) && typeof property.type === 'string'
? [
[
name,
{
type: property.type,
description:
typeof property.description === 'string' ? property.description : '',
},
],
]
: [],
),
)
: {},
})
export const selectWorkflowToolDetail = (
detail: WorkflowToolDetailResponse,
): WorkflowToolProviderResponse => ({
...detail,
privacy_policy: detail.privacy_policy ?? '',
tool: {
...detail.tool,
label: toLocalizedText(detail.tool.label),
description: toLocalizedText(detail.tool.description),
labels: detail.tool.labels ?? [],
parameters: (detail.tool.parameters ?? []).map(toToolParameter),
output_schema: toOutputSchema(detail.tool.output_schema),
},
})
// Uninstalled recommendations are marketplace manifests the console proxies unchanged; keep the
// ones that identify an installable package.
const isMarketplacePlugin = (value: Record<string, unknown>): value is MarketplacePlugin =>
typeof value.type === 'string' &&
typeof value.org === 'string' &&
typeof value.name === 'string' &&
typeof value.plugin_id === 'string' &&
typeof value.latest_package_identifier === 'string'
export const selectRAGRecommendedPlugins = (
data: RagPipelineRecommendedPluginsResponse,
): RAGRecommendedPlugins => ({
installed_recommended_plugins: data.installed_recommended_plugins.map(selectToolProvider),
uninstalled_recommended_plugins: data.uninstalled_recommended_plugins.filter(isMarketplacePlugin),
})
// OpenAPI operations without an id or summary leave those labels empty in the editor.
const toCustomParamSchema = (bundle: ApiToolBundle): CustomParamSchema => ({
operation_id: bundle.operation_id ?? '',
summary: bundle.summary ?? '',
server_url: bundle.server_url,
method: bundle.method,
parameters: (bundle.parameters ?? []).map(toToolParameter),
})
export const selectApiSchemaParameters = (data: ApiSchemaParseResponse) => ({
schema_type: data.schema_type,
parameters_schema: data.parameters_schema.map(toCustomParamSchema),
})
// Stored API tool credentials hold the fields of their auth type. A provider saved without an
// auth type sends no credentials.
const toCredential = (credentials: Record<string, unknown>): Credential => ({
auth_type: isOneOf(AuthType, credentials.auth_type) ? credentials.auth_type : AuthType.none,
api_key_header: getString(credentials, 'api_key_header'),
api_key_value: getString(credentials, 'api_key_value'),
api_key_header_prefix: isOneOf(AuthHeaderPrefix, credentials.api_key_header_prefix)
? credentials.api_key_header_prefix
: undefined,
api_key_query_param: getString(credentials, 'api_key_query_param'),
})
/** The custom tool editor state for a stored API provider. */
export const selectCustomCollection = (detail: ApiProviderDetailResponse) => ({
credentials: toCredential(detail.credentials ?? {}),
icon: detail.icon,
schema_type: detail.schema_type,
schema: detail.schema,
privacy_policy: detail.privacy_policy ?? '',
custom_disclaimer: detail.custom_disclaimer ?? '',
tools: detail.tools.map(toCustomParamSchema),
})
@@ -0,0 +1,329 @@
import type { TriggerEventParameter } from '../../plugins/types'
import type { ToolCredential, ToolParameter } from '../types'
import type { TypeWithI18N } from '@/app/components/header/account-setting/model-provider-page/declarations'
import type { Field } from '@/app/components/workflow/nodes/llm/types'
import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
// Type for form value input with type and value properties
type FormValueInput = {
type?: string
value?: unknown
}
/**
* Form schema type for tool credentials.
* This type represents the schema returned by toolCredentialToFormSchemas.
*/
export type ToolCredentialFormSchema = {
name: string
variable: string
label: TypeWithI18N
type: string
required: boolean
default?: string
tooltip?: TypeWithI18N
placeholder?: TypeWithI18N
show_on: { variable: string; value: string }[]
options?: {
label: TypeWithI18N
value: string
show_on: { variable: string; value: string }[]
}[]
help?: TypeWithI18N | null
url?: string
}
/**
* Form schema type for tool parameters.
* This type represents the schema returned by toolParametersToFormSchemas.
*/
export type ToolFormSchema = {
name: string
variable: string
label: TypeWithI18N
type: string
_type: string
form: string
required: boolean
default?: ToolParameter['default']
tooltip?: TypeWithI18N
show_on: { variable: string; value: string }[]
options?: {
label: TypeWithI18N
value: string
show_on: { variable: string; value: string }[]
}[]
placeholder?: TypeWithI18N
min?: number
max?: number
llm_description?: string
human_description?: TypeWithI18N
multiple?: boolean
url?: string
scope?: string
input_schema?: Field | null
}
export const toType = (type: string) => {
switch (type) {
case 'string':
return 'text-input'
case 'number':
return 'number-input'
case 'boolean':
return 'checkbox'
default:
return type
}
}
export const triggerEventParametersToFormSchemas = (parameters: TriggerEventParameter[]) => {
if (!parameters?.length) return []
return parameters.map((parameter) => {
return {
...parameter,
type: toType(parameter.type),
_type: parameter.type,
tooltip: parameter.description,
}
})
}
export const toolParametersToFormSchemas = (parameters: ToolParameter[]): ToolFormSchema[] => {
if (!parameters) return []
const formSchemas = parameters.map((parameter): ToolFormSchema => {
return {
...parameter,
variable: parameter.name,
type: toType(parameter.type),
_type: parameter.type,
show_on: [],
options: parameter.options?.map((option) => {
return {
...option,
show_on: [],
}
}),
tooltip: parameter.human_description,
}
})
return formSchemas
}
export const toolCredentialToFormSchemas = (
parameters: ToolCredential[],
): ToolCredentialFormSchema[] => {
if (!parameters) return []
const formSchemas = parameters.map((parameter): ToolCredentialFormSchema => {
return {
...parameter,
variable: parameter.name,
type: toType(parameter.type),
label: parameter.label,
tooltip: parameter.help ?? undefined,
show_on: [],
options: parameter.options?.map((option) => {
return {
...option,
show_on: [],
}
}),
}
})
return formSchemas
}
export const addDefaultValue = (
value: Record<string, unknown>,
formSchemas: { variable: string; type: string; default?: unknown }[],
) => {
const newValues = { ...value }
formSchemas.forEach((formSchema) => {
const itemValue = value[formSchema.variable]
if (
formSchema.default !== undefined &&
(value === undefined || itemValue === null || itemValue === '' || itemValue === undefined)
)
newValues[formSchema.variable] = formSchema.default
// Fix: Convert boolean field values to proper boolean type
if (
formSchema.type === 'boolean' &&
itemValue !== undefined &&
itemValue !== null &&
itemValue !== ''
) {
if (typeof itemValue === 'string')
newValues[formSchema.variable] =
itemValue === 'true' || itemValue === '1' || itemValue === 'True'
else if (typeof itemValue === 'number') newValues[formSchema.variable] = itemValue === 1
else if (typeof itemValue === 'boolean') newValues[formSchema.variable] = itemValue
}
})
return newValues
}
const correctInitialData = (
type: string,
target: FormValueInput,
defaultValue: unknown,
): FormValueInput => {
if (type === 'text-input' || type === 'secret-input') target.type = 'mixed'
if (type === 'boolean') {
if (typeof defaultValue === 'string')
target.value = defaultValue === 'true' || defaultValue === '1'
if (typeof defaultValue === 'boolean') target.value = defaultValue
if (typeof defaultValue === 'number') target.value = defaultValue === 1
}
if (type === 'number-input') {
if (typeof defaultValue === 'string' && defaultValue !== '')
target.value = Number.parseFloat(defaultValue)
}
if (type === FormTypeEnum.date || type === FormTypeEnum.dateRange) {
if (typeof defaultValue === 'string') target.value = defaultValue
if (typeof defaultValue === 'object' && defaultValue !== null && !Array.isArray(defaultValue))
target.value = JSON.stringify(defaultValue)
}
if (type === 'app-selector' || type === 'model-selector') target.value = defaultValue
return target
}
export const generateFormValue = (
value: Record<string, unknown>,
formSchemas: { variable: string; default?: unknown; type: string }[],
isReasoning = false,
) => {
const newValues: Record<string, unknown> = {}
formSchemas.forEach((formSchema) => {
const itemValue = value[formSchema.variable]
if (
formSchema.default !== undefined &&
(value === undefined || itemValue === null || itemValue === '' || itemValue === undefined)
) {
const defaultVal = formSchema.default
if (isReasoning) {
newValues[formSchema.variable] = { auto: 1, value: null }
} else {
const initialValue: FormValueInput = { type: 'constant', value: formSchema.default }
newValues[formSchema.variable] = {
value: correctInitialData(formSchema.type, initialValue, defaultVal),
}
}
}
})
return newValues
}
export const getPlainValue = (value: Record<string, { value: unknown }>) => {
const plainValue: Record<string, unknown> = {}
Object.keys(value).forEach((key) => {
plainValue[key] = {
...(value[key]!.value as object),
}
})
return plainValue
}
export const getStructureValue = (
value: Record<string, unknown>,
): Record<string, { value: unknown }> => {
const newValue: Record<string, { value: unknown }> = {}
Object.keys(value).forEach((key) => {
newValue[key] = {
value: value[key],
}
})
return newValue
}
export const getConfiguredValue = (
value: Record<string, unknown>,
formSchemas: { variable: string; type: string; default?: unknown }[],
) => {
const newValues: Record<string, unknown> = { ...value }
formSchemas.forEach((formSchema) => {
const itemValue = value[formSchema.variable]
if (
formSchema.default !== undefined &&
(value === undefined || itemValue === null || itemValue === '' || itemValue === undefined)
) {
const defaultVal = formSchema.default
const initialValue: FormValueInput = {
type: 'constant',
value:
typeof formSchema.default === 'string'
? formSchema.default.replace(/\n/g, '\\n')
: formSchema.default,
}
newValues[formSchema.variable] = correctInitialData(formSchema.type, initialValue, defaultVal)
}
})
return newValues
}
const getVarKindType = (type: FormTypeEnum) => {
if (type === FormTypeEnum.file || type === FormTypeEnum.files) return VarKindType.variable
if (
type === FormTypeEnum.select ||
type === FormTypeEnum.checkbox ||
type === FormTypeEnum.textNumber ||
type === FormTypeEnum.date ||
type === FormTypeEnum.dateRange
)
return VarKindType.constant
if (type === FormTypeEnum.textInput || type === FormTypeEnum.secretInput) return VarKindType.mixed
}
export const generateAgentToolValue = (
value: Record<string, { value?: unknown; auto?: 0 | 1 }>,
formSchemas: { variable: string; default?: unknown; type: string }[],
isReasoning = false,
) => {
const newValues: Record<string, { value: FormValueInput | null; auto?: 0 | 1 }> = {}
if (!isReasoning) {
formSchemas.forEach((formSchema) => {
const itemValue = value[formSchema.variable]
newValues[formSchema.variable] = {
value: {
type: 'constant',
value: itemValue?.value,
},
}
newValues[formSchema.variable]!.value = correctInitialData(
formSchema.type,
newValues[formSchema.variable]!.value!,
itemValue?.value,
)
})
} else {
formSchemas.forEach((formSchema) => {
const itemValue = value[formSchema.variable]
if (itemValue?.auto === 1) {
newValues[formSchema.variable] = {
auto: 1,
value: null,
}
} else {
newValues[formSchema.variable] = {
auto: 0,
value: (itemValue?.value as FormValueInput) || {
type: getVarKindType(formSchema.type as FormTypeEnum),
value: null,
},
}
}
})
}
return newValues
}
@@ -0,0 +1,20 @@
import type { CollectionProviderType } from '../types'
import { consoleQuery } from '@/service/console'
import { CollectionType } from '../types'
// Each provider type is listed by its own console operation; other provider types have no list.
export const getToolListQueryKey = (type?: CollectionProviderType) => {
const tools = consoleQuery.workspaces.current.tools
switch (type) {
case CollectionType.builtIn:
return tools.builtin.get.queryKey()
case CollectionType.custom:
return tools.api.get.queryKey()
case CollectionType.workflow:
return tools.workflow.get.queryKey()
case CollectionType.mcp:
return tools.mcp.get.queryKey()
default:
return undefined
}
}