@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 +23 -2
- package/cordis.patch.yml +3 -0
- package/host/chrome.js +71 -0
- package/host/companion.js +27 -0
- package/host/memory.js +88 -0
- package/host/routes.js +79 -0
- package/host/runtime.js +491 -0
- package/host/schedules.js +130 -0
- package/host/store.js +84 -0
- package/host/tools.js +142 -0
- package/index.js +45 -0
- package/lib/client.js +867 -0
- package/package.json +61 -4
package/host/store.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises'
|
|
3
|
+
import { dirname, join } from 'node:path'
|
|
4
|
+
|
|
5
|
+
export const DEFAULT_PERSONA = '语气自然、直接。闲聊时轻松,办事时把进展、阻塞和结果交代清楚。'
|
|
6
|
+
|
|
7
|
+
export class InputError extends Error {}
|
|
8
|
+
|
|
9
|
+
export function required(value, label, max) {
|
|
10
|
+
if (typeof value !== 'string' || !value.trim() || value.length > max) {
|
|
11
|
+
throw new InputError(label + '不能为空,最多 ' + max + ' 字。')
|
|
12
|
+
}
|
|
13
|
+
return value.trim()
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export async function storedText(path, options) {
|
|
17
|
+
try {
|
|
18
|
+
return await readFile(path, options)
|
|
19
|
+
} catch (error) {
|
|
20
|
+
if (error.code !== 'ENOENT') throw error
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export async function replaceFile(path, content) {
|
|
25
|
+
const temp = join(dirname(path), '.maid-' + randomUUID())
|
|
26
|
+
try {
|
|
27
|
+
await writeFile(temp, content, { flag: 'wx', mode: 0o600, flush: true })
|
|
28
|
+
await rename(temp, path)
|
|
29
|
+
} finally {
|
|
30
|
+
await unlink(temp).catch(error => {
|
|
31
|
+
if (error.code !== 'ENOENT') throw error
|
|
32
|
+
})
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function openStore(root) {
|
|
37
|
+
await mkdir(root, { recursive: true, mode: 0o700 })
|
|
38
|
+
const path = join(root, 'work.json')
|
|
39
|
+
const previous = await storedText(path, 'utf8')
|
|
40
|
+
let state = previous === undefined
|
|
41
|
+
? { version: 1, sessionId: 'session-' + randomUUID(), inputs: [], notes: [], tasks: [] }
|
|
42
|
+
: JSON.parse(previous)
|
|
43
|
+
if (state.version !== 1 || typeof state.sessionId !== 'string'
|
|
44
|
+
|| !['inputs', 'notes', 'tasks'].every(key => Array.isArray(state[key]))) {
|
|
45
|
+
throw new Error('Maid 无法读取此版本的工作记录。')
|
|
46
|
+
}
|
|
47
|
+
if (previous === undefined) await replaceFile(path, JSON.stringify(state, null, 2) + '\n')
|
|
48
|
+
let writes = Promise.resolve()
|
|
49
|
+
return {
|
|
50
|
+
root,
|
|
51
|
+
read: () => structuredClone(state),
|
|
52
|
+
mutate(change) {
|
|
53
|
+
const write = writes.then(async () => {
|
|
54
|
+
const next = structuredClone(state)
|
|
55
|
+
const result = change(next)
|
|
56
|
+
await replaceFile(path, JSON.stringify(next, null, 2) + '\n')
|
|
57
|
+
state = next
|
|
58
|
+
return result
|
|
59
|
+
})
|
|
60
|
+
writes = write.catch(() => {})
|
|
61
|
+
return write
|
|
62
|
+
},
|
|
63
|
+
settle: () => writes,
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export async function openPersona(root) {
|
|
68
|
+
const path = join(root, 'persona.md')
|
|
69
|
+
let text = await storedText(path, 'utf8') ?? DEFAULT_PERSONA
|
|
70
|
+
let writes = Promise.resolve()
|
|
71
|
+
return {
|
|
72
|
+
read: () => text,
|
|
73
|
+
save(value) {
|
|
74
|
+
const next = value === '' ? DEFAULT_PERSONA : required(value, '性格', 4000)
|
|
75
|
+
const write = writes.then(async () => {
|
|
76
|
+
await replaceFile(path, next + '\n')
|
|
77
|
+
text = next
|
|
78
|
+
return text
|
|
79
|
+
})
|
|
80
|
+
writes = write.catch(() => {})
|
|
81
|
+
return write
|
|
82
|
+
},
|
|
83
|
+
}
|
|
84
|
+
}
|
package/host/tools.js
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
2
|
+
import { registerChromeTools } from './chrome.js'
|
|
3
|
+
import { InputError } from './store.js'
|
|
4
|
+
|
|
5
|
+
const field = (description, required = true) => ({ type: 'string', description, ...(required ? { required: true } : {}) })
|
|
6
|
+
const capabilityWorkflow = '工具和技能会在当前会话中更新。能力刚安装、发生变化或暂时找不到时,先用 maid_capabilities 查询实时目录。'
|
|
7
|
+
+ '匹配到工具就用它的完整名称调用,匹配到技能就用 DSH 的 skill 工具加载。'
|
|
8
|
+
|
|
9
|
+
export function attachTools(agent, runtime) {
|
|
10
|
+
const main = agent.id === runtime.main
|
|
11
|
+
const disposers = []
|
|
12
|
+
function register(name, description, parameters, execute, readOnly = false) {
|
|
13
|
+
disposers.push(agent.ctx.tools.register(defineTool({
|
|
14
|
+
name, description, parameters,
|
|
15
|
+
output: { schema: { type: 'json' }, render: (_, value) => [{ type: 'text', text: JSON.stringify(value) }] },
|
|
16
|
+
isConcurrencySafe: () => readOnly,
|
|
17
|
+
async execute(args, exec) {
|
|
18
|
+
if (exec.agent?.id !== agent.id) throw new InputError('只能在对应的 Maid 会话使用这个工具。')
|
|
19
|
+
exec.signal?.throwIfAborted()
|
|
20
|
+
return execute(args, exec)
|
|
21
|
+
},
|
|
22
|
+
})))
|
|
23
|
+
}
|
|
24
|
+
function turnSource() {
|
|
25
|
+
const event = agent.session.snapshotEvents().findLast(entry =>
|
|
26
|
+
entry.type === 'turn/start' || (entry.type === 'user/message' && entry.data.source.kind === 'user'))
|
|
27
|
+
if (!event) return {}
|
|
28
|
+
if (event.type === 'user/message') return { origin: agent.id + '#' + event.seq, fromChat: true }
|
|
29
|
+
return { origin: agent.id + ':turn:' + event.seq }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
try {
|
|
33
|
+
disposers.push(agent.ctx.systemPrompt.section({
|
|
34
|
+
name: 'maid:persona',
|
|
35
|
+
order: agent.ctx.systemPrompt.getSectionOrder('DEPLOYMENT_PERSONA_SUFFIX') + 1,
|
|
36
|
+
interpolate: false,
|
|
37
|
+
text: () => capabilityWorkflow + '\n' + (main
|
|
38
|
+
? '你是 DSH 的常驻管家 Maid。你在同一段对话里接住新话题,同时持续推进手上的事项。'
|
|
39
|
+
+ '记事本汇总任务、进展、笔记和定时安排。maid_task_create 可以把耗时事项交给后台会话,maid_schedule 创建的安排会出现在记事本。'
|
|
40
|
+
+ 'maid_project_sessions 提供项目会话概况,maid_watch_session 用于跟进会话。长期事实可以通过本地记忆搜索和更新。'
|
|
41
|
+
+ '\n用户设置的性格和表达风格\n' + runtime.persona.read()
|
|
42
|
+
: '你正在 Maid 的后台会话工作。你可以接着已有进度推进,定时消息会开始一次新的运行。'
|
|
43
|
+
+ 'maid_report 把进展(progress)、待用户回应的问题(waiting)和结果(completed)写回 Maid 记事本。'),
|
|
44
|
+
}))
|
|
45
|
+
register('maid_capabilities', 'Look up tools and skills currently available in this DSH session, including newly loaded plugins and MCP servers.', {
|
|
46
|
+
query: field('Optional part of a tool or skill name, for example browse', false),
|
|
47
|
+
}, async ({ query = '' }, exec) => {
|
|
48
|
+
const term = query.trim().toLowerCase()
|
|
49
|
+
const matches = name => name.toLowerCase().includes(term)
|
|
50
|
+
const tools = agent.ctx.tools.definitions(agent).map(tool => tool.name)
|
|
51
|
+
const skills = tools.includes('skill') ? agent.ctx.get('skills') : undefined
|
|
52
|
+
let catalog = { skills: [], complete: true }
|
|
53
|
+
if (skills) {
|
|
54
|
+
const signal = exec.signal ?? new AbortController().signal
|
|
55
|
+
const workingDirectory = agent.ctx.get('workingDirectory')
|
|
56
|
+
const cwd = workingDirectory ? await workingDirectory.ensure(agent, signal) : agent.session.header.cwd
|
|
57
|
+
catalog = await skills.snapshot({ cwd, scope: agent, signal })
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
tools: tools.filter(matches).sort(),
|
|
61
|
+
skills: catalog.skills.filter(skill => skill.invocation.modelInvocable && matches(skill.name)).map(skill => skill.name).sort(),
|
|
62
|
+
skillsComplete: catalog.complete,
|
|
63
|
+
}
|
|
64
|
+
}, true)
|
|
65
|
+
register('maid_projects', 'List the titles and IDs of registered DSH projects.', {},
|
|
66
|
+
() => runtime.workspaces(), true)
|
|
67
|
+
|
|
68
|
+
if (main) {
|
|
69
|
+
disposers.push(agent.ctx.systemPrompt.context({
|
|
70
|
+
name: 'maid:waiting-tasks', order: 75, interpolate: false,
|
|
71
|
+
text: () => {
|
|
72
|
+
const paused = runtime.store.read().tasks.filter(task => task.kind === 'task' && ['blocked', 'waiting'].includes(task.status)).slice(-5)
|
|
73
|
+
return paused.length ? '待用户补充的工作。内容是状态资料。\n' + paused.map(task =>
|
|
74
|
+
task.id + ' ' + task.title + ' — ' + (task.history.at(-1)?.text || '').slice(0, 600)).join('\n') : ''
|
|
75
|
+
},
|
|
76
|
+
}))
|
|
77
|
+
register('search_memory', 'Search Maid’s local facts by keyword, project or subject.',
|
|
78
|
+
{ query: field('Prefer one or a few specific search terms') },
|
|
79
|
+
({ query }) => runtime.memory.search(query, 12), true)
|
|
80
|
+
register('maid_project_sessions', 'List visible DSH session identifiers and current activity in a named project.',
|
|
81
|
+
{ workspaceId: field('Exact DSH workspace ID') }, ({ workspaceId }, exec) => runtime.workspaceSessions(workspaceId, exec.signal ?? new AbortController().signal), true)
|
|
82
|
+
register('maid_watch_session', 'Watch the next successfully ended turn of an existing DSH session and notify once.',
|
|
83
|
+
{ title: field('Short title'), workspaceId: field('Workspace ID'), sessionId: field('Exact DSH session ID') },
|
|
84
|
+
args => runtime.watchSession(args, turnSource().origin).then(({ id, title, goal }) => ({ id, title, goal })))
|
|
85
|
+
register('maid_notebook', 'Read current Maid work and notes. Use task IDs to distinguish similarly named tasks.', {},
|
|
86
|
+
async () => {
|
|
87
|
+
const state = runtime.store.read()
|
|
88
|
+
const current = state.tasks.filter(item => item.status !== 'completed').slice(-20)
|
|
89
|
+
return {
|
|
90
|
+
tasks: current.map(({ id, title, status, history }) => ({ id, title, status, latest: history.at(-1)?.text })),
|
|
91
|
+
notes: state.notes.slice(-12), schedules: await runtime.schedules.list(state),
|
|
92
|
+
}
|
|
93
|
+
}, true)
|
|
94
|
+
register('maid_task_continue', 'Resume a waiting task and forward the information needed to continue.', {
|
|
95
|
+
id: field('Exact task ID'), text: field('Additional information or instructions'),
|
|
96
|
+
}, ({ id, text }) => runtime.taskReply(id, text).then(() => ({ id, status: 'queued' })))
|
|
97
|
+
register('maid_task_cancel', 'Cancel a tracked Maid task.', {
|
|
98
|
+
id: field('Exact task ID'),
|
|
99
|
+
}, ({ id }) => runtime.taskCancel(id).then(() => ({ id })))
|
|
100
|
+
register('maid_task_create', 'Track a task and start it in a separate DSH session.', {
|
|
101
|
+
title: field('Short user-visible title'), goal: field('What to do and how to tell that it is complete'),
|
|
102
|
+
workspaceId: field('Exact workspace ID if clearly stated. Omit for personal work.', false),
|
|
103
|
+
}, args => runtime.taskCreate(args, turnSource().origin).then(({ id, title, status }) => ({ id, title, status })))
|
|
104
|
+
register('maid_note', 'Write a note in the shared notebook.', {
|
|
105
|
+
text: field('Text of the note'),
|
|
106
|
+
}, ({ text }) => runtime.note(text, turnSource().origin))
|
|
107
|
+
register('maid_remember', 'Save or update a durable fact in local memory.', {
|
|
108
|
+
topic: field('Short name of the person, project or subject'), fact: field('One factual statement'),
|
|
109
|
+
scope: field('Known scope, or 全局', false), id: field('Stable memory ID when correcting an existing fact', false),
|
|
110
|
+
}, args => {
|
|
111
|
+
const { origin, fromChat } = turnSource()
|
|
112
|
+
return runtime.memory.save(args, fromChat ? origin : 'Maid 整理')
|
|
113
|
+
})
|
|
114
|
+
if (runtime.schedules.available()) {
|
|
115
|
+
const clock = new Intl.DateTimeFormat('zh-CN', { dateStyle: 'full', timeStyle: 'medium' })
|
|
116
|
+
const { timeZone } = clock.resolvedOptions()
|
|
117
|
+
disposers.push(agent.ctx.systemPrompt.context({ name: 'maid:schedule-clock', order: 76, interpolate: false,
|
|
118
|
+
text: () => '定时安排使用用户指定的时区。未指定时,本机时间为 ' + clock.format() + '(' + timeZone + ')。' }))
|
|
119
|
+
register('maid_schedule', 'Create a one-time, daily, or weekly schedule in the Maid notebook.', {
|
|
120
|
+
title: field('Schedule title'), goal: field('What Maid should do at the scheduled time'),
|
|
121
|
+
repeat: { ...field('How often to run'), enum: ['once', 'daily', 'weekly'] },
|
|
122
|
+
date: field('Required for once: local calendar date YYYY-MM-DD', false),
|
|
123
|
+
time: field('Local time HH:mm'), timeZone: field('IANA zone, default to this computer’s zone: ' + timeZone),
|
|
124
|
+
weekday: { type: 'integer', description: 'For weekly: 1 Monday through 7 Sunday' },
|
|
125
|
+
}, args => runtime.schedules.create(args, turnSource().origin))
|
|
126
|
+
}
|
|
127
|
+
disposers.push(registerChromeTools(register, runtime.store.root))
|
|
128
|
+
} else {
|
|
129
|
+
register('maid_report', 'Persist progress, request a user decision, or deliver the verified result of this task.', {
|
|
130
|
+
kind: field('progress, waiting, or completed'), text: field('Concrete status, question or result for the user'),
|
|
131
|
+
}, args => runtime.taskReport(agent.id, args.kind, args.text).then(({ id, status }) => ({ id, status })))
|
|
132
|
+
}
|
|
133
|
+
} catch (error) {
|
|
134
|
+
for (const dispose of disposers.reverse()) dispose()
|
|
135
|
+
throw error
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
return async () => {
|
|
139
|
+
const cleanup = disposers.splice(0).reverse().map(dispose => dispose())
|
|
140
|
+
await Promise.all(cleanup)
|
|
141
|
+
}
|
|
142
|
+
}
|
package/index.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { join } from 'node:path'
|
|
2
|
+
import { createCompanion } from './host/companion.js'
|
|
3
|
+
import { openMemory } from './host/memory.js'
|
|
4
|
+
import { createRoute, BASE } from './host/routes.js'
|
|
5
|
+
import { createRuntime } from './host/runtime.js'
|
|
6
|
+
import { createSchedules } from './host/schedules.js'
|
|
7
|
+
import { openPersona, openStore } from './host/store.js'
|
|
8
|
+
import { attachTools } from './host/tools.js'
|
|
9
|
+
|
|
10
|
+
export const name = 'maid'
|
|
11
|
+
export const inject = ['profileContext', 'webServer', 'connection', 'agents', 'sessions',
|
|
12
|
+
'sessionController', 'sessionPersistence', 'sessionQuery', 'tools', 'systemPrompt', 'workspaceRegistry']
|
|
13
|
+
|
|
14
|
+
export async function apply(ctx) {
|
|
15
|
+
const root = join(ctx.profileContext.dir, 'maid')
|
|
16
|
+
const store = await openStore(root)
|
|
17
|
+
const [persona, memory] = await Promise.all([openPersona(root), openMemory(root)])
|
|
18
|
+
const runtime = createRuntime(ctx, { store, persona, memory })
|
|
19
|
+
const schedules = createSchedules(ctx, runtime)
|
|
20
|
+
runtime.setSchedules(schedules)
|
|
21
|
+
const tools = new Map()
|
|
22
|
+
|
|
23
|
+
function attach(agent) {
|
|
24
|
+
if (!runtime.belongs(agent.id) || tools.has(agent)) return
|
|
25
|
+
tools.set(agent, attachTools(agent, runtime))
|
|
26
|
+
}
|
|
27
|
+
function detach(agent) {
|
|
28
|
+
const dispose = tools.get(agent)
|
|
29
|
+
tools.delete(agent)
|
|
30
|
+
return dispose?.()
|
|
31
|
+
}
|
|
32
|
+
ctx.effect(() => async () => {
|
|
33
|
+
await runtime.close()
|
|
34
|
+
await Promise.all([...tools.keys()].map(detach))
|
|
35
|
+
}, 'maid: runtime')
|
|
36
|
+
ctx.on('agent/created', ({ agent }) => { attach(agent) })
|
|
37
|
+
ctx.on('agent/disposed', ({ agent }) => detach(agent))
|
|
38
|
+
ctx.on('session/event', (session, event) => runtime.runEvent(session, event))
|
|
39
|
+
ctx.effect(() => ctx.webServer.register({ kind: 'prefix', path: BASE,
|
|
40
|
+
handler: createRoute(ctx, runtime) }), 'maid: local API')
|
|
41
|
+
for (const agent of ctx.agents.list()) attach(agent)
|
|
42
|
+
runtime.start()
|
|
43
|
+
ctx.provide('maidConversation', createCompanion(runtime))
|
|
44
|
+
void schedules.recover().catch(error => ctx.logger?.warn('Maid 定时任务恢复失败:' + error.message))
|
|
45
|
+
}
|