@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/CHANGELOG.md +23 -0
- package/LICENSE +21 -0
- package/README.md +82 -2
- package/README.zh.md +83 -0
- package/client.js +1023 -0
- package/cordis.patch.yml +16 -0
- package/docs/DETAIL.md +1 -0
- package/docs/DETAIL.zh.md +1 -0
- package/docs/preview.svg +47 -0
- package/icon.svg +8 -0
- package/index.js +397 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +79 -4
- package/src/mutations.js +81 -0
- package/src/notes.js +399 -0
- package/src/routes.js +208 -0
- package/src/share.js +231 -0
- package/src/store.js +214 -0
- package/src/system.js +123 -0
- package/src/tools.js +244 -0
package/src/mutations.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 便签的三次写操作:新建 / 修改 / 删除。
|
|
3
|
+
*
|
|
4
|
+
* 为什么单独一层:HTTP 路由(面板,人)和助手工具(模型)都要写同一个文件,规则必须一模一样——
|
|
5
|
+
* 校验(parseNoteInput)、重名(conflictOf)、数量上限(LIMITS.notes)、原子写(store.mutate)。
|
|
6
|
+
* 两边各写一遍迟早会漂移,所以只有这一份实现。
|
|
7
|
+
*
|
|
8
|
+
* 返回值统一成 { ok, status, error } 或 { ok, note },让调用方决定是回 HTTP 还是抛给模型。
|
|
9
|
+
*/
|
|
10
|
+
import { randomUUID } from 'node:crypto'
|
|
11
|
+
import { LIMITS, conflictOf, parseNoteInput } from './notes.js'
|
|
12
|
+
|
|
13
|
+
/** 新建一张便签。 */
|
|
14
|
+
export async function createNote(store, raw) {
|
|
15
|
+
const parsed = parseNoteInput(raw)
|
|
16
|
+
if (!parsed.ok) return { ok: false, status: 400, error: parsed.error }
|
|
17
|
+
let problem = null
|
|
18
|
+
let created = null
|
|
19
|
+
await store.mutate((doc) => {
|
|
20
|
+
if (doc.notes.length >= LIMITS.notes) { problem = { status: 409, error: `便签数量已达上限 ${LIMITS.notes}` }; return }
|
|
21
|
+
const dup = conflictOf(doc.notes, parsed.value)
|
|
22
|
+
if (dup) { problem = { status: 409, error: dup }; return }
|
|
23
|
+
const now = new Date().toISOString()
|
|
24
|
+
created = { id: randomUUID(), createdAt: now, updatedAt: now, ...parsed.value }
|
|
25
|
+
doc.notes.push(created)
|
|
26
|
+
})
|
|
27
|
+
if (problem) return { ok: false, ...problem }
|
|
28
|
+
return { ok: true, note: created }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** 改一张便签(部分更新;只提交变化的字段)。 */
|
|
32
|
+
export async function updateNote(store, id, raw) {
|
|
33
|
+
let problem = null
|
|
34
|
+
let updated = null
|
|
35
|
+
await store.mutate((doc) => {
|
|
36
|
+
const note = doc.notes.find((n) => n.id === id)
|
|
37
|
+
if (!note) { problem = { status: 404, error: '便签不存在(可能已被删除)' }; return }
|
|
38
|
+
const parsed = parseNoteInput(raw, { base: note })
|
|
39
|
+
if (!parsed.ok) { problem = { status: 400, error: parsed.error }; return }
|
|
40
|
+
const dup = conflictOf(doc.notes, { ...note, ...parsed.value }, id)
|
|
41
|
+
if (dup) { problem = { status: 409, error: dup }; return }
|
|
42
|
+
Object.assign(note, parsed.value, { updatedAt: new Date().toISOString() })
|
|
43
|
+
updated = note
|
|
44
|
+
})
|
|
45
|
+
if (problem) return { ok: false, ...problem }
|
|
46
|
+
return { ok: true, note: updated }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 删一张便签:**不是真删**,进文件的 `trash` 区(最近 50 条 / 30 天),面板上可以撤销。
|
|
51
|
+
* id 不存在也算成功(幂等:助手重试不会报错)。
|
|
52
|
+
*/
|
|
53
|
+
export async function deleteNote(store, id, now = new Date().toISOString()) {
|
|
54
|
+
let removed = false
|
|
55
|
+
await store.mutate((doc) => {
|
|
56
|
+
const note = doc.notes.find((n) => n.id === id)
|
|
57
|
+
if (!note) return
|
|
58
|
+
doc.notes = doc.notes.filter((n) => n.id !== id)
|
|
59
|
+
doc.trash = Array.isArray(doc.trash) ? doc.trash : []
|
|
60
|
+
doc.trash.unshift({ deletedAt: now, note })
|
|
61
|
+
removed = true
|
|
62
|
+
})
|
|
63
|
+
return { ok: true, removed }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** 从回收站捡回来(同一个 id,所以面板上「撤销」之后它还在原来的位置)。 */
|
|
67
|
+
export async function restoreNote(store, id, now = new Date().toISOString()) {
|
|
68
|
+
let restored = null
|
|
69
|
+
let problem = null
|
|
70
|
+
await store.mutate((doc) => {
|
|
71
|
+
const index = (Array.isArray(doc.trash) ? doc.trash : []).findIndex((t) => t.note && t.note.id === id)
|
|
72
|
+
if (index < 0) { problem = { status: 404, error: '回收站里没有这张便签' }; return }
|
|
73
|
+
if (doc.notes.some((n) => n.id === id)) { problem = { status: 409, error: '这张便签已经在便签簿里了' }; return }
|
|
74
|
+
if (doc.notes.length >= LIMITS.notes) { problem = { status: 409, error: `便签数量已达上限 ${LIMITS.notes}` }; return }
|
|
75
|
+
const [{ note }] = doc.trash.splice(index, 1)
|
|
76
|
+
restored = { ...note, updatedAt: now }
|
|
77
|
+
doc.notes.push(restored)
|
|
78
|
+
})
|
|
79
|
+
if (problem) return { ok: false, ...problem }
|
|
80
|
+
return { ok: true, note: restored }
|
|
81
|
+
}
|
package/src/notes.js
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-prompt-notes —— 纯逻辑层(无 I/O,可直接单测)。
|
|
3
|
+
*
|
|
4
|
+
* 一张「便签」是用户保存的一条常驻配置,有三种形态(kind):
|
|
5
|
+
* prompt 一段常驻提示词(语言规范、团队编码要求……),注入 system prompt
|
|
6
|
+
* skill 一个技能(名称 + 描述 + 正文),登记进 skill 注册表,模型按需加载
|
|
7
|
+
* mcp 一个 MCP 服务器(stdio 命令 / HTTP 地址),登记进 mcpManager,工具出现在工具列表
|
|
8
|
+
* 以及三种作用域(scope):
|
|
9
|
+
* global 所有会话
|
|
10
|
+
* workspace 工作目录在某个路径之内的会话
|
|
11
|
+
* session 仅某一个会话
|
|
12
|
+
*
|
|
13
|
+
* 「适用」是相对一个观察者(viewer = 会话 id + 工作目录)而言的:同一张便签,
|
|
14
|
+
* 对会话 A 生效、对会话 B 不生效。这里所有判定都以 viewer 为参数。
|
|
15
|
+
*/
|
|
16
|
+
import { isAbsolute, relative, resolve } from 'node:path'
|
|
17
|
+
|
|
18
|
+
export const KINDS = Object.freeze(['prompt', 'skill', 'mcp'])
|
|
19
|
+
export const SCOPES = Object.freeze(['global', 'workspace', 'session'])
|
|
20
|
+
/** 便签纸色。具体色值由前端决定;这里只是个枚举。 */
|
|
21
|
+
export const PAPERS = Object.freeze(['yellow', 'pink', 'blue', 'green', 'lilac'])
|
|
22
|
+
/** 每种形态默认的纸色:一眼分辨是提示词、技能还是 MCP。 */
|
|
23
|
+
export const DEFAULT_PAPER = Object.freeze({ prompt: 'yellow', skill: 'blue', mcp: 'green' })
|
|
24
|
+
/** v1 用的是主题 token 名,升级时映射到纸色。 */
|
|
25
|
+
const LEGACY_PAPER = Object.freeze({ brand: 'yellow', success: 'green', warn: 'pink', error: 'pink', idle: 'lilac' })
|
|
26
|
+
|
|
27
|
+
export const LIMITS = Object.freeze({
|
|
28
|
+
title: 80,
|
|
29
|
+
body: 20000,
|
|
30
|
+
description: 300,
|
|
31
|
+
whenToUse: 300,
|
|
32
|
+
tags: 8,
|
|
33
|
+
tag: 24,
|
|
34
|
+
notes: 200,
|
|
35
|
+
target: 1024,
|
|
36
|
+
command: 512,
|
|
37
|
+
url: 1024,
|
|
38
|
+
args: 32,
|
|
39
|
+
arg: 512,
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
/** 与 dsh-skill 的 SKILL_NAME 一致(kebab-case)。 */
|
|
43
|
+
export const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
|
|
44
|
+
/** 与 dsh-mcp-client 的 SERVER_NAME_PATTERN 一致;同时也是工具前缀 mcp__<name>__。 */
|
|
45
|
+
export const MCP_NAME = /^[A-Za-z0-9_-]{1,32}$/
|
|
46
|
+
const SESSION_ID = /^[A-Za-z0-9_.:-]{1,128}$/
|
|
47
|
+
|
|
48
|
+
/** 默认的注入预算(字符数,仅对 prompt 便签计)。0 = 不限。 */
|
|
49
|
+
export const DEFAULT_MAX_CHARS = 8000
|
|
50
|
+
|
|
51
|
+
const HEADER = [
|
|
52
|
+
"## Standing instructions from the user's prompt notes",
|
|
53
|
+
'',
|
|
54
|
+
'The user keeps the notes below and has switched them on for this session. ' +
|
|
55
|
+
"Treat each one as a standing instruction unless the user's current message says otherwise.",
|
|
56
|
+
].join('\n')
|
|
57
|
+
|
|
58
|
+
function clip(text, max) {
|
|
59
|
+
return text.length > max ? text.slice(0, max) : text
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// ───────────────────────── 作用域 ─────────────────────────
|
|
63
|
+
|
|
64
|
+
/** 去掉末尾分隔符并规整;不碰符号链接(纯字符串层面,无 I/O)。 */
|
|
65
|
+
export function normalizePath(p) {
|
|
66
|
+
return resolve(p)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** cwd 是否在 root 之内(含相等)。用 relative 判定,Windows/POSIX 通吃,且不会把 /a/bc 当成 /a/b 的子目录。 */
|
|
70
|
+
export function pathWithin(cwd, root) {
|
|
71
|
+
if (typeof cwd !== 'string' || typeof root !== 'string' || !cwd || !root) return false
|
|
72
|
+
if (!isAbsolute(cwd) || !isAbsolute(root)) return false
|
|
73
|
+
const rel = relative(normalizePath(root), normalizePath(cwd))
|
|
74
|
+
return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* 便签是否适用于某个观察者。
|
|
79
|
+
* @param {{scope:string,target:string}} note
|
|
80
|
+
* @param {{sessionId?:string,cwd?:string}} [viewer] 缺省 = 没有会话上下文,只有全局便签适用
|
|
81
|
+
*/
|
|
82
|
+
export function appliesTo(note, viewer = {}) {
|
|
83
|
+
if (note.scope === 'global') return true
|
|
84
|
+
if (note.scope === 'session') return Boolean(viewer.sessionId) && note.target === viewer.sessionId
|
|
85
|
+
if (note.scope === 'workspace') return pathWithin(viewer.cwd, note.target)
|
|
86
|
+
return false
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// ───────────────────────── 校验 ─────────────────────────
|
|
90
|
+
|
|
91
|
+
export function normalizeTags(input) {
|
|
92
|
+
const list = Array.isArray(input) ? input : typeof input === 'string' ? input.split(/[,,\n]/) : []
|
|
93
|
+
const seen = new Set()
|
|
94
|
+
const out = []
|
|
95
|
+
for (const raw of list) {
|
|
96
|
+
if (typeof raw !== 'string') continue
|
|
97
|
+
const tag = clip(raw.replace(/^#+/, '').replace(/\s+/g, ' ').trim(), LIMITS.tag)
|
|
98
|
+
if (!tag) continue
|
|
99
|
+
const key = tag.toLowerCase()
|
|
100
|
+
if (seen.has(key)) continue
|
|
101
|
+
seen.add(key)
|
|
102
|
+
out.push(tag)
|
|
103
|
+
if (out.length >= LIMITS.tags) break
|
|
104
|
+
}
|
|
105
|
+
return out
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 参数串:已是数组就清洗;是字符串则按空白切分,支持成对的单/双引号。 */
|
|
109
|
+
export function parseArgs(input) {
|
|
110
|
+
if (Array.isArray(input)) return input.filter((a) => typeof a === 'string').map((a) => clip(a, LIMITS.arg)).slice(0, LIMITS.args)
|
|
111
|
+
if (typeof input !== 'string') return []
|
|
112
|
+
const out = []
|
|
113
|
+
const re = /"((?:\\.|[^"\\])*)"|'([^']*)'|(\S+)/g
|
|
114
|
+
let m
|
|
115
|
+
while ((m = re.exec(input)) && out.length < LIMITS.args) {
|
|
116
|
+
out.push(clip(m[1] !== undefined ? m[1].replace(/\\(.)/g, '$1') : (m[2] ?? m[3]), LIMITS.arg))
|
|
117
|
+
}
|
|
118
|
+
return out
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const fail = (error) => ({ ok: false, error })
|
|
122
|
+
|
|
123
|
+
/** 把 kind 对应的子对象洗成规范形态;不属于该 kind 的子对象一律丢掉。 */
|
|
124
|
+
function validateKind(note) {
|
|
125
|
+
if (note.kind === 'prompt') {
|
|
126
|
+
if (!note.body) return fail('正文不能为空')
|
|
127
|
+
return { ok: true }
|
|
128
|
+
}
|
|
129
|
+
if (note.kind === 'skill') {
|
|
130
|
+
const s = note.skill ?? {}
|
|
131
|
+
if (typeof s.name !== 'string' || !SKILL_NAME.test(s.name)) return fail('技能名必须是 kebab-case(小写字母、数字、连字符,如 go-review)')
|
|
132
|
+
if (s.name.length > 64) return fail('技能名过长(≤64)')
|
|
133
|
+
const description = typeof s.description === 'string' ? s.description.replace(/\s+/g, ' ').trim() : ''
|
|
134
|
+
if (!description) return fail('技能必须有一句描述(模型靠它决定何时加载)')
|
|
135
|
+
if (description.length > LIMITS.description) return fail(`技能描述超过 ${LIMITS.description} 字`)
|
|
136
|
+
if (!note.body) return fail('技能正文不能为空')
|
|
137
|
+
|
|
138
|
+
// whenToUse:可选的「什么时候用我」,dsh-skill 会把它带进候选与摘要
|
|
139
|
+
const whenToUse = typeof s.whenToUse === 'string' ? s.whenToUse.replace(/\s+/g, ' ').trim() : ''
|
|
140
|
+
if (whenToUse.length > LIMITS.whenToUse) return fail(`「何时使用」超过 ${LIMITS.whenToUse} 字`)
|
|
141
|
+
|
|
142
|
+
// invocation:两种调用方式至少要留一种;两者都可调用是默认值,不落盘
|
|
143
|
+
const raw = s.invocation === undefined || s.invocation === null ? {} : s.invocation
|
|
144
|
+
if (typeof raw !== 'object' || Array.isArray(raw)) return fail('invocation 必须是对象')
|
|
145
|
+
const modelInvocable = raw.modelInvocable === undefined ? true : raw.modelInvocable
|
|
146
|
+
const userInvocable = raw.userInvocable === undefined ? true : raw.userInvocable
|
|
147
|
+
if (typeof modelInvocable !== 'boolean' || typeof userInvocable !== 'boolean') return fail('invocation 的两个开关必须是布尔值')
|
|
148
|
+
if (!modelInvocable && !userInvocable) return fail('至少要留一种调用方式(模型或用户)')
|
|
149
|
+
|
|
150
|
+
note.skill = { name: s.name, description }
|
|
151
|
+
if (whenToUse) note.skill.whenToUse = whenToUse
|
|
152
|
+
if (!modelInvocable || !userInvocable) note.skill.invocation = { modelInvocable, userInvocable }
|
|
153
|
+
return { ok: true }
|
|
154
|
+
}
|
|
155
|
+
if (note.kind === 'mcp') {
|
|
156
|
+
const m = note.mcp ?? {}
|
|
157
|
+
if (typeof m.name !== 'string' || !MCP_NAME.test(m.name)) return fail('MCP 名只能含字母、数字、下划线、连字符(≤32),它会成为工具前缀 mcp__<名>__')
|
|
158
|
+
if (m.transport !== 'stdio' && m.transport !== 'streamable-http') return fail('transport 必须是 stdio 或 streamable-http')
|
|
159
|
+
if (m.transport === 'stdio') {
|
|
160
|
+
const command = typeof m.command === 'string' ? m.command.trim() : ''
|
|
161
|
+
if (!command) return fail('stdio 的 MCP 必须填启动命令')
|
|
162
|
+
if (command.length > LIMITS.command) return fail('命令过长')
|
|
163
|
+
note.mcp = { name: m.name, transport: 'stdio', command, args: parseArgs(m.args), url: '' }
|
|
164
|
+
} else {
|
|
165
|
+
const url = typeof m.url === 'string' ? m.url.trim() : ''
|
|
166
|
+
let ok = false
|
|
167
|
+
try { const u = new URL(url); ok = u.protocol === 'http:' || u.protocol === 'https:' } catch { /* 非法 URL */ }
|
|
168
|
+
if (!ok) return fail('streamable-http 的 MCP 必须填 http(s) 地址')
|
|
169
|
+
if (url.length > LIMITS.url) return fail('地址过长')
|
|
170
|
+
note.mcp = { name: m.name, transport: 'streamable-http', command: '', args: [], url }
|
|
171
|
+
}
|
|
172
|
+
return { ok: true }
|
|
173
|
+
}
|
|
174
|
+
return fail(`kind 必须是 ${KINDS.join(' / ')} 之一`)
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function validateScope(note) {
|
|
178
|
+
if (!SCOPES.includes(note.scope)) return fail(`scope 必须是 ${SCOPES.join(' / ')} 之一`)
|
|
179
|
+
if (note.scope === 'global') { note.target = ''; return { ok: true } }
|
|
180
|
+
const target = typeof note.target === 'string' ? note.target.trim() : ''
|
|
181
|
+
if (!target) return fail(note.scope === 'session' ? '会话作用域需要会话 id' : '工作区作用域需要目录路径')
|
|
182
|
+
if (target.length > LIMITS.target) return fail('作用域目标过长')
|
|
183
|
+
if (note.scope === 'session') {
|
|
184
|
+
if (!SESSION_ID.test(target)) return fail('会话 id 含非法字符')
|
|
185
|
+
note.target = target
|
|
186
|
+
} else {
|
|
187
|
+
if (!isAbsolute(target)) return fail('工作区路径必须是绝对路径')
|
|
188
|
+
note.target = normalizePath(target)
|
|
189
|
+
}
|
|
190
|
+
return { ok: true }
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* 校验并合成一张便签(新建或部分更新)。
|
|
195
|
+
*
|
|
196
|
+
* @param {unknown} raw 请求体(不可信)
|
|
197
|
+
* @param {{ base?: object }} [opts] 更新时传现有便签;缺省 = 新建
|
|
198
|
+
* @returns {{ ok: true, value: object } | { ok: false, error: string }} value 是「应写入的字段」,
|
|
199
|
+
* 新建时是完整便签(除 id/时间戳),更新时只含变化的字段。
|
|
200
|
+
*/
|
|
201
|
+
export function parseNoteInput(raw, opts = {}) {
|
|
202
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return fail('请求体必须是 JSON 对象')
|
|
203
|
+
const base = opts.base
|
|
204
|
+
const creating = base === undefined
|
|
205
|
+
|
|
206
|
+
if (!creating && 'kind' in raw && raw.kind !== base.kind) return fail('不能更改便签的类型(请新建一张)')
|
|
207
|
+
|
|
208
|
+
const kind = creating ? raw.kind ?? 'prompt' : base.kind
|
|
209
|
+
const note = creating
|
|
210
|
+
? { kind, scope: 'global', target: '', title: '', body: '', tags: [], color: DEFAULT_PAPER[kind] ?? 'yellow', enabled: kind !== 'mcp' }
|
|
211
|
+
: structuredClone({ kind: base.kind, scope: base.scope, target: base.target, title: base.title, body: base.body,
|
|
212
|
+
tags: base.tags, color: base.color, enabled: base.enabled, skill: base.skill, mcp: base.mcp })
|
|
213
|
+
if (!KINDS.includes(kind)) return fail(`kind 必须是 ${KINDS.join(' / ')} 之一`)
|
|
214
|
+
|
|
215
|
+
const touched = new Set()
|
|
216
|
+
const take = (key, fn) => { if (key in raw) { const r = fn(raw[key]); if (r) return r; touched.add(key) } return null }
|
|
217
|
+
|
|
218
|
+
const errors = [
|
|
219
|
+
take('title', (v) => { if (typeof v !== 'string') return fail('title 必须是字符串'); note.title = clip(v.replace(/\s+/g, ' ').trim(), LIMITS.title) }),
|
|
220
|
+
take('body', (v) => {
|
|
221
|
+
if (typeof v !== 'string') return fail('body 必须是字符串')
|
|
222
|
+
const body = v.replace(/\r\n?/g, '\n').trim()
|
|
223
|
+
if (body.length > LIMITS.body) return fail(`正文超过 ${LIMITS.body} 字上限`)
|
|
224
|
+
note.body = body
|
|
225
|
+
}),
|
|
226
|
+
take('tags', (v) => { note.tags = normalizeTags(v) }),
|
|
227
|
+
take('color', (v) => { if (!PAPERS.includes(v)) return fail(`color 必须是 ${PAPERS.join(' / ')} 之一`); note.color = v }),
|
|
228
|
+
take('enabled', (v) => { if (typeof v !== 'boolean') return fail('enabled 必须是布尔值'); note.enabled = v }),
|
|
229
|
+
take('scope', (v) => { note.scope = v }),
|
|
230
|
+
take('target', (v) => { note.target = v }),
|
|
231
|
+
take('skill', (v) => { if (v === null || typeof v !== 'object') return fail('skill 必须是对象'); note.skill = { ...(note.skill ?? {}), ...v } }),
|
|
232
|
+
take('mcp', (v) => { if (v === null || typeof v !== 'object') return fail('mcp 必须是对象'); note.mcp = { ...(note.mcp ?? {}), ...v } }),
|
|
233
|
+
].find(Boolean)
|
|
234
|
+
if (errors) return errors
|
|
235
|
+
|
|
236
|
+
// 只在 scope 变成 global 时清 target;从 global 改成别的作用域必须同时给 target。
|
|
237
|
+
const sc = validateScope(note)
|
|
238
|
+
if (!sc.ok) return sc
|
|
239
|
+
const k = validateKind(note)
|
|
240
|
+
if (!k.ok) return k
|
|
241
|
+
if (kind !== 'skill') delete note.skill
|
|
242
|
+
if (kind !== 'mcp') delete note.mcp
|
|
243
|
+
|
|
244
|
+
if (creating) return { ok: true, value: note }
|
|
245
|
+
// 更新:只返回真正变化的字段(scope/target 一起带上,避免半更新)
|
|
246
|
+
const value = {}
|
|
247
|
+
for (const key of Object.keys(note)) {
|
|
248
|
+
if (JSON.stringify(note[key]) !== JSON.stringify(base[key])) value[key] = note[key]
|
|
249
|
+
}
|
|
250
|
+
return { ok: true, value }
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* 同一作用域里不能重名:MCP 名全库唯一(它是登记名、也是工具前缀 mcp__<名>__);
|
|
255
|
+
* skill 名在同一个 scope + target 里唯一。
|
|
256
|
+
* 路由(人写的请求)和助手工具共用这一条,免得两边判断不一致。
|
|
257
|
+
* @param {object[]} notes 现有便签
|
|
258
|
+
* @param {object} value 待写入的字段(新建时用它;更新时先与旧值合并)
|
|
259
|
+
* @param {string} [excludeId] 更新时排除自己
|
|
260
|
+
* @returns {string|null} 冲突说明(给人/给模型看的一句话),无冲突返回 null
|
|
261
|
+
*/
|
|
262
|
+
export function conflictOf(notes, value, excludeId) {
|
|
263
|
+
for (const n of notes) {
|
|
264
|
+
if (n.id === excludeId) continue
|
|
265
|
+
if (value.kind === 'mcp' && n.kind === 'mcp' && n.mcp && value.mcp && n.mcp.name === value.mcp.name) {
|
|
266
|
+
return `已有一张 MCP 便签使用名字 "${value.mcp.name}"`
|
|
267
|
+
}
|
|
268
|
+
if (value.kind === 'skill' && n.kind === 'skill' && n.skill && value.skill && n.skill.name === value.skill.name && n.scope === value.scope && n.target === value.target) {
|
|
269
|
+
return `这个作用域里已有同名技能 "${value.skill.name}"`
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return null
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// ───────────────────────── 展示与注入 ─────────────────────────
|
|
276
|
+
|
|
277
|
+
/** 标题为空时用正文首行(skill / mcp 用各自的名字)顶上。 */
|
|
278
|
+
export function displayTitle(note) {
|
|
279
|
+
if (note.title) return note.title
|
|
280
|
+
if (note.kind === 'skill' && note.skill?.name) return note.skill.name
|
|
281
|
+
if (note.kind === 'mcp' && note.mcp?.name) return note.mcp.name
|
|
282
|
+
const first = String(note.body ?? '').split('\n').find((line) => line.trim()) ?? ''
|
|
283
|
+
const t = first.replace(/^#+\s*/, '').trim()
|
|
284
|
+
return t.length > 40 ? `${t.slice(0, 40)}…` : t || '(untitled)'
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
export function renderBlock(note) {
|
|
288
|
+
return `### ${displayTitle(note)}\n${note.body}`
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** 注入顺序固定为「创建先后」:顺序稳定,编辑某条不会让其余内容的 KV cache 前缀失效。 */
|
|
292
|
+
export function injectionOrder(notes) {
|
|
293
|
+
return [...notes].sort((a, b) => (a.createdAt < b.createdAt ? -1 : a.createdAt > b.createdAt ? 1 : a.id < b.id ? -1 : 1))
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* 决定对某个观察者,哪些 prompt 便签真的会被注入。
|
|
298
|
+
*
|
|
299
|
+
* 预算对「最终渲染出的字符数」算(含标题与头部),与模型实际看到的一致。
|
|
300
|
+
* 一条放不下就整条放弃(不截断:被截一半的规则比没有更危险),但后面更短的仍可入选。
|
|
301
|
+
*
|
|
302
|
+
* @returns {{ injected: object[], overflow: string[], used: number, max: number }}
|
|
303
|
+
*/
|
|
304
|
+
export function planInjection(notes, maxChars = DEFAULT_MAX_CHARS, opts = {}) {
|
|
305
|
+
const max = Number.isFinite(maxChars) && maxChars >= 0 ? Math.floor(maxChars) : DEFAULT_MAX_CHARS
|
|
306
|
+
const injected = []
|
|
307
|
+
const overflow = []
|
|
308
|
+
if (opts.paused === true) return { injected, overflow, used: 0, max }
|
|
309
|
+
let used = HEADER.length
|
|
310
|
+
for (const note of injectionOrder(notes)) {
|
|
311
|
+
if (note.kind !== 'prompt' || note.enabled !== true || !appliesTo(note, opts.viewer)) continue
|
|
312
|
+
const cost = renderBlock(note).length + 2
|
|
313
|
+
if (max > 0 && used + cost > max) { overflow.push(note.id); continue }
|
|
314
|
+
injected.push(note)
|
|
315
|
+
used += cost
|
|
316
|
+
}
|
|
317
|
+
if (injected.length === 0) used = 0
|
|
318
|
+
return { injected, overflow, used, max }
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
export function renderSection(injected) {
|
|
322
|
+
if (!injected.length) return ''
|
|
323
|
+
return `${HEADER}\n\n${injected.map(renderBlock).join('\n\n')}`
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** 对某个观察者生效的 skill / MCP 便签(总开关关闭时为空)。 */
|
|
327
|
+
export function effectiveNotes(notes, kind, viewer, paused = false) {
|
|
328
|
+
if (paused) return []
|
|
329
|
+
return injectionOrder(notes).filter((n) => n.kind === kind && n.enabled === true && appliesTo(n, viewer))
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* 给每张便签标出「相对观察者」的状态,供面板分组:
|
|
334
|
+
* injected 正在生效(prompt 已注入 / skill 已装载 / MCP 已登记)
|
|
335
|
+
* overflow 已启用且适用,但字数预算放不下(仅 prompt)
|
|
336
|
+
* paused 已启用且适用,但总开关关了
|
|
337
|
+
* elsewhere 已启用,但不适用于当前会话/工作区
|
|
338
|
+
* off 未启用
|
|
339
|
+
* @param {Record<string, object>} [runtime] MCP 运行时状态,按 MCP 名索引
|
|
340
|
+
*/
|
|
341
|
+
export function describeNotes(notes, plan, opts = {}) {
|
|
342
|
+
const { paused = false, viewer, runtime = {} } = opts
|
|
343
|
+
const injectedIds = new Set(plan.injected.map((n) => n.id))
|
|
344
|
+
const overflowIds = new Set(plan.overflow)
|
|
345
|
+
return notes.map((note) => {
|
|
346
|
+
const applies = appliesTo(note, viewer)
|
|
347
|
+
let status
|
|
348
|
+
if (!note.enabled) status = 'off'
|
|
349
|
+
else if (!applies) status = 'elsewhere'
|
|
350
|
+
else if (paused) status = 'paused'
|
|
351
|
+
else if (note.kind === 'prompt') status = injectedIds.has(note.id) ? 'injected' : overflowIds.has(note.id) ? 'overflow' : 'off'
|
|
352
|
+
else status = 'injected'
|
|
353
|
+
const out = { ...note, status, applies, chars: note.kind === 'prompt' ? renderBlock(note).length : note.body.length }
|
|
354
|
+
// 只有启用的便签才附运行时状态:未启用时 mcpManager 里同名的条目(比如用户自己配置的)不是这张便签的。
|
|
355
|
+
if (note.kind === 'mcp' && note.enabled && note.mcp && runtime[note.mcp.name]) out.runtime = runtime[note.mcp.name]
|
|
356
|
+
return out
|
|
357
|
+
})
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// ───────────────────────── skill 适配 ─────────────────────────
|
|
361
|
+
|
|
362
|
+
/** 一张 skill 便签 → dsh-skill 的候选(SkillCandidate)。 */
|
|
363
|
+
export function skillCandidate(note) {
|
|
364
|
+
return {
|
|
365
|
+
name: note.skill.name,
|
|
366
|
+
description: note.skill.description,
|
|
367
|
+
...(note.skill.whenToUse ? { whenToUse: note.skill.whenToUse } : {}),
|
|
368
|
+
invocation: {
|
|
369
|
+
modelInvocable: note.skill.invocation?.modelInvocable !== false,
|
|
370
|
+
userInvocable: note.skill.invocation?.userInvocable !== false,
|
|
371
|
+
},
|
|
372
|
+
source: 'prompt-notes',
|
|
373
|
+
provider: 'prompt-notes',
|
|
374
|
+
resourceBase: { kind: 'opaque', description: 'a sticky note kept in the user\'s prompt-notes panel; it has no files' },
|
|
375
|
+
rank: 250,
|
|
376
|
+
locator: note.id,
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** 一张 skill 便签 → 完整 skill 定义(含正文)。 */
|
|
381
|
+
export function skillDefinition(note) {
|
|
382
|
+
const { rank, locator, ...summary } = skillCandidate(note)
|
|
383
|
+
return { ...summary, content: note.body }
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* MCP 便签 → mcpManager.register 的 entry。
|
|
388
|
+
*
|
|
389
|
+
* TODO(prompt-notes): 暂不支持 env / headers。它们常带令牌,明文存进便签文件不合适;
|
|
390
|
+
* 等接上凭据服务后用 `${credential:REF}` 模板引用(mcpManager 已支持 expandTemplates),
|
|
391
|
+
* 而不是把密钥写进 notes.json。目前 stdio 子进程继承 DSH 的(已清洗的)环境变量。
|
|
392
|
+
* TODO(prompt-notes): 技能还差「附带资源文件」;whenToUse 与调用策略(invocation)已经补上(M7)。
|
|
393
|
+
*/
|
|
394
|
+
export function mcpEntry(note) {
|
|
395
|
+
const m = note.mcp
|
|
396
|
+
return m.transport === 'stdio'
|
|
397
|
+
? { transport: 'stdio', command: m.command, args: m.args }
|
|
398
|
+
: { transport: 'streamable-http', url: m.url }
|
|
399
|
+
}
|