@wbohui123/blueprint-studio 0.0.0-stage → 2.0.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/LICENSE +661 -0
- package/README.md +72 -2
- package/package.json +33 -4
- package/src/DeepSeek/344/275/231/351/242/235.js +33 -0
- package/src/index.js +5307 -0
- package/src//344/272/247/347/211/251.js +386 -0
- package/src//344/273/273/345/212/241/345/273/212/351/242/204/350/247/210.js +119 -0
- package/src//344/274/232/350/257/235/345/277/253/347/205/247/350/257/273/345/217/226.js +14 -0
- package/src//345/200/237/346/235/245/347/232/204//344/272/247/347/211/251.js +87 -0
- package/src//345/200/237/346/235/245/347/232/204//345/252/222/344/275/223/346/234/215/345/212/241.js +485 -0
- package/src//345/200/237/346/235/245/347/232/204//345/274/200/347/273/210/347/253/257.js +44 -0
- package/src//345/200/237/346/235/245/347/232/204//346/235/202/351/241/271.js +67 -0
- package/src//345/200/237/346/235/245/347/232/204//346/256/213/347/225/231/350/277/233/347/250/213.js +181 -0
- package/src//345/200/237/346/235/245/347/232/204//346/266/210/346/201/257/345/215/217/350/256/256.js +48 -0
- package/src//345/200/237/346/235/245/347/232/204//347/225/231/344/270/213/347/232/204/350/277/233/347/250/213.js +35 -0
- package/src//345/200/237/346/235/245/347/232/204//347/273/210/347/253/257.js +20 -0
- package/src//345/200/237/346/235/245/347/232/204//350/243/205/346/217/220/344/276/233/346/226/271.js +26 -0
- package/src//345/200/237/346/235/245/347/232/204//350/267/257/345/276/204.js +21 -0
- package/src//345/200/237/346/235/245/347/232/204//351/227/256/347/255/224.js +48 -0
- package/src//345/200/237/346/235/245/347/232/204//351/241/271/347/233/256/345/210/240/351/231/244/347/212/266/346/200/201.js +5 -0
- package/src//345/200/237/346/235/245/347/232/204//351/241/271/347/233/256/345/220/215/347/247/260.js +116 -0
- package/src//345/200/237/346/235/245/347/232/204//351/241/271/347/233/256/345/255/230/345/202/250.js +92 -0
- package/src//345/200/237/346/235/245/347/232/204//351/241/271/347/233/256/351/231/204/344/273/266.js +55 -0
- package/src//345/201/234/346/255/242/345/220/216/345/217/260.js +18 -0
- package/src//345/212/251/347/220/206.js +157 -0
- package/src//345/220/215/345/206/214/350/247/206/345/233/276.js +251 -0
- package/src//345/220/215/345/206/214/350/257/273/347/274/223/345/255/230.js +70 -0
- package/src//345/233/236/350/257/235/346/217/220/351/206/222.js +38 -0
- package/src//345/233/276/347/272/270/345/256/236/346/227/266.js +91 -0
- package/src//345/244/226/351/203/250run/344/272/247/347/211/251.js +75 -0
- package/src//345/244/226/351/203/250run/350/247/206/345/233/276.js +86 -0
- package/src//345/244/226/351/203/250/345/215/217/345/212/251.js +101 -0
- package/src//345/252/222/344/275/223/350/256/276/347/275/256.js +12 -0
- package/src//345/255/220/344/273/243/347/220/206.js +337 -0
- package/src//345/256/236/346/227/266/350/276/223/345/207/272.js +90 -0
- package/src//345/267/245/344/275/234/346/227/266/351/227/264.js +170 -0
- package/src//345/271/263/345/217/260/345/205/245/345/217/243.js +703 -0
- package/src//346/211/247/350/241/214/350/203/275/345/212/233.js +2 -0
- package/src//346/214/201/347/273/255/347/233/256/346/240/207.js +3 -0
- package/src//346/217/220/347/244/272/347/273/237/350/256/241.js +24 -0
- package/src//346/226/207/344/273/266/345/244/271.js +26 -0
- package/src//346/226/260/345/220/215/345/206/214.js +145 -0
- package/src//346/226/260/351/241/271/347/233/256.js +203 -0
- package/src//346/227/247/345/212/237/350/203/275/346/241/251.js +34 -0
- package/src//346/235/220/346/226/231.js +97 -0
- package/src//346/240/221/346/221/230/350/246/201/347/233/230.js +37 -0
- package/src//346/240/221/350/264/246/346/234/254.js +11 -0
- package/src//347/225/214/351/235/242/350/257/255/350/250/200.js +25 -0
- package/src//347/273/210/347/253/257.js +128 -0
- package/src//350/212/202/347/202/271/344/277/241/346/201/257.js +56 -0
- package/src//350/256/260/345/277/206/345/205/245/345/217/243.js +51 -0
- package/src//350/275/257/344/273/266.js +227 -0
- package/src//350/277/220/350/241/214/347/212/266/346/200/201.js +38 -0
- package/src//350/277/236/346/216/245.js +385 -0
- package/src//351/227/256/347/255/224/351/223/276.js +160 -0
- package/src//351/241/271/347/233/256/345/210/206/347/273/204.js +67 -0
- package/src//351/241/271/347/233/256/345/220/215/347/247/260/345/205/245/345/217/243.js +23 -0
- package/src//351/241/271/347/233/256/345/255/230/345/202/250/345/205/245/345/217/243.js +30 -0
- package/src//351/241/271/347/233/256/346/223/215/344/275/234.js +34 -0
- package/src//351/241/271/347/233/256/350/207/252/345/212/250/345/201/234/346/255/242.js +107 -0
- package/src//351/241/271/347/233/256/350/256/241/351/207/217.js +114 -0
- package/src//351/242/204/350/247/210.js +157 -0
- package/viewer//347/225/214/351/235/242/350/257/255/350/250/200.js +97 -0
- package/viewer//350/213/261/346/226/207.json +1535 -0
- package//345/215/225/344/273/267.json +126 -0
package/src//345/200/237/346/235/245/347/232/204//345/252/222/344/275/223/346/234/215/345/212/241.js
ADDED
|
@@ -0,0 +1,485 @@
|
|
|
1
|
+
// 从旧系统 node/src/媒体服务.js 拷来:11-09 只拷了第 1–152 行(目录、凭据),11-25 用户「把之前版本的硅基流动的图像 api 加进去」,把调用那半(第 153 行起:callMedia、会话附件、存档)也拷回来,节点的 media_catalog/media_call(host/src/媒体工具.js)用它。
|
|
2
|
+
/** 媒体 API 的目录、凭据与调用;配置走原生 settings/credentials,结果落当前项目。 */
|
|
3
|
+
import { randomUUID } from 'node:crypto'
|
|
4
|
+
import { readFile, writeFile, rename, mkdir, stat, realpath, readdir } from 'node:fs/promises'
|
|
5
|
+
import { join, relative, extname, basename, isAbsolute } from 'node:path'
|
|
6
|
+
import { realpathSync, existsSync } from 'node:fs'
|
|
7
|
+
import { resolve, dirname, sep } from 'node:path'
|
|
8
|
+
|
|
9
|
+
/** 旧版 项目隔离.js 的 文件许可 的小替身:路径落在项目里(技能夹只读)才放行,回真实路径;不在就报错。新结构的整体边界由 隔离.js 管,这里只管媒体读写的文件。 */
|
|
10
|
+
function 真路径(path) {
|
|
11
|
+
let 已有 = path, 尾 = []
|
|
12
|
+
while (!existsSync(已有) && dirname(已有) !== 已有) { 尾.unshift(已有.slice(dirname(已有).length + 1)); 已有 = dirname(已有) }
|
|
13
|
+
try { return resolve(realpathSync(已有), ...尾) } catch { return path }
|
|
14
|
+
}
|
|
15
|
+
const 在内 = (根, path) => { const r = 真路径(根); return path === r || path.startsWith(r.endsWith(sep) ? r : r + sep) }
|
|
16
|
+
function 文件许可(范围, 路径, 写 = false, 基准 = 范围.根) {
|
|
17
|
+
const 实际 = 真路径(resolve(基准, String(路径)))
|
|
18
|
+
if (在内(范围.根, 实际) || (!写 && 范围.技能 && 在内(范围.技能, 实际))) return 实际
|
|
19
|
+
throw new Error('PROJECT_ISOLATION: 只能访问当前项目的文件;不能访问其他项目、父目录或宿主账本。')
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export const MEDIA_NS = 'blueprint-media'
|
|
23
|
+
export const MEDIA_OPERATIONS = {
|
|
24
|
+
'image.generate': '生成图片', 'video.generate': '生成视频', 'audio.generate': '生成音频',
|
|
25
|
+
'image.analyze': '理解图片', 'video.analyze': '理解视频', 'audio.analyze': '理解音频', 'audio.transcribe': '音频转文字',
|
|
26
|
+
}
|
|
27
|
+
export const MEDIA_PROTOCOLS = [
|
|
28
|
+
{ id: 'openai-media', name: 'OpenAI 兼容媒体接口', operations: ['image.generate','video.generate','audio.generate','image.analyze','audio.analyze','audio.transcribe'], hint: '支持标准图片、视频、语音与视觉接口;服务商须提供相应用途的端点。' },
|
|
29
|
+
{ id: 'gemini-media', name: 'Gemini 原生多模态接口', operations: ['image.generate','image.analyze','video.analyze','audio.analyze','audio.transcribe'], hint: '支持原生图片生成,以及图片、视频、音频理解。模型能力按服务商实际支持勾选。' },
|
|
30
|
+
{ id: 'fal-queue', name: 'fal 媒体接口', operations: Object.keys(MEDIA_OPERATIONS), hint: '模型 ID 填 fal 的完整模型路径,例如 fal-ai/flux/schnell。' },
|
|
31
|
+
{ id: 'openai-chat-media', name: '对话接口多模态', operations: ['image.analyze','video.analyze','audio.analyze','audio.transcribe','audio.generate'], hint: '看图、听声音、看视频、转文字、配音都走 /chat/completions(小米 MiMo 就是这种):图片、wav/mp3 音频、视频直接放进消息;配音把要念的文字放进 assistant 消息,用 audio 参数(voice、format)取回音频。' },
|
|
32
|
+
{ id: 'siliconflow-image', name: '硅基流动图片接口', operations: ['image.generate'], hint: '文生图和支持参考图的图片模型均走图片生成接口;尺寸使用 image_size。Z-Image-Turbo 仅支持文生图,编辑模型的参考能力按模型说明使用。' },
|
|
33
|
+
]
|
|
34
|
+
export const MEDIA_PRESETS = [
|
|
35
|
+
{ id: 'media-siliconflow', name: '文生图 · 硅基流动', kind:'media', baseURL:'https://api.siliconflow.cn/v1', api:'siliconflow-image', models:[{id:'Tongyi-MAI/Z-Image-Turbo',name:'Z-Image-Turbo',operations:['image.generate'],description:'由文字生成背景、插图、纹理;不接收参考图片。尺寸使用 image_size。',defaults:{image_size:'1280x1280'}}] },
|
|
36
|
+
{ id: 'media-mimo', name: '看图/听声音/看视频/转写/语音生成 · 小米 MiMo', kind:'media', baseURL:'https://api.xiaomimimo.com/v1', api:'openai-chat-media', models:[
|
|
37
|
+
{id:'mimo-v2.6-flash',name:'MiMo-V2.6-Flash',operations:['image.analyze','video.analyze','audio.analyze'],description:'看图、听声音、看视频,回答画面里有什么、听起来怎样:乐器、情绪、人声、在唱还是在说。速度、响度、削波这类数字它说不准,用 ffmpeg 量;整段视频里第几秒发生了什么也不可靠,要定时刻先抽帧、标好时间再给它看。音频只收 wav、mp3。',defaults:{max_tokens:4000}},
|
|
38
|
+
{id:'mimo-v2.5-asr',name:'MiMo-V2.5-ASR',operations:['audio.transcribe'],description:'把人声逐字转成文字;咬字不清的短词可能听错。音频只收 wav、mp3。',defaults:{}},
|
|
39
|
+
{id:'mimo-v2.5-tts',name:'MiMo-V2.5-TTS · 语音生成,不支持音乐',operations:['audio.generate'],description:'只做语音生成:把文字念成语音,适合台词、旁白;不支持音乐生成,不会唱歌,也做不了音效。voice 默认 mimo_default(女声),format 可选 wav 或 mp3。',defaults:{voice:'mimo_default',format:'wav'}},
|
|
40
|
+
] },
|
|
41
|
+
{ id: 'media-openai', name: '图片/视频/音频 · OpenAI 兼容', kind:'media', baseURL:'https://api.openai.com/v1', api:'openai-media' },
|
|
42
|
+
{ id: 'media-gemini', name: '图片/视频/音频理解 · Gemini', kind:'media', baseURL:'https://generativelanguage.googleapis.com/v1beta', api:'gemini-media' },
|
|
43
|
+
{ id: 'media-fal', name: '媒体生成 · fal', kind:'media', baseURL:'https://queue.fal.run', api:'fal-queue' },
|
|
44
|
+
{ id: 'media-custom', name: '自定义多模态 API', kind:'media', baseURL:'', api:'openai-media' },
|
|
45
|
+
]
|
|
46
|
+
const MIME = {'.png':'image/png','.jpg':'image/jpeg','.jpeg':'image/jpeg','.webp':'image/webp','.gif':'image/gif','.mp4':'video/mp4','.mov':'video/quicktime','.webm':'video/webm','.mp3':'audio/mpeg','.wav':'audio/wav','.m4a':'audio/mp4','.aac':'audio/aac','.ogg':'audio/ogg','.flac':'audio/flac','.opus':'audio/ogg'}
|
|
47
|
+
const EXT = {'image/png':'png','image/jpeg':'jpg','image/webp':'webp','image/gif':'gif','video/mp4':'mp4','video/webm':'webm','audio/mpeg':'mp3','audio/mp3':'mp3','audio/wav':'wav','audio/x-wav':'wav','audio/mp4':'m4a','audio/aac':'aac','audio/ogg':'ogg','audio/flac':'flac'}
|
|
48
|
+
const idOf = value => {
|
|
49
|
+
if (typeof value !== 'string' || !/^[a-z][a-z0-9-]{0,63}$/.test(value) || ['constructor','prototype','__proto__'].includes(value)) throw new Error('连接标识须为小写字母、数字和连字符')
|
|
50
|
+
return value
|
|
51
|
+
}
|
|
52
|
+
const descriptor = ctx => ctx.get('settings')?.describe().find(d => d.ns === MEDIA_NS)
|
|
53
|
+
const profiles = ctx => descriptor(ctx)?.value?.connections || {}
|
|
54
|
+
export function mediaEndpoint(value) {
|
|
55
|
+
let url; try { url = new URL(String(value || '').trim()) } catch { throw new Error('请填写完整的媒体 API 地址') }
|
|
56
|
+
if (!['https:','http:'].includes(url.protocol) || url.username || url.password || url.hash || url.search) throw new Error('媒体 API 地址须为 HTTP(S) 基础地址,不含密码或查询参数')
|
|
57
|
+
return url.href.replace(/\/+$/,'')
|
|
58
|
+
}
|
|
59
|
+
function object(value, label) {
|
|
60
|
+
if (typeof value === 'string') { try { value = JSON.parse(value || '{}') } catch { throw new Error(`${label}须为有效 JSON`) } }
|
|
61
|
+
if (!value || Array.isArray(value) || typeof value !== 'object' || JSON.stringify(value).length > 16000) throw new Error(`${label}须为 JSON 对象,且不超过 16KB`)
|
|
62
|
+
return value
|
|
63
|
+
}
|
|
64
|
+
export function normalizeMedia(body) {
|
|
65
|
+
const api = MEDIA_PROTOCOLS.find(x => x.id === body.api)
|
|
66
|
+
if (!api) throw new Error('请选择支持的媒体接口')
|
|
67
|
+
if (!Array.isArray(body.models) || !body.models.length || body.models.length > 200) throw new Error('请添加 1 到 200 个媒体模型')
|
|
68
|
+
const seen = new Set()
|
|
69
|
+
return { name: String(body.name || body.id).trim().slice(0,100), baseURL:mediaEndpoint(body.baseURL), api:api.id, models:body.models.map(m => {
|
|
70
|
+
const id = String(m.id || '').trim()
|
|
71
|
+
if (!id || id.length > 200 || /[\x00-\x1f]/.test(id) || seen.has(id)) throw new Error('媒体模型 ID 不能为空、重复或包含控制字符')
|
|
72
|
+
if (api.id === 'fal-queue' && (!/^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9._-]+)*$/.test(id) || id.split('/').some(p=>p === '.' || p === '..'))) throw new Error('fal 模型 ID 须为完整模型路径')
|
|
73
|
+
seen.add(id)
|
|
74
|
+
const operations = [...new Set(m.operations || [])]
|
|
75
|
+
if (!operations.length || operations.some(x => !api.operations.includes(x))) throw new Error(`请为 ${id} 勾选该接口支持的模型用途`)
|
|
76
|
+
return { id, name:String(m.name || id).trim().slice(0,200), operations, description:String(m.description || '').slice(0,1000), defaults:object(m.defaults || {},'默认参数') }
|
|
77
|
+
}) }
|
|
78
|
+
}
|
|
79
|
+
/** 对话接口里一个媒体文件的样子:图片 image_url,音频 input_audio(只收 wav、mp3),视频 video_url。 */
|
|
80
|
+
function 对话媒体片段(f, operation) {
|
|
81
|
+
const 数据 = f.data.toString('base64')
|
|
82
|
+
if (operation === 'image.analyze' && f.mimeType.startsWith('image/')) return {type:'image_url',image_url:{url:`data:${f.mimeType};base64,${数据}`}}
|
|
83
|
+
if (['audio.analyze','audio.transcribe'].includes(operation) && ['audio/wav','audio/mpeg'].includes(f.mimeType)) return {type:'input_audio',input_audio:{data:数据,format:f.mimeType === 'audio/wav' ? 'wav' : 'mp3'}}
|
|
84
|
+
if (operation === 'video.analyze' && f.mimeType.startsWith('video/')) return {type:'video_url',video_url:{url:`data:${f.mimeType};base64,${数据}`}}
|
|
85
|
+
throw new Error(operation.startsWith('audio') ? '这个接口的音频只收 wav、mp3,先用 ffmpeg 转一下' : '这个文件类型和所选用途对不上')
|
|
86
|
+
}
|
|
87
|
+
function hide(error, secret = '') { return String(error?.message || error).split(secret || '\u0000').join('[已隐藏]').replace(/\bsk-[\w-]{6,}/g,'[已隐藏]').slice(0,600) }
|
|
88
|
+
|
|
89
|
+
export function createMediaManager(ctx) {
|
|
90
|
+
let tail = Promise.resolve()
|
|
91
|
+
const exclusive = fn => { const run = tail.then(fn); tail = run.catch(()=>{}); return run }
|
|
92
|
+
async function list() {
|
|
93
|
+
const d = descriptor(ctx)
|
|
94
|
+
if (!d) return []
|
|
95
|
+
return Promise.all(Object.entries(profiles(ctx)).map(async ([id,p]) => {
|
|
96
|
+
const key = await ctx.get('credentials').describe(p.apiKeyEnv)
|
|
97
|
+
return { id, ...p, apiKeyEnv:undefined, kind:'media', namespace:MEDIA_NS, revision:d.revision, native:false, editable:ctx.get('settings').writable, deletable:ctx.get('settings').writable, projects:[], key:{configured:!!key.configured, writable:!!key.writable, source:key.source || ''}, active:!!key.configured, models:p.models.map(m=>({...m,defaults:JSON.stringify(m.defaults || {},null,2)})) }
|
|
98
|
+
}))
|
|
99
|
+
}
|
|
100
|
+
async function cleanup(ref) {
|
|
101
|
+
if (ref?.startsWith('BLUEPRINT_MEDIA_') && !Object.values(profiles(ctx)).some(p=>p.apiKeyEnv === ref)) await ctx.get('credentials').unset(ref)
|
|
102
|
+
}
|
|
103
|
+
async function save(body) { return exclusive(async () => {
|
|
104
|
+
const settings = ctx.get('settings'), credentials = ctx.get('credentials'), d = descriptor(ctx)
|
|
105
|
+
if (!d || !settings.writable) throw new Error('媒体配置未加载或只读,请重新启动 Blueprint')
|
|
106
|
+
const id = idOf(body.id), old = profiles(ctx)[id]
|
|
107
|
+
if (!!old !== !!body.existing) throw new Error(old ? '连接标识已被使用' : '媒体连接不存在')
|
|
108
|
+
const next = normalizeMedia(body)
|
|
109
|
+
let key = String(body.apiKey || '').trim()
|
|
110
|
+
if (!key && !old?.apiKeyEnv && ['localhost','127.0.0.1','[::1]'].includes(new URL(next.baseURL).hostname)) key='local-no-auth'
|
|
111
|
+
if (key.length > 8192 || /[\r\n]/.test(key)) throw new Error('API Key 格式不正确')
|
|
112
|
+
const ref = key ? `BLUEPRINT_MEDIA_${id.replaceAll('-','_').toUpperCase()}_${randomUUID().slice(0,8).toUpperCase()}` : old?.apiKeyEnv || `BLUEPRINT_MEDIA_${id.replaceAll('-','_').toUpperCase()}`
|
|
113
|
+
if (key) await credentials.set(ref,key)
|
|
114
|
+
try { await settings.mutate(MEDIA_NS,[{op:'set',path:['connections',id],value:{...next,apiKeyEnv:ref}}],body.revision ?? d.revision) }
|
|
115
|
+
catch (error) { if (key) await credentials.unset(ref); throw new Error(hide(error,key)) }
|
|
116
|
+
let warning = ''; if (old?.apiKeyEnv !== ref) try { await cleanup(old?.apiKeyEnv) } catch { warning='已保存,旧 Key 未能清理' }
|
|
117
|
+
return {id,warning}
|
|
118
|
+
}) }
|
|
119
|
+
async function remove(body) { return exclusive(async () => {
|
|
120
|
+
const d = descriptor(ctx), id = idOf(body.id), p = profiles(ctx)[id]
|
|
121
|
+
if (!p || !ctx.get('settings').writable) throw new Error('媒体连接不存在或只读')
|
|
122
|
+
await ctx.get('settings').mutate(MEDIA_NS,[{op:'unset',path:['connections',id]}],body.revision ?? d.revision)
|
|
123
|
+
let warning = ''; try { await cleanup(p.apiKeyEnv) } catch { warning='连接已删除,托管 Key 未能清理' }
|
|
124
|
+
return {id,warning}
|
|
125
|
+
}) }
|
|
126
|
+
async function catalog() {
|
|
127
|
+
return (await list()).filter(p => p.active).flatMap(p => p.models.map(m => ({ connection:p.id, provider:p.name, model:m.id, name:m.name, operations:m.operations, description:m.description, defaults:JSON.parse(m.defaults), protocol:p.api })))
|
|
128
|
+
}
|
|
129
|
+
async function check(body) {
|
|
130
|
+
const profile = normalizeMedia(body), old = profiles(ctx)[body.id]
|
|
131
|
+
const key = String(body.apiKey || '').trim() || (old?.apiKeyEnv ? (await ctx.get('credentials').resolve(old.apiKeyEnv))?.value : '')
|
|
132
|
+
if (!key && !['localhost','127.0.0.1','[::1]'].includes(new URL(profile.baseURL).hostname)) throw new Error('请填写媒体 API Key')
|
|
133
|
+
return {model:body.model || profile.models[0].id,latency:0,message:'配置格式与 Key 来源有效;尚未向服务商发送生成请求'}
|
|
134
|
+
}
|
|
135
|
+
async function discover(body, fetcher = globalThis.fetch) {
|
|
136
|
+
if (body.api === 'fal-queue') throw new Error('fal 的模型请手动添加完整模型路径,例如 fal-ai/flux/schnell')
|
|
137
|
+
const base = mediaEndpoint(body.baseURL), old = profiles(ctx)[body.id]
|
|
138
|
+
const key = String(body.apiKey || '').trim() || (old?.apiKeyEnv ? (await ctx.get('credentials').resolve(old.apiKeyEnv))?.value : '')
|
|
139
|
+
if (!key && !['localhost','127.0.0.1','[::1]'].includes(new URL(base).hostname)) throw new Error('请先填写 API Key')
|
|
140
|
+
const headers = key ? body.api === 'gemini-media' ? {'x-goog-api-key':key} : {Authorization:`Bearer ${key}`} : {}
|
|
141
|
+
try {
|
|
142
|
+
const data = await jsonResponse(await fetcher(`${base}/models${body.api === 'siliconflow-image' ? '?type=image' : ''}`,{headers,signal:AbortSignal.timeout(30000),redirect:'error'}))
|
|
143
|
+
const rows = data.models || data.data
|
|
144
|
+
if (!Array.isArray(rows) || !rows.length) throw new Error('服务没有返回模型列表,请手动添加')
|
|
145
|
+
return {models:rows.slice(0,200).map(m=>({id:String(m.id || m.name).replace(/^models\//,''),name:m.displayName || m.name || m.id})),message:'已获取模型列表;添加时请勾选每个模型实际支持的媒体用途'}
|
|
146
|
+
} catch(error) {throw new Error(hide(error,key))}
|
|
147
|
+
}
|
|
148
|
+
return {list,save,remove,catalog,check,discover}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async function bytes(response, limit, signal) {
|
|
152
|
+
const chunks = []; let size = 0
|
|
153
|
+
try {
|
|
154
|
+
for await (const chunk of response.body || []) {
|
|
155
|
+
signal?.throwIfAborted(); size += chunk.byteLength
|
|
156
|
+
if (size > limit) throw new Error(`API 返回内容超过 ${Math.round(limit/1024/1024)}MB`)
|
|
157
|
+
chunks.push(chunk)
|
|
158
|
+
}
|
|
159
|
+
} catch (error) { await response.body?.cancel().catch(()=>{}); throw error }
|
|
160
|
+
return Buffer.concat(chunks)
|
|
161
|
+
}
|
|
162
|
+
async function jsonResponse(response, signal) {
|
|
163
|
+
const raw = await bytes(response,64*1024*1024,signal)
|
|
164
|
+
let data; try { data = JSON.parse(raw.toString('utf8')) } catch { throw new Error(`媒体 API 未返回 JSON(HTTP ${response.status})`) }
|
|
165
|
+
if (!response.ok || data.error) throw new Error(`媒体 API 请求失败(HTTP ${response.status}):${data.error?.message || data.error || data.message || '请检查地址、模型与参数'}`)
|
|
166
|
+
return data
|
|
167
|
+
}
|
|
168
|
+
async function inputFiles(root, paths = [], cwd = root) {
|
|
169
|
+
if (!Array.isArray(paths) || paths.length > 8) throw new Error('每次最多输入 8 个本项目媒体文件')
|
|
170
|
+
const scope = {根:root,技能:root}, result = []; let total = 0
|
|
171
|
+
for (const path of paths) {
|
|
172
|
+
const file = 文件许可(scope,path,false,cwd), info = await stat(file), mimeType = MIME[extname(file).toLowerCase()]
|
|
173
|
+
total += info.size
|
|
174
|
+
if (!info.isFile() || !mimeType) throw new Error('请输入本项目中的图片、视频或音频文件')
|
|
175
|
+
if (total > 20*1024*1024) throw new Error('媒体直接上传合计上限为 20MB,请先压缩或截取与问题有关的部分')
|
|
176
|
+
result.push({name:basename(file),mimeType,data:await readFile(file)})
|
|
177
|
+
}
|
|
178
|
+
return result
|
|
179
|
+
}
|
|
180
|
+
/** 原生全日志保留压缩与 offload 前已收到的附件;不遍历父链或接纳日志外的 ID。 */
|
|
181
|
+
export async function sessionMediaAttachments(session, ctx, signal) {
|
|
182
|
+
const refs=new Map()
|
|
183
|
+
if (!session?.id) return refs
|
|
184
|
+
const query = ctx?.get('sessionQuery')
|
|
185
|
+
if (!query?.observeSession) throw new Error('当前部署没有原生会话观察服务,无法核对媒体附件归属')
|
|
186
|
+
function visit(blocks) {
|
|
187
|
+
for(const block of blocks || []) {
|
|
188
|
+
const ref=block.attachment, mimeType=ref?.mediaType || block.mediaType || MIME[extname(ref?.name || '').toLowerCase()]
|
|
189
|
+
if (['image','file'].includes(block.type) && ref?.attachmentId && /^(image|audio|video)\//.test(mimeType || '')) refs.set(ref.attachmentId,{ref,type:block.type,mimeType})
|
|
190
|
+
if (Array.isArray(block.content)) visit(block.content)
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
const observation = await query.observeSession(session.id, { projectionMode: 'none', ...(signal ? { signal } : {}) })
|
|
194
|
+
try {
|
|
195
|
+
for (const event of observation.events) {
|
|
196
|
+
if (event.type === 'user/message') visit(event.data?.content)
|
|
197
|
+
else if (event.type === 'tool/result') visit(event.data?.message?.content)
|
|
198
|
+
}
|
|
199
|
+
} finally { observation[Symbol.dispose]() }
|
|
200
|
+
return refs
|
|
201
|
+
}
|
|
202
|
+
async function inputAttachments(ctx,session,ids=[],signal) {
|
|
203
|
+
if(!Array.isArray(ids) || ids.length>8) throw new Error('每次最多使用 8 个本会话媒体附件')
|
|
204
|
+
if (!ids.length) return []
|
|
205
|
+
const refs=await sessionMediaAttachments(session,ctx,signal),files=[];let size=0
|
|
206
|
+
for(const id of ids) {
|
|
207
|
+
const item=refs.get(id)
|
|
208
|
+
if(!item) throw new Error('该媒体附件不在当前会话中;用 media_catalog 查看可用附件')
|
|
209
|
+
const service=ctx.get('attachments')
|
|
210
|
+
if(!service) throw new Error('当前部署没有附件读取服务')
|
|
211
|
+
let data
|
|
212
|
+
if(item.ref.bytes>20*1024*1024) throw new Error('媒体直接上传上限为 20MB,请先压缩或截取相关部分')
|
|
213
|
+
if(item.type==='image') data=Buffer.from((await service.readImage(item.ref,signal)).data)
|
|
214
|
+
else {
|
|
215
|
+
const chunks=[];let count=0
|
|
216
|
+
for await(const chunk of service.readFileStream(item.ref,signal)) {
|
|
217
|
+
count+=chunk.byteLength;if(count>20*1024*1024) throw new Error('媒体附件超过 20MB')
|
|
218
|
+
chunks.push(chunk)
|
|
219
|
+
}
|
|
220
|
+
data=Buffer.concat(chunks)
|
|
221
|
+
}
|
|
222
|
+
size+=data.length;if(size>20*1024*1024) throw new Error('媒体附件合计超过 20MB')
|
|
223
|
+
files.push({name:item.ref.name || 'attachment',mimeType:item.mimeType,data})
|
|
224
|
+
}
|
|
225
|
+
return files
|
|
226
|
+
}
|
|
227
|
+
function suffixMime(operation) { return operation.startsWith('image.') ? 'image/png' : operation.startsWith('video.') ? 'video/mp4' : 'audio/mpeg' }
|
|
228
|
+
function modelPath(id) { return id.split('/').map(encodeURIComponent).join('/') }
|
|
229
|
+
|
|
230
|
+
function generationName(value) {
|
|
231
|
+
if (typeof value !== 'string' || !value.trim()) throw new Error('生成图片、视频或音频时必须填写 name,说明生成物的内容')
|
|
232
|
+
const name = value.trim()
|
|
233
|
+
if ([...name].length > 60 || /[\\/<>:"|?*\u0000-\u001f\u007f]/u.test(name) || /^[.]|[.]$/.test(name)) throw new Error('生成物名称须为 60 字以内的短名,不能包含路径或文件名非法字符')
|
|
234
|
+
if (!/\p{L}/u.test(name) || /^[a-z]$/i.test(name)) throw new Error('生成物名称须说明内容,不能只用数字、符号或单个字母')
|
|
235
|
+
return name
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async function 写媒体说明(scope, job, promptPath) {
|
|
239
|
+
if (!job.operation.endsWith('.generate')) return
|
|
240
|
+
const path = 文件许可(scope, join(scope.根, '.blueprint-tmp', '生成', job.id, '说明.md'), true)
|
|
241
|
+
try { await stat(path); return } catch (error) { if (error.code !== 'ENOENT') throw error }
|
|
242
|
+
let prompt
|
|
243
|
+
try { prompt = await readFile(promptPath, 'utf8') }
|
|
244
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; prompt = '旧任务未保存提示词' }
|
|
245
|
+
const kind = { image: '图片', video: '视频', audio: '音频' }[job.operation.split('.')[0]]
|
|
246
|
+
const first = job.name || [...prompt.replace(/\s+/g, ' ').trim()].slice(0, 40).join('')
|
|
247
|
+
const text = `AI 生成的${kind}:${first}\n\n模型:${job.connection}/${job.model}\n用途:${job.operation}\n生成时间:${job.createdAt}\n回执:\`.blueprint-evidence/media/${job.id}.json\`\n\n完整提示词:\n\n${prompt}\n`
|
|
248
|
+
try { await writeFile(path, text, { flag: 'wx' }) }
|
|
249
|
+
catch (error) { if (error.code !== 'EEXIST') throw error }
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** 上架后只改已有结果路径;同一任务继续查询归档文件,不再提交生成请求。 */
|
|
253
|
+
export async function 更新媒体归档路径(根, 移动们) {
|
|
254
|
+
根 = await realpath(根)
|
|
255
|
+
const scope = {根, 技能:根, 机器写入:true}
|
|
256
|
+
const moves = 移动们.map(({from, to}) => {
|
|
257
|
+
if (typeof from !== 'string' || typeof to !== 'string' || isAbsolute(from) || isAbsolute(to)) throw new Error('媒体归档路径须为项目相对路径')
|
|
258
|
+
const source = relative(根, 文件许可(scope, from))
|
|
259
|
+
const target = relative(根, 文件许可(scope, to, true))
|
|
260
|
+
if (!source || !target) throw new Error('媒体归档不能移动项目根目录')
|
|
261
|
+
return {from:source, to:target}
|
|
262
|
+
}).sort((a, b) => b.from.length - a.from.length)
|
|
263
|
+
if (!moves.length) return []
|
|
264
|
+
const receiptDir = 文件许可(scope, join(根, '.blueprint-evidence', 'media'))
|
|
265
|
+
let names
|
|
266
|
+
try { names = await readdir(receiptDir) }
|
|
267
|
+
catch (error) { if (error.code === 'ENOENT') return []; throw error }
|
|
268
|
+
const changed = []
|
|
269
|
+
for (const name of names.filter(name => /^[0-9a-f-]{36}\.json$/.test(name))) {
|
|
270
|
+
const path = 文件许可(scope, join(receiptDir, name), true)
|
|
271
|
+
const job = JSON.parse(await readFile(path, 'utf8'))
|
|
272
|
+
let modified = false
|
|
273
|
+
for (const file of job.result?.files || []) {
|
|
274
|
+
const move = moves.find(move => file.path === move.from || file.path.startsWith(move.from + '/'))
|
|
275
|
+
if (!move) continue
|
|
276
|
+
file.path = move.to + file.path.slice(move.from.length)
|
|
277
|
+
modified = true
|
|
278
|
+
}
|
|
279
|
+
if (!modified) continue
|
|
280
|
+
const temporary = 文件许可(scope, `${path}.${randomUUID()}.tmp`, true)
|
|
281
|
+
await writeFile(temporary, JSON.stringify(job, null, 2), {mode:0o600})
|
|
282
|
+
await rename(temporary, path)
|
|
283
|
+
changed.push(job.id)
|
|
284
|
+
}
|
|
285
|
+
return changed
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** 一次调用或一次查询;异步任务留回执,重启后按 job 查询不会重复生成。 */
|
|
289
|
+
export async function callMedia(ctx, args, {root, cwd = root, signal, session, fetch:fetcher = globalThis.fetch} = {}) {
|
|
290
|
+
root = await realpath(root)
|
|
291
|
+
const controllerSignal = signal ? AbortSignal.any([signal,AbortSignal.timeout(300000)]) : AbortSignal.timeout(300000)
|
|
292
|
+
const scope = {根:root,技能:root,机器写入:true}
|
|
293
|
+
const receiptDir = 文件许可(scope,join(root,'.blueprint-evidence','media'),true)
|
|
294
|
+
let job, receipt
|
|
295
|
+
if (args.action === 'status') {
|
|
296
|
+
if (!/^[0-9a-f-]{36}$/.test(args.job || '')) throw new Error('请填写 media_call 返回的任务编号')
|
|
297
|
+
receipt = 文件许可(scope,join(receiptDir,`${args.job}.json`))
|
|
298
|
+
job = JSON.parse(await readFile(receipt,'utf8'))
|
|
299
|
+
if (job.result) {
|
|
300
|
+
for (const file of job.result.files || []) await stat(文件许可(scope,file.path))
|
|
301
|
+
return job.result
|
|
302
|
+
}
|
|
303
|
+
} else {
|
|
304
|
+
if (args.action && args.action !== 'run') throw new Error('媒体动作须为 run 或 status')
|
|
305
|
+
const name = args.operation?.endsWith('.generate') ? generationName(args.name) : undefined
|
|
306
|
+
job = {id:randomUUID(),connection:idOf(args.connection),model:String(args.model || ''),operation:args.operation,...(name ? {name} : {}),createdAt:new Date().toISOString()}
|
|
307
|
+
receipt = 文件许可(scope,join(receiptDir,`${job.id}.json`),true)
|
|
308
|
+
}
|
|
309
|
+
const profile = profiles(ctx)[job.connection]
|
|
310
|
+
if (!profile) throw new Error('媒体 API 未配置,请在 API 页面添加连接')
|
|
311
|
+
const model = profile.models.find(m=>m.id === job.model)
|
|
312
|
+
if (args.action !== 'status' && (!model || !model.operations.includes(job.operation))) throw new Error('所选媒体模型没有配置这项用途;先用 media_catalog 查看可用服务')
|
|
313
|
+
const key = (await ctx.get('credentials').resolve(profile.apiKeyEnv))?.value || ''
|
|
314
|
+
const local = ['localhost','127.0.0.1','[::1]'].includes(new URL(profile.baseURL).hostname)
|
|
315
|
+
if (!key && !local) throw new Error('媒体 API 尚未配置 Key')
|
|
316
|
+
const base = mediaEndpoint(profile.baseURL), api = profile.api
|
|
317
|
+
if (job.baseURL && (job.baseURL !== base || job.api !== api)) throw new Error('该任务创建后的连接地址或协议已改变,无法向新接口查询旧任务')
|
|
318
|
+
const headers = key ? api === 'gemini-media' ? {'x-goog-api-key':key} : {Authorization:`${api === 'fal-queue' ? 'Key' : 'Bearer'} ${key}`} : {}
|
|
319
|
+
const request = async (path, body, method = body ? 'POST' : 'GET') => {
|
|
320
|
+
const multipart = body instanceof FormData
|
|
321
|
+
if (method === 'POST') { job.requestSentAt=new Date().toISOString(); await saveReceipt() }
|
|
322
|
+
return fetcher(base + path,{method,headers:{...headers,...(body && !multipart ? {'Content-Type':'application/json'} : {})},body:body ? multipart ? body : JSON.stringify(body) : undefined,signal:controllerSignal,redirect:'error'})
|
|
323
|
+
}
|
|
324
|
+
const send = async (path,body,method) => jsonResponse(await request(path,body,method),controllerSignal)
|
|
325
|
+
const saveReceipt = async () => {
|
|
326
|
+
await mkdir(receiptDir,{recursive:true}); 文件许可(scope,receiptDir,true)
|
|
327
|
+
const temporary = 文件许可(scope,`${receipt}.${randomUUID()}.tmp`,true)
|
|
328
|
+
await writeFile(temporary,JSON.stringify(job,null,2),{mode:0o600}); await rename(temporary,receipt)
|
|
329
|
+
}
|
|
330
|
+
const outputDir = 文件许可(scope,join(root,'.blueprint-tmp','生成',job.id),true)
|
|
331
|
+
const promptPath = 文件许可(scope, join(receiptDir, `${job.id}.提示词.txt`), true)
|
|
332
|
+
const files = [], texts = []
|
|
333
|
+
const asset = async (data,mimeType) => {
|
|
334
|
+
if (!data.length) throw new Error('媒体 API 返回了空文件')
|
|
335
|
+
if (data.subarray(0,8).equals(Buffer.from('89504e470d0a1a0a','hex'))) mimeType='image/png'
|
|
336
|
+
else if (data[0] === 0xff && data[1] === 0xd8) mimeType='image/jpeg'
|
|
337
|
+
else if (data.subarray(0,4).toString() === 'RIFF') mimeType=data.subarray(8,12).toString() === 'WEBP' ? 'image/webp' : 'audio/wav'
|
|
338
|
+
else if (!EXT[mimeType]) mimeType=suffixMime(job.operation)
|
|
339
|
+
if (job.operation.endsWith('.generate') && !mimeType.startsWith(job.operation.split('.')[0]+'/')) throw new Error('媒体 API 返回的文件类型与所需生成用途不符')
|
|
340
|
+
await mkdir(outputDir,{recursive:true}); 文件许可(scope,outputDir,true)
|
|
341
|
+
const path = 文件许可(scope,join(outputDir,`${job.name || MEDIA_OPERATIONS[job.operation]}-${files.length+1}.${EXT[mimeType] || 'bin'}`),true)
|
|
342
|
+
await writeFile(path,data)
|
|
343
|
+
files.push({path:relative(root,path),mimeType,bytes:data.length})
|
|
344
|
+
await 写媒体说明(scope, job, promptPath)
|
|
345
|
+
}
|
|
346
|
+
const download = async (url,mimeType,authenticated = false) => {
|
|
347
|
+
const parsed = new URL(url)
|
|
348
|
+
if (!['http:','https:'].includes(parsed.protocol) || parsed.username || parsed.password) throw new Error('媒体结果下载地址无效')
|
|
349
|
+
if (authenticated && parsed.origin !== new URL(base).origin) throw new Error('拒绝把 API Key 发往其他下载地址')
|
|
350
|
+
const response = await fetcher(parsed.href,{headers:authenticated ? headers : {},signal:controllerSignal,redirect:'error'})
|
|
351
|
+
if (!response.ok) throw new Error(`媒体结果下载失败(HTTP ${response.status});可用同一 job 重试下载`)
|
|
352
|
+
await asset(await bytes(response,256*1024*1024,controllerSignal),response.headers.get('content-type')?.split(';')[0] || mimeType)
|
|
353
|
+
}
|
|
354
|
+
try {
|
|
355
|
+
let data
|
|
356
|
+
if (args.action === 'status') {
|
|
357
|
+
if (job.downloads?.length) {
|
|
358
|
+
for (const item of job.downloads) await download(item.url,item.mimeType)
|
|
359
|
+
} else if (api === 'openai-media' && job.remoteId) {
|
|
360
|
+
data = await send(`/videos/${encodeURIComponent(job.remoteId)}`)
|
|
361
|
+
if (data.status === 'failed') throw new Error(data.error?.message || '视频生成失败')
|
|
362
|
+
if (data.status !== 'completed') return {job:job.id,status:data.status,progress:data.progress,files:[]}
|
|
363
|
+
await download(`${base}/videos/${encodeURIComponent(job.remoteId)}/content`,'video/mp4',true)
|
|
364
|
+
} else if (api === 'fal-queue' && job.remoteId) {
|
|
365
|
+
data = await send(job.statusPath || `/${modelPath(job.model)}/requests/${encodeURIComponent(job.remoteId)}/status`)
|
|
366
|
+
if (data.error) throw new Error(data.error)
|
|
367
|
+
if (data.status !== 'COMPLETED') return {job:job.id,status:data.status,files:[]}
|
|
368
|
+
data = await send(job.responsePath || `/${modelPath(job.model)}/requests/${encodeURIComponent(job.remoteId)}`)
|
|
369
|
+
} else throw new Error('该任务没有可查询的远端编号或已取得的下载地址;请检查回执中的状态,勿重复提交')
|
|
370
|
+
} else {
|
|
371
|
+
const prompt = String(args.prompt || '').trim()
|
|
372
|
+
if (!prompt || prompt.length > 30000) throw new Error('请填写媒体生成描述或需要理解的问题,最多 30000 字符')
|
|
373
|
+
const input = [...await inputFiles(root,args.files,cwd),...await inputAttachments(ctx,session,args.attachments,controllerSignal)]
|
|
374
|
+
if(input.length>8 || input.reduce((total,file)=>total+file.data.length,0)>20*1024*1024) throw new Error('每次媒体输入最多 8 个文件、合计 20MB')
|
|
375
|
+
const options = {...model.defaults,...object(args.options || {},'调用参数')}
|
|
376
|
+
job.baseURL = base; job.api = api; job.status = 'submitting'
|
|
377
|
+
await saveReceipt()
|
|
378
|
+
if (job.operation.endsWith('.generate')) await writeFile(promptPath, String(args.prompt), { flag: 'wx', mode: 0o600 })
|
|
379
|
+
if (api === 'gemini-media') {
|
|
380
|
+
const parts = [{text:prompt},...input.map(f=>({inlineData:{mimeType:f.mimeType,data:f.data.toString('base64')}}))]
|
|
381
|
+
data = await send(`/models/${encodeURIComponent(job.model.replace(/^models\//,''))}:generateContent`,{contents:[{role:'user',parts}],generationConfig:{...options,...(job.operation === 'image.generate' ? {responseModalities:['TEXT','IMAGE']} : {})}})
|
|
382
|
+
} else if (api === 'fal-queue') {
|
|
383
|
+
const media = input.map(f=>`data:${f.mimeType};base64,${f.data.toString('base64')}`)
|
|
384
|
+
const payload = {...options,prompt,...(media.length ? {[input[0].mimeType.startsWith('image/') ? media.length > 1 ? 'image_urls' : 'image_url' : input[0].mimeType.startsWith('video/') ? 'video_url' : 'audio_url']:media.length > 1 ? media : media[0]} : {})}
|
|
385
|
+
data = await send(`/${modelPath(job.model)}`,payload)
|
|
386
|
+
if (!data.request_id) throw new Error('fal 未返回任务编号')
|
|
387
|
+
job.remoteId = String(data.request_id)
|
|
388
|
+
for (const [key,field] of [['status_url','statusPath'],['response_url','responsePath']]) if (data[key]) {
|
|
389
|
+
const url = new URL(data[key]), apiURL = new URL(base), prefix = apiURL.pathname.replace(/\/$/,'')
|
|
390
|
+
if (url.origin !== apiURL.origin || !url.pathname.startsWith(prefix+'/') || url.username || url.password) throw new Error('fal 返回的任务地址与配置的 API 不同')
|
|
391
|
+
job[field] = url.pathname.slice(prefix.length)+url.search
|
|
392
|
+
}
|
|
393
|
+
job.status='queued'; await saveReceipt()
|
|
394
|
+
return {job:job.id,status:'queued',files:[]}
|
|
395
|
+
} else if (api === 'siliconflow-image') {
|
|
396
|
+
if (input.length>3 || input.some(f=>!f.mimeType.startsWith('image/'))) throw new Error('硅基流动图片接口最多接受三张参考图片,且须使用支持参考图的模型')
|
|
397
|
+
if (input.length && job.model === 'Tongyi-MAI/Z-Image-Turbo') throw new Error('Z-Image-Turbo 只支持文生图;参考图编辑请选择支持参考图的模型')
|
|
398
|
+
const payload={...options,model:job.model,prompt}
|
|
399
|
+
if (args.options?.size && !args.options?.image_size) payload.image_size=args.options.size
|
|
400
|
+
else if (!payload.image_size && payload.size) payload.image_size=payload.size
|
|
401
|
+
delete payload.size
|
|
402
|
+
for (let i=0;i<input.length;i++) payload[i ? `image${i+1}` : 'image']=`data:${input[i].mimeType};base64,${input[i].data.toString('base64')}`
|
|
403
|
+
data=await send('/images/generations',payload)
|
|
404
|
+
job.downloads=[...(data.images || []),...(data.data || [])].filter(item=>item.url).map(item=>({url:item.url,mimeType:'image/png'}))
|
|
405
|
+
if (job.downloads.length) {job.status='generated';await saveReceipt()}
|
|
406
|
+
} else if (api === 'openai-chat-media') {
|
|
407
|
+
// 小米 MiMo 这类:看、听、转写、配音都走对话接口。配音的文字放在 assistant 消息里,audio 参数取回音频。
|
|
408
|
+
if (job.operation === 'audio.generate') {
|
|
409
|
+
if (input.length) throw new Error('配音把要念的文字写在 prompt 里,不接收媒体文件')
|
|
410
|
+
const { voice, format = 'wav', instruction, ...rest } = options
|
|
411
|
+
data = await send('/chat/completions',{...rest,model:job.model,stream:false,audio:{format,...(voice ? {voice} : {})},
|
|
412
|
+
messages:[...(instruction ? [{role:'user',content:String(instruction)}] : []),{role:'assistant',content:prompt}]})
|
|
413
|
+
const audio = data?.choices?.[0]?.message?.audio
|
|
414
|
+
if (!audio?.data) throw new Error('配音接口没有返回音频;检查模型和 audio 参数')
|
|
415
|
+
await asset(Buffer.from(audio.data,'base64'),format === 'mp3' ? 'audio/mpeg' : 'audio/wav')
|
|
416
|
+
} else {
|
|
417
|
+
if (!input.length) throw new Error('媒体理解需要本项目中的媒体文件')
|
|
418
|
+
// 转写模型只收音频,带上文字会被拒(MiMo 回 Param Incorrect)。
|
|
419
|
+
const 片段 = input.map(f=>对话媒体片段(f,job.operation))
|
|
420
|
+
data = await send('/chat/completions',{...options,model:job.model,stream:false,messages:[{role:'user',content:job.operation === 'audio.transcribe' ? 片段 : [{type:'text',text:prompt},...片段]}]})
|
|
421
|
+
}
|
|
422
|
+
} else if (api === 'openai-media') {
|
|
423
|
+
if (job.operation === 'video.generate') {
|
|
424
|
+
if (input.length>1 || input.some(f=>!f.mimeType.startsWith('image/'))) throw new Error('标准视频生成接口最多接受一张参考图片')
|
|
425
|
+
const form = new FormData()
|
|
426
|
+
for (const [k,v] of Object.entries({...options,model:job.model,prompt})) form.set(k,String(v))
|
|
427
|
+
if (input.length) form.set('input_reference',new Blob([input[0].data],{type:input[0].mimeType}),input[0].name)
|
|
428
|
+
data = await send('/videos',form)
|
|
429
|
+
if (!data.id) throw new Error('视频 API 未返回任务编号')
|
|
430
|
+
job.remoteId = String(data.id); job.status=data.status || 'queued'; await saveReceipt()
|
|
431
|
+
return {job:job.id,status:job.status,files:[]}
|
|
432
|
+
} else if (job.operation === 'image.generate') {
|
|
433
|
+
if (input.some(f=>!f.mimeType.startsWith('image/'))) throw new Error('图片编辑的参考输入须为图片文件')
|
|
434
|
+
if (input.length) {
|
|
435
|
+
const form = new FormData()
|
|
436
|
+
for (const [k,v] of Object.entries({...options,model:job.model,prompt})) form.set(k,String(v))
|
|
437
|
+
for (const file of input) form.append(input.length > 1 ? 'image[]' : 'image',new Blob([file.data],{type:file.mimeType}),file.name)
|
|
438
|
+
data = await send('/images/edits',form)
|
|
439
|
+
} else data = await send('/images/generations',{...options,model:job.model,prompt})
|
|
440
|
+
} else if (job.operation === 'audio.generate') {
|
|
441
|
+
if (input.length) throw new Error('标准语音生成接口使用待朗读文字;声音克隆需接入相应专用接口')
|
|
442
|
+
const response = await request('/audio/speech',{voice:'alloy',...options,model:job.model,input:prompt,response_format:options.response_format || 'mp3'})
|
|
443
|
+
if (!response.ok) await jsonResponse(response,controllerSignal)
|
|
444
|
+
if (/json|text\/html/.test(response.headers.get('content-type') || '')) throw new Error('语音 API 未返回音频文件,请检查接口和模型')
|
|
445
|
+
await asset(await bytes(response,256*1024*1024,controllerSignal),response.headers.get('content-type')?.split(';')[0] || 'audio/mpeg')
|
|
446
|
+
} else if (job.operation === 'audio.transcribe') {
|
|
447
|
+
if (input.length !== 1 || !input[0].mimeType.startsWith('audio/')) throw new Error('音频转文字需要一个音频文件')
|
|
448
|
+
const form = new FormData()
|
|
449
|
+
for (const [k,v] of Object.entries({...options,model:job.model,response_format:'json'})) form.set(k,String(v))
|
|
450
|
+
form.set('file',new Blob([input[0].data],{type:input[0].mimeType}),input[0].name)
|
|
451
|
+
data = await send('/audio/transcriptions',form)
|
|
452
|
+
} else {
|
|
453
|
+
if (!input.length) throw new Error('媒体理解需要本项目中的媒体文件')
|
|
454
|
+
const content = [{type:'text',text:prompt},...input.map(f=> {
|
|
455
|
+
if (job.operation === 'image.analyze' && f.mimeType.startsWith('image/')) return {type:'image_url',image_url:{url:`data:${f.mimeType};base64,${f.data.toString('base64')}`}}
|
|
456
|
+
if (job.operation === 'audio.analyze' && ['audio/wav','audio/mpeg'].includes(f.mimeType)) return {type:'input_audio',input_audio:{data:f.data.toString('base64'),format:f.mimeType === 'audio/wav' ? 'wav' : 'mp3'}}
|
|
457
|
+
throw new Error('该理解接口不支持此文件类型;视频理解可添加 Gemini 接口')
|
|
458
|
+
})]
|
|
459
|
+
data = await send('/chat/completions',{...options,model:job.model,messages:[{role:'user',content}],stream:false})
|
|
460
|
+
}
|
|
461
|
+
} else throw new Error('未支持的媒体接口')
|
|
462
|
+
}
|
|
463
|
+
if (data) {
|
|
464
|
+
for (const image of data.data || []) {
|
|
465
|
+
if (image.b64_json) await asset(Buffer.from(image.b64_json,'base64'),'image/png')
|
|
466
|
+
else if (image.url) await download(image.url,'image/png')
|
|
467
|
+
}
|
|
468
|
+
for (const part of data.candidates?.[0]?.content?.parts || []) {
|
|
469
|
+
if (part.text) texts.push(part.text)
|
|
470
|
+
if (part.inlineData?.data) await asset(Buffer.from(part.inlineData.data,'base64'),part.inlineData.mimeType || suffixMime(job.operation))
|
|
471
|
+
}
|
|
472
|
+
for (const item of [...(data.images || []),...['image','video','audio','audio_file'].map(k=>data[k]).filter(Boolean)]) if (item.url) await download(item.url,item.content_type || suffixMime(job.operation))
|
|
473
|
+
for (const value of [data.text,data.transcription,data.choices?.[0]?.message?.content]) if (typeof value === 'string' && value) texts.push(value)
|
|
474
|
+
}
|
|
475
|
+
if (!files.length && !texts.length) throw new Error('媒体服务未返回可用文件或文字结果')
|
|
476
|
+
if (job.operation.endsWith('.generate') && !files.length) throw new Error('媒体服务只返回了文字,未生成所需媒体文件')
|
|
477
|
+
const result = {job:job.id,status:'completed',files,...(texts.length ? {text:texts.join('\n').slice(0,20000)} : {}),...(data?.usage || data?.usageMetadata ? {usage:data.usage || data.usageMetadata} : {})}
|
|
478
|
+
job.status='completed'; job.result=result; await saveReceipt(); return result
|
|
479
|
+
} catch (error) {
|
|
480
|
+
job.lastError=hide(error,key)
|
|
481
|
+
if (job.status !== 'completed') job.status=job.remoteId || job.downloads?.length ? 'pending' : job.requestSentAt ? 'unknown' : 'failed'
|
|
482
|
+
await saveReceipt().catch(()=>{})
|
|
483
|
+
throw new Error(`${job.lastError};本地任务 ${job.id}${job.remoteId || job.downloads?.length ? ',可用 status 查询或重试下载,勿重复生成' : job.status === 'unknown' ? ',提交结果未确定,请检查服务商任务记录后再决定是否重新生成' : ''}`)
|
|
484
|
+
}
|
|
485
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/** 开一个终端窗口跑一条命令,让用户看着(装 Homebrew、Codex/Claude Code 登录都要输东西)。11-30 从 软件.js、子代理.js 两份 macOS 专用的抽出来,加 Windows。
|
|
2
|
+
* macOS:写一个 .command 交给 open(终端.app 打开);Windows:写一个 .ps1,用 start 开新的 PowerShell 窗口跑完不关;别的系统不开,报错让用户自己复制命令跑。
|
|
3
|
+
* dsh 的 open-in-app 只能在某个目录开终端,不能带命令,所以这里自己开。 */
|
|
4
|
+
import { execFile, spawn } from 'node:child_process'
|
|
5
|
+
import { writeFile, chmod } from 'node:fs/promises'
|
|
6
|
+
import { join } from 'node:path'
|
|
7
|
+
import { tmpdir } from 'node:os'
|
|
8
|
+
|
|
9
|
+
const 单引号sh = text => `'${String(text).replace(/'/g, `'\\''`)}'`
|
|
10
|
+
const 单引号ps = text => `'${String(text).replace(/'/g, "''")}'`
|
|
11
|
+
|
|
12
|
+
/** 这台电脑的终端里怎么写这条命令(给用户复制用,也是窗口里实际跑的):argv 是程序和参数。 */
|
|
13
|
+
export function 终端命令(argv, platform = process.platform) {
|
|
14
|
+
return platform === 'win32' ? `& ${argv.map(单引号ps).join(' ')}` : argv.map(单引号sh).join(' ')
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** 能不能开:给界面判断要不要显示按钮。 */
|
|
18
|
+
export const 能开终端 = (platform = process.platform) => platform === 'darwin' || platform === 'win32'
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* 开窗口:名字用来起临时文件名;开头、结尾是窗口里先后打印的两句;命令是 终端命令() 写好的一行(Windows 上是 PowerShell 写法)。
|
|
22
|
+
*/
|
|
23
|
+
export async function 开终端跑({ 名字, 开头, 命令, 结尾 }) {
|
|
24
|
+
if (process.platform === 'darwin') {
|
|
25
|
+
const file = join(tmpdir(), `Blueprint-${名字}.command`)
|
|
26
|
+
await writeFile(file, `#!/bin/zsh\ncd ~\nprintf '%s\\n\\n' ${单引号sh(开头)}\n${命令}\nprintf '\\n%s\\n' ${单引号sh(结尾)}\n`)
|
|
27
|
+
await chmod(file, 0o755)
|
|
28
|
+
await new Promise((done, fail) => execFile('open', [file], error => error ? fail(error) : done()))
|
|
29
|
+
return
|
|
30
|
+
}
|
|
31
|
+
if (process.platform === 'win32') {
|
|
32
|
+
const file = join(tmpdir(), `Blueprint-${名字}.ps1`)
|
|
33
|
+
// 带 BOM 的 UTF-8:Windows PowerShell 5 没有 BOM 会按本地代码页读,中文变乱码。
|
|
34
|
+
await writeFile(file, `Set-Location ~\nWrite-Host ${单引号ps(开头)}\nWrite-Host ''\n${命令}\nWrite-Host ''\nWrite-Host ${单引号ps(结尾)}\n`, 'utf8')
|
|
35
|
+
await new Promise((done, fail) => {
|
|
36
|
+
const child = spawn('cmd.exe', ['/d', '/c', 'start', '""', 'powershell.exe', '-NoExit', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', file],
|
|
37
|
+
{ detached: true, stdio: 'ignore', windowsHide: true })
|
|
38
|
+
child.once('error', fail)
|
|
39
|
+
child.once('spawn', () => { child.unref(); done() })
|
|
40
|
+
})
|
|
41
|
+
return
|
|
42
|
+
}
|
|
43
|
+
throw new Error('这台电脑上打不开终端,请复制下面的命令自己运行')
|
|
44
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// 从旧系统 context/src/程序协助.js、node/src/通用工具.js、node/src/纸条等待.js、node/src/规则.js、prompt/src/项目技能.js、prompt/src/index.js 的几段 拷来(2026-11-09 搬回 Blueprint 前端时,旧包不复活,只拷这些纯小工具)。
|
|
2
|
+
import { 消息来自 } from './消息协议.js'
|
|
3
|
+
|
|
4
|
+
/** dsh 原生帮手的两种开法(程序协助.js)。 */
|
|
5
|
+
export const 子run提供方们 = Object.freeze(['spawn', 'fork'])
|
|
6
|
+
|
|
7
|
+
/** 模型常把入口再包一层 call_tool,剥掉看实际调的那一把(通用工具.js)。 */
|
|
8
|
+
const 是调用 = value => value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
9
|
+
&& typeof value.name === 'string' && Object.hasOwn(value, 'arguments')
|
|
10
|
+
function 剥外壳(args) {
|
|
11
|
+
let actual = args
|
|
12
|
+
while (actual?.name === 'call_tool' && 是调用(actual.arguments)) actual = actual.arguments
|
|
13
|
+
return actual
|
|
14
|
+
}
|
|
15
|
+
export function 展开工具调用(name, args) {
|
|
16
|
+
let parsed = args
|
|
17
|
+
try { if (typeof parsed === 'string') parsed = JSON.parse(parsed) } catch { return { name, arguments: args } }
|
|
18
|
+
if (name === 'call_tool' && typeof parsed?.name === 'string' && parsed.arguments && typeof parsed.arguments === 'object') {
|
|
19
|
+
const actual = 剥外壳(parsed)
|
|
20
|
+
return { name: actual.name, arguments: actual.arguments }
|
|
21
|
+
}
|
|
22
|
+
return { name, arguments: args }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** 仅供读旧账本(纸条等待.js)。 */
|
|
26
|
+
export const 纸条等待事件 = 'blueprint/waiting-for-notes'
|
|
27
|
+
export const 条件等待事件 = 'blueprint/waiting-for-conditions'
|
|
28
|
+
|
|
29
|
+
/** 读事件判状态的纯函数(规则.js)。新系统的账本里没有这些标记,判出来是 false,无害。 */
|
|
30
|
+
export const 回话停下 = 'blueprint-reply-stop'
|
|
31
|
+
export const 是回话停下 = message => message?.role === 'user' && message.source?.summary === 回话停下
|
|
32
|
+
export const 用户回话 = 'blueprint-user-reply'
|
|
33
|
+
export const 是用户回话 = message => message?.role === 'user' && message.source?.summary === 用户回话
|
|
34
|
+
const 开工的工具 = new Set(['next', 'dispatch', 'finish'])
|
|
35
|
+
export function 调的工具(data) {
|
|
36
|
+
if (data?.name !== 'call_tool') return data?.name
|
|
37
|
+
try { const a = typeof data.arguments === 'string' ? JSON.parse(data.arguments) : data.arguments; return a?.name } catch { return undefined }
|
|
38
|
+
}
|
|
39
|
+
export const 是开工调用 = e => e?.type === 'tool/call' && 开工的工具.has(调的工具(e.data))
|
|
40
|
+
export function 等用户回话的(事件们) {
|
|
41
|
+
const 们 = 事件们 || []
|
|
42
|
+
let 头 = -1
|
|
43
|
+
for (let i = 们.length - 1; i >= 0; i--) if (们[i]?.type === 'turn/start') { 头 = i; break }
|
|
44
|
+
if (头 < 0) return false
|
|
45
|
+
const 这轮 = 们.slice(头 + 1), 尾 = 这轮.findLastIndex(e => e?.type === 'turn/end')
|
|
46
|
+
if (这轮[尾]?.data?.reason?.kind !== 'completed') return false
|
|
47
|
+
const 标记 = 这轮.slice(0, 尾).findLastIndex(e => e?.type === 'user/message' && (是用户回话(e.data) || 是回话停下(e.data)))
|
|
48
|
+
return 标记 >= 0 && !这轮.slice(标记 + 1, 尾).some(是开工调用)
|
|
49
|
+
}
|
|
50
|
+
export const 用户续工来路 = 'blueprint-node-resume'
|
|
51
|
+
export const 是用户续工输入 = message => !!message && (message.role === undefined || message.role === 'user')
|
|
52
|
+
&& (['user', 'api'].includes(message.source?.kind) || 消息来自(message, `plugin:${用户续工来路}`))
|
|
53
|
+
export function 用户停下的(事件们) {
|
|
54
|
+
for (let i = 事件们.length - 1; i >= 0; i--) {
|
|
55
|
+
const e = 事件们[i]
|
|
56
|
+
if (e?.type === 'user/message' && 是用户续工输入(e.data)) return false
|
|
57
|
+
if (e?.type === 'user/message' && 是回话停下(e.data)) return true
|
|
58
|
+
if (!e || e.type !== 'turn/end') continue
|
|
59
|
+
const r = e.data && e.data.reason
|
|
60
|
+
if (r?.kind === 'aborted' && r.reason?.kind === 'user') return true
|
|
61
|
+
}
|
|
62
|
+
return false
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** 技能页过滤用的常量表(项目技能.js、prompt/index.js)。 */
|
|
66
|
+
export const 退役技能名 = Object.freeze(['orient', 'what', 'how', 'execute'])
|
|
67
|
+
export const 节点本体技能名 = Object.freeze([])
|