@wangpinlan/dsh-vision-bridge 0.0.0-stage → 0.1.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 +21 -0
- package/README.md +110 -2
- package/client.js +470 -0
- package/cordis.patch.yml +18 -0
- package/docs/DETAIL.md +59 -0
- package/icon.svg +6 -0
- package/index.js +500 -0
- package/lib/pure.js +97 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +67 -3
package/docs/DETAIL.md
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# 视觉桥接(Vision bridge)
|
|
2
|
+
|
|
3
|
+
让**纯文本模型路由**获得「看」图的能力,并且是**模型主动调用工具**式的读图:
|
|
4
|
+
|
|
5
|
+
- 用户发的图仍然以缩略图留在消息里(GUI 可点开大图);
|
|
6
|
+
- 纯文本模型在请求里看到的是 DSH 内置的图像占位符;
|
|
7
|
+
- 模型调用 `read_image` 时,由本机(或任意 OpenAI 兼容)视觉模型生成文字描述,
|
|
8
|
+
描述出现在工具结果/思维链里。
|
|
9
|
+
|
|
10
|
+
## 工作原理
|
|
11
|
+
|
|
12
|
+
1. **不改写会话事件**。用户消息里的 `image` 块原样落盘,前端照常渲染缩略图。
|
|
13
|
+
2. **请求侧使用 DSH 内置的 text-only 降级**。当路由声明的 `input` 明确不含
|
|
14
|
+
`image` 时,`LlmRuntime` 会把图像块投影成
|
|
15
|
+
`[image omitted because this model accepts text only; attachment sha256:XXXXXXXX]`
|
|
16
|
+
占位文字,纯文本后端永远收不到图像块。
|
|
17
|
+
3. **插件给纯文本路由的 agent 安装 `read_image` 变体**。在 `agent/created` 时
|
|
18
|
+
判定路由声明的输入模态;只有「明确不含 image」的路由才会在 agent scope 注册
|
|
19
|
+
同名工具,遮蔽内置的 `read_image`。变体读取附件字节并调用视觉模型,把文字
|
|
20
|
+
描述作为工具结果返回;内置工具那条「路由必须支持图像」的门控因此不适用。
|
|
21
|
+
4. **系统提示注入读图约定**,告诉模型占位符意味着有一张可读的图,以及
|
|
22
|
+
`read_image` 的 `file_path` 该传什么。
|
|
23
|
+
|
|
24
|
+
多模态路由(例如声明了 `image` 的 deepseek 模型)不会被安装变体,原生视觉能力
|
|
25
|
+
完全不受影响。
|
|
26
|
+
|
|
27
|
+
## 调用约定
|
|
28
|
+
|
|
29
|
+
模型看到占位符后应调用:
|
|
30
|
+
|
|
31
|
+
```json
|
|
32
|
+
{ "file_path": "attachment:sha256:XXXXXXXX" }
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
`XXXXXXXX` 是占位符里的摘要前缀(完整 64 位也可以)。变体也接受:
|
|
36
|
+
|
|
37
|
+
- `sha256:XXXXXXXX`
|
|
38
|
+
- 附件内容寻址对象路径 `~/.dsh/attachments/v1/objects/<xx>/<sha256>`
|
|
39
|
+
- 普通图片文件路径(PNG/JPEG/WebP/GIF)
|
|
40
|
+
|
|
41
|
+
## 配置
|
|
42
|
+
|
|
43
|
+
| 键 | 说明 |
|
|
44
|
+
| --- | --- |
|
|
45
|
+
| `baseUrl` | 视觉模型的 OpenAI 兼容 API 基址,例如 `http://127.0.0.1:8080/v1` |
|
|
46
|
+
| `model` | 视觉模型名,例如 `qwen3-vl-4b` |
|
|
47
|
+
| `apiKey` | 可选;本地 llama-server 通常留空 |
|
|
48
|
+
| `prompt` | 可选;自定义转述指令,留空用内置默认 |
|
|
49
|
+
| `maxTokens` | 单张图片描述的最大 token 数,默认 768 |
|
|
50
|
+
| `providers` | 只对这些 provider 生效;留空表示按路由声明的输入模态自动判定 |
|
|
51
|
+
|
|
52
|
+
安装后可在 Web 的 **Plugins 页 → 视觉桥接** 的插件行点「配置」直接编辑以上字段;
|
|
53
|
+
表单写入 profile 的设置文档,保存后按 Host 的配置重载生效。`baseUrl` 或 `model`
|
|
54
|
+
为空时插件处于 inert 状态:不注册任何监听器或提示段。
|
|
55
|
+
|
|
56
|
+
## 开关
|
|
57
|
+
|
|
58
|
+
bundle 的 **enabled** 状态即总开关:禁用时 `apply` 不运行,系统提示与 `read_image`
|
|
59
|
+
变体一并撤回,会话立即恢复原生行为。无需重启。
|
package/icon.svg
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
<svg width="36" height="36" viewBox="0 0 36 36" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">
|
|
2
|
+
<path d="M3 18 C8.5 8.5 27.5 8.5 33 18 C27.5 27.5 8.5 27.5 3 18 Z"/>
|
|
3
|
+
<rect x="12.5" y="12.5" width="11" height="11" rx="2.5"/>
|
|
4
|
+
<circle cx="20.7" cy="16" r="1.2"/>
|
|
5
|
+
<path d="M14.3 21.6 L17.8 18.1 L21.3 21.6"/>
|
|
6
|
+
</svg>
|
package/index.js
ADDED
|
@@ -0,0 +1,500 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-vision-bridge — 让纯文本模型「主动看见」图片。
|
|
3
|
+
*
|
|
4
|
+
* v4 架构(请求边界改写 + per-agent read_image 变体):
|
|
5
|
+
*
|
|
6
|
+
* 1. **不改写会话事件**。用户消息里的 image 块原样落盘,GUI 仍渲染缩略图。
|
|
7
|
+
* 2. **GUI 上传不受限**。路由仍声明 `input: [text, image]`(否则
|
|
8
|
+
* `session-controller` 的图片准入会以 `MODEL_DOES_NOT_SUPPORT_IMAGES`
|
|
9
|
+
* 拒绝上传)。桥接与否由插件配置决定,而不是路由声明。
|
|
10
|
+
* 3. **请求边界改写**:包装 `llm.prepareCall()`,对命中 `providers` 名单
|
|
11
|
+
* (或声明为 text-only)的路由,在 `preparedCall.stream()` 交给 adapter
|
|
12
|
+
* 之前把每个 image 块换成一段占位文字(带完整 attachment id 与调用指引)。
|
|
13
|
+
* 纯文本后端永远收不到图像块;事件与 GUI 完全不受影响。
|
|
14
|
+
* 4. **per-agent `read_image` 变体**:目标路由的 agent 创建时(以及每次
|
|
15
|
+
* pre-step 幂等补装),在 `agent.ctx` 注册同名工具。agent scope 的 own
|
|
16
|
+
* 注册优先于继承的全局工具,因此变体直接遮蔽内置 `read_image`(内置那条
|
|
17
|
+
* 「路由必须支持图像」的门控也因此不再适用)。变体读取附件字节 → 调用
|
|
18
|
+
* 外挂 OpenAI 兼容视觉模型 → 以文字描述作为工具结果(出现在思维链里)。
|
|
19
|
+
* 5. **系统提示**按 agent 注入简短约定,强化「占位符 → read_image」的用法。
|
|
20
|
+
*
|
|
21
|
+
* 生效范围:`config.providers` 非空时只对这些 provider 生效;为空时退化为
|
|
22
|
+
* 「路由声明明确不含 image」才桥接。多模态路由(如 deepseek-flash)不受影响。
|
|
23
|
+
*
|
|
24
|
+
* 开关语义:bundle 的 enabled 状态即总开关;`config.baseUrl` / `model` 为空时
|
|
25
|
+
* 插件 inert。
|
|
26
|
+
*
|
|
27
|
+
* @module @local/dsh-vision-bridge
|
|
28
|
+
*/
|
|
29
|
+
import { basename } from 'node:path'
|
|
30
|
+
import { readFile } from 'node:fs/promises'
|
|
31
|
+
import { markAgentLoopRequest } from '@deepseek-ai/dsh-llm'
|
|
32
|
+
import Schema from '@deepseek-ai/schemastery'
|
|
33
|
+
import {
|
|
34
|
+
buildVisionInstruction,
|
|
35
|
+
digestFromPath,
|
|
36
|
+
replaceImagesWithPlaceholders,
|
|
37
|
+
sniffMediaType,
|
|
38
|
+
} from './lib/pure.js'
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* 未提供任何提示词时使用的默认指令:中性描述型,不预设「检查」或任何具体场景。
|
|
42
|
+
* 调用方模型想指定关注点时,应通过 read_image 的 `prompt` 参数传入。
|
|
43
|
+
*/
|
|
44
|
+
const DEFAULT_PROMPT =
|
|
45
|
+
'你是图像描述助手。一个看不到图的助手会拿你的描述来回答用户,请用简体中文客观、完整地描述这张图片。\n' +
|
|
46
|
+
'请覆盖:1) 画面主体、布局与各部分相对位置;2) 图中出现的所有文字,逐字转写并说明大致位置;\n' +
|
|
47
|
+
'3) 若下方附有用户当前的问题或目标,优先回答用户关心的部分。'
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 注入系统提示的读图约定。请求边界换出来的占位文字本身已带调用提示,
|
|
51
|
+
* 这段系统提示用于强化「看到占位符必须先读图」的行为。
|
|
52
|
+
*/
|
|
53
|
+
const PROMPT_GUIDE =
|
|
54
|
+
'Some user messages contain an image placeholder of the form ' +
|
|
55
|
+
'"[image omitted because this model cannot decode images directly ... attachment sha256:XXXXXXXX]". ' +
|
|
56
|
+
'That placeholder means the user attached an image you cannot see directly. ' +
|
|
57
|
+
'To view its content, call the read_image tool with file_path set to ' +
|
|
58
|
+
'"attachment:sha256:XXXXXXXX" (use the digest from the placeholder). The tool returns a ' +
|
|
59
|
+
'detailed textual description of the image. Call read_image for every such placeholder ' +
|
|
60
|
+
'before answering, because the image content is usually the core of the question. ' +
|
|
61
|
+
'When the user has a specific goal (read the text, check the layout, find an element), ' +
|
|
62
|
+
'pass it as the read_image prompt parameter so the vision model knows what to report.'
|
|
63
|
+
|
|
64
|
+
/** 供模型阅读的工具描述。 */
|
|
65
|
+
const TOOL_DESCRIPTION =
|
|
66
|
+
'Read an image and return a detailed textual description of its content. ' +
|
|
67
|
+
'Use file_path = "attachment:sha256:XXXXXXXX" for the image placeholder shown in a ' +
|
|
68
|
+
'message, or pass a path to a PNG/JPEG/WebP/GIF file. ' +
|
|
69
|
+
'Pass the optional prompt parameter to tell the vision model what to focus on ' +
|
|
70
|
+
'(for example "read all the text", "check the layout", "describe the subject"). ' +
|
|
71
|
+
'When omitted, the deployment default prompt and the current user question are used. ' +
|
|
72
|
+
'The result is text, not the image itself.'
|
|
73
|
+
|
|
74
|
+
/** 插件配置。字段均可选;baseUrl 或 model 为空时插件不生效。 */
|
|
75
|
+
export const Config = Schema.object({
|
|
76
|
+
// 每个字段都标记 `.volatile()`:DSH 设置页只投影 volatile 字段(见
|
|
77
|
+
// packages/settings/settings/src/schema.ts 的 volatileForm),否则该插件不会
|
|
78
|
+
// 出现在设置文档的 namespaces 里,前端表单永远停在「配置加载中」。
|
|
79
|
+
baseUrl: Schema.string()
|
|
80
|
+
.description('外挂视觉模型的 OpenAI 兼容 API 基址,例如 http://127.0.0.1:8080/v1')
|
|
81
|
+
.default('')
|
|
82
|
+
.volatile(),
|
|
83
|
+
model: Schema.string()
|
|
84
|
+
.description('视觉模型名,例如 qwen3-vl-4b')
|
|
85
|
+
.default('')
|
|
86
|
+
.volatile(),
|
|
87
|
+
apiKey: Schema.string()
|
|
88
|
+
.description('可选;本地 llama-server 通常留空')
|
|
89
|
+
.default('')
|
|
90
|
+
.volatile(),
|
|
91
|
+
prompt: Schema.string()
|
|
92
|
+
.description('可选;自定义转述指令,留空用内置默认')
|
|
93
|
+
.default('')
|
|
94
|
+
.volatile(),
|
|
95
|
+
maxTokens: Schema.natural()
|
|
96
|
+
.min(64)
|
|
97
|
+
.description('单张图片描述的最大 token 数')
|
|
98
|
+
.default(768)
|
|
99
|
+
.volatile(),
|
|
100
|
+
providers: Schema.array(Schema.string())
|
|
101
|
+
.description('需要桥接的 provider 名单;留空表示只桥接声明为 text-only 的路由')
|
|
102
|
+
.default([])
|
|
103
|
+
.volatile(),
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* 把 volatile 配置字段解包成普通值。运行时每个 volatile 字段是 `{ get, set }`
|
|
108
|
+
* 包装(schemastery/cosmokit),插件内部按普通对象读取更直接。
|
|
109
|
+
* @param config - Cordis 传入的插件配置。
|
|
110
|
+
*/
|
|
111
|
+
function plainConfig(config) {
|
|
112
|
+
const read = value => value !== null && typeof value === 'object' && typeof value.get === 'function'
|
|
113
|
+
? value.get()
|
|
114
|
+
: value
|
|
115
|
+
return {
|
|
116
|
+
baseUrl: read(config.baseUrl) ?? '',
|
|
117
|
+
model: read(config.model) ?? '',
|
|
118
|
+
apiKey: read(config.apiKey) ?? '',
|
|
119
|
+
prompt: read(config.prompt) ?? '',
|
|
120
|
+
maxTokens: read(config.maxTokens) ?? 768,
|
|
121
|
+
providers: read(config.providers) ?? [],
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** 附件服务是唯一硬依赖;llm 用于请求边界改写与路由判定。 */
|
|
126
|
+
export const inject = ['attachments']
|
|
127
|
+
|
|
128
|
+
// ---------------------------------------------------------------------------
|
|
129
|
+
// 路由判定
|
|
130
|
+
// ---------------------------------------------------------------------------
|
|
131
|
+
|
|
132
|
+
/** 请求边界改写与变体安装共用的路由判定缓存。 */
|
|
133
|
+
const routeCache = new Map()
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* 当前路由是否需要桥接。
|
|
137
|
+
* @param provider - provider id。
|
|
138
|
+
* @param model - model id。
|
|
139
|
+
* @param config - 插件配置。
|
|
140
|
+
* @param llm - llm 服务(可能缺失)。
|
|
141
|
+
* @param signal - 取消信号。
|
|
142
|
+
*/
|
|
143
|
+
async function isTargetSelection(provider, model, config, llm, signal) {
|
|
144
|
+
if (typeof provider !== 'string' || typeof model !== 'string') return false
|
|
145
|
+
if (config.providers.length > 0) return config.providers.includes(provider)
|
|
146
|
+
if (llm === undefined) return false
|
|
147
|
+
const key = `${provider}\u0000${model}`
|
|
148
|
+
if (routeCache.has(key)) return routeCache.get(key)
|
|
149
|
+
try {
|
|
150
|
+
const info = await llm.resolveModelInfo(provider, model, signal)
|
|
151
|
+
const modalities = info?.inputModalities
|
|
152
|
+
// 只有「明确声明了模态且不含 image」才算纯文本路由;未声明时保守不接管。
|
|
153
|
+
const textOnly = Array.isArray(modalities) && modalities.length > 0 && !modalities.includes('image')
|
|
154
|
+
routeCache.set(key, textOnly)
|
|
155
|
+
return textOnly
|
|
156
|
+
} catch {
|
|
157
|
+
return false
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** 当前 agent 所在路由是否需要桥接。 */
|
|
162
|
+
async function isTargetAgent(agent, config, llm, signal) {
|
|
163
|
+
const selection = agent?.model?.current?.()
|
|
164
|
+
if (selection === undefined) return false
|
|
165
|
+
return isTargetSelection(selection.provider, selection.model, config, llm, signal)
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// ---------------------------------------------------------------------------
|
|
169
|
+
// 通用工具
|
|
170
|
+
// ---------------------------------------------------------------------------
|
|
171
|
+
|
|
172
|
+
/** 取出一个事件里可能携带图像块的消息内容;不适用时返回 undefined。 */
|
|
173
|
+
function messageContentOf(event) {
|
|
174
|
+
if (event.type === 'user/message') return event.data?.content
|
|
175
|
+
if (event.type === 'tool/result') return event.data?.message?.content
|
|
176
|
+
return undefined
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* 取会话里最后一条真实用户消息的文本,作为视觉模型的上下文。
|
|
181
|
+
* 只取 source.kind === 'user' 的消息,跳过运行时上下文/系统回显。
|
|
182
|
+
* @returns 用户问题文本(已截断),没有时返回空串。
|
|
183
|
+
*/
|
|
184
|
+
function latestUserQuestion(session) {
|
|
185
|
+
if (session === undefined) return ''
|
|
186
|
+
try {
|
|
187
|
+
const messages = session.deriveMessages()
|
|
188
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
189
|
+
const message = messages[index]
|
|
190
|
+
if (message?.role !== 'user' || message.source?.kind !== 'user') continue
|
|
191
|
+
const text = (message.content ?? [])
|
|
192
|
+
.filter(block => block?.type === 'text' && typeof block.text === 'string')
|
|
193
|
+
.map(block => block.text)
|
|
194
|
+
.join('\n')
|
|
195
|
+
.trim()
|
|
196
|
+
if (text.length > 0) return text.slice(0, 1500)
|
|
197
|
+
}
|
|
198
|
+
} catch {
|
|
199
|
+
// 取不到上下文时退化为纯描述指令。
|
|
200
|
+
}
|
|
201
|
+
return ''
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** 在会话已落盘的事件里,按摘要前缀找到完整的图像附件引用。 */
|
|
205
|
+
function findAttachmentRef(session, digest) {
|
|
206
|
+
if (session === undefined) return undefined
|
|
207
|
+
try {
|
|
208
|
+
for (const seq of session.surface.nodes) {
|
|
209
|
+
const event = session.eventAt(seq)
|
|
210
|
+
if (event === undefined) continue
|
|
211
|
+
const content = messageContentOf(event)
|
|
212
|
+
if (!Array.isArray(content)) continue
|
|
213
|
+
for (const block of content) {
|
|
214
|
+
if (block?.type !== 'image') continue
|
|
215
|
+
const attachmentId = String(block.attachment?.attachmentId ?? '')
|
|
216
|
+
if (attachmentId.startsWith(`sha256:${digest}`)) return block.attachment
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
} catch {
|
|
220
|
+
return undefined
|
|
221
|
+
}
|
|
222
|
+
return undefined
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// ---------------------------------------------------------------------------
|
|
226
|
+
// 请求边界:image 块 → 占位文字
|
|
227
|
+
// ---------------------------------------------------------------------------
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* 把请求消息里的 image 块换成占位文字。
|
|
231
|
+
* @param options - `preparedCall.stream()` 收到的请求。
|
|
232
|
+
* @returns 改写后的请求(无图时原样返回)。
|
|
233
|
+
*/
|
|
234
|
+
function withTextPlaceholders(options) {
|
|
235
|
+
const { messages, changed } = replaceImagesWithPlaceholders(options?.messages)
|
|
236
|
+
if (!changed) return options
|
|
237
|
+
// 复制而不是就地修改:loop 构造的请求是 deep-frozen 的。
|
|
238
|
+
const wrapped = { ...options, messages }
|
|
239
|
+
// 保住「由 agent loop 构造」的身份标记(WeakSet),供下游监听器识别。
|
|
240
|
+
markAgentLoopRequest(wrapped)
|
|
241
|
+
return wrapped
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// ---------------------------------------------------------------------------
|
|
245
|
+
// 视觉模型调用
|
|
246
|
+
// ---------------------------------------------------------------------------
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* 规范化 OpenAI 兼容基址:用户常填 `http://host:8080`,而接口在 `/v1` 下。
|
|
250
|
+
* 已含 `/v1`(或其它 `/vN`)的地址原样使用。
|
|
251
|
+
*/
|
|
252
|
+
function apiBase(raw) {
|
|
253
|
+
const trimmed = String(raw ?? '').trim().replace(/\/+$/, '')
|
|
254
|
+
if (trimmed === '') return trimmed
|
|
255
|
+
return /\/v\d+(?:$|\/)/iu.test(trimmed) ? trimmed : `${trimmed}/v1`
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* 调用外挂 OpenAI 兼容视觉模型,把图片字节转述成文字。
|
|
260
|
+
* @returns 转述文字;失败返回 null。
|
|
261
|
+
*/
|
|
262
|
+
async function describeBytes(config, data, mediaType, signal, modelPrompt, contextText) {
|
|
263
|
+
try {
|
|
264
|
+
const base64 = Buffer.from(data).toString('base64')
|
|
265
|
+
const dataUrl = `data:${mediaType};base64,${base64}`
|
|
266
|
+
// 模型自带 prompt 时完全按它的来;否则用部署默认并附上用户当前的问题。
|
|
267
|
+
const { instruction, context } = buildVisionInstruction(config.prompt, modelPrompt, contextText, DEFAULT_PROMPT)
|
|
268
|
+
const userText = context.length > 0
|
|
269
|
+
? `${instruction}\n\n用户当前的问题/目标:\n${context}`
|
|
270
|
+
: instruction
|
|
271
|
+
const headers = { 'Content-Type': 'application/json' }
|
|
272
|
+
if (config.apiKey && config.apiKey.trim()) headers.Authorization = `Bearer ${config.apiKey.trim()}`
|
|
273
|
+
|
|
274
|
+
const base = apiBase(config.baseUrl)
|
|
275
|
+
const response = await fetch(`${base}/chat/completions`, {
|
|
276
|
+
method: 'POST',
|
|
277
|
+
headers,
|
|
278
|
+
signal,
|
|
279
|
+
body: JSON.stringify({
|
|
280
|
+
model: config.model,
|
|
281
|
+
messages: [{
|
|
282
|
+
role: 'user',
|
|
283
|
+
content: [
|
|
284
|
+
{ type: 'text', text: userText },
|
|
285
|
+
{ type: 'image_url', image_url: { url: dataUrl } },
|
|
286
|
+
],
|
|
287
|
+
}],
|
|
288
|
+
max_tokens: config.maxTokens,
|
|
289
|
+
stream: false,
|
|
290
|
+
}),
|
|
291
|
+
})
|
|
292
|
+
if (!response.ok) return null
|
|
293
|
+
const json = await response.json()
|
|
294
|
+
const text = json?.choices?.[0]?.message?.content
|
|
295
|
+
return typeof text === 'string' && text.trim() ? text.trim() : null
|
|
296
|
+
} catch {
|
|
297
|
+
return null
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// ---------------------------------------------------------------------------
|
|
302
|
+
// read_image 变体
|
|
303
|
+
// ---------------------------------------------------------------------------
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* 构造 per-agent 的 `read_image` 变体定义:返回文字描述,不返回 image 块。
|
|
307
|
+
* @param ctx - 插件上下文(取 attachments 服务)。
|
|
308
|
+
* @param config - 插件配置。
|
|
309
|
+
*/
|
|
310
|
+
function createReadImageTool(ctx, config) {
|
|
311
|
+
return {
|
|
312
|
+
name: 'read_image',
|
|
313
|
+
description: TOOL_DESCRIPTION,
|
|
314
|
+
parameters: {
|
|
315
|
+
file_path: {
|
|
316
|
+
type: 'string',
|
|
317
|
+
required: true,
|
|
318
|
+
description: 'A path to an image file, or "attachment:sha256:<digest>" taken from an image placeholder.',
|
|
319
|
+
},
|
|
320
|
+
prompt: {
|
|
321
|
+
type: 'string',
|
|
322
|
+
description: 'Optional instruction for the vision model, e.g. "read all the text", "check the layout", '
|
|
323
|
+
+ '"describe the subject". Omit to use the deployment default prompt and the current user question.',
|
|
324
|
+
},
|
|
325
|
+
},
|
|
326
|
+
output: {
|
|
327
|
+
schema: {
|
|
328
|
+
type: 'object',
|
|
329
|
+
additionalProperties: false,
|
|
330
|
+
properties: {
|
|
331
|
+
path: { type: 'string' },
|
|
332
|
+
description: { type: 'string' },
|
|
333
|
+
},
|
|
334
|
+
// 标准 JSON Schema:`required` 必须是数组,不能写成属性级 `required: true`
|
|
335
|
+
// (后者会被 assertSupportedJsonSchema 拒绝,工具注册因此失败)。
|
|
336
|
+
required: ['path', 'description'],
|
|
337
|
+
},
|
|
338
|
+
// 工具结果的模型可见形态:只有文字描述,不携带 image 块。
|
|
339
|
+
render: (_args, value) => [{ type: 'text', text: value.description }],
|
|
340
|
+
},
|
|
341
|
+
// 读附件/本地文件,与目标机器无关。
|
|
342
|
+
environment: 'independent',
|
|
343
|
+
async execute(args, exec) {
|
|
344
|
+
const filePath = typeof args?.file_path === 'string' ? args.file_path.trim() : ''
|
|
345
|
+
if (filePath.length === 0) throw new Error('file_path must be a non-empty string')
|
|
346
|
+
const modelPrompt = typeof args?.prompt === 'string' ? args.prompt : ''
|
|
347
|
+
const attachments = ctx.get('attachments')
|
|
348
|
+
if (attachments === undefined) throw new Error('no attachment service is mounted')
|
|
349
|
+
|
|
350
|
+
// 1) 附件引用(占位符里的摘要 / 附件对象路径)。
|
|
351
|
+
const digest = digestFromPath(filePath)
|
|
352
|
+
if (digest !== undefined) {
|
|
353
|
+
const ref = findAttachmentRef(exec.agent?.session, digest)
|
|
354
|
+
if (ref === undefined) throw new Error(`no image attachment matches "${filePath}"`)
|
|
355
|
+
let stored
|
|
356
|
+
try {
|
|
357
|
+
stored = await attachments.readImage(ref, exec.signal)
|
|
358
|
+
} catch (error) {
|
|
359
|
+
throw new Error(`cannot read attachment "${filePath}": ${error instanceof Error ? error.message : String(error)}`)
|
|
360
|
+
}
|
|
361
|
+
const mediaType = stored.ref?.mediaType ?? ref.mediaType ?? 'image/png'
|
|
362
|
+
const description = await describeBytes(config, stored.data, mediaType, exec.signal, modelPrompt, latestUserQuestion(exec.agent?.session))
|
|
363
|
+
if (description === null) throw new Error('the vision model returned no description; check that the local vision server is running')
|
|
364
|
+
return { path: filePath, description }
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// 2) 普通文件路径:读出字节、落成附件(内容寻址幂等),再转述。
|
|
368
|
+
let bytes
|
|
369
|
+
try {
|
|
370
|
+
bytes = await readFile(filePath, { signal: exec.signal })
|
|
371
|
+
} catch (error) {
|
|
372
|
+
throw new Error(`cannot read "${filePath}": ${error instanceof Error ? error.message : String(error)}`)
|
|
373
|
+
}
|
|
374
|
+
const mediaType = sniffMediaType(bytes)
|
|
375
|
+
if (mediaType === undefined) throw new Error(`"${filePath}" is not a supported PNG/JPEG/WebP/GIF image`)
|
|
376
|
+
await attachments.saveImage({ data: new Uint8Array(bytes), mediaType, name: basename(filePath) })
|
|
377
|
+
const description = await describeBytes(config, bytes, mediaType, exec.signal, modelPrompt, latestUserQuestion(exec.agent?.session))
|
|
378
|
+
if (description === null) throw new Error('the vision model returned no description; check that the local vision server is running')
|
|
379
|
+
return { path: filePath, description }
|
|
380
|
+
},
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// ---------------------------------------------------------------------------
|
|
385
|
+
// 插件入口
|
|
386
|
+
// ---------------------------------------------------------------------------
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* 挂载视觉桥接:请求边界换占位文字,给目标路由的 agent 安装 read_image 变体。
|
|
390
|
+
* @param ctx - Cordis 上下文。
|
|
391
|
+
* @param config - 插件配置。
|
|
392
|
+
*/
|
|
393
|
+
export function apply(ctx, config) {
|
|
394
|
+
/** 配置不完整时插件 inert:什么都不注册,图像原样发往路由。 */
|
|
395
|
+
const settings = plainConfig(config)
|
|
396
|
+
const configured = () =>
|
|
397
|
+
Boolean(settings.baseUrl && settings.baseUrl.trim() && settings.model && settings.model.trim())
|
|
398
|
+
if (!configured()) return
|
|
399
|
+
|
|
400
|
+
const llm = ctx.get('llm')
|
|
401
|
+
const tool = createReadImageTool(ctx, settings)
|
|
402
|
+
/** 已经安装过变体的 agent;判定失败时不标记,便于模型切换后补装。 */
|
|
403
|
+
const installed = new WeakSet()
|
|
404
|
+
|
|
405
|
+
// --- 请求边界:包装 prepareCall,在 adapter 收到请求前替换 image 块 ---
|
|
406
|
+
if (llm !== undefined && typeof llm.prepareCall === 'function') {
|
|
407
|
+
const hadOwn = Object.hasOwn(llm, 'prepareCall')
|
|
408
|
+
const originalPrepare = llm.prepareCall
|
|
409
|
+
llm.prepareCall = async function prepareCallWithVisionBridge(callConfig, signal) {
|
|
410
|
+
const prepared = await originalPrepare.call(this, callConfig, signal)
|
|
411
|
+
if (prepared === undefined) return prepared
|
|
412
|
+
if (!(await isTargetSelection(callConfig.provider, callConfig.model, settings, this, signal))) return prepared
|
|
413
|
+
return {
|
|
414
|
+
...prepared,
|
|
415
|
+
stream: options => prepared.stream(withTextPlaceholders(options)),
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
// 插件卸载时恢复原方法,避免留下失效包装。
|
|
419
|
+
ctx.effect(() => () => {
|
|
420
|
+
if (hadOwn) llm.prepareCall = originalPrepare
|
|
421
|
+
else delete llm.prepareCall
|
|
422
|
+
}, 'vision-bridge.prepareCall')
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/** 为目标 agent 安装 read_image 变体与读图约定(同步、幂等)。 */
|
|
426
|
+
function install(agent) {
|
|
427
|
+
if (installed.has(agent)) return true
|
|
428
|
+
try {
|
|
429
|
+
if (agent.ctx.get('tools') === undefined) return false
|
|
430
|
+
try {
|
|
431
|
+
agent.ctx.tools.register(tool)
|
|
432
|
+
} catch {
|
|
433
|
+
// 同 scope 已有同名注册时静默跳过。
|
|
434
|
+
}
|
|
435
|
+
try {
|
|
436
|
+
agent.ctx.inject(['systemPrompt'], (scoped) => {
|
|
437
|
+
scoped.effect(
|
|
438
|
+
() => scoped.systemPrompt.section({
|
|
439
|
+
name: 'vision-bridge',
|
|
440
|
+
order: 900,
|
|
441
|
+
text: PROMPT_GUIDE,
|
|
442
|
+
}),
|
|
443
|
+
'vision-bridge.prompt-section',
|
|
444
|
+
)
|
|
445
|
+
})
|
|
446
|
+
} catch {
|
|
447
|
+
// 没有 systemPrompt 服务时仅保留工具变体。
|
|
448
|
+
}
|
|
449
|
+
installed.add(agent)
|
|
450
|
+
return true
|
|
451
|
+
} catch {
|
|
452
|
+
return false
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* 配置了 provider 名单时同步判定并安装:providers 判定是纯字符串比较,
|
|
458
|
+
* 所以 agent 创建阶段就能装好,首轮工具列表不会漏掉 read_image。
|
|
459
|
+
*/
|
|
460
|
+
function installIfListed(agent) {
|
|
461
|
+
if (installed.has(agent)) return true
|
|
462
|
+
if (settings.providers.length === 0) return false
|
|
463
|
+
const selection = agent.model?.current?.()
|
|
464
|
+
if (selection === undefined || !settings.providers.includes(selection.provider)) return false
|
|
465
|
+
return install(agent)
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/** 幂等地为目标 agent 安装变体;provider 名单为空时按路由声明的模态判定。 */
|
|
469
|
+
async function ensureInstalled(agent, signal) {
|
|
470
|
+
if (installed.has(agent)) return
|
|
471
|
+
if (installIfListed(agent)) return
|
|
472
|
+
if (settings.providers.length > 0) return
|
|
473
|
+
try {
|
|
474
|
+
if (!(await isTargetAgent(agent, settings, llm, signal))) return
|
|
475
|
+
install(agent)
|
|
476
|
+
} catch {
|
|
477
|
+
// 任何意外都不影响会话继续运行。
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// 新建/恢复会话时立即判定(名单命中时同步装好);模型选择在会话中途切换时由 pre-step 补装。
|
|
482
|
+
ctx.on('agent/created', ({ agent, signal }) => {
|
|
483
|
+
if (installIfListed(agent)) return undefined
|
|
484
|
+
return ensureInstalled(agent, signal)
|
|
485
|
+
})
|
|
486
|
+
ctx.on('agent/pre-step', async (payload, next) => {
|
|
487
|
+
if (!installIfListed(payload.agent)) await ensureInstalled(payload.agent, payload.signal)
|
|
488
|
+
return next()
|
|
489
|
+
})
|
|
490
|
+
|
|
491
|
+
// 插件重载时,已存在的会话不会重新触发 agent/created:遍历补装一次。
|
|
492
|
+
try {
|
|
493
|
+
const agents = ctx.get('agents')
|
|
494
|
+
if (agents !== undefined && typeof agents.list === 'function') {
|
|
495
|
+
for (const agent of agents.list()) void ensureInstalled(agent)
|
|
496
|
+
}
|
|
497
|
+
} catch {
|
|
498
|
+
// agents 服务不可用时不补装,行为等同插件未启用。
|
|
499
|
+
}
|
|
500
|
+
}
|
package/lib/pure.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure helpers for the vision bridge: no Cordis, no services, no I/O.
|
|
3
|
+
* Kept separate so `node --test` can cover them without booting the Host.
|
|
4
|
+
*
|
|
5
|
+
* @module @wangpinglan/dsh-vision-bridge/lib/pure
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Sniff a supported image format from its leading bytes.
|
|
10
|
+
* Mirrors the formats the built-in `read_image` accepts.
|
|
11
|
+
* @param {Uint8Array} data - file bytes.
|
|
12
|
+
* @returns {'image/png'|'image/jpeg'|'image/webp'|'image/gif'|undefined} media type, or undefined when unsupported.
|
|
13
|
+
*/
|
|
14
|
+
export function sniffMediaType(data) {
|
|
15
|
+
if (data.length >= 8
|
|
16
|
+
&& data[0] === 0x89 && data[1] === 0x50 && data[2] === 0x4e && data[3] === 0x47) return 'image/png'
|
|
17
|
+
if (data.length >= 3 && data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) return 'image/jpeg'
|
|
18
|
+
if (data.length >= 6
|
|
19
|
+
&& data[0] === 0x47 && data[1] === 0x49 && data[2] === 0x46 && data[3] === 0x38) return 'image/gif'
|
|
20
|
+
if (data.length >= 12
|
|
21
|
+
&& data[0] === 0x52 && data[1] === 0x49 && data[2] === 0x46 && data[3] === 0x46
|
|
22
|
+
&& data[8] === 0x57 && data[9] === 0x45 && data[10] === 0x42 && data[11] === 0x50) return 'image/webp'
|
|
23
|
+
return undefined
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Extract an attachment digest from a model-supplied `file_path`.
|
|
28
|
+
* Accepts `attachment:sha256:<8~64 hex>`, `sha256:<8~64 hex>`, and the
|
|
29
|
+
* content-addressed object path `.../objects/<xx>/<64 hex>`.
|
|
30
|
+
* @param {unknown} filePath - raw argument value.
|
|
31
|
+
* @returns {string|undefined} hex digest prefix, or undefined for a plain file path.
|
|
32
|
+
*/
|
|
33
|
+
export function digestFromPath(filePath) {
|
|
34
|
+
if (typeof filePath !== 'string') return undefined
|
|
35
|
+
const value = filePath.trim()
|
|
36
|
+
const attachment = /^attachment:(?:sha256:)?([a-f0-9]{8,64})$/u.exec(value)
|
|
37
|
+
if (attachment !== null) return attachment[1]
|
|
38
|
+
const brand = /^sha256:([a-f0-9]{8,64})$/u.exec(value)
|
|
39
|
+
if (brand !== null) return brand[1]
|
|
40
|
+
const object = /(?:^|[/\\])objects[/\\][a-f0-9]{2}[/\\]([a-f0-9]{64})$/u.exec(value)
|
|
41
|
+
if (object !== null) return object[1]
|
|
42
|
+
return undefined
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Model-facing placeholder for one image occurrence.
|
|
47
|
+
* @param {{ attachmentId?: unknown }} ref - attachment reference carried by the image block.
|
|
48
|
+
* @returns {string} placeholder text.
|
|
49
|
+
*/
|
|
50
|
+
export function placeholderText(ref) {
|
|
51
|
+
const id = String(ref?.attachmentId ?? 'sha256:unknown')
|
|
52
|
+
return `[image omitted because this model cannot decode images directly. ` +
|
|
53
|
+
`attachment ${id}. To view its content, call read_image with file_path "attachment:${id}".]`
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Replace every image content block with a text placeholder.
|
|
58
|
+
* Returns the original inputs when no message carries an image.
|
|
59
|
+
* @param {readonly { content?: readonly { type?: string }[] }[]} messages - request messages.
|
|
60
|
+
* @returns {{ messages: readonly unknown[], changed: boolean }} copied messages and whether anything changed.
|
|
61
|
+
*/
|
|
62
|
+
export function replaceImagesWithPlaceholders(messages) {
|
|
63
|
+
if (!Array.isArray(messages)) return { messages, changed: false }
|
|
64
|
+
let changed = false
|
|
65
|
+
const next = messages.map((message) => {
|
|
66
|
+
const content = Array.isArray(message?.content) ? message.content : undefined
|
|
67
|
+
if (content === undefined) return message
|
|
68
|
+
let mutated = false
|
|
69
|
+
const blocks = content.map((block) => {
|
|
70
|
+
if (block?.type !== 'image') return block
|
|
71
|
+
mutated = true
|
|
72
|
+
return { type: 'text', text: placeholderText(block.attachment) }
|
|
73
|
+
})
|
|
74
|
+
if (!mutated) return message
|
|
75
|
+
changed = true
|
|
76
|
+
return { ...message, content: blocks }
|
|
77
|
+
})
|
|
78
|
+
return { messages: changed ? next : messages, changed }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* 组装发给视觉模型的指令与上下文。
|
|
83
|
+
* 模型自己传了 prompt 就完全按它的来;否则用部署默认(或内置默认),并附上用户当前的问题。
|
|
84
|
+
* @param {string|undefined} configPrompt 部署默认提示词,可为空。
|
|
85
|
+
* @param {string|undefined} modelPrompt 调用方(read_image)传入的提示词,可为空。
|
|
86
|
+
* @param {string|undefined} userContext 用户当前的问题,仅在没有模型提示词时使用。
|
|
87
|
+
* @param {string} defaultPrompt 内置兜底提示词。
|
|
88
|
+
* @returns {{ instruction: string, context: string }}
|
|
89
|
+
*/
|
|
90
|
+
export function buildVisionInstruction(configPrompt, modelPrompt, userContext, defaultPrompt) {
|
|
91
|
+
const model = typeof modelPrompt === 'string' ? modelPrompt.trim() : ''
|
|
92
|
+
if (model.length > 0) return { instruction: model, context: '' }
|
|
93
|
+
const configured = typeof configPrompt === 'string' ? configPrompt.trim() : ''
|
|
94
|
+
const instruction = configured.length > 0 ? configured : defaultPrompt
|
|
95
|
+
const context = typeof userContext === 'string' ? userContext.trim() : ''
|
|
96
|
+
return { instruction, context }
|
|
97
|
+
}
|
package/locale/en.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "Vision bridge",
|
|
4
|
+
"description": "Let a text-only model read images on demand through read_image: an external OpenAI-compatible vision model produces the description, while the image stays as a thumbnail in the conversation.",
|
|
5
|
+
"detail": "docs/DETAIL.md"
|
|
6
|
+
}
|
|
7
|
+
}
|