@fish-under-sea/dsh-visual-companion 0.1.2 → 0.1.4
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 +143 -143
- package/bin/visual-companion.mjs +248 -248
- package/cordis.patch.yml +18 -18
- package/lib/index.js +323 -323
- package/lib/message.js +42 -42
- package/package.json +74 -69
- package/README.md.bak-20261005-232506 +0 -132
- package/lib/index.js.bak-20261005-231756 +0 -229
package/lib/index.js
CHANGED
|
@@ -1,324 +1,324 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @fish-under-sea/dsh-visual-companion —— 视觉伴侣唤醒插件(host-only)
|
|
3
|
-
*
|
|
4
|
-
* 唯一职责:观察视觉伴侣目录里的 `state/pending.json`(由配套的本地服务
|
|
5
|
-
* `visual-companion.mjs` 在用户按下「提交给助手」时写入),一有新的提交就给
|
|
6
|
-
* **目标会话**投一条用户消息并起一轮,于是「网页上点完就继续」,
|
|
7
|
-
* 用户不必回到终端把选择再复述一遍。
|
|
8
|
-
*
|
|
9
|
-
* 唤醒优先级(逐个 try,返回真正成功的那条):
|
|
10
|
-
* 1. `agent.followup(createUserMessage(...))` —— 与斜杠命令注入用户消息同一条公开路径;
|
|
11
|
-
* 2. `agent.steer(...)` —— 目标正在跑时;
|
|
12
|
-
* 3. `ctx.subagents[Symbol.for('dsh.subagent.deliverPrompt' | 'queuePrompt')]` ——
|
|
13
|
-
* 可续期子代理的宿主内部投递钩子(协议与 AgentTeams 的 harness-compat 一致)。
|
|
14
|
-
*
|
|
15
|
-
* 设计取舍:
|
|
16
|
-
* - host-only,不声明 `dsh.client`,不注册前端;
|
|
17
|
-
* - 配置只有 `watchDir`:非空则加载即自动绑定(配置热重载/重启后不会掉绑定);
|
|
18
|
-
* - 目标会话由 `pending.json` 自带(服务端 `--session` 写入),不在配置里钉死;
|
|
19
|
-
* - 长生命周期资源(fs watcher)归当前 fiber,插件卸载即释放。
|
|
20
|
-
*
|
|
21
|
-
* @module @fish-under-sea/dsh-visual-companion
|
|
22
|
-
*/
|
|
23
|
-
import { spawn } from 'node:child_process'
|
|
24
|
-
import { watch } from 'node:fs'
|
|
25
|
-
import { mkdir, readFile } from 'node:fs/promises'
|
|
26
|
-
import { basename, join } from 'node:path'
|
|
27
|
-
import { fileURLToPath } from 'node:url'
|
|
28
|
-
|
|
29
|
-
import { createUserMessage } from '@deepseek-ai/dsh-llm'
|
|
30
|
-
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
31
|
-
import z from '@deepseek-ai/schemastery'
|
|
32
|
-
|
|
33
|
-
import { companionMessage } from './message.js'
|
|
34
|
-
|
|
35
|
-
export { companionMessage }
|
|
36
|
-
|
|
37
|
-
export const name = 'visual-companion'
|
|
38
|
-
export const inject = ['tools', 'commands']
|
|
39
|
-
|
|
40
|
-
/** 与 AgentTeams `harness-compat` 相同的进程稳定符号(宿主内部子代理投递协议)。 */
|
|
41
|
-
const hostPromptQueue = Symbol.for('dsh.subagent.queuePrompt')
|
|
42
|
-
const hostPromptDeliver = Symbol.for('dsh.subagent.deliverPrompt')
|
|
43
|
-
|
|
44
|
-
/** 插件配置:`watchDir` 非空时加载即自动绑定。 */
|
|
45
|
-
export const Config = z.object({
|
|
46
|
-
watchDir: z.string().default(''),
|
|
47
|
-
})
|
|
48
|
-
|
|
49
|
-
/** 当前绑定(单绑定:一个进程同时只服务一个视觉伴侣目录)。 */
|
|
50
|
-
const state = {
|
|
51
|
-
dir: null,
|
|
52
|
-
sessionId: null,
|
|
53
|
-
watcher: null,
|
|
54
|
-
lastFingerprint: null,
|
|
55
|
-
lastWake: null,
|
|
56
|
-
wakeCount: 0,
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
const clean = (v) => String(v ?? '').replace(/\s+/g, ' ').trim()
|
|
60
|
-
|
|
61
|
-
function userMessage(text) {
|
|
62
|
-
return createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } })
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
function agentsRegistry(ctx) {
|
|
66
|
-
const registry = ctx.get('agents')
|
|
67
|
-
return registry !== undefined && typeof registry.get === 'function' ? registry : undefined
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
/** 尝试把一条消息投进目标会话并起一轮;返回成功的策略。 */
|
|
71
|
-
async function wake(ctx, sessionId, text) {
|
|
72
|
-
const attempts = []
|
|
73
|
-
const registry = agentsRegistry(ctx)
|
|
74
|
-
if (registry === undefined) throw new Error('agents 服务不可用:无法按 sessionId 找到会话')
|
|
75
|
-
const target = registry.get(sessionId)
|
|
76
|
-
if (target === undefined) throw new Error(`找不到会话 ${sessionId} 的 live agent`)
|
|
77
|
-
|
|
78
|
-
const tryOne = async (label, fn) => {
|
|
79
|
-
try {
|
|
80
|
-
const result = await fn()
|
|
81
|
-
return { ok: true, label, messageId: result === undefined ? '' : String(result) }
|
|
82
|
-
} catch (error) {
|
|
83
|
-
attempts.push(`${label}: ${String(error?.message ?? error)}`)
|
|
84
|
-
return { ok: false, label }
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
const followup = await tryOne('agent.followup', () => target.followup(userMessage(text)))
|
|
89
|
-
if (followup.ok) return { ...followup, attempts }
|
|
90
|
-
const steer = await tryOne('agent.steer', () => target.steer(userMessage(text)))
|
|
91
|
-
if (steer.ok) return { ...steer, attempts }
|
|
92
|
-
|
|
93
|
-
const subagents = ctx.get('subagents')
|
|
94
|
-
const deliver = subagents?.[hostPromptDeliver]
|
|
95
|
-
const queue = subagents?.[hostPromptQueue]
|
|
96
|
-
const content = [{ type: 'text', text }]
|
|
97
|
-
const signal = AbortSignal.timeout(15_000)
|
|
98
|
-
if (typeof deliver === 'function') {
|
|
99
|
-
const r = await tryOne('subagents.deliverPrompt(queue)', () => deliver(target, sessionId, content, { kind: 'user' }, signal, 'queue'))
|
|
100
|
-
if (r.ok) return { ...r, attempts }
|
|
101
|
-
}
|
|
102
|
-
if (typeof queue === 'function') {
|
|
103
|
-
const r = await tryOne('subagents.queuePrompt', () => queue(target, sessionId, content, { kind: 'user' }, signal))
|
|
104
|
-
if (r.ok) return { ...r, attempts }
|
|
105
|
-
}
|
|
106
|
-
throw new Error(`所有唤醒策略都失败 → ${attempts.join(' | ')}`)
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
async function readPending(dir) {
|
|
110
|
-
try {
|
|
111
|
-
const parsed = JSON.parse(await readFile(join(dir, 'state', 'pending.json'), 'utf8'))
|
|
112
|
-
return parsed !== null && typeof parsed === 'object' ? parsed : undefined
|
|
113
|
-
} catch {
|
|
114
|
-
return undefined
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
function fingerprintOf(pending) {
|
|
119
|
-
return `${pending.ts ?? ''}|${pending.at ?? ''}|${pending.choice ?? ''}|${pending.text ?? ''}|${JSON.stringify(pending.selections ?? '')}|${pending.note ?? ''}`
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
async function handleSubmit(ctx, pending) {
|
|
123
|
-
const fp = fingerprintOf(pending)
|
|
124
|
-
if (fp === state.lastFingerprint) return
|
|
125
|
-
state.lastFingerprint = fp
|
|
126
|
-
const sessionId = pending.sessionId === undefined ? state.sessionId : String(pending.sessionId)
|
|
127
|
-
if (sessionId === null || sessionId === '') {
|
|
128
|
-
state.lastWake = { ok: false, detail: '未绑定 sessionId,无法唤醒' }
|
|
129
|
-
return
|
|
130
|
-
}
|
|
131
|
-
try {
|
|
132
|
-
const result = await wake(ctx, sessionId, companionMessage(pending))
|
|
133
|
-
state.wakeCount += 1
|
|
134
|
-
state.lastWake = { ok: true, detail: `${result.label} → message ${result.messageId || '(unknown id)'}` }
|
|
135
|
-
ctx.logger?.info?.(`visual-companion: 唤醒 ${sessionId} 成功(${result.label})`)
|
|
136
|
-
} catch (error) {
|
|
137
|
-
state.lastWake = { ok: false, detail: String(error?.message ?? error) }
|
|
138
|
-
ctx.logger?.warn?.(`visual-companion: 唤醒 ${sessionId} 失败:${state.lastWake.detail}`)
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
function arm(ctx, dir, sessionId) {
|
|
143
|
-
state.watcher?.close?.()
|
|
144
|
-
state.dir = dir
|
|
145
|
-
state.sessionId = sessionId
|
|
146
|
-
state.lastFingerprint = null
|
|
147
|
-
const watchDir = join(dir, 'state')
|
|
148
|
-
state.watcher = watch(watchDir, { persistent: false }, (_event, filename) => {
|
|
149
|
-
if (filename !== null && basename(String(filename)) !== 'pending.json') return
|
|
150
|
-
void readPending(dir).then((pending) => (pending === undefined ? undefined : handleSubmit(ctx, pending)))
|
|
151
|
-
})
|
|
152
|
-
state.watcher.on?.('error', (error) => ctx.logger?.warn?.(`visual-companion: 观察 ${watchDir} 出错:${String(error)}`))
|
|
153
|
-
ctx.logger?.info?.(`visual-companion: 已绑定 ${watchDir}/pending.json → 会话 ${sessionId ?? '(由 pending.json 自带)'}`)
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
function disarm() {
|
|
157
|
-
state.watcher?.close?.()
|
|
158
|
-
state.watcher = null
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
function registerTool(ctx) {
|
|
162
|
-
ctx.tools.register(defineTool({
|
|
163
|
-
name: 'visual_companion',
|
|
164
|
-
description: '视觉伴侣唤醒开关。arm 绑定一个视觉伴侣目录(观察其中的 state/pending.json)与目标会话;之后用户在页面上提交选择时,会直接给该会话投一条用户消息并起一轮,无需他回终端复述。disarm 解绑;status 查看绑定与最近一次唤醒结果;wake 立刻用给定文本探测唤醒链路(验证用)。',
|
|
165
|
-
parameters: {
|
|
166
|
-
action: { type: 'string', required: true, enum: ['arm', 'disarm', 'status', 'wake'], description: '要执行的动作。' },
|
|
167
|
-
dir: { type: 'string', description: 'arm 用:视觉伴侣根目录(内含 state/pending.json)。' },
|
|
168
|
-
session_id: { type: 'string', description: 'arm/wake 用:要唤醒的会话 id;arm 时可省略,之后由 pending.json 自带。' },
|
|
169
|
-
text: { type: 'string', description: 'wake 用:投递的文本。' },
|
|
170
|
-
},
|
|
171
|
-
output: {
|
|
172
|
-
schema: {
|
|
173
|
-
type: 'object',
|
|
174
|
-
additionalProperties: false,
|
|
175
|
-
properties: {
|
|
176
|
-
status: { type: 'string', required: true },
|
|
177
|
-
detail: { type: 'string' },
|
|
178
|
-
},
|
|
179
|
-
},
|
|
180
|
-
render: (_args, value) => [{ type: 'text', text: `${value.status}${value.detail === undefined ? '' : ` — ${value.detail}`}` }],
|
|
181
|
-
},
|
|
182
|
-
async execute(args) {
|
|
183
|
-
if (args.action === 'arm') {
|
|
184
|
-
const dir = clean(args.dir)
|
|
185
|
-
if (dir === '') return { status: 'arm 失败', detail: '需要 dir' }
|
|
186
|
-
arm(ctx, dir, args.session_id === undefined || clean(args.session_id) === '' ? null : clean(args.session_id))
|
|
187
|
-
return { status: '已绑定', detail: `${dir}/state/pending.json → ${state.sessionId ?? '(由 pending.json 自带 sessionId)'}` }
|
|
188
|
-
}
|
|
189
|
-
if (args.action === 'disarm') {
|
|
190
|
-
disarm()
|
|
191
|
-
return { status: '已解绑' }
|
|
192
|
-
}
|
|
193
|
-
if (args.action === 'wake') {
|
|
194
|
-
const sessionId = clean(args.session_id) || clean(state.sessionId)
|
|
195
|
-
const text = clean(args.text) === '' ? '【视觉伴侣】唤醒链路自检。' : clean(args.text)
|
|
196
|
-
if (sessionId === '') return { status: 'wake 失败', detail: '需要 session_id' }
|
|
197
|
-
try {
|
|
198
|
-
const result = await wake(ctx, sessionId, text)
|
|
199
|
-
state.wakeCount += 1
|
|
200
|
-
state.lastWake = { ok: true, detail: `${result.label} → message ${result.messageId || '(unknown id)'}` }
|
|
201
|
-
return { status: '唤醒成功', detail: `${sessionId} via ${result.label}(messageId=${result.messageId || 'unknown'})` }
|
|
202
|
-
} catch (error) {
|
|
203
|
-
const detail = String(error?.message ?? error)
|
|
204
|
-
state.lastWake = { ok: false, detail }
|
|
205
|
-
return { status: '唤醒失败', detail }
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
const pending = state.dir === null ? undefined : await readPending(state.dir)
|
|
209
|
-
return {
|
|
210
|
-
status: state.watcher === null ? '未绑定' : '已绑定',
|
|
211
|
-
detail: [
|
|
212
|
-
`dir=${state.dir ?? '(none)'}`,
|
|
213
|
-
`session=${state.sessionId ?? '(from pending)'}`,
|
|
214
|
-
`wakes=${state.wakeCount}`,
|
|
215
|
-
`last=${state.lastWake === null ? '(none)' : `${state.lastWake.ok ? 'ok' : 'fail'}: ${state.lastWake.detail}`}`,
|
|
216
|
-
`pending=${pending === undefined ? '(none)' : JSON.stringify(pending).slice(0, 120)}`,
|
|
217
|
-
].join(' | '),
|
|
218
|
-
}
|
|
219
|
-
},
|
|
220
|
-
}))
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
/** 斜杠命令名:`/companion`。 */
|
|
224
|
-
const COMPANION_COMMAND = 'companion'
|
|
225
|
-
|
|
226
|
-
/** 被本插件拉起的服务进程(卸载时收尸;复用已有服务时保持 null)。 */
|
|
227
|
-
let spawnedService = null
|
|
228
|
-
|
|
229
|
-
/** 本地伴侣服务脚本(随本包发布)。 */
|
|
230
|
-
function companionBin() {
|
|
231
|
-
return fileURLToPath(new URL('../bin/visual-companion.mjs', import.meta.url))
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
/** 伴侣根目录:配置了 watchDir 就用它,否则退回工作区下的 .dsh-visual。 */
|
|
235
|
-
function companionDir(config) {
|
|
236
|
-
const configured = clean(config?.watchDir)
|
|
237
|
-
return configured === '' ? join(process.cwd(), '.dsh-visual') : configured
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
async function readServerInfo(dir) {
|
|
241
|
-
try {
|
|
242
|
-
const parsed = JSON.parse(await readFile(join(dir, 'state', 'server-info'), 'utf8'))
|
|
243
|
-
return parsed !== null && typeof parsed === 'object' ? parsed : undefined
|
|
244
|
-
} catch {
|
|
245
|
-
return undefined
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
/** 服务没在跑就后台拉起(零依赖、detached、丢弃 stdio),并等它写出 server-info。 */
|
|
250
|
-
async function ensureService(ctx, dir, sessionId) {
|
|
251
|
-
const existing = await readServerInfo(dir)
|
|
252
|
-
if (existing?.url !== undefined) return existing
|
|
253
|
-
await mkdir(join(dir, 'screen'), { recursive: true })
|
|
254
|
-
await mkdir(join(dir, 'state'), { recursive: true })
|
|
255
|
-
const args = [companionBin(), '--dir', dir, '--port', '0']
|
|
256
|
-
if (sessionId !== '') args.push('--session', sessionId)
|
|
257
|
-
const child = spawn(process.execPath, args, { detached: true, stdio: 'ignore' })
|
|
258
|
-
child.unref()
|
|
259
|
-
spawnedService = child
|
|
260
|
-
ctx.logger?.info?.(`visual-companion: 已拉起伴侣服务(pid=${child.pid ?? '?'},dir=${dir})`)
|
|
261
|
-
for (let i = 0; i < 24; i += 1) {
|
|
262
|
-
const info = await readServerInfo(dir)
|
|
263
|
-
if (info?.url !== undefined) return info
|
|
264
|
-
await new Promise((resolve) => setTimeout(resolve, 250))
|
|
265
|
-
}
|
|
266
|
-
return undefined
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
/** 把服务打印的 url 与 key 拼成可直接打开的完整地址。 */
|
|
270
|
-
function withKey(info) {
|
|
271
|
-
const url = String(info?.url ?? '')
|
|
272
|
-
const key = String(info?.key ?? '')
|
|
273
|
-
if (url === '' || key === '' || url.includes('key=')) return url
|
|
274
|
-
return `${url}${url.includes('?') ? '&' : '?'}key=${encodeURIComponent(key)}`
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
/**
|
|
278
|
-
* 注册 `/companion`:起服务并让当前会话的助手接手。
|
|
279
|
-
* 服务只负责写文件;「绑观察器」与「开右侧栏」交给会话里的助手(它有 sidebar_open 与
|
|
280
|
-
* visual_companion 工具,且能从自己的 $env:DSH_SESSION_ID 拿到本会话 id)。
|
|
281
|
-
*/
|
|
282
|
-
function registerCommand(ctx, config) {
|
|
283
|
-
ctx.commands.register({
|
|
284
|
-
name: COMPANION_COMMAND,
|
|
285
|
-
description: '
|
|
286
|
-
input: { hint: '[<想看的主题>]' },
|
|
287
|
-
async handler(invocation) {
|
|
288
|
-
const dir = companionDir(config)
|
|
289
|
-
const sessionId = clean(invocation?.agent?.sessionId ?? invocation?.agent?.id ?? '')
|
|
290
|
-
let info
|
|
291
|
-
try {
|
|
292
|
-
info = await ensureService(ctx, dir, sessionId)
|
|
293
|
-
} catch (error) {
|
|
294
|
-
return { kind: 'error', text: `视觉伴侣启动失败:${String(error?.message ?? error)}` }
|
|
295
|
-
}
|
|
296
|
-
if (info === undefined) {
|
|
297
|
-
return { kind: 'error', text: `伴侣服务未就绪(没有写出 ${join(dir, 'state', 'server-info')});可手动运行 bin/visual-companion.mjs 后重试` }
|
|
298
|
-
}
|
|
299
|
-
const url = withKey(info)
|
|
300
|
-
if (state.dir !== dir || state.watcher === null) arm(ctx, dir, sessionId === '' ? null : sessionId)
|
|
301
|
-
const topic = clean(invocation?.rawInput)
|
|
302
|
-
invocation?.agent?.followup?.(userMessage([
|
|
303
|
-
`【视觉伴侣】本地服务已就绪:${url}`,
|
|
304
|
-
`请接着做三件事:① 用 sidebar_open 把这个 URL 开在右侧栏;② 用 visual_companion({action:"arm", dir:"${dir}", session_id:"<本会话 id>"}) 绑上观察器(本会话 id 读 $env:DSH_SESSION_ID;若这个服务绑的是别的会话,重启它并带 --session);③ 把${topic === '' ? '要看的原型' : `「${topic}」的原型`}写成 HTML 片段放进 ${join(dir, 'screen')} 目录。`,
|
|
305
|
-
'用户点选并按「提交给助手」后,你会自动收到消息,不必让他回终端复述。',
|
|
306
|
-
].join('\n')))
|
|
307
|
-
return { kind: 'success', text: `视觉伴侣已就绪:${url}(已让助手打开右侧栏并准备第一屏)` }
|
|
308
|
-
},
|
|
309
|
-
})
|
|
310
|
-
}
|
|
311
|
-
export function apply(ctx, config) {
|
|
312
|
-
registerTool(ctx)
|
|
313
|
-
registerCommand(ctx, config)
|
|
314
|
-
// 长生命周期资源归当前 fiber:插件卸载时关闭 watcher 与本插件拉起的服务。
|
|
315
|
-
ctx.effect(() => () => {
|
|
316
|
-
spawnedService?.kill?.()
|
|
317
|
-
spawnedService = null
|
|
318
|
-
disarm()
|
|
319
|
-
})
|
|
320
|
-
const watchDir = clean(config?.watchDir)
|
|
321
|
-
// 目标会话不在这里钉死:由 pending.json 自带(伴侣服务用 --session 写入)。
|
|
322
|
-
if (watchDir !== '') arm(ctx, watchDir, null)
|
|
323
|
-
ctx.logger?.info?.(`visual-companion: 已加载(v0.1.2)${watchDir === '' ? ',未自动绑定' : `,自动绑定 ${watchDir}`}`)
|
|
1
|
+
/**
|
|
2
|
+
* @fish-under-sea/dsh-visual-companion —— 视觉伴侣唤醒插件(host-only)
|
|
3
|
+
*
|
|
4
|
+
* 唯一职责:观察视觉伴侣目录里的 `state/pending.json`(由配套的本地服务
|
|
5
|
+
* `visual-companion.mjs` 在用户按下「提交给助手」时写入),一有新的提交就给
|
|
6
|
+
* **目标会话**投一条用户消息并起一轮,于是「网页上点完就继续」,
|
|
7
|
+
* 用户不必回到终端把选择再复述一遍。
|
|
8
|
+
*
|
|
9
|
+
* 唤醒优先级(逐个 try,返回真正成功的那条):
|
|
10
|
+
* 1. `agent.followup(createUserMessage(...))` —— 与斜杠命令注入用户消息同一条公开路径;
|
|
11
|
+
* 2. `agent.steer(...)` —— 目标正在跑时;
|
|
12
|
+
* 3. `ctx.subagents[Symbol.for('dsh.subagent.deliverPrompt' | 'queuePrompt')]` ——
|
|
13
|
+
* 可续期子代理的宿主内部投递钩子(协议与 AgentTeams 的 harness-compat 一致)。
|
|
14
|
+
*
|
|
15
|
+
* 设计取舍:
|
|
16
|
+
* - host-only,不声明 `dsh.client`,不注册前端;
|
|
17
|
+
* - 配置只有 `watchDir`:非空则加载即自动绑定(配置热重载/重启后不会掉绑定);
|
|
18
|
+
* - 目标会话由 `pending.json` 自带(服务端 `--session` 写入),不在配置里钉死;
|
|
19
|
+
* - 长生命周期资源(fs watcher)归当前 fiber,插件卸载即释放。
|
|
20
|
+
*
|
|
21
|
+
* @module @fish-under-sea/dsh-visual-companion
|
|
22
|
+
*/
|
|
23
|
+
import { spawn } from 'node:child_process'
|
|
24
|
+
import { watch } from 'node:fs'
|
|
25
|
+
import { mkdir, readFile } from 'node:fs/promises'
|
|
26
|
+
import { basename, join } from 'node:path'
|
|
27
|
+
import { fileURLToPath } from 'node:url'
|
|
28
|
+
|
|
29
|
+
import { createUserMessage } from '@deepseek-ai/dsh-llm'
|
|
30
|
+
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
31
|
+
import z from '@deepseek-ai/schemastery'
|
|
32
|
+
|
|
33
|
+
import { companionMessage } from './message.js'
|
|
34
|
+
|
|
35
|
+
export { companionMessage }
|
|
36
|
+
|
|
37
|
+
export const name = 'visual-companion'
|
|
38
|
+
export const inject = ['tools', 'commands']
|
|
39
|
+
|
|
40
|
+
/** 与 AgentTeams `harness-compat` 相同的进程稳定符号(宿主内部子代理投递协议)。 */
|
|
41
|
+
const hostPromptQueue = Symbol.for('dsh.subagent.queuePrompt')
|
|
42
|
+
const hostPromptDeliver = Symbol.for('dsh.subagent.deliverPrompt')
|
|
43
|
+
|
|
44
|
+
/** 插件配置:`watchDir` 非空时加载即自动绑定。 */
|
|
45
|
+
export const Config = z.object({
|
|
46
|
+
watchDir: z.string().default(''),
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
/** 当前绑定(单绑定:一个进程同时只服务一个视觉伴侣目录)。 */
|
|
50
|
+
const state = {
|
|
51
|
+
dir: null,
|
|
52
|
+
sessionId: null,
|
|
53
|
+
watcher: null,
|
|
54
|
+
lastFingerprint: null,
|
|
55
|
+
lastWake: null,
|
|
56
|
+
wakeCount: 0,
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const clean = (v) => String(v ?? '').replace(/\s+/g, ' ').trim()
|
|
60
|
+
|
|
61
|
+
function userMessage(text) {
|
|
62
|
+
return createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } })
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function agentsRegistry(ctx) {
|
|
66
|
+
const registry = ctx.get('agents')
|
|
67
|
+
return registry !== undefined && typeof registry.get === 'function' ? registry : undefined
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 尝试把一条消息投进目标会话并起一轮;返回成功的策略。 */
|
|
71
|
+
async function wake(ctx, sessionId, text) {
|
|
72
|
+
const attempts = []
|
|
73
|
+
const registry = agentsRegistry(ctx)
|
|
74
|
+
if (registry === undefined) throw new Error('agents 服务不可用:无法按 sessionId 找到会话')
|
|
75
|
+
const target = registry.get(sessionId)
|
|
76
|
+
if (target === undefined) throw new Error(`找不到会话 ${sessionId} 的 live agent`)
|
|
77
|
+
|
|
78
|
+
const tryOne = async (label, fn) => {
|
|
79
|
+
try {
|
|
80
|
+
const result = await fn()
|
|
81
|
+
return { ok: true, label, messageId: result === undefined ? '' : String(result) }
|
|
82
|
+
} catch (error) {
|
|
83
|
+
attempts.push(`${label}: ${String(error?.message ?? error)}`)
|
|
84
|
+
return { ok: false, label }
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const followup = await tryOne('agent.followup', () => target.followup(userMessage(text)))
|
|
89
|
+
if (followup.ok) return { ...followup, attempts }
|
|
90
|
+
const steer = await tryOne('agent.steer', () => target.steer(userMessage(text)))
|
|
91
|
+
if (steer.ok) return { ...steer, attempts }
|
|
92
|
+
|
|
93
|
+
const subagents = ctx.get('subagents')
|
|
94
|
+
const deliver = subagents?.[hostPromptDeliver]
|
|
95
|
+
const queue = subagents?.[hostPromptQueue]
|
|
96
|
+
const content = [{ type: 'text', text }]
|
|
97
|
+
const signal = AbortSignal.timeout(15_000)
|
|
98
|
+
if (typeof deliver === 'function') {
|
|
99
|
+
const r = await tryOne('subagents.deliverPrompt(queue)', () => deliver(target, sessionId, content, { kind: 'user' }, signal, 'queue'))
|
|
100
|
+
if (r.ok) return { ...r, attempts }
|
|
101
|
+
}
|
|
102
|
+
if (typeof queue === 'function') {
|
|
103
|
+
const r = await tryOne('subagents.queuePrompt', () => queue(target, sessionId, content, { kind: 'user' }, signal))
|
|
104
|
+
if (r.ok) return { ...r, attempts }
|
|
105
|
+
}
|
|
106
|
+
throw new Error(`所有唤醒策略都失败 → ${attempts.join(' | ')}`)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function readPending(dir) {
|
|
110
|
+
try {
|
|
111
|
+
const parsed = JSON.parse(await readFile(join(dir, 'state', 'pending.json'), 'utf8'))
|
|
112
|
+
return parsed !== null && typeof parsed === 'object' ? parsed : undefined
|
|
113
|
+
} catch {
|
|
114
|
+
return undefined
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function fingerprintOf(pending) {
|
|
119
|
+
return `${pending.ts ?? ''}|${pending.at ?? ''}|${pending.choice ?? ''}|${pending.text ?? ''}|${JSON.stringify(pending.selections ?? '')}|${pending.note ?? ''}`
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function handleSubmit(ctx, pending) {
|
|
123
|
+
const fp = fingerprintOf(pending)
|
|
124
|
+
if (fp === state.lastFingerprint) return
|
|
125
|
+
state.lastFingerprint = fp
|
|
126
|
+
const sessionId = pending.sessionId === undefined ? state.sessionId : String(pending.sessionId)
|
|
127
|
+
if (sessionId === null || sessionId === '') {
|
|
128
|
+
state.lastWake = { ok: false, detail: '未绑定 sessionId,无法唤醒' }
|
|
129
|
+
return
|
|
130
|
+
}
|
|
131
|
+
try {
|
|
132
|
+
const result = await wake(ctx, sessionId, companionMessage(pending))
|
|
133
|
+
state.wakeCount += 1
|
|
134
|
+
state.lastWake = { ok: true, detail: `${result.label} → message ${result.messageId || '(unknown id)'}` }
|
|
135
|
+
ctx.logger?.info?.(`visual-companion: 唤醒 ${sessionId} 成功(${result.label})`)
|
|
136
|
+
} catch (error) {
|
|
137
|
+
state.lastWake = { ok: false, detail: String(error?.message ?? error) }
|
|
138
|
+
ctx.logger?.warn?.(`visual-companion: 唤醒 ${sessionId} 失败:${state.lastWake.detail}`)
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function arm(ctx, dir, sessionId) {
|
|
143
|
+
state.watcher?.close?.()
|
|
144
|
+
state.dir = dir
|
|
145
|
+
state.sessionId = sessionId
|
|
146
|
+
state.lastFingerprint = null
|
|
147
|
+
const watchDir = join(dir, 'state')
|
|
148
|
+
state.watcher = watch(watchDir, { persistent: false }, (_event, filename) => {
|
|
149
|
+
if (filename !== null && basename(String(filename)) !== 'pending.json') return
|
|
150
|
+
void readPending(dir).then((pending) => (pending === undefined ? undefined : handleSubmit(ctx, pending)))
|
|
151
|
+
})
|
|
152
|
+
state.watcher.on?.('error', (error) => ctx.logger?.warn?.(`visual-companion: 观察 ${watchDir} 出错:${String(error)}`))
|
|
153
|
+
ctx.logger?.info?.(`visual-companion: 已绑定 ${watchDir}/pending.json → 会话 ${sessionId ?? '(由 pending.json 自带)'}`)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function disarm() {
|
|
157
|
+
state.watcher?.close?.()
|
|
158
|
+
state.watcher = null
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function registerTool(ctx) {
|
|
162
|
+
ctx.tools.register(defineTool({
|
|
163
|
+
name: 'visual_companion',
|
|
164
|
+
description: '视觉伴侣唤醒开关。arm 绑定一个视觉伴侣目录(观察其中的 state/pending.json)与目标会话;之后用户在页面上提交选择时,会直接给该会话投一条用户消息并起一轮,无需他回终端复述。disarm 解绑;status 查看绑定与最近一次唤醒结果;wake 立刻用给定文本探测唤醒链路(验证用)。',
|
|
165
|
+
parameters: {
|
|
166
|
+
action: { type: 'string', required: true, enum: ['arm', 'disarm', 'status', 'wake'], description: '要执行的动作。' },
|
|
167
|
+
dir: { type: 'string', description: 'arm 用:视觉伴侣根目录(内含 state/pending.json)。' },
|
|
168
|
+
session_id: { type: 'string', description: 'arm/wake 用:要唤醒的会话 id;arm 时可省略,之后由 pending.json 自带。' },
|
|
169
|
+
text: { type: 'string', description: 'wake 用:投递的文本。' },
|
|
170
|
+
},
|
|
171
|
+
output: {
|
|
172
|
+
schema: {
|
|
173
|
+
type: 'object',
|
|
174
|
+
additionalProperties: false,
|
|
175
|
+
properties: {
|
|
176
|
+
status: { type: 'string', required: true },
|
|
177
|
+
detail: { type: 'string' },
|
|
178
|
+
},
|
|
179
|
+
},
|
|
180
|
+
render: (_args, value) => [{ type: 'text', text: `${value.status}${value.detail === undefined ? '' : ` — ${value.detail}`}` }],
|
|
181
|
+
},
|
|
182
|
+
async execute(args) {
|
|
183
|
+
if (args.action === 'arm') {
|
|
184
|
+
const dir = clean(args.dir)
|
|
185
|
+
if (dir === '') return { status: 'arm 失败', detail: '需要 dir' }
|
|
186
|
+
arm(ctx, dir, args.session_id === undefined || clean(args.session_id) === '' ? null : clean(args.session_id))
|
|
187
|
+
return { status: '已绑定', detail: `${dir}/state/pending.json → ${state.sessionId ?? '(由 pending.json 自带 sessionId)'}` }
|
|
188
|
+
}
|
|
189
|
+
if (args.action === 'disarm') {
|
|
190
|
+
disarm()
|
|
191
|
+
return { status: '已解绑' }
|
|
192
|
+
}
|
|
193
|
+
if (args.action === 'wake') {
|
|
194
|
+
const sessionId = clean(args.session_id) || clean(state.sessionId)
|
|
195
|
+
const text = clean(args.text) === '' ? '【视觉伴侣】唤醒链路自检。' : clean(args.text)
|
|
196
|
+
if (sessionId === '') return { status: 'wake 失败', detail: '需要 session_id' }
|
|
197
|
+
try {
|
|
198
|
+
const result = await wake(ctx, sessionId, text)
|
|
199
|
+
state.wakeCount += 1
|
|
200
|
+
state.lastWake = { ok: true, detail: `${result.label} → message ${result.messageId || '(unknown id)'}` }
|
|
201
|
+
return { status: '唤醒成功', detail: `${sessionId} via ${result.label}(messageId=${result.messageId || 'unknown'})` }
|
|
202
|
+
} catch (error) {
|
|
203
|
+
const detail = String(error?.message ?? error)
|
|
204
|
+
state.lastWake = { ok: false, detail }
|
|
205
|
+
return { status: '唤醒失败', detail }
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
const pending = state.dir === null ? undefined : await readPending(state.dir)
|
|
209
|
+
return {
|
|
210
|
+
status: state.watcher === null ? '未绑定' : '已绑定',
|
|
211
|
+
detail: [
|
|
212
|
+
`dir=${state.dir ?? '(none)'}`,
|
|
213
|
+
`session=${state.sessionId ?? '(from pending)'}`,
|
|
214
|
+
`wakes=${state.wakeCount}`,
|
|
215
|
+
`last=${state.lastWake === null ? '(none)' : `${state.lastWake.ok ? 'ok' : 'fail'}: ${state.lastWake.detail}`}`,
|
|
216
|
+
`pending=${pending === undefined ? '(none)' : JSON.stringify(pending).slice(0, 120)}`,
|
|
217
|
+
].join(' | '),
|
|
218
|
+
}
|
|
219
|
+
},
|
|
220
|
+
}))
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** 斜杠命令名:`/companion`。 */
|
|
224
|
+
const COMPANION_COMMAND = 'companion'
|
|
225
|
+
|
|
226
|
+
/** 被本插件拉起的服务进程(卸载时收尸;复用已有服务时保持 null)。 */
|
|
227
|
+
let spawnedService = null
|
|
228
|
+
|
|
229
|
+
/** 本地伴侣服务脚本(随本包发布)。 */
|
|
230
|
+
function companionBin() {
|
|
231
|
+
return fileURLToPath(new URL('../bin/visual-companion.mjs', import.meta.url))
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** 伴侣根目录:配置了 watchDir 就用它,否则退回工作区下的 .dsh-visual。 */
|
|
235
|
+
function companionDir(config) {
|
|
236
|
+
const configured = clean(config?.watchDir)
|
|
237
|
+
return configured === '' ? join(process.cwd(), '.dsh-visual') : configured
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async function readServerInfo(dir) {
|
|
241
|
+
try {
|
|
242
|
+
const parsed = JSON.parse(await readFile(join(dir, 'state', 'server-info'), 'utf8'))
|
|
243
|
+
return parsed !== null && typeof parsed === 'object' ? parsed : undefined
|
|
244
|
+
} catch {
|
|
245
|
+
return undefined
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** 服务没在跑就后台拉起(零依赖、detached、丢弃 stdio),并等它写出 server-info。 */
|
|
250
|
+
async function ensureService(ctx, dir, sessionId) {
|
|
251
|
+
const existing = await readServerInfo(dir)
|
|
252
|
+
if (existing?.url !== undefined) return existing
|
|
253
|
+
await mkdir(join(dir, 'screen'), { recursive: true })
|
|
254
|
+
await mkdir(join(dir, 'state'), { recursive: true })
|
|
255
|
+
const args = [companionBin(), '--dir', dir, '--port', '0']
|
|
256
|
+
if (sessionId !== '') args.push('--session', sessionId)
|
|
257
|
+
const child = spawn(process.execPath, args, { detached: true, stdio: 'ignore' })
|
|
258
|
+
child.unref()
|
|
259
|
+
spawnedService = child
|
|
260
|
+
ctx.logger?.info?.(`visual-companion: 已拉起伴侣服务(pid=${child.pid ?? '?'},dir=${dir})`)
|
|
261
|
+
for (let i = 0; i < 24; i += 1) {
|
|
262
|
+
const info = await readServerInfo(dir)
|
|
263
|
+
if (info?.url !== undefined) return info
|
|
264
|
+
await new Promise((resolve) => setTimeout(resolve, 250))
|
|
265
|
+
}
|
|
266
|
+
return undefined
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** 把服务打印的 url 与 key 拼成可直接打开的完整地址。 */
|
|
270
|
+
function withKey(info) {
|
|
271
|
+
const url = String(info?.url ?? '')
|
|
272
|
+
const key = String(info?.key ?? '')
|
|
273
|
+
if (url === '' || key === '' || url.includes('key=')) return url
|
|
274
|
+
return `${url}${url.includes('?') ? '&' : '?'}key=${encodeURIComponent(key)}`
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* 注册 `/companion`:起服务并让当前会话的助手接手。
|
|
279
|
+
* 服务只负责写文件;「绑观察器」与「开右侧栏」交给会话里的助手(它有 sidebar_open 与
|
|
280
|
+
* visual_companion 工具,且能从自己的 $env:DSH_SESSION_ID 拿到本会话 id)。
|
|
281
|
+
*/
|
|
282
|
+
function registerCommand(ctx, config) {
|
|
283
|
+
ctx.commands.register({
|
|
284
|
+
name: COMPANION_COMMAND,
|
|
285
|
+
description: '视觉伴侣 · 启动本地零依赖服务并把原型页开在右侧栏 —— 你点选 + 写备注后按「提交给助手」,会话自动继续',
|
|
286
|
+
input: { hint: '[<想看的主题>]' },
|
|
287
|
+
async handler(invocation) {
|
|
288
|
+
const dir = companionDir(config)
|
|
289
|
+
const sessionId = clean(invocation?.agent?.sessionId ?? invocation?.agent?.id ?? '')
|
|
290
|
+
let info
|
|
291
|
+
try {
|
|
292
|
+
info = await ensureService(ctx, dir, sessionId)
|
|
293
|
+
} catch (error) {
|
|
294
|
+
return { kind: 'error', text: `视觉伴侣启动失败:${String(error?.message ?? error)}` }
|
|
295
|
+
}
|
|
296
|
+
if (info === undefined) {
|
|
297
|
+
return { kind: 'error', text: `伴侣服务未就绪(没有写出 ${join(dir, 'state', 'server-info')});可手动运行 bin/visual-companion.mjs 后重试` }
|
|
298
|
+
}
|
|
299
|
+
const url = withKey(info)
|
|
300
|
+
if (state.dir !== dir || state.watcher === null) arm(ctx, dir, sessionId === '' ? null : sessionId)
|
|
301
|
+
const topic = clean(invocation?.rawInput)
|
|
302
|
+
invocation?.agent?.followup?.(userMessage([
|
|
303
|
+
`【视觉伴侣】本地服务已就绪:${url}`,
|
|
304
|
+
`请接着做三件事:① 用 sidebar_open 把这个 URL 开在右侧栏;② 用 visual_companion({action:"arm", dir:"${dir}", session_id:"<本会话 id>"}) 绑上观察器(本会话 id 读 $env:DSH_SESSION_ID;若这个服务绑的是别的会话,重启它并带 --session);③ 把${topic === '' ? '要看的原型' : `「${topic}」的原型`}写成 HTML 片段放进 ${join(dir, 'screen')} 目录。`,
|
|
305
|
+
'用户点选并按「提交给助手」后,你会自动收到消息,不必让他回终端复述。',
|
|
306
|
+
].join('\n')))
|
|
307
|
+
return { kind: 'success', text: `视觉伴侣已就绪:${url}(已让助手打开右侧栏并准备第一屏)` }
|
|
308
|
+
},
|
|
309
|
+
})
|
|
310
|
+
}
|
|
311
|
+
export function apply(ctx, config) {
|
|
312
|
+
registerTool(ctx)
|
|
313
|
+
registerCommand(ctx, config)
|
|
314
|
+
// 长生命周期资源归当前 fiber:插件卸载时关闭 watcher 与本插件拉起的服务。
|
|
315
|
+
ctx.effect(() => () => {
|
|
316
|
+
spawnedService?.kill?.()
|
|
317
|
+
spawnedService = null
|
|
318
|
+
disarm()
|
|
319
|
+
})
|
|
320
|
+
const watchDir = clean(config?.watchDir)
|
|
321
|
+
// 目标会话不在这里钉死:由 pending.json 自带(伴侣服务用 --session 写入)。
|
|
322
|
+
if (watchDir !== '') arm(ctx, watchDir, null)
|
|
323
|
+
ctx.logger?.info?.(`visual-companion: 已加载(v0.1.2)${watchDir === '' ? ',未自动绑定' : `,自动绑定 ${watchDir}`}`)
|
|
324
324
|
}
|