dsh-lovart-mcp 0.12.5 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -0
- package/client.js +130 -0
- package/cordis.patch.yml +4 -0
- package/lib/catalog.mjs +175 -0
- package/lib/index.js +204 -13
- package/lib/panel.mjs +38 -4
- package/lib/payload.mjs +117 -0
- package/lib/proxy.mjs +28 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -26,6 +26,7 @@ dsh plugin install dsh-lovart-mcp
|
|
|
26
26
|
| 想做的事 | 工具 |
|
|
27
27
|
|---|---|
|
|
28
28
|
| 生成图片或视频 | `lovart_generate` |
|
|
29
|
+
| 取回产物(图片 / 视频 URL) | `lovart_task` |
|
|
29
30
|
| 先看会用多少积分 | `lovart_quote` |
|
|
30
31
|
| 查支持的模型 | `lovart_catalog` |
|
|
31
32
|
| 改图、放大、抠图、分层、上传、查任务、管项目 | `lovart_tool` |
|
|
@@ -33,11 +34,38 @@ dsh plugin install dsh-lovart-mcp
|
|
|
33
34
|
| 看项目、模型权限、任务与素材记录 | `lovart_account` |
|
|
34
35
|
| 添加 / 移除账号 | 面板的「新增账号」与卡片上的「移除」,或 `lovart_add_account` / `lovart_remove_account` |
|
|
35
36
|
| 设置代理 | `lovart_set_proxy` |
|
|
37
|
+
| 开关模型与能力 | 面板的「模型与能力」,或 `lovart_switch` / `lovart_switches` |
|
|
36
38
|
| 导出 / 导入登录 | 面板按钮,或 `lovart_export_credential` / `lovart_import_credential` |
|
|
37
39
|
| 导出 / 导入任务与素材记录 | 面板按钮,或 `lovart_export_state` / `lovart_import_state` |
|
|
38
40
|
|
|
39
41
|
提交生成前会先给出积分报价,确认后才执行。
|
|
40
42
|
|
|
43
|
+
## 生成模式
|
|
44
|
+
|
|
45
|
+
`lovart_generate` 会自己判断模式,返回里的 `mode` 会告诉你用的是哪一种:
|
|
46
|
+
|
|
47
|
+
| 模式 | 怎么触发 | 说明 |
|
|
48
|
+
| --- | --- | --- |
|
|
49
|
+
| 文生图 | 只给 prompt | 默认 1K Relax 模型,通常 0 积分 |
|
|
50
|
+
| 参考图生图 | `ref_images` | 传 `count` 可以一次出多张 |
|
|
51
|
+
| 文生视频 | prompt + `duration` | 视频模型多为会员专属,先用 `lovart_quote` 看积分 |
|
|
52
|
+
| 首帧生视频 | `first_frame` | 首帧用 Lovart 托管的 URL |
|
|
53
|
+
| 首尾帧生视频 | `first_frame` + `last_frame` | 只在支持首尾帧的模型上有效 |
|
|
54
|
+
| 参考图 / 参考视频生视频 | `ref_images` / `ref_video` | 参考视频用于跟随运动 |
|
|
55
|
+
|
|
56
|
+
**参考图必须由 Lovart 托管。** 本地截图、关键帧先 `lovart_tool(tool:"upload_asset")` 上传,拿到 URL 再传进来;直接传外部链接会被网关以 `InvalidParameter.FormatUnsupported` 拒绝。插件会对非 lovart.ai 的链接给出提示。
|
|
57
|
+
|
|
58
|
+
生成是异步的:`lovart_generate` 只负责提交,返回 `task_ids`。要产物就再调 `lovart_task(task_ids: "...", wait: "true")`,它会轮询到完成,并把最终的图片或视频 URL 直接给你。传 `project_id` 可以把结果放进已有项目。
|
|
59
|
+
|
|
60
|
+
## 模型与能力
|
|
61
|
+
|
|
62
|
+
面板底部有一块「模型与能力」:能力按生成、编辑、素材、项目、任务、模型目录、账户、评估分组,模型按厂商(openai、vertex、seedance……)分组。
|
|
63
|
+
|
|
64
|
+
- 点组里的名字 = 单独开关这一项
|
|
65
|
+
- 点「关闭整组」= 一次关掉整组
|
|
66
|
+
|
|
67
|
+
关掉的能力会从 DSH 的工具列表里消失(连 `mcp__lovart-a__*` 这样的原始工具也没有了),关掉的模型不能用于生成。所有开关都写进插件配置,重启后保留。也可以用 `lovart_switch` 切换、`lovart_switches` 查看当前状态。
|
|
68
|
+
|
|
41
69
|
## 网络
|
|
42
70
|
|
|
43
71
|
连不上 Lovart 时,在面板的「代理」填 HTTP 代理地址并保存,或:
|
package/client.js
CHANGED
|
@@ -409,6 +409,135 @@ window.__ModuleLoader__.load({
|
|
|
409
409
|
)
|
|
410
410
|
}
|
|
411
411
|
|
|
412
|
+
function SwitchBoardBox() {
|
|
413
|
+
const [board, setBoard] = React.useState(null)
|
|
414
|
+
const [busyId, setBusyId] = React.useState('')
|
|
415
|
+
const [error, setError] = React.useState('')
|
|
416
|
+
React.useEffect(() => {
|
|
417
|
+
let alive = true
|
|
418
|
+
fetch(`${API}/switches`, { headers: { accept: 'application/json' } })
|
|
419
|
+
.then((response) => response.json())
|
|
420
|
+
.then((body) => { if (alive) setBoard(body) })
|
|
421
|
+
.catch((failure) => { if (alive) setError(String((failure && failure.message) || failure)) })
|
|
422
|
+
return () => { alive = false }
|
|
423
|
+
}, [])
|
|
424
|
+
const toggle = async (payload) => {
|
|
425
|
+
const key = payload.groupId || payload.id || ''
|
|
426
|
+
setBusyId(key)
|
|
427
|
+
try {
|
|
428
|
+
const response = await fetch(`${API}/switches`, {
|
|
429
|
+
method: 'POST',
|
|
430
|
+
headers: { 'content-type': 'application/json' },
|
|
431
|
+
body: JSON.stringify(payload),
|
|
432
|
+
})
|
|
433
|
+
const body = await response.json().catch(() => ({}))
|
|
434
|
+
if (!response.ok) {
|
|
435
|
+
setError(body.error || `切换失败(${response.status})`)
|
|
436
|
+
return
|
|
437
|
+
}
|
|
438
|
+
setError('')
|
|
439
|
+
if (body.board) setBoard(body.board)
|
|
440
|
+
else if (body.board === undefined) setBoard((current) => current)
|
|
441
|
+
} catch (failure) {
|
|
442
|
+
setError(String((failure && failure.message) || failure))
|
|
443
|
+
} finally {
|
|
444
|
+
setBusyId('')
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
if (board === null) {
|
|
448
|
+
return h('div', { style: { fontSize: '12px', opacity: 0.6 } }, error || '模型与能力加载中…')
|
|
449
|
+
}
|
|
450
|
+
if (!board || !Array.isArray(board.groups)) {
|
|
451
|
+
return h('div', {
|
|
452
|
+
style: {
|
|
453
|
+
display: 'flex',
|
|
454
|
+
flexDirection: 'column',
|
|
455
|
+
gap: '4px',
|
|
456
|
+
border: '1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,.3))',
|
|
457
|
+
borderRadius: '10px',
|
|
458
|
+
padding: '10px 12px',
|
|
459
|
+
},
|
|
460
|
+
},
|
|
461
|
+
h('div', { style: { fontSize: '13px', fontWeight: 600 } }, '模型与能力'),
|
|
462
|
+
note(error || board.error || '开关看板没拿到数据,刷新页面再试;账号卡片不受影响。', 'danger'),
|
|
463
|
+
)
|
|
464
|
+
}
|
|
465
|
+
const totals = board.totals || { tools: 0, models: 0, disabledItems: 0, disabledGroups: 0 }
|
|
466
|
+
const chip = (item) => h('button', {
|
|
467
|
+
key: `${item.kind}:${item.id}`,
|
|
468
|
+
type: 'button',
|
|
469
|
+
title: item.detail || item.label,
|
|
470
|
+
disabled: busyId !== '' && busyId !== item.id,
|
|
471
|
+
onClick: () => toggle({ id: item.id, kind: item.kind }),
|
|
472
|
+
style: {
|
|
473
|
+
font: 'inherit',
|
|
474
|
+
fontSize: '11px',
|
|
475
|
+
lineHeight: '18px',
|
|
476
|
+
padding: '1px 7px',
|
|
477
|
+
borderRadius: '999px',
|
|
478
|
+
cursor: 'pointer',
|
|
479
|
+
border: '1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,.3))',
|
|
480
|
+
background: item.disabled ? 'rgba(127,127,127,.10)' : 'transparent',
|
|
481
|
+
color: item.disabled ? 'var(--dsw-alias-text-secondary, #888)' : 'inherit',
|
|
482
|
+
textDecoration: item.disabled ? 'line-through' : 'none',
|
|
483
|
+
opacity: busyId === item.id ? 0.5 : 1,
|
|
484
|
+
},
|
|
485
|
+
}, item.label)
|
|
486
|
+
const groupRow = (group) => h('div', {
|
|
487
|
+
key: group.id,
|
|
488
|
+
style: { display: 'flex', flexDirection: 'column', gap: '4px', padding: '6px 0' },
|
|
489
|
+
},
|
|
490
|
+
h('div', { style: { display: 'flex', alignItems: 'center', gap: '8px' } },
|
|
491
|
+
h('button', {
|
|
492
|
+
type: 'button',
|
|
493
|
+
disabled: busyId !== '' && busyId !== group.id,
|
|
494
|
+
onClick: () => toggle({ groupId: group.id }),
|
|
495
|
+
style: {
|
|
496
|
+
font: 'inherit',
|
|
497
|
+
fontSize: '11px',
|
|
498
|
+
lineHeight: '18px',
|
|
499
|
+
padding: '1px 8px',
|
|
500
|
+
borderRadius: '6px',
|
|
501
|
+
cursor: 'pointer',
|
|
502
|
+
border: '1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,.3))',
|
|
503
|
+
background: group.disabled ? 'rgba(127,127,127,.10)' : 'transparent',
|
|
504
|
+
color: 'inherit',
|
|
505
|
+
},
|
|
506
|
+
}, group.disabled ? `启用「${group.label}」整组` : `关闭「${group.label}」整组`),
|
|
507
|
+
h('span', { style: { fontSize: '11px', opacity: 0.55 } },
|
|
508
|
+
`${group.kind === 'tool' ? '能力' : '模型'} · ${group.items.length} 项`),
|
|
509
|
+
),
|
|
510
|
+
h('div', { style: { display: 'flex', flexWrap: 'wrap', gap: '5px' } }, group.items.map(chip)),
|
|
511
|
+
)
|
|
512
|
+
const toolGroups = board.groups.filter((group) => group.kind === 'tool')
|
|
513
|
+
const modelGroups = board.groups.filter((group) => group.kind === 'model')
|
|
514
|
+
return h('div', {
|
|
515
|
+
style: {
|
|
516
|
+
display: 'flex',
|
|
517
|
+
flexDirection: 'column',
|
|
518
|
+
gap: '4px',
|
|
519
|
+
border: '1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,.3))',
|
|
520
|
+
borderRadius: '10px',
|
|
521
|
+
padding: '10px 12px',
|
|
522
|
+
},
|
|
523
|
+
},
|
|
524
|
+
h('div', { style: { fontSize: '13px', fontWeight: 600 } }, '模型与能力'),
|
|
525
|
+
h('div', { style: { fontSize: '11px', opacity: 0.65 } },
|
|
526
|
+
'点名字可单独开关,点「关闭整组」可一次关掉一组。关闭后对应的 MCP 工具会从 DSH 里消失,模型也不能被用于生成。'),
|
|
527
|
+
error ? note(error, 'danger') : null,
|
|
528
|
+
h('div', { style: { display: 'flex', gap: '16px', flexWrap: 'wrap', fontSize: '11px', opacity: 0.6 } },
|
|
529
|
+
h('span', null, `能力 ${totals.tools} 项 · 已关 ${totals.disabledItems}`),
|
|
530
|
+
h('span', null, `模型 ${totals.models} 项 · 组 ${totals.disabledGroups}`),
|
|
531
|
+
),
|
|
532
|
+
h('div', { style: { fontSize: '12px', fontWeight: 600, marginTop: '4px' } }, '能力'),
|
|
533
|
+
toolGroups.map(groupRow),
|
|
534
|
+
h('div', { style: { fontSize: '12px', fontWeight: 600, marginTop: '4px' } }, '模型'),
|
|
535
|
+
modelGroups.length === 0
|
|
536
|
+
? h('div', { style: { fontSize: '11px', opacity: 0.6 } }, '先登录一个账号,模型列表才能拉取。')
|
|
537
|
+
: modelGroups.map(groupRow),
|
|
538
|
+
)
|
|
539
|
+
}
|
|
540
|
+
|
|
412
541
|
function Panel() {
|
|
413
542
|
const { data, busy, action, load, login, addAccount, removeAccount, exportAccount, importBundle, exportState, importStateText, saveProxy } = useStatus()
|
|
414
543
|
const [proxyDraft, setProxyDraft] = React.useState(null)
|
|
@@ -454,6 +583,7 @@ window.__ModuleLoader__.load({
|
|
|
454
583
|
})),
|
|
455
584
|
),
|
|
456
585
|
h(AddAccountBox, { onAdd: addAccount, busy }),
|
|
586
|
+
h(SwitchBoardBox, null),
|
|
457
587
|
action && action.kind === 'add'
|
|
458
588
|
? note(`已新增账号 ${action.id}(${action.label})${action.saved ? ',并写入插件配置' : ',仅本次会话有效'}。点上面的「登录」去授权。`)
|
|
459
589
|
: null,
|
package/cordis.patch.yml
CHANGED
package/lib/catalog.mjs
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Capability catalog: which Lovart MCP tools the plugin offers, how they group,
|
|
3
|
+
* and how model ids group by vendor. Used by the panel (to render switches), by
|
|
4
|
+
* the plugin tools (to refuse disabled calls) and by the stdio proxy (to hide
|
|
5
|
+
* disabled tools from DSH entirely).
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export const TOOL_GROUPS = [
|
|
9
|
+
{ id: 'generation', label: '生成', tools: ['generate_image', 'generate_video'] },
|
|
10
|
+
{ id: 'editing', label: '编辑', tools: ['edit_image', 'separate_layers', 'vectorize', 'upscale', 'remove_video_background'] },
|
|
11
|
+
{ id: 'assets', label: '素材', tools: ['upload_asset'] },
|
|
12
|
+
{ id: 'projects', label: '项目', tools: ['create_project', 'rename_project', 'list_projects'] },
|
|
13
|
+
{ id: 'tasks', label: '任务', tools: ['get_task', 'get_task_status', 'cancel_task'] },
|
|
14
|
+
{ id: 'models', label: '模型目录', tools: ['list_models', 'describe_model'] },
|
|
15
|
+
{ id: 'account', label: '账户', tools: ['get_credits'] },
|
|
16
|
+
{ id: 'ranking', label: '评估', tools: ['rank_candidates_with_jev'] },
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
export const TOOL_LABELS = {
|
|
20
|
+
generate_image: '生成图片',
|
|
21
|
+
generate_video: '生成视频',
|
|
22
|
+
edit_image: '编辑图片',
|
|
23
|
+
separate_layers: '拆分层',
|
|
24
|
+
vectorize: '矢量化',
|
|
25
|
+
upscale: '放大',
|
|
26
|
+
remove_video_background: '视频去背',
|
|
27
|
+
upload_asset: '上传素材',
|
|
28
|
+
create_project: '新建项目',
|
|
29
|
+
rename_project: '重命名项目',
|
|
30
|
+
list_projects: '项目列表',
|
|
31
|
+
get_task: '任务详情',
|
|
32
|
+
get_task_status: '任务状态',
|
|
33
|
+
cancel_task: '取消任务',
|
|
34
|
+
list_models: '模型列表',
|
|
35
|
+
describe_model: '模型参数',
|
|
36
|
+
get_credits: '积分余额',
|
|
37
|
+
rank_candidates_with_jev: '候选评分',
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Empty switch state. */
|
|
41
|
+
export function emptyDisabled() {
|
|
42
|
+
return { tools: [], models: [], groups: [] }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Normalise whatever the config holds into the three-array shape. */
|
|
46
|
+
export function normalizeDisabled(raw) {
|
|
47
|
+
const source = raw !== null && typeof raw === 'object' ? raw : {}
|
|
48
|
+
const list = (value) => (Array.isArray(value) ? value.filter((item) => typeof item === 'string' && item !== '') : [])
|
|
49
|
+
return {
|
|
50
|
+
tools: Array.from(new Set(list(source.tools))),
|
|
51
|
+
models: Array.from(new Set(list(source.models))),
|
|
52
|
+
groups: Array.from(new Set(list(source.groups))),
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function groupOfTool(name) {
|
|
57
|
+
const group = TOOL_GROUPS.find((entry) => entry.tools.includes(name))
|
|
58
|
+
return group?.id ?? null
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** True when the tool itself or its whole group is switched off. */
|
|
62
|
+
export function isToolDisabled(name, disabled) {
|
|
63
|
+
const state = normalizeDisabled(disabled)
|
|
64
|
+
if (state.tools.includes(name)) return true
|
|
65
|
+
const group = groupOfTool(name)
|
|
66
|
+
return group !== null && state.groups.includes(`tool:${group}`)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function modelVendor(name) {
|
|
70
|
+
const text = typeof name === 'string' ? name : ''
|
|
71
|
+
const slash = text.indexOf('/')
|
|
72
|
+
return slash > 0 ? text.slice(0, slash) : 'other'
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** True when the model itself or its whole vendor group is switched off. */
|
|
76
|
+
export function isModelDisabled(name, disabled) {
|
|
77
|
+
const state = normalizeDisabled(disabled)
|
|
78
|
+
if (state.models.includes(name)) return true
|
|
79
|
+
return state.groups.includes(`model:${modelVendor(name)}`)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function filterToolList(tools, disabled) {
|
|
83
|
+
if (!Array.isArray(tools)) return tools
|
|
84
|
+
return tools.filter((tool) => !isToolDisabled(tool?.name, disabled))
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Flat list of every tool switched off, groups expanded. */
|
|
88
|
+
export function expandToolNames(disabled) {
|
|
89
|
+
const state = normalizeDisabled(disabled)
|
|
90
|
+
const names = new Set(state.tools)
|
|
91
|
+
for (const group of TOOL_GROUPS) {
|
|
92
|
+
if (state.groups.includes(`tool:${group.id}`)) for (const tool of group.tools) names.add(tool)
|
|
93
|
+
}
|
|
94
|
+
return Array.from(names)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Panel payload: switch groups plus every individual entry. */
|
|
98
|
+
export function switchBoard(models, disabled) {
|
|
99
|
+
const state = normalizeDisabled(disabled)
|
|
100
|
+
const toolGroups = TOOL_GROUPS.map((group) => ({
|
|
101
|
+
id: `tool:${group.id}`,
|
|
102
|
+
kind: 'tool',
|
|
103
|
+
label: group.label,
|
|
104
|
+
disabled: state.groups.includes(`tool:${group.id}`),
|
|
105
|
+
items: group.tools.map((name) => ({
|
|
106
|
+
id: name,
|
|
107
|
+
kind: 'tool',
|
|
108
|
+
label: TOOL_LABELS[name] ?? name,
|
|
109
|
+
disabled: state.tools.includes(name),
|
|
110
|
+
})),
|
|
111
|
+
}))
|
|
112
|
+
|
|
113
|
+
const byVendor = new Map()
|
|
114
|
+
for (const model of Array.isArray(models) ? models : []) {
|
|
115
|
+
const name = model?.name ?? model?.id
|
|
116
|
+
if (typeof name !== 'string' || name === '') continue
|
|
117
|
+
const vendor = modelVendor(name)
|
|
118
|
+
if (!byVendor.has(vendor)) byVendor.set(vendor, [])
|
|
119
|
+
byVendor.get(vendor).push({
|
|
120
|
+
id: name,
|
|
121
|
+
kind: 'model',
|
|
122
|
+
label: model?.display_name ?? model?.displayName ?? name,
|
|
123
|
+
detail: `${model?.kind ?? 'image'}${model?.members_only === true ? ' · 会员' : ''}${model?.default === true ? ' · 默认' : ''}`,
|
|
124
|
+
disabled: state.models.includes(name),
|
|
125
|
+
})
|
|
126
|
+
}
|
|
127
|
+
const modelGroups = Array.from(byVendor.entries())
|
|
128
|
+
.sort((a, b) => a[0].localeCompare(b[0]))
|
|
129
|
+
.map(([vendor, items]) => ({
|
|
130
|
+
id: `model:${vendor}`,
|
|
131
|
+
kind: 'model',
|
|
132
|
+
label: vendor,
|
|
133
|
+
disabled: state.groups.includes(`model:${vendor}`),
|
|
134
|
+
items: items.sort((a, b) => a.id.localeCompare(b.id)),
|
|
135
|
+
}))
|
|
136
|
+
|
|
137
|
+
const groupCount = [...toolGroups, ...modelGroups].filter((group) => group.disabled).length
|
|
138
|
+
return {
|
|
139
|
+
disabled: state,
|
|
140
|
+
groups: [...toolGroups, ...modelGroups],
|
|
141
|
+
totals: {
|
|
142
|
+
tools: toolGroups.reduce((sum, group) => sum + group.items.length, 0),
|
|
143
|
+
models: modelGroups.reduce((sum, group) => sum + group.items.length, 0),
|
|
144
|
+
disabledGroups: groupCount,
|
|
145
|
+
disabledItems:
|
|
146
|
+
state.tools.length +
|
|
147
|
+
state.models.length +
|
|
148
|
+
toolGroups.filter((group) => group.disabled).reduce((sum, group) => sum + group.items.length, 0) +
|
|
149
|
+
modelGroups.filter((group) => group.disabled).reduce((sum, group) => sum + group.items.length, 0),
|
|
150
|
+
},
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Dispatch a single toggle against the stored state. A group toggle clears the
|
|
156
|
+
* per-item flags inside it so the two levels cannot contradict each other.
|
|
157
|
+
*/
|
|
158
|
+
export function applyToggle(disabled, { id, kind, groupId } = {}) {
|
|
159
|
+
const state = normalizeDisabled(disabled)
|
|
160
|
+
if (typeof groupId === 'string' && groupId !== '') {
|
|
161
|
+
const isGroup = groupId.startsWith('tool:') || groupId.startsWith('model:')
|
|
162
|
+
const exists = state.groups.includes(groupId)
|
|
163
|
+
state.groups = exists ? state.groups.filter((item) => item !== groupId) : [...state.groups, groupId]
|
|
164
|
+
if (exists === false) {
|
|
165
|
+
const prefix = groupId.startsWith('tool:') ? 'tools' : 'models'
|
|
166
|
+
state[prefix] = state[prefix].filter((item) => (prefix === 'tools' ? `tool:${groupOfTool(item)}` : `model:${modelVendor(item)}`) !== groupId)
|
|
167
|
+
}
|
|
168
|
+
return isGroup ? state : state
|
|
169
|
+
}
|
|
170
|
+
if (typeof id !== 'string' || id === '') return state
|
|
171
|
+
const bucket = kind === 'model' ? 'models' : 'tools'
|
|
172
|
+
const exists = state[bucket].includes(id)
|
|
173
|
+
state[bucket] = exists ? state[bucket].filter((item) => item !== id) : [...state[bucket], id]
|
|
174
|
+
return state
|
|
175
|
+
}
|
package/lib/index.js
CHANGED
|
@@ -26,11 +26,13 @@ import { homedir } from 'node:os'
|
|
|
26
26
|
import { join } from 'node:path'
|
|
27
27
|
import { fileURLToPath } from 'node:url'
|
|
28
28
|
import { callTool } from './mcp-call.mjs'
|
|
29
|
-
import { extractTaskHandles, readCredits, readModels, readProjects, readTasks } from './account-data.mjs'
|
|
29
|
+
import { extractTaskHandles, readCredits, readModels, readProjects, readTasks, summarizeTask } from './account-data.mjs'
|
|
30
30
|
import { applyTaskStatus, listAssets, listTasks, loadLedger, recordAsset, recordTasks, saveLedger } from './ledger.mjs'
|
|
31
31
|
import { buildState, mergeState, parseState } from './state.mjs'
|
|
32
32
|
import { CONFIRM_THRESHOLD_CREDITS, FREE_TOOLS, catalog, quote, quoteExtra } from './pricing.mjs'
|
|
33
33
|
import { createBundlePayload, newKey, open as openBundle, seal } from './vault.mjs'
|
|
34
|
+
import { TOOL_GROUPS, applyToggle, expandToolNames, isModelDisabled, isToolDisabled, normalizeDisabled, switchBoard } from './catalog.mjs'
|
|
35
|
+
import { buildGeneratePayload } from './payload.mjs'
|
|
34
36
|
|
|
35
37
|
export const name = 'lovart-mcp'
|
|
36
38
|
export const inject = ['tools', 'credentials', 'mcpManager']
|
|
@@ -223,6 +225,8 @@ function importStateText(text) {
|
|
|
223
225
|
export async function apply(ctx, config = {}) {
|
|
224
226
|
setProxy(config?.proxy)
|
|
225
227
|
const accounts = normalizeAccounts(config?.accounts)
|
|
228
|
+
/** Tools/models switched off from the panel; enforced here and in the proxy. */
|
|
229
|
+
let disabled = normalizeDisabled(config?.disabled)
|
|
226
230
|
const credentials = ctx.credentials
|
|
227
231
|
const logger = ctx.logger
|
|
228
232
|
const disposers = []
|
|
@@ -267,6 +271,7 @@ export async function apply(ctx, config = {}) {
|
|
|
267
271
|
env: {
|
|
268
272
|
LOVART_TOKEN: access,
|
|
269
273
|
LOVART_MCP_URL: MCP_URL,
|
|
274
|
+
LOVART_DISABLED_TOOLS: expandToolNames(disabled).join(','),
|
|
270
275
|
...(resolveProxy() === '' ? {} : { LOVART_PROXY: resolveProxy() }),
|
|
271
276
|
},
|
|
272
277
|
toolCallTimeoutMs: 180000,
|
|
@@ -505,6 +510,90 @@ export async function apply(ctx, config = {}) {
|
|
|
505
510
|
}
|
|
506
511
|
}
|
|
507
512
|
|
|
513
|
+
async function persistDisabled() {
|
|
514
|
+
const editor = ctx.get?.('configEditor')
|
|
515
|
+
const entry = await entryForAccounts()
|
|
516
|
+
if (editor === undefined || entry === undefined) return false
|
|
517
|
+
try {
|
|
518
|
+
await editor.edit(entry, (current) => ({ ...(current ?? {}), disabled }))
|
|
519
|
+
return true
|
|
520
|
+
} catch (error) {
|
|
521
|
+
logger?.warn?.(`lovart-mcp: could not persist switches — ${error instanceof Error ? error.message : String(error)}`)
|
|
522
|
+
return false
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/**
|
|
527
|
+
* Save the switch board and remount every account: the proxy receives the
|
|
528
|
+
* disabled list through its env, so the raw `mcp__lovart-*__*` tools really
|
|
529
|
+
* disappear instead of merely being refused by the plugin wrappers.
|
|
530
|
+
*/
|
|
531
|
+
async function setDisabledState(next) {
|
|
532
|
+
disabled = normalizeDisabled(next)
|
|
533
|
+
const saved = await persistDisabled()
|
|
534
|
+
for (const account of accounts) void mountAccount(account)
|
|
535
|
+
return { disabled, saved }
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
let modelCache = { at: 0, items: [] }
|
|
539
|
+
async function loadModelCatalogue() {
|
|
540
|
+
if (modelCache.items.length > 0 && Date.now() - modelCache.at < 300_000) return modelCache.items
|
|
541
|
+
const account = accounts.find((entry) => mounted.has(entry.id)) ?? accounts[0]
|
|
542
|
+
if (account === undefined) return []
|
|
543
|
+
const access = await readValue(credentials, account.refs.access)
|
|
544
|
+
if (access === undefined) return []
|
|
545
|
+
const items = []
|
|
546
|
+
for (const kind of ['image', 'video']) {
|
|
547
|
+
try {
|
|
548
|
+
const page = await readModels(access, kind)
|
|
549
|
+
for (const model of page?.models ?? []) items.push({ ...model, kind: model?.kind ?? kind })
|
|
550
|
+
} catch (error) {
|
|
551
|
+
logger?.debug?.(`lovart-mcp: model catalogue (${kind}) — ${error instanceof Error ? error.message : String(error)}`)
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
if (items.length > 0) modelCache = { at: Date.now(), items }
|
|
555
|
+
return items
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
disposers.push(ctx.tools.register(defineTool({
|
|
559
|
+
name: 'lovart_switches',
|
|
560
|
+
description: 'Show which Lovart capabilities and models are switched off, grouped by capability family and model vendor. Mirrors the panel section 模型与能力.',
|
|
561
|
+
parameters: {},
|
|
562
|
+
output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
|
|
563
|
+
async execute() {
|
|
564
|
+
const models = await loadModelCatalogue()
|
|
565
|
+
const board = switchBoard(models, disabled)
|
|
566
|
+
const rows = board.groups.map((group) => ({
|
|
567
|
+
id: group.id,
|
|
568
|
+
label: group.label,
|
|
569
|
+
disabled: group.disabled,
|
|
570
|
+
items: group.items.map((item) => ({ id: item.id, label: item.label, disabled: item.disabled })),
|
|
571
|
+
}))
|
|
572
|
+
return JSON.stringify({ disabled: board.disabled, totals: board.totals, groups: rows }, null, 2)
|
|
573
|
+
},
|
|
574
|
+
})))
|
|
575
|
+
|
|
576
|
+
disposers.push(ctx.tools.register(defineTool({
|
|
577
|
+
name: 'lovart_switch',
|
|
578
|
+
description: 'Switch a Lovart capability group, capability, model group or model on or off. Use "tool:editing" / "model:vertex" for whole groups, or a tool name such as "upscale" / a model id such as "openai/gpt-image-2" for a single item. Disabled capabilities disappear from DSH and disabled models cannot be used for generation.',
|
|
579
|
+
parameters: {
|
|
580
|
+
target: { type: 'string', description: 'Group id ("tool:editing", "model:vertex"), tool name ("upscale") or model id ("openai/gpt-image-2").' },
|
|
581
|
+
},
|
|
582
|
+
output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
|
|
583
|
+
async execute(args) {
|
|
584
|
+
const target = String(args.target ?? '').trim()
|
|
585
|
+
if (target === '') return 'target is required, for example target:"tool:editing" or target:"upscale"'
|
|
586
|
+
let next
|
|
587
|
+
if (target.startsWith('tool:') || target.startsWith('model:')) {
|
|
588
|
+
next = applyToggle(disabled, { groupId: target })
|
|
589
|
+
} else {
|
|
590
|
+
next = applyToggle(disabled, { id: target, kind: target.includes('/') ? 'model' : 'tool' })
|
|
591
|
+
}
|
|
592
|
+
const result = await setDisabledState(next)
|
|
593
|
+
return JSON.stringify({ ok: true, saved: result.saved, disabled: result.disabled }, null, 2)
|
|
594
|
+
},
|
|
595
|
+
})))
|
|
596
|
+
|
|
508
597
|
disposers.push(ctx.tools.register(defineTool({
|
|
509
598
|
name: 'lovart_set_proxy',
|
|
510
599
|
description: 'Route all Lovart traffic (OAuth token calls and MCP) through an HTTP proxy, or clear it. Node fetch ignores HTTPS_PROXY, so this is the supported switch behind a firewall. Persists the value into the plugin config and remounts every account.',
|
|
@@ -713,6 +802,11 @@ export async function apply(ctx, config = {}) {
|
|
|
713
802
|
aspect_ratio: { type: 'string', description: 'Aspect ratio such as 1:1, 16:9, 9:16.' },
|
|
714
803
|
duration: { type: 'string', description: 'Video length in seconds.' },
|
|
715
804
|
count: { type: 'string', description: 'Number of outputs; images map to "n".' },
|
|
805
|
+
ref_images: { type: 'string', description: 'Reference image URLs for image editing or video conditioning. Lovart must host them: upload with lovart_tool(tool:"upload_asset") first. Accepts one URL, a comma-separated list, or a JSON array.' },
|
|
806
|
+
first_frame: { type: 'string', description: 'Video only: URL of the opening frame (Lovart-hosted). Turns the call into image-to-video.' },
|
|
807
|
+
last_frame: { type: 'string', description: 'Video only: URL of the closing frame for models that interpolate between two frames.' },
|
|
808
|
+
ref_video: { type: 'string', description: 'Video only: URL of a video whose motion should be followed (Lovart-hosted).' },
|
|
809
|
+
project_id: { type: 'string', description: 'Optional Lovart project to add the artifacts to; omit and one is created.' },
|
|
716
810
|
confirm_credits: { type: 'string', description: 'Set to "true" to accept the quoted cost and submit.' },
|
|
717
811
|
options: { type: 'string', description: 'Optional JSON object with extra model parameters.' },
|
|
718
812
|
},
|
|
@@ -723,6 +817,9 @@ export async function apply(ctx, config = {}) {
|
|
|
723
817
|
const access = await readValue(credentials, account.refs.access)
|
|
724
818
|
if (access === undefined) return `lovart-${account.id} is not authorized. Run lovart_login(account: "${account.id}") first.`
|
|
725
819
|
const kind = typeof args.kind === 'string' && args.kind === 'video' ? 'video' : 'image'
|
|
820
|
+
if (isToolDisabled(kind === 'video' ? 'generate_video' : 'generate_image', disabled)) {
|
|
821
|
+
return `generate_${kind} is switched off in the Lovart panel (模型与能力). Turn it back on to generate.`
|
|
822
|
+
}
|
|
726
823
|
const priced = quote({
|
|
727
824
|
kind,
|
|
728
825
|
model: typeof args.model === 'string' ? args.model : undefined,
|
|
@@ -730,6 +827,9 @@ export async function apply(ctx, config = {}) {
|
|
|
730
827
|
duration: typeof args.duration === 'string' ? args.duration : undefined,
|
|
731
828
|
count: typeof args.count === 'string' ? args.count : 1,
|
|
732
829
|
})
|
|
830
|
+
if (isModelDisabled(priced.model, disabled)) {
|
|
831
|
+
return `Model ${priced.model} is switched off in the Lovart panel (模型与能力). Pick another model or turn it back on.`
|
|
832
|
+
}
|
|
733
833
|
if (priced.needsConfirmation && String(args.confirm_credits ?? '').toLowerCase() !== 'true') {
|
|
734
834
|
return JSON.stringify({
|
|
735
835
|
status: 'needs_confirmation',
|
|
@@ -745,19 +845,28 @@ export async function apply(ctx, config = {}) {
|
|
|
745
845
|
return 'options must be a JSON object, for example {"quality":"medium"}'
|
|
746
846
|
}
|
|
747
847
|
}
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
848
|
+
let built
|
|
849
|
+
try {
|
|
850
|
+
built = buildGeneratePayload({
|
|
851
|
+
kind,
|
|
852
|
+
prompt: args.prompt,
|
|
853
|
+
model: priced.model,
|
|
854
|
+
aspectRatio: typeof args.aspect_ratio === 'string' ? args.aspect_ratio : undefined,
|
|
855
|
+
resolution: typeof args.resolution === 'string' ? args.resolution : undefined,
|
|
856
|
+
size: typeof args.size === 'string' ? args.size : undefined,
|
|
857
|
+
duration: typeof args.duration === 'string' ? args.duration : undefined,
|
|
858
|
+
count: typeof args.count === 'string' ? args.count : 1,
|
|
859
|
+
refImages: args.ref_images,
|
|
860
|
+
firstFrame: typeof args.first_frame === 'string' ? args.first_frame : undefined,
|
|
861
|
+
lastFrame: typeof args.last_frame === 'string' ? args.last_frame : undefined,
|
|
862
|
+
refVideo: typeof args.ref_video === 'string' ? args.ref_video : undefined,
|
|
863
|
+
projectId: typeof args.project_id === 'string' ? args.project_id : undefined,
|
|
864
|
+
options: extra,
|
|
865
|
+
})
|
|
866
|
+
} catch (error) {
|
|
867
|
+
return `Cannot build the ${kind} request: ${error instanceof Error ? error.message : String(error)}`
|
|
759
868
|
}
|
|
760
|
-
|
|
869
|
+
const payload = built.payload
|
|
761
870
|
const toolName = kind === 'video' ? 'generate_video' : 'generate_image'
|
|
762
871
|
try {
|
|
763
872
|
const result = await callTool(access, toolName, payload)
|
|
@@ -776,6 +885,8 @@ export async function apply(ctx, config = {}) {
|
|
|
776
885
|
estimatedUsd: priced.usd,
|
|
777
886
|
relaxEligible: priced.relax.eligible,
|
|
778
887
|
trackedTasks: recorded,
|
|
888
|
+
mode: built.mode,
|
|
889
|
+
warnings: built.warnings,
|
|
779
890
|
result,
|
|
780
891
|
}, null, 2)
|
|
781
892
|
} catch (error) {
|
|
@@ -784,6 +895,75 @@ export async function apply(ctx, config = {}) {
|
|
|
784
895
|
},
|
|
785
896
|
})))
|
|
786
897
|
|
|
898
|
+
disposers.push(ctx.tools.register(defineTool({
|
|
899
|
+
name: 'lovart_task',
|
|
900
|
+
description: 'Read Lovart tasks and hand back the artifacts — the final image or video URLs — once they finish. Pass the task ids that lovart_generate returned; set wait:"true" to poll until every task settles.',
|
|
901
|
+
parameters: {
|
|
902
|
+
account: { type: 'string', description: 'Account id; defaults to the first configured account.' },
|
|
903
|
+
task_ids: { type: 'string', description: 'One task id, a comma-separated list, or a JSON array.' },
|
|
904
|
+
wait: { type: 'string', description: 'Set to "true" to block until the tasks complete.' },
|
|
905
|
+
timeout_seconds: { type: 'string', description: 'Polling budget in seconds, default 120, max 900.' },
|
|
906
|
+
},
|
|
907
|
+
output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
|
|
908
|
+
async execute(args) {
|
|
909
|
+
const account = findAccount(String(args.account ?? ''))
|
|
910
|
+
if (account === undefined) return `Unknown account "${args.account}". Known: ${accounts.map((entry) => entry.id).join(', ')}`
|
|
911
|
+
const access = await readValue(credentials, account.refs.access)
|
|
912
|
+
if (access === undefined) return `lovart-${account.id} is not authorized. Run lovart_login(account: "${account.id}") first.`
|
|
913
|
+
const raw = String(args.task_ids ?? '').trim()
|
|
914
|
+
let ids = []
|
|
915
|
+
if (raw.startsWith('[')) {
|
|
916
|
+
try {
|
|
917
|
+
const parsed = JSON.parse(raw)
|
|
918
|
+
if (Array.isArray(parsed)) ids = parsed.map((item) => String(item).trim()).filter(Boolean)
|
|
919
|
+
} catch {
|
|
920
|
+
return 'task_ids must be a JSON array of strings, or a comma-separated list.'
|
|
921
|
+
}
|
|
922
|
+
} else if (raw !== '') {
|
|
923
|
+
ids = raw.split(',').map((item) => item.trim()).filter(Boolean)
|
|
924
|
+
}
|
|
925
|
+
if (ids.length === 0) return 'task_ids is required: pass the ids returned by lovart_generate.'
|
|
926
|
+
const waiting = String(args.wait ?? '').toLowerCase() === 'true'
|
|
927
|
+
const budgetSeconds = Math.min(Math.max(Number(args.timeout_seconds ?? 120) || 120, 5), 900)
|
|
928
|
+
const deadline = Date.now() + budgetSeconds * 1000
|
|
929
|
+
const settled = new Set(['completed', 'failed', 'error', 'cancelled', 'canceled'])
|
|
930
|
+
const rowsFrom = (payload) => {
|
|
931
|
+
const list = Array.isArray(payload)
|
|
932
|
+
? payload
|
|
933
|
+
: Array.isArray(payload?.tasks)
|
|
934
|
+
? payload.tasks
|
|
935
|
+
: Array.isArray(payload?.result?.tasks)
|
|
936
|
+
? payload.result.tasks
|
|
937
|
+
: payload?.task_id !== undefined || payload?.taskId !== undefined
|
|
938
|
+
? [payload]
|
|
939
|
+
: []
|
|
940
|
+
return list.map((item) => summarizeTask(item)).filter((item) => item !== null && item.taskId !== null)
|
|
941
|
+
}
|
|
942
|
+
let rows = []
|
|
943
|
+
for (;;) {
|
|
944
|
+
try {
|
|
945
|
+
rows = rowsFrom(await callTool(access, 'get_task_status', { task_ids: ids }, { timeoutMs: 30000 }))
|
|
946
|
+
} catch (error) {
|
|
947
|
+
return `Could not read tasks: ${error instanceof Error ? error.message : String(error)}`
|
|
948
|
+
}
|
|
949
|
+
if (!waiting) break
|
|
950
|
+
if (rows.length > 0 && rows.every((row) => row.status !== null && settled.has(String(row.status).toLowerCase()))) break
|
|
951
|
+
if (Date.now() >= deadline) break
|
|
952
|
+
await new Promise((resolve) => setTimeout(resolve, 3000))
|
|
953
|
+
}
|
|
954
|
+
try {
|
|
955
|
+
const ledger = loadLedger()
|
|
956
|
+
if (applyTaskStatus(ledger, rows)) saveLedger(ledger)
|
|
957
|
+
} catch { /* the ledger is a convenience, never a hard failure */ }
|
|
958
|
+
return JSON.stringify({
|
|
959
|
+
account: `lovart-${account.id}`,
|
|
960
|
+
waited: waiting,
|
|
961
|
+
tasks: rows,
|
|
962
|
+
artifacts: rows.flatMap((row) => row.artifacts ?? []).filter((item) => item.url),
|
|
963
|
+
}, null, 2)
|
|
964
|
+
},
|
|
965
|
+
})))
|
|
966
|
+
|
|
787
967
|
disposers.push(ctx.tools.register(defineTool({
|
|
788
968
|
name: 'lovart_export_credential',
|
|
789
969
|
description: 'Export one account login as an encrypted bundle plus a separate one-time key file. Tokens are never printed: move both files to another DSH machine and run lovart_import_credential there. Only for your own machines — sharing an account login breaks Lovart terms and gives full control of that account.',
|
|
@@ -927,6 +1107,9 @@ export async function apply(ctx, config = {}) {
|
|
|
927
1107
|
async execute(args) {
|
|
928
1108
|
const tool = String(args.tool ?? '').trim()
|
|
929
1109
|
if (!tool) return 'tool is required, for example tool:"get_task_status"'
|
|
1110
|
+
if (isToolDisabled(tool, disabled)) {
|
|
1111
|
+
return `${tool} is switched off in the Lovart panel (模型与能力). Turn it back on to call it.`
|
|
1112
|
+
}
|
|
930
1113
|
const wanted = String(args.account ?? accounts[0]?.id ?? '').trim()
|
|
931
1114
|
const target = accounts.find((item) => item.id === wanted) ?? accounts[0]
|
|
932
1115
|
if (!target) return 'No Lovart account configured. Run lovart_add_account first.'
|
|
@@ -1120,6 +1303,14 @@ export async function apply(ctx, config = {}) {
|
|
|
1120
1303
|
for (const account of accounts) await mountAccount(account)
|
|
1121
1304
|
return saved
|
|
1122
1305
|
},
|
|
1306
|
+
loadModels: () => loadModelCatalogue(),
|
|
1307
|
+
switchBoard: (models) => switchBoard(models, disabled),
|
|
1308
|
+
toggleSwitch: async ({ id, kind, groupId } = {}) => {
|
|
1309
|
+
const next = applyToggle(disabled, { id, kind, groupId })
|
|
1310
|
+
const result = await setDisabledState(next)
|
|
1311
|
+
const models = await loadModelCatalogue()
|
|
1312
|
+
return { ...result, board: switchBoard(models, result.disabled) }
|
|
1313
|
+
},
|
|
1123
1314
|
})
|
|
1124
1315
|
if (typeof disposePanel === 'function') disposers.push(disposePanel)
|
|
1125
1316
|
} catch (error) {
|
package/lib/panel.mjs
CHANGED
|
@@ -73,7 +73,7 @@ function readBody(req, limitBytes = 200_000) {
|
|
|
73
73
|
})
|
|
74
74
|
}
|
|
75
75
|
|
|
76
|
-
export function registerPanel(ctx, { accounts, credentials, login, addAccount, removeAccount, exportAccount, importAccount, exportState, importState, getProxy, setProxyValue }) {
|
|
76
|
+
export function registerPanel(ctx, { accounts, credentials, login, addAccount, removeAccount, exportAccount, importAccount, exportState, importState, getProxy, setProxyValue, loadModels, switchBoard, toggleSwitch }) {
|
|
77
77
|
const server = ctx.get?.('webServer')
|
|
78
78
|
if (server === undefined || typeof server.register !== 'function') return undefined
|
|
79
79
|
const connection = ctx.get?.('connection')
|
|
@@ -131,11 +131,12 @@ export function registerPanel(ctx, { accounts, credentials, login, addAccount, r
|
|
|
131
131
|
return { generatedAt: new Date(now).toISOString(), proxy: proxy || null, accounts: rows }
|
|
132
132
|
}
|
|
133
133
|
|
|
134
|
-
const
|
|
134
|
+
const latestKey = Symbol.for('dsh.lovart.panel.latest')
|
|
135
|
+
const serve = async (req, res) => {
|
|
135
136
|
try {
|
|
136
137
|
if (!allowed(req)) return writeJson(res, 403, { error: 'forbidden' })
|
|
137
138
|
const url = new URL(req.url ?? '/', 'http://dsh.internal')
|
|
138
|
-
const route = url.pathname.slice(PANEL_API.length).replace(/^\/+/, '')
|
|
139
|
+
const route = url.pathname.slice(PANEL_API.length).replace(/^\/+/, '').replace(/\/+$/, '')
|
|
139
140
|
if (route === 'status' && (req.method === 'GET' || req.method === 'HEAD')) {
|
|
140
141
|
return writeJson(res, 200, await status())
|
|
141
142
|
}
|
|
@@ -191,6 +192,29 @@ export function registerPanel(ctx, { accounts, credentials, login, addAccount, r
|
|
|
191
192
|
return writeJson(res, 404, { error: String(error instanceof Error ? error.message : error).slice(0, 300) })
|
|
192
193
|
}
|
|
193
194
|
}
|
|
195
|
+
if (route === 'switches' && (req.method === 'GET' || req.method === 'HEAD')) {
|
|
196
|
+
if (typeof switchBoard !== 'function') return writeJson(res, 501, { error: 'switches are not available' })
|
|
197
|
+
const models = typeof loadModels === 'function' ? await loadModels() : []
|
|
198
|
+
return writeJson(res, 200, switchBoard(models))
|
|
199
|
+
}
|
|
200
|
+
if (route === 'switches' && req.method === 'POST') {
|
|
201
|
+
if (typeof toggleSwitch !== 'function') return writeJson(res, 501, { error: 'switches are not available' })
|
|
202
|
+
let body
|
|
203
|
+
try {
|
|
204
|
+
body = JSON.parse(await readBody(req))
|
|
205
|
+
} catch (error) {
|
|
206
|
+
return writeJson(res, 400, { error: String(error instanceof Error ? error.message : error).slice(0, 200) })
|
|
207
|
+
}
|
|
208
|
+
const groupId = typeof body?.groupId === 'string' && body.groupId !== '' ? body.groupId : undefined
|
|
209
|
+
const id = typeof body?.id === 'string' && body.id !== '' ? body.id : undefined
|
|
210
|
+
if (groupId === undefined && id === undefined) return writeJson(res, 400, { error: 'id or groupId is required' })
|
|
211
|
+
try {
|
|
212
|
+
const result = await toggleSwitch({ id, kind: body?.kind, groupId })
|
|
213
|
+
return writeJson(res, 200, { ok: true, saved: result.saved, board: result.board })
|
|
214
|
+
} catch (error) {
|
|
215
|
+
return writeJson(res, 500, { error: String(error instanceof Error ? error.message : error).slice(0, 300) })
|
|
216
|
+
}
|
|
217
|
+
}
|
|
194
218
|
if (route === 'export' && req.method === 'POST') {
|
|
195
219
|
if (typeof exportAccount !== 'function') return writeJson(res, 501, { error: 'export is not available' })
|
|
196
220
|
const id = url.searchParams.get('account')
|
|
@@ -254,11 +278,21 @@ export function registerPanel(ctx, { accounts, credentials, login, addAccount, r
|
|
|
254
278
|
return writeJson(res, 500, { error: String(error instanceof Error ? error.message : error).slice(0, 300) })
|
|
255
279
|
}
|
|
256
280
|
}
|
|
257
|
-
return writeJson(res, 404, { error: 'not found' })
|
|
281
|
+
return writeJson(res, 404, { error: 'not found', route, version: 'panel' })
|
|
258
282
|
} catch (error) {
|
|
259
283
|
return writeJson(res, 500, { error: String(error instanceof Error ? error.message : error).slice(0, 300) })
|
|
260
284
|
}
|
|
261
285
|
}
|
|
262
286
|
|
|
287
|
+
// Several generations of this package can be alive at once: a webServer prefix
|
|
288
|
+
// route cannot be replaced, so the first registration keeps answering. Let every
|
|
289
|
+
// older handler forward to the newest one instead of serving stale routes.
|
|
290
|
+
const handler = async (req, res) => {
|
|
291
|
+
const latest = globalThis[latestKey]
|
|
292
|
+
if (latest !== undefined && latest !== handler) return latest(req, res)
|
|
293
|
+
return serve(req, res)
|
|
294
|
+
}
|
|
295
|
+
globalThis[latestKey] = handler
|
|
296
|
+
|
|
263
297
|
return server.register({ kind: 'prefix', path: PANEL_API, handler })
|
|
264
298
|
}
|
package/lib/payload.mjs
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure builders for Lovart MCP payloads.
|
|
3
|
+
*
|
|
4
|
+
* The gateway's `generate_image` / `generate_video` tools only accept a few
|
|
5
|
+
* top-level fields; every model-specific field (resolution, size, quality, ...)
|
|
6
|
+
* belongs inside `params`. Media arguments must point at files Lovart hosts
|
|
7
|
+
* itself, so anything from elsewhere has to go through `upload_asset` first.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export const MODES = [
|
|
11
|
+
{ id: 'text-to-image', kind: 'image', label: '文生图', needs: ['prompt'] },
|
|
12
|
+
{ id: 'image-with-references', kind: 'image', label: '参考图生图(图生图)', needs: ['prompt', 'ref_images'] },
|
|
13
|
+
{ id: 'text-to-video', kind: 'video', label: '文生视频', needs: ['prompt'] },
|
|
14
|
+
{ id: 'first-frame-video', kind: 'video', label: '首帧生视频', needs: ['first_frame'] },
|
|
15
|
+
{ id: 'first-last-frame-video', kind: 'video', label: '首尾帧生视频', needs: ['first_frame', 'last_frame'] },
|
|
16
|
+
{ id: 'video-with-references', kind: 'video', label: '参考图/参考视频生视频', needs: ['ref_images'] },
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
const MEDIA_FIELDS = ['ref_images', 'first_frame', 'last_frame', 'ref_video']
|
|
20
|
+
|
|
21
|
+
function asList(value) {
|
|
22
|
+
if (value === undefined || value === null) return []
|
|
23
|
+
if (Array.isArray(value)) return value.map((item) => String(item).trim()).filter(Boolean)
|
|
24
|
+
const text = String(value).trim()
|
|
25
|
+
if (text === '') return []
|
|
26
|
+
if (text.startsWith('[')) {
|
|
27
|
+
let parsed
|
|
28
|
+
try {
|
|
29
|
+
parsed = JSON.parse(text)
|
|
30
|
+
} catch {
|
|
31
|
+
throw new Error('media lists must be a URL, a comma-separated list, or a JSON array of URLs')
|
|
32
|
+
}
|
|
33
|
+
if (!Array.isArray(parsed)) throw new Error('media lists must be a JSON array of URLs')
|
|
34
|
+
return parsed.map((item) => String(item).trim()).filter(Boolean)
|
|
35
|
+
}
|
|
36
|
+
return text.split(',').map((item) => item.trim()).filter(Boolean)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function assertUrl(value, field) {
|
|
40
|
+
let url
|
|
41
|
+
try {
|
|
42
|
+
url = new URL(value)
|
|
43
|
+
} catch {
|
|
44
|
+
throw new Error(`${field} must be an HTTP(S) URL, got ${JSON.stringify(value)}`)
|
|
45
|
+
}
|
|
46
|
+
if (url.protocol !== 'https:' && url.protocol !== 'http:') {
|
|
47
|
+
throw new Error(`${field} must be an HTTP(S) URL, got ${url.protocol}`)
|
|
48
|
+
}
|
|
49
|
+
return url
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function detectMode({ kind = 'image', refImages = [], firstFrame, lastFrame, refVideo } = {}) {
|
|
53
|
+
if (kind === 'video') {
|
|
54
|
+
if (firstFrame !== undefined && lastFrame !== undefined) return 'first-last-frame-video'
|
|
55
|
+
if (firstFrame !== undefined) return 'first-frame-video'
|
|
56
|
+
if (refVideo !== undefined) return 'video-with-references'
|
|
57
|
+
if (refImages.length > 0) return 'video-with-references'
|
|
58
|
+
return 'text-to-video'
|
|
59
|
+
}
|
|
60
|
+
return refImages.length > 0 ? 'image-with-references' : 'text-to-image'
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function buildGeneratePayload(input) {
|
|
64
|
+
const kind = input.kind === 'video' ? 'video' : 'image'
|
|
65
|
+
const prompt = typeof input.prompt === 'string' ? input.prompt : ''
|
|
66
|
+
if (prompt.trim() === '') throw new Error('prompt is required')
|
|
67
|
+
if (typeof input.model !== 'string' || input.model === '') throw new Error('model is required')
|
|
68
|
+
const refImages = asList(input.refImages)
|
|
69
|
+
const warnings = []
|
|
70
|
+
const media = { refImages }
|
|
71
|
+
for (const [field, key] of [['firstFrame', 'firstFrame'], ['lastFrame', 'lastFrame'], ['refVideo', 'refVideo']]) {
|
|
72
|
+
const value = input[field]
|
|
73
|
+
if (value !== undefined && value !== null && String(value).trim() !== '') media[key] = String(value).trim()
|
|
74
|
+
}
|
|
75
|
+
for (const list of [refImages, [media.firstFrame, media.lastFrame, media.refVideo].filter(Boolean)].flat()) assertUrl(list, 'media')
|
|
76
|
+
if (media.lastFrame !== undefined && media.firstFrame === undefined) {
|
|
77
|
+
warnings.push('last_frame without first_frame: only some models interpolate from the end frame alone.')
|
|
78
|
+
}
|
|
79
|
+
for (const url of refImages) {
|
|
80
|
+
if (!/(^|\.)lovart\.ai$/.test(new URL(url).hostname)) {
|
|
81
|
+
warnings.push(`${url} is not hosted by Lovart; upload it with lovart_tool(tool:"upload_asset") first, otherwise the gateway rejects the format.`)
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const params = {}
|
|
86
|
+
if (typeof input.resolution === 'string' && input.resolution !== '') {
|
|
87
|
+
params.resolution = kind === 'video' ? input.resolution.toLowerCase() : input.resolution
|
|
88
|
+
}
|
|
89
|
+
if (kind === 'image' && typeof input.size === 'string' && input.size !== '') params.size = input.size
|
|
90
|
+
if (input.options !== undefined && input.options !== null) {
|
|
91
|
+
if (typeof input.options !== 'object' || Array.isArray(input.options)) throw new Error('options must be a JSON object')
|
|
92
|
+
Object.assign(params, input.options)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const payload = { prompt, model: input.model }
|
|
96
|
+
if (typeof input.aspectRatio === 'string' && input.aspectRatio !== '') payload.aspect_ratio = input.aspectRatio
|
|
97
|
+
if (typeof input.projectId === 'string' && input.projectId !== '') payload.project_id = input.projectId
|
|
98
|
+
if (kind === 'image') {
|
|
99
|
+
const count = Number(input.count ?? 1)
|
|
100
|
+
if (Number.isFinite(count) && count > 1) payload.n = Math.trunc(count)
|
|
101
|
+
if (refImages.length > 0) payload.ref_images = refImages
|
|
102
|
+
} else {
|
|
103
|
+
const duration = Number(input.duration)
|
|
104
|
+
if (Number.isFinite(duration) && duration > 0) payload.duration = Math.trunc(duration)
|
|
105
|
+
if (media.firstFrame !== undefined) payload.first_frame = media.firstFrame
|
|
106
|
+
if (media.lastFrame !== undefined) payload.last_frame = media.lastFrame
|
|
107
|
+
if (refImages.length > 0) payload.ref_images = refImages
|
|
108
|
+
if (media.refVideo !== undefined) payload.ref_video = media.refVideo
|
|
109
|
+
}
|
|
110
|
+
if (Object.keys(params).length > 0) payload.params = params
|
|
111
|
+
|
|
112
|
+
return {
|
|
113
|
+
payload,
|
|
114
|
+
mode: detectMode({ kind, refImages, firstFrame: media.firstFrame, lastFrame: media.lastFrame, refVideo: media.refVideo }),
|
|
115
|
+
warnings,
|
|
116
|
+
}
|
|
117
|
+
}
|
package/lib/proxy.mjs
CHANGED
|
@@ -6,6 +6,15 @@
|
|
|
6
6
|
const MCP_URL = process.env.LOVART_MCP_URL ?? 'https://lgw.lovart.ai/v1/openapi/mcp/widgets'
|
|
7
7
|
const TOKEN = process.env.LOVART_TOKEN ?? ''
|
|
8
8
|
const { httpRequest } = await import('./net.mjs')
|
|
9
|
+
const { filterToolList, isToolDisabled } = await import('./catalog.mjs')
|
|
10
|
+
|
|
11
|
+
// Tools switched off from the panel. The proxy hides them from tools/list and
|
|
12
|
+
// refuses tools/call, so the raw mcp__lovart-*__* tools really disappear.
|
|
13
|
+
const DISABLED = (process.env.LOVART_DISABLED_TOOLS ?? '')
|
|
14
|
+
.split(',')
|
|
15
|
+
.map((item) => item.trim())
|
|
16
|
+
.filter((item) => item !== '')
|
|
17
|
+
const switched = { tools: DISABLED, models: [], groups: [] }
|
|
9
18
|
|
|
10
19
|
if (TOKEN === '') {
|
|
11
20
|
process.stderr.write('lovart proxy: LOVART_TOKEN is missing\n')
|
|
@@ -26,14 +35,23 @@ function remember(message) {
|
|
|
26
35
|
}
|
|
27
36
|
}
|
|
28
37
|
|
|
38
|
+
function sanitize(message) {
|
|
39
|
+
if (message === null || typeof message !== 'object') return message
|
|
40
|
+
const tools = message.result?.tools
|
|
41
|
+
if (!Array.isArray(tools)) return message
|
|
42
|
+
const kept = filterToolList(tools, switched)
|
|
43
|
+
if (kept.length === tools.length) return message
|
|
44
|
+
return { ...message, result: { ...message.result, tools: kept } }
|
|
45
|
+
}
|
|
46
|
+
|
|
29
47
|
function emit(parsed) {
|
|
30
48
|
if (Array.isArray(parsed)) {
|
|
31
|
-
for (const item of parsed) if (item !== null && typeof item === 'object') { remember(item); write(item) }
|
|
49
|
+
for (const item of parsed) if (item !== null && typeof item === 'object') { remember(item); write(sanitize(item)) }
|
|
32
50
|
return
|
|
33
51
|
}
|
|
34
52
|
if (parsed === null || typeof parsed !== 'object') return
|
|
35
53
|
remember(parsed)
|
|
36
|
-
if (parsed.id !== undefined || parsed.method !== undefined || parsed.error !== undefined) write(parsed)
|
|
54
|
+
if (parsed.id !== undefined || parsed.method !== undefined || parsed.error !== undefined) write(sanitize(parsed))
|
|
37
55
|
}
|
|
38
56
|
|
|
39
57
|
async function forward(message) {
|
|
@@ -109,6 +127,14 @@ process.stdin.on('data', (chunk) => {
|
|
|
109
127
|
continue
|
|
110
128
|
}
|
|
111
129
|
sequence += 1
|
|
130
|
+
if (message?.method === 'tools/call' && isToolDisabled(message?.params?.name, switched)) {
|
|
131
|
+
write({
|
|
132
|
+
jsonrpc: '2.0',
|
|
133
|
+
id: message.id ?? null,
|
|
134
|
+
error: { code: -32601, message: `lovart proxy: tool "${message.params?.name}" is disabled in the plugin panel` },
|
|
135
|
+
})
|
|
136
|
+
continue
|
|
137
|
+
}
|
|
112
138
|
void forward(message).catch((error) => {
|
|
113
139
|
if (message?.id === undefined || message?.id === null) return
|
|
114
140
|
write({
|