@ceasarxuu/dsh-maid 0.0.0-stage → 0.1.16

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 CHANGED
@@ -1,3 +1,24 @@
1
- # Temporary Holding Version
1
+ # Maid
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Maid 是 DeepSeek Harness 的本地个人助理。它在 DSH 左栏提供一个独立入口,显示待你处理的事项数量,并使用同一段对话接收交代,在记事本中持续跟进任务、笔记和定时安排。
4
+
5
+ ## 安装
6
+
7
+ 此版本面向 DSH `0.2.2-rc.5` 至 `0.3.0` 之前的版本。使用 `pnpm install --frozen-lockfile` 安装开发依赖,运行 `pnpm pack` 生成安装包。在 DSH 的插件设置中安装生成的 .tgz 文件并重新启动 Host。
8
+
9
+ ## 使用
10
+
11
+ - 从 DSH 左栏打开 Maid 就可以在全局会话里发消息,无需选择工作区。可以打断当前回复,或请 Maid 创建后台任务。持续运行的任务有独立的 DSH 会话,进展可以从记事本打开。需要补充信息的任务可以在详情里接续。也可以请 Maid 关注指定工作区会话的下一次成功结束。
12
+ - 通过原生输入区的「记事本」按钮打开 DSH 右侧记事本,在其中登记笔记和后台任务。宿主启用 DSH Schedule 时,可以从对话或记事本创建仅一次、每天或每周的定时安排。记事本也显示和 Maid 主会话关联的 DSH 原生定时安排。原生安排可在记事本暂停或恢复,时间规则在 DSH 的「自动化任务」中调整。下次投递由 DSH 管理,Maid 后台任务的运行结果显示在会话的「Maid 动态」和任务详情。
13
+ - Maid 会话顶部的「设置」紧跟「对话」。在这里手动编辑性格、恢复默认,或记录、搜索、更正和忘掉事实。Maid 可以搜索、保存和更新本地事实。
14
+ - 在 Maid 主会话中可以操作当前打开的 Chrome。支持列出标签页、打开网页、读取页面控件、点击和填写表单字段。首次使用前,在 Chrome 打开 `chrome://inspect/#remote-debugging` 启用远程调试,然后在 Chrome 的连接提示中选择允许。
15
+
16
+ ## 数据与工具
17
+
18
+ 数据位于当前 DSH profile 下的 `maid/`。该目录也是 Maid 主会话固定的内部工作目录,由插件管理,不出现在工作区选择器中。任务、消息投递和笔记保存为 `work.json`,性格保存在 `persona.md`,事实保存在 `memory/` 的 Markdown 文件。模型会话使用 DSH 的原生存储。
19
+
20
+ Maid 的主会话和后台会话使用 DSH 当前模式和插件提供的工具,沿用 DSH 原生权限。主会话还提供项目跟进、记事本、定时安排、本地记忆和 Chrome 工具。后台会话通过 `maid_report` 把进展和结果写回记事本。
21
+
22
+ Host 加载新的工具、MCP 或技能后,Maid 在原会话的下一次模型请求中继续使用更新后的能力。Maid 可通过 `maid_capabilities` 查询当前会话的实时工具和技能目录。
23
+
24
+ 聊天使用 DSH 原生收件箱,并在 Maid 收到用户消息时请求落盘。后台任务先写入 Maid 本地记录,再由 DSH 确认投递。断开前端连接后,工作继续由运行中的 DSH Host 处理。Host 重启时,待投递的消息重新投递,进行中的普通任务从之前的执行记录恢复。早期版本中多次投递失败的消息仍可在会话的「Maid 动态」中重试。定时到期与补投沿用 DSH Schedule 的规则。
@@ -0,0 +1,3 @@
1
+ - insert:
2
+ - id: maid
3
+ name: '@ceasarxuu/dsh-maid'
package/host/chrome.js ADDED
@@ -0,0 +1,71 @@
1
+ import { createRequire } from 'node:module'
2
+ import { dirname, resolve } from 'node:path'
3
+ import { Client } from '@modelcontextprotocol/client'
4
+ import { StdioClientTransport } from '@modelcontextprotocol/client/stdio'
5
+ import { InputError } from './store.js'
6
+
7
+ const require = createRequire(import.meta.url)
8
+ const pageId = { type: 'integer', description: 'Page ID returned by maid_chrome_list_pages or maid_chrome_new_page.', required: true }
9
+ const uid = { type: 'string', description: 'Element UID from the latest snapshot of this page.', required: true }
10
+ const url = { type: 'string', description: 'An HTTP or HTTPS URL.', required: true }
11
+ const value = { type: 'string', description: 'The text or option to enter.', required: true }
12
+
13
+ const browserTools = [
14
+ ['list_pages', 'List open tabs in the user’s Chrome.', {}],
15
+ ['new_page', 'Open a web URL in a new Chrome tab.', { url }],
16
+ ['navigate_page', 'Open a web URL in an existing Chrome tab.', { pageId, url }],
17
+ ['take_snapshot', 'Read the page’s text and controls. Use the returned element UIDs to interact with the page.', { pageId }],
18
+ ['click', 'Click one element from the current page snapshot.', { pageId, uid }],
19
+ ['fill', 'Fill one input or select one option from the current page snapshot.', { pageId, uid, value }],
20
+ ]
21
+
22
+ export function registerChromeTools(register, directory) {
23
+ const lifetime = new AbortController()
24
+ let connection
25
+
26
+ function connect() {
27
+ if (connection) return connection.ready
28
+ const manifestPath = require.resolve('chrome-devtools-mcp/package.json')
29
+ const cli = resolve(dirname(manifestPath), require(manifestPath).bin['chrome-devtools-mcp'])
30
+ const client = new Client({ name: 'dsh-maid', version: '1' })
31
+ const transport = new StdioClientTransport({
32
+ command: process.execPath,
33
+ args: [cli, '--auto-connect', '--no-usage-statistics', '--no-javascript-evaluation', '--no-file-navigations'],
34
+ env: {
35
+ CHROME_DEVTOOLS_MCP_NO_CONFIG_DISCOVERY: '1',
36
+ ...(process.env.ELECTRON_RUN_AS_NODE === '1' && { ELECTRON_RUN_AS_NODE: '1' }),
37
+ },
38
+ cwd: directory,
39
+ })
40
+ client.onclose = () => { if (connection?.client === client) connection = undefined }
41
+ const ready = client.connect(transport, { timeout: 10_000 }).then(() => client).catch(async error => {
42
+ if (connection?.client === client) connection = undefined
43
+ await client.close().catch(() => {})
44
+ throw error
45
+ })
46
+ connection = { client, ready }
47
+ return ready
48
+ }
49
+
50
+ for (const [name, description, parameters] of browserTools) {
51
+ register('maid_chrome_' + name, description, parameters, async (args, exec) => {
52
+ const signal = exec.signal ? AbortSignal.any([exec.signal, lifetime.signal]) : lifetime.signal
53
+ signal.throwIfAborted()
54
+ if (args.url !== undefined && (!/^https?:\/\//i.test(args.url) || !URL.canParse(args.url))) {
55
+ throw new InputError('Chrome 只接受有效的 HTTP 或 HTTPS 网页地址。')
56
+ }
57
+ const client = await connect()
58
+ signal.throwIfAborted()
59
+ const arguments_ = name === 'navigate_page' ? { ...args, type: 'url' } : args
60
+ const result = await client.callTool({ name, arguments: arguments_ }, { signal, timeout: 60_000 })
61
+ const text = result.content.filter(block => block.type === 'text').map(block => block.text).join('\n')
62
+ if (result.isError) throw new Error(text || 'Chrome 操作失败。')
63
+ return text
64
+ })
65
+ }
66
+
67
+ return async () => {
68
+ lifetime.abort()
69
+ await connection?.client.close()
70
+ }
71
+ }
@@ -0,0 +1,27 @@
1
+ export function createCompanion(runtime) {
2
+ const { persona, memory } = runtime
3
+ return {
4
+ get sessionId() { return runtime.main },
5
+ prepare: runtime.prepareConversation,
6
+ async notebook() {
7
+ const { notes, tasks, notices, schedules, scheduleAvailable } = await runtime.notebook()
8
+ return {
9
+ notes: notes.map(({ id, text, at }) => ({ id, text, at })),
10
+ tasks: tasks.map(({ id, kind, title, status, createdAt, latest, goal, result }) => ({
11
+ id, kind, title, status, createdAt, latest, goal, result,
12
+ })),
13
+ notices: notices.map(({ id, kind, text, at, taskId }) => ({ id, kind, text, at, taskId })),
14
+ schedules: schedules.map(({ id, title, status, next }) => ({ id, title, status, next })),
15
+ scheduleAvailable,
16
+ }
17
+ },
18
+ readPersona: () => ({ text: persona.read() }),
19
+ savePersona: async (text) => ({ text: await persona.save(text) }),
20
+ async searchMemory(query = '') {
21
+ return (await memory.search(query, 100)).map(({ source, ...entry }) => {
22
+ const fromChat = source.startsWith(runtime.main + '#')
23
+ return { ...entry, source: fromChat ? '来自对话' : source, fromChat }
24
+ })
25
+ },
26
+ }
27
+ }
package/host/memory.js ADDED
@@ -0,0 +1,88 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { mkdir, readdir, lstat, open, unlink } from 'node:fs/promises'
3
+ import { join } from 'node:path'
4
+ import { InputError, replaceFile, required } from './store.js'
5
+
6
+ const ID = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/
7
+
8
+ export async function openMemory(root) {
9
+ const folder = join(root, 'memory')
10
+ await mkdir(folder, { recursive: true, mode: 0o700 })
11
+ let writes = Promise.resolve()
12
+ const mutate = operation => {
13
+ const write = writes.then(operation)
14
+ writes = write.catch(() => {})
15
+ return write
16
+ }
17
+ const pathFor = id => {
18
+ if (typeof id !== 'string' || !ID.test(id)) throw new InputError('记忆 ID 无效。')
19
+ return join(folder, id + '.md')
20
+ }
21
+
22
+ async function read(id) {
23
+ const path = pathFor(id)
24
+ try {
25
+ const info = await lstat(path)
26
+ if (!info.isFile() || info.size > 32000) return undefined
27
+ const handle = await open(path, 'r')
28
+ try {
29
+ const raw = await handle.readFile('utf8')
30
+ const [heading, scope, source, updatedAt, , ...body] = raw.split('\n')
31
+ if (!heading.startsWith('# ') || !scope?.startsWith('范围:')
32
+ || !source?.startsWith('来源:') || !updatedAt?.startsWith('更新:')) return undefined
33
+ return { id, topic: heading.slice(2), scope: scope.slice(3), source: source.slice(3),
34
+ updatedAt: updatedAt.slice(3), fact: body.join('\n').trim() }
35
+ } finally {
36
+ await handle.close()
37
+ }
38
+ } catch (error) {
39
+ if (error.code !== 'ENOENT') throw error
40
+ }
41
+ }
42
+
43
+ async function search(query = '', limit = 20) {
44
+ if (typeof query !== 'string' || query.length > 500) throw new InputError('搜索内容无效。')
45
+ const terms = query.toLocaleLowerCase().trim().split(/\s+/).filter(Boolean)
46
+ const matches = []
47
+ for (const file of await readdir(folder, { withFileTypes: true })) {
48
+ if (!file.isFile() || !file.name.endsWith('.md')) continue
49
+ const id = file.name.slice(0, -3)
50
+ if (!ID.test(id)) continue
51
+ const entry = await read(id)
52
+ if (!entry) continue
53
+ const text = [entry.topic, entry.scope, entry.fact].join('\n').toLocaleLowerCase()
54
+ if (terms.every(term => text.includes(term))) matches.push(entry)
55
+ }
56
+ return matches.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)).slice(0, limit)
57
+ }
58
+
59
+ return {
60
+ search,
61
+ read,
62
+ save(input, source) {
63
+ return mutate(async () => {
64
+ const id = input.id || randomUUID()
65
+ const previous = input.id ? await read(id) : undefined
66
+ if (input.id && !previous) throw new InputError('找不到这条记忆。')
67
+ const topic = required(input.topic, '主题', 120).replace(/[\r\n]+/g, ' ')
68
+ const scope = required(input.scope || '全局', '范围', 120).replace(/[\r\n]+/g, ' ')
69
+ const fact = required(input.fact, '事实', 4000)
70
+ if (!input.id) {
71
+ const entries = await search(topic, Infinity)
72
+ const existing = entries.find(item => item.topic === topic && item.scope === scope && item.fact === fact)
73
+ if (existing) return existing
74
+ }
75
+ const entry = { id, topic, scope, fact, source, updatedAt: new Date().toISOString() }
76
+ await replaceFile(pathFor(id), '# ' + topic + '\n范围:' + scope + '\n来源:' + source
77
+ + '\n更新:' + entry.updatedAt + '\n\n' + fact + '\n')
78
+ return entry
79
+ })
80
+ },
81
+ forget(id) {
82
+ return mutate(async () => {
83
+ if (!await read(id)) throw new InputError('找不到这条记忆。')
84
+ await unlink(pathFor(id))
85
+ })
86
+ },
87
+ }
88
+ }
package/host/routes.js ADDED
@@ -0,0 +1,79 @@
1
+ import manifest from '../package.json' with { type: 'json' }
2
+ import { InputError, required } from './store.js'
3
+
4
+ export const BASE = '/plugin/maid'
5
+ const MAX_BODY = 128 * 1024
6
+
7
+ function reply(res, code, value) {
8
+ res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store',
9
+ 'X-Content-Type-Options': 'nosniff', 'X-DSH-Maid-Version': manifest.version })
10
+ res.end(JSON.stringify(value))
11
+ }
12
+
13
+ async function json(req) {
14
+ if (req.headers['content-type']?.split(';')[0].trim() !== 'application/json') {
15
+ throw new InputError('请以 JSON 提交请求。')
16
+ }
17
+ const parts = []
18
+ let size = 0
19
+ for await (const part of req.iterator({ destroyOnReturn: false })) {
20
+ size += part.length
21
+ if (size > MAX_BODY) throw new InputError('请求内容过长。')
22
+ parts.push(part)
23
+ }
24
+ let value
25
+ try { value = JSON.parse(Buffer.concat(parts).toString('utf8')) }
26
+ catch { throw new InputError('请求内容无法读取。') }
27
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new InputError('请求内容无效。')
28
+ return value
29
+ }
30
+
31
+ export function createRoute(ctx, runtime) {
32
+ const { schedules, memory, persona } = runtime
33
+ const writes = new Map([
34
+ ['conversation', () => runtime.prepareConversation()],
35
+ ['message', body => runtime.submit(body)],
36
+ ['interrupt', () => runtime.interrupt()],
37
+ ['note', body => runtime.note(body.text, required(body.id, '请求 ID', 80))],
38
+ ['task', body => runtime.taskCreate(body, required(body.id, '请求 ID', 80))],
39
+ ['task/reply', body => runtime.taskReply(body.id, body.text)],
40
+ ['task/cancel', body => runtime.taskCancel(body.id)],
41
+ ['persona', body => persona.save(body.text)],
42
+ ['memory', body => memory.save(body, '用户手动记录')],
43
+ ['memory/forget', body => memory.forget(body.id)],
44
+ ['schedule', body => schedules.create(body, required(body.id, '请求 ID', 80))],
45
+ ['schedule/edit', body => schedules.edit(body)],
46
+ ])
47
+
48
+ return async (req, res) => {
49
+ try {
50
+ const admission = ctx.connection.admit(req)
51
+ if (admission.rejection !== undefined) return reply(res, admission.rejection, { error: 'DSH 未授权当前浏览器访问。' })
52
+ const address = req.socket.remoteAddress || ''
53
+ if (admission.peer !== ctx.connection.browserPeer || (address !== '::1' && !/^(?:::ffff:)?127\./i.test(address))) {
54
+ return reply(res, 403, { error: 'Maid 仅向本机的 DSH 浏览器界面开放。' })
55
+ }
56
+ const url = new URL(req.url, 'http://localhost')
57
+ const path = url.pathname.slice(BASE.length + 1)
58
+ if (req.method === 'GET') {
59
+ if (path === 'attention') return reply(res, 200, runtime.attention())
60
+ if (path === 'notebook') return reply(res, 200, await runtime.notebook())
61
+ if (path === 'state') return reply(res, 200, await runtime.snapshot(url.searchParams.get('before')))
62
+ if (path === 'task') return reply(res, 200, runtime.readTask(url.searchParams.get('id')))
63
+ if (path === 'persona') return reply(res, 200, { text: persona.read() })
64
+ if (path === 'memory') {
65
+ const entries = await memory.search(url.searchParams.get('query') ?? '', 100)
66
+ return reply(res, 200, entries.map(entry => ({ ...entry, fromChat: entry.source.startsWith(runtime.main + '#') })))
67
+ }
68
+ if (path === 'memory/source') return reply(res, 200, await runtime.memorySource(url.searchParams.get('id')))
69
+ }
70
+ const operation = req.method === 'POST' ? writes.get(path) : undefined
71
+ if (operation) return reply(res, 200, await operation(await json(req)) ?? { ok: true })
72
+ reply(res, 404, { error: '找不到这个 Maid 接口。' })
73
+ } catch (error) {
74
+ if (error instanceof InputError) return reply(res, 400, { error: error.message })
75
+ ctx.logger?.warn('Maid 请求失败:' + error.message)
76
+ reply(res, 500, { error: 'Maid 暂时无法完成操作。请检查 DSH 宿主日志。' })
77
+ }
78
+ }
79
+ }