@fish-under-sea/dsh-visual-companion 0.1.1 → 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.
Files changed (3) hide show
  1. package/README.md +12 -0
  2. package/lib/index.js +100 -5
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -82,6 +82,18 @@ node "$env:DSH_HOME\profiles\<profile>\node_modules\@fish-under-sea\dsh-visual-c
82
82
  | `events.jsonl` | 逐条追加:`click` 是点选过程(不唤醒),`submit` 是完整提交(唤醒一次) |
83
83
  | `server-info` / `server-stopped` | 服务启动信息与退出原因 |
84
84
 
85
+ ### 斜杠命令 `/companion`
86
+
87
+ 在会话里直接输入:
88
+
89
+ ```text
90
+ /companion [想看的主题]
91
+ ```
92
+
93
+ 插件会:**①** 若本地服务没在跑就后台拉起它(零依赖、自动分配端口);**②** 把带会话密钥的完整 URL 交给当前会话的助手,让它用 `sidebar_open` 开在右侧栏;**③** 让助手绑好观察器并把第一屏原型写进 `screen/`。之后你只管点选 + 写备注 + 按「提交给助手」。
94
+
95
+ > 命令只负责「起服务 + 交接」,页面上该显示什么仍由助手写 HTML 片段决定 —— 所以它比手敲 `bin/visual-companion.mjs` 省事,但不会替你决定看什么。
96
+
85
97
  ## 配置
86
98
 
87
99
  | 键 | 默认 | 说明 |
package/lib/index.js CHANGED
@@ -20,9 +20,11 @@
20
20
  *
21
21
  * @module @fish-under-sea/dsh-visual-companion
22
22
  */
23
+ import { spawn } from 'node:child_process'
23
24
  import { watch } from 'node:fs'
24
- import { readFile } from 'node:fs/promises'
25
+ import { mkdir, readFile } from 'node:fs/promises'
25
26
  import { basename, join } from 'node:path'
27
+ import { fileURLToPath } from 'node:url'
26
28
 
27
29
  import { createUserMessage } from '@deepseek-ai/dsh-llm'
28
30
  import { defineTool } from '@deepseek-ai/dsh-tools'
@@ -33,7 +35,7 @@ import { companionMessage } from './message.js'
33
35
  export { companionMessage }
34
36
 
35
37
  export const name = 'visual-companion'
36
- export const inject = ['tools']
38
+ export const inject = ['tools', 'commands']
37
39
 
38
40
  /** 与 AgentTeams `harness-compat` 相同的进程稳定符号(宿主内部子代理投递协议)。 */
39
41
  const hostPromptQueue = Symbol.for('dsh.subagent.queuePrompt')
@@ -218,12 +220,105 @@ function registerTool(ctx) {
218
220
  }))
219
221
  }
220
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
+ }
221
311
  export function apply(ctx, config) {
222
312
  registerTool(ctx)
223
- // 长生命周期资源归当前 fiber:插件卸载时关闭 watcher。
224
- ctx.effect(() => () => disarm())
313
+ registerCommand(ctx, config)
314
+ // 长生命周期资源归当前 fiber:插件卸载时关闭 watcher 与本插件拉起的服务。
315
+ ctx.effect(() => () => {
316
+ spawnedService?.kill?.()
317
+ spawnedService = null
318
+ disarm()
319
+ })
225
320
  const watchDir = clean(config?.watchDir)
226
321
  // 目标会话不在这里钉死:由 pending.json 自带(伴侣服务用 --session 写入)。
227
322
  if (watchDir !== '') arm(ctx, watchDir, null)
228
- ctx.logger?.info?.(`visual-companion: 已加载(v0.1.0)${watchDir === '' ? ',未自动绑定' : `,自动绑定 ${watchDir}`}`)
323
+ ctx.logger?.info?.(`visual-companion: 已加载(v0.1.2)${watchDir === '' ? ',未自动绑定' : `,自动绑定 ${watchDir}`}`)
229
324
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fish-under-sea/dsh-visual-companion",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "把「视觉伴侣页面上的提交」变成一条用户消息:用户在网页上点选、写备注、按提交,DSH 会话自动起一轮继续工作,不必回终端复述。",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",