@kpeace/dsh-prompt-notes 0.0.0-stage → 0.3.0

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/src/system.js ADDED
@@ -0,0 +1,123 @@
1
+ /**
2
+ * 系统联动:读出「系统本身已经注入了什么」,让面板把它们当成只读便签摆出来。
3
+ *
4
+ * 全部是现场读取,不缓存业务数据、不替系统做任何决定:
5
+ * sections / contexts ← systemPrompt.assemble() 的真实结果(模型这一轮实际会看到的)
6
+ * skills ← skills.list()(含各 provider 来源)
7
+ * mcp ← mcpManager.list() 的连接状态 + assemble 里的 mcp__* 工具
8
+ *
9
+ * assemble() 会跑完整的 waterfall(含别的插件的监听器),所以:只在面板请求时才调、
10
+ * 3 秒内同一观察者复用结果、任何一步失败都只记进 errors,不让整个接口失败。
11
+ */
12
+
13
+ const CACHE_MS = 3000
14
+ /** 每段正文最多回传这么多字符;面板是预览,不是日志查看器。 */
15
+ const MAX_TEXT = 6000
16
+
17
+ function clip(text) {
18
+ const s = String(text ?? '')
19
+ return s.length > MAX_TEXT ? { text: s.slice(0, MAX_TEXT), truncated: true } : { text: s, truncated: false }
20
+ }
21
+
22
+ /** 通过一个 context 尝试取服务;缺失/抛错都当不存在。 */
23
+ function service(ctx, key) {
24
+ try { return ctx[key] } catch { return undefined }
25
+ }
26
+
27
+ /**
28
+ * 把请求里的 (sessionId, cwd) 解析成观察者。会话存在时以服务端为准——
29
+ * 前端传来的 cwd 只是兜底(会话列表摘要里的 cwd 可能滞后于 cd 命令)。
30
+ */
31
+ export function resolveViewer(ctx, { sessionId, cwd } = {}) {
32
+ const agents = service(ctx, 'agents')
33
+ let agent
34
+ try { agent = sessionId && agents?.get ? agents.get(sessionId) : undefined } catch { agent = undefined }
35
+ let liveCwd
36
+ if (agent) {
37
+ try { liveCwd = service(ctx, 'workingDirectory')?.get?.(agent.session) } catch { liveCwd = undefined }
38
+ }
39
+ return {
40
+ agent,
41
+ viewer: { sessionId: sessionId || undefined, cwd: liveCwd ?? (cwd || undefined) },
42
+ found: Boolean(agent),
43
+ }
44
+ }
45
+
46
+ /** 活动 agent 的会话 id 列表(给「这个会话 id 是否真实存在」做提示用)。 */
47
+ export function liveSessionIds(ctx) {
48
+ try { return (service(ctx, 'agents')?.list?.() ?? []).map((a) => a.id) } catch { return [] }
49
+ }
50
+
51
+ const cache = new Map()
52
+
53
+ /**
54
+ * @param {object} ctx 插件的 context
55
+ * @param {{sessionId?:string,cwd?:string}} query
56
+ * @param {{ selfSection: string }} opts 本插件注入的 section 名,用来在结果里标记「这是我自己的」
57
+ */
58
+ export async function collectSystem(ctx, query, opts) {
59
+ const key = `${query.sessionId ?? ''}|${query.cwd ?? ''}`
60
+ const hit = cache.get(key)
61
+ if (hit && Date.now() - hit.at < CACHE_MS) return hit.value
62
+
63
+ const { agent, viewer, found } = resolveViewer(ctx, query)
64
+ const errors = []
65
+ const out = {
66
+ session: { id: viewer.sessionId ?? null, cwd: viewer.cwd ?? null, found },
67
+ sections: [], contexts: [], skills: [], mcp: [], tools: { count: 0, mcpCount: 0 },
68
+ errors,
69
+ }
70
+
71
+ // 1) 真实的 prompt 组装结果
72
+ try {
73
+ const sp = service(ctx, 'systemPrompt')
74
+ if (!sp?.assemble) throw new Error('systemPrompt service unavailable')
75
+ const assembly = await sp.assemble(agent ? { agent, scope: agent } : {})
76
+ out.sections = (assembly.sections ?? []).map((s) => ({ name: s.name, mine: s.name === opts.selfSection, chars: String(s.text ?? '').length, ...clip(s.text) }))
77
+ out.contexts = (assembly.contexts ?? []).map((c) => ({ name: c.name, chars: String(c.text ?? '').length, ...clip(c.text) }))
78
+ const tools = assembly.tools ?? []
79
+ out.tools = { count: tools.length, mcpCount: tools.filter((t) => String(t.name).startsWith('mcp__')).length }
80
+ out.mcpTools = tools.filter((t) => String(t.name).startsWith('mcp__')).map((t) => t.name)
81
+ } catch (error) {
82
+ errors.push(`prompt: ${String(error?.message ?? error)}`)
83
+ }
84
+
85
+ // 2) skill 目录
86
+ try {
87
+ const skills = service(ctx, 'skills')
88
+ if (skills?.list) {
89
+ const list = await skills.list({ cwd: viewer.cwd, ...(agent ? { scope: agent } : {}) })
90
+ out.skills = list.map((s) => ({
91
+ name: s.name, description: s.description, source: s.source, provider: s.provider,
92
+ mine: s.provider === 'prompt-notes',
93
+ ...(s.whenToUse ? { whenToUse: s.whenToUse } : {}),
94
+ modelInvocable: s.invocation?.modelInvocable !== false,
95
+ userInvocable: s.invocation?.userInvocable !== false,
96
+ }))
97
+ }
98
+ } catch (error) {
99
+ errors.push(`skills: ${String(error?.message ?? error)}`)
100
+ }
101
+
102
+ // 3) MCP 服务器
103
+ try {
104
+ const mgr = service(ctx, 'mcpManager')
105
+ if (mgr?.list) {
106
+ out.mcp = mgr.list().map((v) => ({
107
+ name: v.name, configured: v.configured, state: v.status?.state ?? 'unknown',
108
+ error: v.status?.lastError ?? undefined,
109
+ tools: (out.mcpTools ?? []).filter((t) => t.startsWith(`mcp__${v.name}__`)).length,
110
+ }))
111
+ }
112
+ } catch (error) {
113
+ errors.push(`mcp: ${String(error?.message ?? error)}`)
114
+ }
115
+ delete out.mcpTools
116
+
117
+ cache.set(key, { at: Date.now(), value: out })
118
+ if (cache.size > 32) cache.delete(cache.keys().next().value)
119
+ return out
120
+ }
121
+
122
+ /** 仅供测试:清缓存。 */
123
+ export function _resetSystemCache() { cache.clear() }
package/src/tools.js ADDED
@@ -0,0 +1,244 @@
1
+ /**
2
+ * 助手工具:让模型也能读写便签(note_list / note_create / note_update / note_delete)。
3
+ *
4
+ * 为什么这套工具需要「安全边界」而不是简单地转发到路由:
5
+ * 1. MCP 便签钉上 = 在本机以 DSH 的权限启动一条命令。这件事只能由人做,
6
+ * 所以助手创建的 MCP 便签一律未钉住,助手也不能把任何 MCP 便签改成启用。
7
+ * 2. 改一张**已在跑**的 MCP 便签的启动命令,会触发重登记 → 换一条新命令去跑。
8
+ * 所以助手只能改 MCP 便签的标题 / 备注 / 标签这些纯装饰字段,不能动 mcp / enabled / scope / target。
9
+ * 3. 一次调用只动一张便签(不批量),正文长度沿用 parseNoteInput 的上限,
10
+ * 列表里的正文有总额度上限 —— 助手不该一次把整个便签簿灌进上下文。
11
+ * 4. 校验、重名、数量上限全部复用 src/mutations.js / src/notes.js,与面板走的 HTTP 端同一条路径。
12
+ *
13
+ * 工具的结果一律是一段文本(JSON),模型读它就是数据;错误直接抛,工具管线会把它变成
14
+ * 一次「工具失败」结果,不会中断整轮对话。
15
+ */
16
+ import { appliesTo } from './notes.js'
17
+ import { createNote, deleteNote, updateNote } from './mutations.js'
18
+
19
+ export const NOTE_TOOL_NAMES = Object.freeze(['note_list', 'note_create', 'note_update', 'note_delete'])
20
+ /** 列表里最多回传这么多字符的正文(跨便签合计),超了只给摘要。 */
21
+ const LIST_BODY_BUDGET = 6000
22
+ /** 单张便签回传的正文上限。 */
23
+ const LIST_BODY_PER_NOTE = 2000
24
+
25
+ const KINDS = ['prompt', 'skill', 'mcp']
26
+ const SCOPES = ['global', 'workspace', 'session']
27
+
28
+ // execute 返回的是**值**(这里是给模型读的一段文本),render 才把它包成内容块。
29
+ const text = (value) => [{ type: 'text', text: String(value) }]
30
+ const json = (rows) => JSON.stringify(rows, null, 1)
31
+
32
+ const SKILL_SCHEMA = {
33
+ type: 'object',
34
+ additionalProperties: false,
35
+ properties: {
36
+ name: { type: 'string', description: 'kebab-case, e.g. go-review' },
37
+ description: { type: 'string', description: 'one line; the model decides when to load the skill by this' },
38
+ whenToUse: { type: 'string', description: 'optional: when this skill applies, e.g. "when reviewing Go code"' },
39
+ invocation: {
40
+ type: 'object',
41
+ additionalProperties: false,
42
+ description: 'who may invoke it; default both',
43
+ properties: {
44
+ modelInvocable: { type: 'boolean' },
45
+ userInvocable: { type: 'boolean' },
46
+ },
47
+ },
48
+ },
49
+ }
50
+ const MCP_SCHEMA = {
51
+ type: 'object',
52
+ additionalProperties: false,
53
+ properties: {
54
+ name: { type: 'string', description: 'becomes the tool prefix mcp__<name>__' },
55
+ transport: { type: 'string', enum: ['stdio', 'streamable-http'] },
56
+ command: { type: 'string' },
57
+ args: { type: 'array', items: { type: 'string' } },
58
+ url: { type: 'string' },
59
+ },
60
+ }
61
+
62
+ /** 便签 → 给模型看的紧凑形态(不含内部字段,正文按额度给)。 */
63
+ function brief(note, viewer, bodyBudget) {
64
+ const out = {
65
+ id: note.id, kind: note.kind, scope: note.scope, target: note.target || undefined,
66
+ title: note.title || undefined, enabled: note.enabled, applies: appliesTo(note, viewer),
67
+ chars: String(note.body || '').length, updatedAt: note.updatedAt,
68
+ }
69
+ if (note.kind === 'skill' && note.skill) {
70
+ out.skill = {
71
+ name: note.skill.name,
72
+ description: note.skill.description,
73
+ ...(note.skill.whenToUse ? { whenToUse: note.skill.whenToUse } : {}),
74
+ invocation: {
75
+ modelInvocable: note.skill.invocation?.modelInvocable !== false,
76
+ userInvocable: note.skill.invocation?.userInvocable !== false,
77
+ },
78
+ }
79
+ }
80
+ if (note.kind === 'mcp' && note.mcp) out.mcp = { name: note.mcp.name, transport: note.mcp.transport, command: note.mcp.command || undefined, url: note.mcp.url || undefined }
81
+ if (bodyBudget !== undefined) {
82
+ const body = String(note.body || '')
83
+ const take = Math.min(body.length, LIST_BODY_PER_NOTE, Math.max(0, bodyBudget))
84
+ if (take > 0) { out.body = body.slice(0, take); if (take < body.length) out.truncated = true }
85
+ }
86
+ return out
87
+ }
88
+
89
+ /**
90
+ * @param {{ store: object, viewerOf: (agent: object|undefined) => {sessionId?:string, cwd?:string} }} deps
91
+ */
92
+ export function createNoteToolDefinitions({ store, viewerOf }) {
93
+ const viewerFor = (exec) => {
94
+ try { return viewerOf(exec?.agent) || {} } catch { return {} }
95
+ }
96
+
97
+ return [
98
+ {
99
+ name: 'note_list',
100
+ description: [
101
+ "List the user's prompt notes: the sticky notes in the Notes tab that carry standing prompts, skills, and MCP server configs.",
102
+ 'Each row says which kind and scope it has, whether it applies to this session right now, and whether it is pinned (enabled).',
103
+ 'Read-only. Set includeBody to include the note text; the total is capped, so list without it first.',
104
+ ].join(' '),
105
+ parameters: {
106
+ type: 'object',
107
+ additionalProperties: false,
108
+ properties: {
109
+ kind: { type: 'string', enum: KINDS },
110
+ scope: { type: 'string', enum: SCOPES },
111
+ includeBody: { type: 'boolean', description: 'include note text (capped by a total budget)' },
112
+ },
113
+ },
114
+ output: { schema: { type: 'string' }, render: (_args, value) => text(value) },
115
+ execute(args = {}, exec) {
116
+ const viewer = viewerFor(exec)
117
+ const doc = store.snapshot()
118
+ const picked = doc.notes
119
+ .filter((n) => (args.kind ? n.kind === args.kind : true) && (args.scope ? n.scope === args.scope : true))
120
+ let budget = args.includeBody ? LIST_BODY_BUDGET : undefined
121
+ const rows = picked.map((n) => {
122
+ const row = brief(n, viewer, budget)
123
+ if (budget !== undefined) budget -= String(row.body || '').length
124
+ return row
125
+ })
126
+ return json({ viewer, paused: doc.paused, count: rows.length, notes: rows })
127
+ },
128
+ },
129
+
130
+ {
131
+ name: 'note_create',
132
+ description: [
133
+ "Create one note for the user: a standing prompt (injected into sessions by scope), a skill (listed in the model's skill catalog), or an MCP server config.",
134
+ 'MCP notes are ALWAYS created unpinned and the assistant cannot enable one — only the user can pin an MCP server in the panel, because pinning starts a local process.',
135
+ 'This writes the user\'s real notes file: keep bodies short and do not paste secrets.',
136
+ ].join(' '),
137
+ parameters: {
138
+ type: 'object',
139
+ additionalProperties: false,
140
+ required: ['body'],
141
+ properties: {
142
+ kind: { type: 'string', enum: KINDS, description: 'default prompt' },
143
+ body: { type: 'string', description: 'note text' },
144
+ title: { type: 'string' },
145
+ scope: { type: 'string', enum: SCOPES, description: 'default global' },
146
+ target: { type: 'string', description: 'session id or absolute directory, required for session / workspace scope' },
147
+ enabled: { type: 'boolean', description: 'ignored (always false) for MCP notes' },
148
+ tags: { type: 'array', items: { type: 'string' } },
149
+ skill: SKILL_SCHEMA,
150
+ mcp: MCP_SCHEMA,
151
+ },
152
+ },
153
+ output: { schema: { type: 'string' }, render: (_args, value) => text(value) },
154
+ async execute(args = {}, exec) {
155
+ const input = { ...args }
156
+ delete input.includeBody
157
+ // 助手建的 MCP 便签一律未钉住:钉上等于在本机启动一条命令,只能由人决定。
158
+ if ((input.kind ?? 'prompt') === 'mcp') delete input.enabled
159
+ const result = await createNote(store, input)
160
+ if (!result.ok) throw new Error(result.error)
161
+ const viewer = viewerFor(exec)
162
+ const row = brief(result.note, viewer, 0)
163
+ const note = (input.kind ?? 'prompt') === 'mcp'
164
+ ? 'created unpinned; the user has to pin it in the panel to start it'
165
+ : 'created'
166
+ return json({ ok: true, note: row, hint: note })
167
+ },
168
+ },
169
+
170
+ {
171
+ name: 'note_update',
172
+ description: [
173
+ 'Update one note by id; fields you omit stay unchanged. You cannot change a note\'s kind.',
174
+ 'For MCP notes you may only change title, body and tags: the assistant cannot enable an MCP note or alter its command, scope or target — only the user can edit those in the panel.',
175
+ ].join(' '),
176
+ parameters: {
177
+ type: 'object',
178
+ additionalProperties: false,
179
+ required: ['id'],
180
+ properties: {
181
+ id: { type: 'string' },
182
+ title: { type: 'string' },
183
+ body: { type: 'string' },
184
+ tags: { type: 'array', items: { type: 'string' } },
185
+ scope: { type: 'string', enum: SCOPES },
186
+ target: { type: 'string' },
187
+ enabled: { type: 'boolean' },
188
+ skill: SKILL_SCHEMA,
189
+ mcp: MCP_SCHEMA,
190
+ },
191
+ },
192
+ output: { schema: { type: 'string' }, render: (_args, value) => text(value) },
193
+ async execute(args = {}, exec) {
194
+ const id = typeof args.id === 'string' ? args.id : ''
195
+ const note = store.snapshot().notes.find((n) => n.id === id)
196
+ if (!note) throw new Error(`no note with id "${id}" (use note_list to find one)`)
197
+ if (note.kind === 'mcp') {
198
+ const blocked = ['mcp', 'enabled', 'scope', 'target'].filter((k) => k in args)
199
+ if (blocked.length) {
200
+ throw new Error(`only the user can change ${blocked.join(', ')} on an MCP note; the assistant may change title, body or tags`)
201
+ }
202
+ }
203
+ const patch = { ...args }
204
+ delete patch.id
205
+ delete patch.includeBody
206
+ const result = await updateNote(store, id, patch)
207
+ if (!result.ok) throw new Error(result.error)
208
+ const viewer = viewerFor(exec)
209
+ return json({ ok: true, note: brief(result.note, viewer, LIST_BODY_PER_NOTE) })
210
+ },
211
+ },
212
+
213
+ {
214
+ name: 'note_delete',
215
+ description: 'Delete one note by id. It stops being injected / registered immediately. It goes to a trash the user can undo from; the assistant cannot restore it.',
216
+ parameters: {
217
+ type: 'object',
218
+ additionalProperties: false,
219
+ required: ['id'],
220
+ properties: { id: { type: 'string' } },
221
+ },
222
+ output: { schema: { type: 'string' }, render: (_args, value) => text(value) },
223
+ async execute(args = {}) {
224
+ const id = typeof args.id === 'string' ? args.id : ''
225
+ if (!id) throw new Error('id is required')
226
+ const before = store.snapshot().notes.find((n) => n.id === id)
227
+ const result = await deleteNote(store, id)
228
+ return json({ ok: true, deleted: result.removed, id, kind: before?.kind })
229
+ },
230
+ },
231
+ ]
232
+ }
233
+
234
+ /**
235
+ * 注册到工具服务上;返回一个「全部撤销」的函数(测试和插件卸载都用得上)。
236
+ * @param {object} tools ctx.tools(必须带 register)
237
+ * @param {{ store: object, viewerOf: Function }} deps
238
+ */
239
+ export function registerNoteTools(tools, deps) {
240
+ if (!tools?.register) return () => {}
241
+ const disposers = []
242
+ for (const definition of createNoteToolDefinitions(deps)) disposers.push(tools.register(definition))
243
+ return () => { for (const fn of disposers) { try { fn() } catch { /* 已随插件卸载 */ } } }
244
+ }