@fish-under-sea/dsh-visual-companion 0.1.2 → 0.1.3

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/lib/index.js CHANGED
@@ -282,7 +282,7 @@ function withKey(info) {
282
282
  function registerCommand(ctx, config) {
283
283
  ctx.commands.register({
284
284
  name: COMPANION_COMMAND,
285
- description: '启动视觉伴侣(本地零依赖服务)并把原型页开在右侧栏 —— 你点选 + 写备注后按「提交给助手」,会话自动继续,不必回终端复述',
285
+ description: '视觉伴侣 · 启动本地零依赖服务并把原型页开在右侧栏 —— 你点选 + 写备注后按「提交给助手」,会话自动继续',
286
286
  input: { hint: '[<想看的主题>]' },
287
287
  async handler(invocation) {
288
288
  const dir = companionDir(config)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fish-under-sea/dsh-visual-companion",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "把「视觉伴侣页面上的提交」变成一条用户消息:用户在网页上点选、写备注、按提交,DSH 会话自动起一轮继续工作,不必回终端复述。",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -1,132 +0,0 @@
1
- <div align="center">
2
-
3
- # @fish-under-sea/dsh-visual-companion
4
-
5
- **网页上点完就继续** —— 用户在视觉伴侣页面选好选项、写两句备注、按下「提交给助手」,DSH 会话立刻收到一条用户消息并自动起一轮。
6
-
7
- [![npm](https://img.shields.io/npm/v/@fish-under-sea/dsh-visual-companion?style=flat-square&label=npm&color=cb3837)](https://www.npmjs.com/package/@fish-under-sea/dsh-visual-companion)
8
- ![license](https://img.shields.io/badge/license-MIT-green?style=flat-square)
9
- ![node](https://img.shields.io/badge/node-%5E22.19%20%7C%7C%20%3E%3D24-339933?style=flat-square)
10
- ![DSH](https://img.shields.io/badge/DSH-%3E%3D0.2.0--rc.2-4b6ef6?style=flat-square)
11
- ![host-only](https://img.shields.io/badge/plugin-host--only-6b7280?style=flat-square)
12
-
13
- </div>
14
-
15
- ## 解决什么问题
16
-
17
- 用网页看原型、比布局、选方案时,最烦的两件事:
18
-
19
- 1. **看完还得回终端打字复述**:「我选 B,另外配色再冷一点」—— 看图的人不该兼职打字员;
20
- 2. **或者相反,点一下就唤醒一次**:连点三个选项,助手被打断三次,既吵又费 token。
21
-
22
- 本插件把两件事一起解决:**点选过程完全静默**(只改页面本地状态),**只有按下「提交给助手」才唤醒一次**,并把整组选择连同备注一次性送达。
23
-
24
- ## 效果
25
-
26
- - **点选静默**:任意点选、取消、填备注都不发请求、不叫醒会话;
27
- - **一次提交 = 一次唤醒**:整组选择 + 备注拼成一条用户消息,例如
28
- `【视觉伴侣】用户在页面上选好了 2 项:A(单栏布局)、C(混合方案),备注:间距再大一点。已同步给你,直接往下走就行(不必再问他)。`
29
- - **自动继续**:会话收到后直接起一轮接着干,不需要用户复述;
30
- - **界面自适应**:单选 / 多选(容器加 `data-multiselect`)、备注框、等待屏;页面没有可选项时自动隐藏提交栏。
31
-
32
- ## 安装
33
-
34
- ```sh
35
- # 推荐:从 npm 安装(--profile 后跟本机 profile 名:桌面版 desktop,Web 版 web)
36
- dsh plugin --profile <profile> add @fish-under-sea/dsh-visual-companion
37
-
38
- # 改源码时才用 link:(仓库源码即安装源,改完重启 DSH 即生效)
39
- dsh plugin --profile <profile> add "link:<仓库路径>/packages/dsh-visual-companion"
40
- ```
41
-
42
- 装完**重启该 profile 的宿主**(新插件包需要重启才进组合;之后只改 `cordis.patch.yml` 内容可热重载)。
43
-
44
- ## 使用
45
-
46
- 本包由**两部分**组成,都不接触模型 API:宿主插件(`lib/index.js`)只投消息,本地服务(`bin/visual-companion.mjs`)只写文件。
47
-
48
- **1)起本地服务**(受管后台任务;目录放工作区内的临时目录):
49
-
50
- ```powershell
51
- node "$env:DSH_HOME\profiles\<profile>\node_modules\@fish-under-sea\dsh-visual-companion\bin\visual-companion.mjs" `
52
- --dir "<工作区>\.dsh-visual" --port 0 --session "$env:DSH_SESSION_ID"
53
- # → 打印 { url, port, key, screenDir, stateDir, pendingFile, session }
54
- ```
55
-
56
- **2)写一屏 HTML 片段**到 `<dir>\screen\`(语义化文件名、别复用;需要完全控制页面时才写完整文档,即以 `<!DOCTYPE` / `<html` 开头)。
57
-
58
- **3)打开页面**:把 `url` 连同 `?key=` 一起交给用户(DSH 里用 `sidebar_open` 开在右侧栏)。密钥缺失会被 403 拒绝。
59
-
60
- 服务自带的框架样式提供这些类,写片段即可用:
61
-
62
- | 用途 | 类 |
63
- | --- | --- |
64
- | 选项(单选 / 容器加 `data-multiselect` 变多选) | `.options` > `.option[data-choice]`,点击调 `toggleSelect(this)`;`.cards` > `.card` 同款 |
65
- | 视觉块 | `.mockup`、`.split`、`.pros-cons`、`.mock-nav`、`.mock-sidebar`、`.mock-content`、`.mock-button`、`.mock-input`、`.placeholder` |
66
- | 文字层级 | `h2` / `h3` / `.subtitle` / `.section` / `.label` |
67
-
68
- 插件注册一个工具 `visual_companion`:
69
-
70
- | action | 参数 | 作用 |
71
- | --- | --- | --- |
72
- | `arm` | `dir`、`session_id?` | 绑定目录与目标会话;`session_id` 可省略(之后由 `pending.json` 自带) |
73
- | `disarm` | — | 解绑并关闭观察器 |
74
- | `status` | — | 绑定状态、唤醒次数、最近一次结果、当前 `pending.json` |
75
- | `wake` | `session_id`、`text` | 立刻探测唤醒链路(不经过页面) |
76
-
77
- 落盘文件都在 `<dir>\state\`:
78
-
79
- | 文件 | 内容 |
80
- | --- | --- |
81
- | `pending.json` | **只有提交才写**:`{type:"submit", selections:[{choice,text}], note, at, sessionId}`,插件观察它 |
82
- | `events.jsonl` | 逐条追加:`click` 是点选过程(不唤醒),`submit` 是完整提交(唤醒一次) |
83
- | `server-info` / `server-stopped` | 服务启动信息与退出原因 |
84
-
85
- ## 配置
86
-
87
- | 键 | 默认 | 说明 |
88
- | --- | --- | --- |
89
- | `watchDir` | `""` | 非空则**加载即自动绑定**该目录(配置热重载 / 重启都不会掉绑定);留空则用 `visual_companion` 手动 `arm` |
90
-
91
- 目标会话**不写进配置**:它由每次提交写入的 `sessionId` 决定(服务启动时的 `--session`),所以同一个服务可以服务不同会话,配置里也不会留机器专属的会话 id。
92
-
93
- 机器相关的绝对路径不写进共享 bundle,需要自动绑定时在自己的 profile patch 层用同 id 覆盖:
94
-
95
- ```yaml
96
- - id: visual-companion
97
- name: '@fish-under-sea/dsh-visual-companion'
98
- config:
99
- watchDir: D:/some/workspace/.dsh-visual
100
- ```
101
-
102
- ## 兼容与边界
103
-
104
- 投递按「越接近公开面越优先」逐个降级,返回真正成功的那条:
105
-
106
- 1. `agent.followup(createUserMessage(...))` —— 与斜杠命令注入用户消息同一条路径;
107
- 2. `agent.steer(...)` —— 目标正在跑时;
108
- 3. `ctx.subagents[Symbol.for('dsh.subagent.queuePrompt' | 'deliverPrompt')]` —— 可续期子代理的宿主内部投递钩子。
109
-
110
- - **host-only**:不声明 `dsh.client`,无前端、无构建;
111
- - 服务零依赖(只用 Node 标准库)、端口自动分配、URL 带会话密钥;`--host 0.0.0.0 --url-host <主机名>` 可用于远程 / 容器,但**必须保留 `?key=`**;
112
- - 服务**闲置 4 小时自动退出**(`--idle-minutes` 可调),原型文件是临时产物,别当交付物;
113
- - 降级链:无 Node → 自包含 HTML + `present`;无侧边栏浏览器 → 把完整 URL 交给用户手动打开;连插件都没装 → 下一轮手工读 `events.jsonl`;
114
- - 需要 Node `^22.19.0 || >=24`、DSH `>=0.2.0-rc.2`;不需要任何 API key;
115
- - **已知限制**:宿主插件代码不热重载 —— 改 `lib/index.js` 后要重启宿主;只改 `cordis.patch.yml` 的内容可热重载。
116
-
117
- ## 开发与测试
118
-
119
- ```sh
120
- node packages/dsh-visual-companion/test/visual-companion.test.mjs # 语料渲染 + 清单契约(7 用例)
121
- pnpm pack # 产物检查:files 覆盖 bin / lib / patch / README
122
- ```
123
-
124
- `lib/message.js` 是**零依赖纯函数**(语料渲染),所以测试与调用方不装 `@deepseek-ai/*` 也能验证文案;`lib/index.js` 才依赖宿主提供的 `@deepseek-ai/dsh-llm`、`dsh-tools`、`schemastery`(已声明为可选 peer)。
125
-
126
- ## 与聚合包的关系
127
-
128
- 本包是 [`@fish-under-sea/dsh-fish`](https://github.com/Fish-under-sea/dsh-fish) 聚合包的成员之一:聚合包的 bundle 层会把这一行插进 profile,所以装聚合包等于装齐 Fish 自建插件。单独安装本包则只影响这一项。
129
-
130
- ## 许可
131
-
132
- MIT © Fish-under-sea
@@ -1,229 +0,0 @@
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 { watch } from 'node:fs'
24
- import { readFile } from 'node:fs/promises'
25
- import { basename, join } from 'node:path'
26
-
27
- import { createUserMessage } from '@deepseek-ai/dsh-llm'
28
- import { defineTool } from '@deepseek-ai/dsh-tools'
29
- import z from '@deepseek-ai/schemastery'
30
-
31
- import { companionMessage } from './message.js'
32
-
33
- export { companionMessage }
34
-
35
- export const name = 'visual-companion'
36
- export const inject = ['tools']
37
-
38
- /** 与 AgentTeams `harness-compat` 相同的进程稳定符号(宿主内部子代理投递协议)。 */
39
- const hostPromptQueue = Symbol.for('dsh.subagent.queuePrompt')
40
- const hostPromptDeliver = Symbol.for('dsh.subagent.deliverPrompt')
41
-
42
- /** 插件配置:`watchDir` 非空时加载即自动绑定。 */
43
- export const Config = z.object({
44
- watchDir: z.string().default(''),
45
- })
46
-
47
- /** 当前绑定(单绑定:一个进程同时只服务一个视觉伴侣目录)。 */
48
- const state = {
49
- dir: null,
50
- sessionId: null,
51
- watcher: null,
52
- lastFingerprint: null,
53
- lastWake: null,
54
- wakeCount: 0,
55
- }
56
-
57
- const clean = (v) => String(v ?? '').replace(/\s+/g, ' ').trim()
58
-
59
- function userMessage(text) {
60
- return createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } })
61
- }
62
-
63
- function agentsRegistry(ctx) {
64
- const registry = ctx.get('agents')
65
- return registry !== undefined && typeof registry.get === 'function' ? registry : undefined
66
- }
67
-
68
- /** 尝试把一条消息投进目标会话并起一轮;返回成功的策略。 */
69
- async function wake(ctx, sessionId, text) {
70
- const attempts = []
71
- const registry = agentsRegistry(ctx)
72
- if (registry === undefined) throw new Error('agents 服务不可用:无法按 sessionId 找到会话')
73
- const target = registry.get(sessionId)
74
- if (target === undefined) throw new Error(`找不到会话 ${sessionId} 的 live agent`)
75
-
76
- const tryOne = async (label, fn) => {
77
- try {
78
- const result = await fn()
79
- return { ok: true, label, messageId: result === undefined ? '' : String(result) }
80
- } catch (error) {
81
- attempts.push(`${label}: ${String(error?.message ?? error)}`)
82
- return { ok: false, label }
83
- }
84
- }
85
-
86
- const followup = await tryOne('agent.followup', () => target.followup(userMessage(text)))
87
- if (followup.ok) return { ...followup, attempts }
88
- const steer = await tryOne('agent.steer', () => target.steer(userMessage(text)))
89
- if (steer.ok) return { ...steer, attempts }
90
-
91
- const subagents = ctx.get('subagents')
92
- const deliver = subagents?.[hostPromptDeliver]
93
- const queue = subagents?.[hostPromptQueue]
94
- const content = [{ type: 'text', text }]
95
- const signal = AbortSignal.timeout(15_000)
96
- if (typeof deliver === 'function') {
97
- const r = await tryOne('subagents.deliverPrompt(queue)', () => deliver(target, sessionId, content, { kind: 'user' }, signal, 'queue'))
98
- if (r.ok) return { ...r, attempts }
99
- }
100
- if (typeof queue === 'function') {
101
- const r = await tryOne('subagents.queuePrompt', () => queue(target, sessionId, content, { kind: 'user' }, signal))
102
- if (r.ok) return { ...r, attempts }
103
- }
104
- throw new Error(`所有唤醒策略都失败 → ${attempts.join(' | ')}`)
105
- }
106
-
107
- async function readPending(dir) {
108
- try {
109
- const parsed = JSON.parse(await readFile(join(dir, 'state', 'pending.json'), 'utf8'))
110
- return parsed !== null && typeof parsed === 'object' ? parsed : undefined
111
- } catch {
112
- return undefined
113
- }
114
- }
115
-
116
- function fingerprintOf(pending) {
117
- return `${pending.ts ?? ''}|${pending.at ?? ''}|${pending.choice ?? ''}|${pending.text ?? ''}|${JSON.stringify(pending.selections ?? '')}|${pending.note ?? ''}`
118
- }
119
-
120
- async function handleSubmit(ctx, pending) {
121
- const fp = fingerprintOf(pending)
122
- if (fp === state.lastFingerprint) return
123
- state.lastFingerprint = fp
124
- const sessionId = pending.sessionId === undefined ? state.sessionId : String(pending.sessionId)
125
- if (sessionId === null || sessionId === '') {
126
- state.lastWake = { ok: false, detail: '未绑定 sessionId,无法唤醒' }
127
- return
128
- }
129
- try {
130
- const result = await wake(ctx, sessionId, companionMessage(pending))
131
- state.wakeCount += 1
132
- state.lastWake = { ok: true, detail: `${result.label} → message ${result.messageId || '(unknown id)'}` }
133
- ctx.logger?.info?.(`visual-companion: 唤醒 ${sessionId} 成功(${result.label})`)
134
- } catch (error) {
135
- state.lastWake = { ok: false, detail: String(error?.message ?? error) }
136
- ctx.logger?.warn?.(`visual-companion: 唤醒 ${sessionId} 失败:${state.lastWake.detail}`)
137
- }
138
- }
139
-
140
- function arm(ctx, dir, sessionId) {
141
- state.watcher?.close?.()
142
- state.dir = dir
143
- state.sessionId = sessionId
144
- state.lastFingerprint = null
145
- const watchDir = join(dir, 'state')
146
- state.watcher = watch(watchDir, { persistent: false }, (_event, filename) => {
147
- if (filename !== null && basename(String(filename)) !== 'pending.json') return
148
- void readPending(dir).then((pending) => (pending === undefined ? undefined : handleSubmit(ctx, pending)))
149
- })
150
- state.watcher.on?.('error', (error) => ctx.logger?.warn?.(`visual-companion: 观察 ${watchDir} 出错:${String(error)}`))
151
- ctx.logger?.info?.(`visual-companion: 已绑定 ${watchDir}/pending.json → 会话 ${sessionId ?? '(由 pending.json 自带)'}`)
152
- }
153
-
154
- function disarm() {
155
- state.watcher?.close?.()
156
- state.watcher = null
157
- }
158
-
159
- function registerTool(ctx) {
160
- ctx.tools.register(defineTool({
161
- name: 'visual_companion',
162
- description: '视觉伴侣唤醒开关。arm 绑定一个视觉伴侣目录(观察其中的 state/pending.json)与目标会话;之后用户在页面上提交选择时,会直接给该会话投一条用户消息并起一轮,无需他回终端复述。disarm 解绑;status 查看绑定与最近一次唤醒结果;wake 立刻用给定文本探测唤醒链路(验证用)。',
163
- parameters: {
164
- action: { type: 'string', required: true, enum: ['arm', 'disarm', 'status', 'wake'], description: '要执行的动作。' },
165
- dir: { type: 'string', description: 'arm 用:视觉伴侣根目录(内含 state/pending.json)。' },
166
- session_id: { type: 'string', description: 'arm/wake 用:要唤醒的会话 id;arm 时可省略,之后由 pending.json 自带。' },
167
- text: { type: 'string', description: 'wake 用:投递的文本。' },
168
- },
169
- output: {
170
- schema: {
171
- type: 'object',
172
- additionalProperties: false,
173
- properties: {
174
- status: { type: 'string', required: true },
175
- detail: { type: 'string' },
176
- },
177
- },
178
- render: (_args, value) => [{ type: 'text', text: `${value.status}${value.detail === undefined ? '' : ` — ${value.detail}`}` }],
179
- },
180
- async execute(args) {
181
- if (args.action === 'arm') {
182
- const dir = clean(args.dir)
183
- if (dir === '') return { status: 'arm 失败', detail: '需要 dir' }
184
- arm(ctx, dir, args.session_id === undefined || clean(args.session_id) === '' ? null : clean(args.session_id))
185
- return { status: '已绑定', detail: `${dir}/state/pending.json → ${state.sessionId ?? '(由 pending.json 自带 sessionId)'}` }
186
- }
187
- if (args.action === 'disarm') {
188
- disarm()
189
- return { status: '已解绑' }
190
- }
191
- if (args.action === 'wake') {
192
- const sessionId = clean(args.session_id) || clean(state.sessionId)
193
- const text = clean(args.text) === '' ? '【视觉伴侣】唤醒链路自检。' : clean(args.text)
194
- if (sessionId === '') return { status: 'wake 失败', detail: '需要 session_id' }
195
- try {
196
- const result = await wake(ctx, sessionId, text)
197
- state.wakeCount += 1
198
- state.lastWake = { ok: true, detail: `${result.label} → message ${result.messageId || '(unknown id)'}` }
199
- return { status: '唤醒成功', detail: `${sessionId} via ${result.label}(messageId=${result.messageId || 'unknown'})` }
200
- } catch (error) {
201
- const detail = String(error?.message ?? error)
202
- state.lastWake = { ok: false, detail }
203
- return { status: '唤醒失败', detail }
204
- }
205
- }
206
- const pending = state.dir === null ? undefined : await readPending(state.dir)
207
- return {
208
- status: state.watcher === null ? '未绑定' : '已绑定',
209
- detail: [
210
- `dir=${state.dir ?? '(none)'}`,
211
- `session=${state.sessionId ?? '(from pending)'}`,
212
- `wakes=${state.wakeCount}`,
213
- `last=${state.lastWake === null ? '(none)' : `${state.lastWake.ok ? 'ok' : 'fail'}: ${state.lastWake.detail}`}`,
214
- `pending=${pending === undefined ? '(none)' : JSON.stringify(pending).slice(0, 120)}`,
215
- ].join(' | '),
216
- }
217
- },
218
- }))
219
- }
220
-
221
- export function apply(ctx, config) {
222
- registerTool(ctx)
223
- // 长生命周期资源归当前 fiber:插件卸载时关闭 watcher。
224
- ctx.effect(() => () => disarm())
225
- const watchDir = clean(config?.watchDir)
226
- // 目标会话不在这里钉死:由 pending.json 自带(伴侣服务用 --session 写入)。
227
- if (watchDir !== '') arm(ctx, watchDir, null)
228
- ctx.logger?.info?.(`visual-companion: 已加载(v0.1.0)${watchDir === '' ? ',未自动绑定' : `,自动绑定 ${watchDir}`}`)
229
- }