lingshu-skill 0.0.0-stage → 3.79.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 +2571 -0
- package/LICENSE +21 -0
- package/README.md +698 -3
- package/SKILL-lite.md +45 -0
- package/SKILL-tiny.md +37 -0
- package/SKILL.md +379 -0
- package/assets/panel.html +5616 -0
- package/cordis-plugin/lingshu-cron/cordis.patch.yml +3 -0
- package/cordis-plugin/lingshu-cron/index.js +4 -0
- package/cordis-plugin/lingshu-cron/package.json +34 -0
- package/cordis-plugin/lingshu-cron/plugin.js +1040 -0
- package/cordis-plugin/lingshu-guard/plugin.js +473 -0
- package/cordis-plugin/lingshu-im/plugin.js +635 -0
- package/cordis-plugin/lingshu-startup/README.md +123 -0
- package/cordis-plugin/lingshu-startup/cordis.patch.yml +3 -0
- package/cordis-plugin/lingshu-startup/index.js +4 -0
- package/cordis-plugin/lingshu-startup/package.json +25 -0
- package/cordis-plugin/lingshu-startup/plugin.js +352 -0
- package/cordis.patch.yml +3 -0
- package/docs/commands.md +243 -0
- package/docs/mechanics.md +610 -0
- package/docs/models.md +52 -0
- package/docs/npm-/345/217/221/345/270/203/350/257/264/346/230/216.md +49 -0
- package/docs/panel-api.md +198 -0
- package/docs/recovery.md +90 -0
- package/docs/tgz-/345/256/211/350/243/205/350/257/264/346/230/216.md +53 -0
- package/docs//350/277/233/345/261/225/344/270/216/345/276/205/345/212/236.md +802 -0
- package/index.js +102 -0
- package/package.json +52 -6
- package/scripts/_panel_smoke_v299.py +27 -0
- package/scripts/_smoke_v299.py +31 -0
- package/scripts/_sync_trae_cn.py +34 -0
- package/scripts/assembler.py +197 -0
- package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +53 -0
- package/scripts/astrbot_plugin_lingshu/PATCH_NOTES.md +28 -0
- package/scripts/astrbot_plugin_lingshu/README.md +58 -0
- package/scripts/astrbot_plugin_lingshu/_conf_schema.json +92 -0
- package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +2571 -0
- package/scripts/astrbot_plugin_lingshu/engine/README.md +698 -0
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +45 -0
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +37 -0
- package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +379 -0
- package/scripts/astrbot_plugin_lingshu/engine/assets/panel.html +5616 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/commands.md +243 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/mechanics.md +610 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/models.md +52 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/panel-api.md +198 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/recovery.md +90 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_panel_smoke_v299.py +27 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_smoke_v299.py +31 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_sync_trae_cn.py +34 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/assembler.py +197 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/behavior_baseline.py +280 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/bench.py +192 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/brain.py +46 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/check_pressure_sync.py +55 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/check_tag.py +215 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/checkpoint.py +165 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +4850 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/context_ab.py +260 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +2025 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/dream.py +1137 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/emotion.py +1180 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/failures.py +107 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/fallback_embed.py +114 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +4745 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/growth_parts.py +263 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/insights.py +131 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/make_dsh_tgz.py +92 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_dialogue.py +242 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_embed.py +159 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_lesson.py +160 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_score.py +210 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_topic.py +177 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +4352 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/npm_prepack.py +31 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_build.py +115 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_cloud.py +609 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +2703 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panels.py +591 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/persona.py +2309 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/retriever.py +195 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/safety.py +368 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/session_import.py +736 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/session_rag.py +228 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/session_summary.py +123 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/summarizer.py +252 -0
- package/scripts/astrbot_plugin_lingshu/main.py +703 -0
- package/scripts/astrbot_plugin_lingshu/make_checksums.py +87 -0
- package/scripts/astrbot_plugin_lingshu/metadata.yaml +7 -0
- package/scripts/behavior_baseline.py +280 -0
- package/scripts/bench.py +192 -0
- package/scripts/brain.py +46 -0
- package/scripts/check_pressure_sync.py +55 -0
- package/scripts/check_tag.py +215 -0
- package/scripts/check_version.py +265 -0
- package/scripts/checkpoint.py +165 -0
- package/scripts/cli.py +4850 -0
- package/scripts/context_ab.py +260 -0
- package/scripts/core.py +2025 -0
- package/scripts/dream.py +1137 -0
- package/scripts/emotion.py +1180 -0
- package/scripts/failures.py +107 -0
- package/scripts/fallback_embed.py +114 -0
- package/scripts/growth.py +4745 -0
- package/scripts/growth_parts.py +263 -0
- package/scripts/hooks/pre-commit +18 -0
- package/scripts/hooks/pre-push +20 -0
- package/scripts/insights.py +131 -0
- package/scripts/make_dsh_tgz.py +92 -0
- package/scripts/make_manifest.py +254 -0
- package/scripts/make_plugin_zip.py +88 -0
- package/scripts/mem_dialogue.py +242 -0
- package/scripts/mem_embed.py +159 -0
- package/scripts/mem_lesson.py +160 -0
- package/scripts/mem_score.py +210 -0
- package/scripts/mem_topic.py +177 -0
- package/scripts/memory.py +4352 -0
- package/scripts/npm_prepack.py +31 -0
- package/scripts/panel_build.py +115 -0
- package/scripts/panel_cloud.py +609 -0
- package/scripts/panel_server.py +2703 -0
- package/scripts/panels.py +591 -0
- package/scripts/persona.py +2309 -0
- package/scripts/recreate_push.ps1 +117 -0
- package/scripts/retriever.py +195 -0
- package/scripts/run_tests.py +91 -0
- package/scripts/safety.py +368 -0
- package/scripts/session_import.py +736 -0
- package/scripts/session_rag.py +228 -0
- package/scripts/session_summary.py +123 -0
- package/scripts/summarizer.py +252 -0
- package/scripts/sync_engine.py +139 -0
- package/scripts/update_dsh_copy.ps1 +107 -0
- package/start-panel.bat +60 -0
|
@@ -0,0 +1,473 @@
|
|
|
1
|
+
// 灵枢 · 群聊发言人鉴权插件(lingshu-guard)
|
|
2
|
+
//
|
|
3
|
+
// 为什么需要它:dsh-im 把 QQ/微信/飞书等 IM 会话接进 DSH 后,群聊里任何成员都
|
|
4
|
+
// 能跟模型聊天——但模型手里的工具是宿主的全部能力:shell、写文件、subagent……
|
|
5
|
+
// 群友一句「帮我执行」就等于把终端交出去了。本插件在工具执行前按「发言人是谁」
|
|
6
|
+
// 做鉴权:
|
|
7
|
+
// * 桌面会话(没有 IM 绑定)不受影响,工具照常;
|
|
8
|
+
// * 群聊/私聊里的 owner 放行一切工具;
|
|
9
|
+
// * 其他人只放行只读工具,其余拒绝;拿不到发言人身份时 fail-closed。
|
|
10
|
+
//
|
|
11
|
+
// 机制(签名读自 app.asar 内 @deepseek-ai/dsh-tools 源码,别凭记忆改):
|
|
12
|
+
// src/index.ts guard(guard: ToolGuard): () => void
|
|
13
|
+
// src/contracts.ts type ToolGuard = (execution: Readonly<ToolExecution>) => string | ToolGuardDenial | undefined
|
|
14
|
+
// interface ToolGuardDenial { readonly reason: string; readonly info?: ToolErrorInfo }
|
|
15
|
+
// src/pipeline.ts pre-execute → 审批 → checkGuards → 工具体;
|
|
16
|
+
// guard 返回 string 即拒绝(作为模型可见的失败原因),
|
|
17
|
+
// 返回 undefined 放行;守卫是单调的(后注册监听器翻不了案)。
|
|
18
|
+
// 所以:优先 ctx.tools.guard(fn),在 agent/created 时注册到该 agent 的 ctx 上
|
|
19
|
+
// (tools.guard 的 effect 归 agent 作用域所有,agent 销毁自动清理;guard 同时
|
|
20
|
+
// 覆盖该 agent 派生的子 agent)。宿主太旧没有 tools.guard 时退回
|
|
21
|
+
// agentCtx.on('tools/pre-execute', …)(waterfall,同样随 agent 作用域清理)。
|
|
22
|
+
// 两种路径都返回明确的 deny 原因;不存在「只能返回布尔」的 API。
|
|
23
|
+
//
|
|
24
|
+
// 身份(编码与 cordis-plugin/lingshu-im/plugin.js 的 toIdentity 完全一致):
|
|
25
|
+
// channel = encodeURIComponent(platform) + '@' + encodeURIComponent(botId)
|
|
26
|
+
// user = channel + ':' + encodeURIComponent(senderId)
|
|
27
|
+
// group = chatType !== 'dm' 时取 chatId,私聊为空
|
|
28
|
+
// 两路来源互补(与 lingshu-im 相同,事件先到/服务后加载都能覆盖):
|
|
29
|
+
// 1. dshIm.describeConversationSync(sessionId) ← 宿主只读服务(同步反查)
|
|
30
|
+
// 2. dsh-im/session-pre-bind 事件缓存 ← 绑定瞬间的 channel/sender
|
|
31
|
+
// groups 的 conversationKey 解析不出 senderId 时会话侧为 null,恰好靠事件缓存
|
|
32
|
+
// 和 describe 的 authors 快照补齐;两路都没有 senderId 就按 fail-closed 拒绝。
|
|
33
|
+
//
|
|
34
|
+
// 配置(~/.brain-memory/config.json 的 guard 段;支持 BRAIN_MEMORY_HOME 与 .home
|
|
35
|
+
// 指针;宿主透传的 config 优先级更高):
|
|
36
|
+
// { "guard": { "enabled": true, "shadow": false, "owners": [],
|
|
37
|
+
// "readOnlyAllow": ["read", ...], "logPath": "" } }
|
|
38
|
+
// * owners:缺省(未配或空数组)回退同文件顶层 owners 数组——与 CLI 的
|
|
39
|
+
// channel 身份编码一致(形如 "qq@qq_xxx:C858…"),不用再维护第二份名单。
|
|
40
|
+
// * shadow=false(默认):已启用拦截——非 owner 调用有副作用工具直接拒绝并记日志。
|
|
41
|
+
// 显式设 shadow=true 进入观察模式:只记日志不拦,启动时会打一条明确的 warn。
|
|
42
|
+
//
|
|
43
|
+
// 日志:JSONL,默认 ~/.brain-memory/lingshu-guard.log,字段
|
|
44
|
+
// {ts, action:'allow'|'deny'|'shadow-deny', tool, sender, channel, group}
|
|
45
|
+
// deny = 已拦截;shadow-deny = 观察模式(shadow=true)下"本该拦截"只记账。
|
|
46
|
+
// 只记录 IM 会话的判定;桌面会话不产生日志。
|
|
47
|
+
|
|
48
|
+
import { appendFileSync, mkdirSync, readFileSync, statSync } from 'node:fs'
|
|
49
|
+
import { homedir } from 'node:os'
|
|
50
|
+
import { dirname, join } from 'node:path'
|
|
51
|
+
|
|
52
|
+
export const name = 'dsh-lingshu-guard'
|
|
53
|
+
|
|
54
|
+
// 默认只读白名单:v3.75 收紧——移除 read/glob/grep/web_search。
|
|
55
|
+
// 原因:这些"只读"工具可读任意本地路径(read/glob/grep)或把内容外带(web_search),
|
|
56
|
+
// 而灵枢记忆与 token 就是 HOME 下的明文 *.jsonl / config.json。非 owner 一句
|
|
57
|
+
// "读 ~/.brain-memory/hippocampus.jsonl 贴出来"就能绕过 channel/consent 门控拿到
|
|
58
|
+
// 全体成员跨群记忆和密钥。现在只放行**不接触本地路径、无副作用**的工具。
|
|
59
|
+
// 需要让非 owner 读记忆时,应走灵枢自带的 channel recall(有 group/consent 门控),
|
|
60
|
+
// 不靠通用文件读取工具。显式 readOnlyAllow 可覆盖此表(用户自己承担风险)。
|
|
61
|
+
const DEFAULT_READ_ONLY = [
|
|
62
|
+
'list_agents',
|
|
63
|
+
'skill',
|
|
64
|
+
'todo_write',
|
|
65
|
+
'ask_user_question',
|
|
66
|
+
]
|
|
67
|
+
|
|
68
|
+
// guard 段默认值。shadow 默认 false:默认就拦(安全优先),不再"只记日志不拦"。
|
|
69
|
+
// 需要先观察误伤时显式设 shadow=true,启动会打 warn(观察模式,敏感命令不拦)。
|
|
70
|
+
const DEFAULT_GUARD = {
|
|
71
|
+
enabled: true,
|
|
72
|
+
shadow: false,
|
|
73
|
+
readOnlyAllow: null, // null = 用 DEFAULT_READ_ONLY
|
|
74
|
+
logPath: '',
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const enc = (v) => encodeURIComponent(String(v ?? ''))
|
|
78
|
+
const asText = (v) => String(v ?? '').trim()
|
|
79
|
+
|
|
80
|
+
// ---------------------------------------------------------------- 配置
|
|
81
|
+
|
|
82
|
+
/** 记忆目录:BRAIN_MEMORY_HOME > ~/.brain-memory/.home 指针 > ~/.brain-memory。 */
|
|
83
|
+
function memoryHome() {
|
|
84
|
+
const env = asText(process.env.BRAIN_MEMORY_HOME)
|
|
85
|
+
if (env) return env
|
|
86
|
+
const base = join(homedir(), '.brain-memory')
|
|
87
|
+
try {
|
|
88
|
+
const ptr = readFileSync(join(base, '.home'), 'utf8').trim()
|
|
89
|
+
if (ptr) return ptr
|
|
90
|
+
} catch { /* 没有指针文件就用默认目录 */ }
|
|
91
|
+
return base
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// config.json 很小但每次工具调用都读不划算:按 mtime 缓存一份(brain.py 改完
|
|
95
|
+
// 配置、文件 mtime 变化后下一次调用即生效,不用重启宿主)。
|
|
96
|
+
let configCache = { path: '', mtime: -1, data: {} }
|
|
97
|
+
|
|
98
|
+
function readBrainConfig() {
|
|
99
|
+
try {
|
|
100
|
+
const file = join(memoryHome(), 'config.json')
|
|
101
|
+
let mtime = -1
|
|
102
|
+
try { mtime = statSync(file).mtimeMs } catch { mtime = -1 }
|
|
103
|
+
if (configCache.path === file && configCache.mtime === mtime) return configCache.data
|
|
104
|
+
let data = {}
|
|
105
|
+
if (mtime >= 0) {
|
|
106
|
+
try {
|
|
107
|
+
const parsed = JSON.parse(readFileSync(file, 'utf8'))
|
|
108
|
+
data = parsed && typeof parsed === 'object' ? parsed : {}
|
|
109
|
+
} catch { data = {} }
|
|
110
|
+
}
|
|
111
|
+
configCache = { path: file, mtime, data }
|
|
112
|
+
return data
|
|
113
|
+
} catch {
|
|
114
|
+
return {}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function stringList(value) {
|
|
119
|
+
if (!Array.isArray(value)) return []
|
|
120
|
+
return value
|
|
121
|
+
.filter((x) => typeof x === 'string' || typeof x === 'number')
|
|
122
|
+
.map((x) => String(x).trim())
|
|
123
|
+
.filter(Boolean)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* 合并默认值、config.json 的 guard 段与宿主透传 config。
|
|
128
|
+
* 宿主 config(profile/bundle 里显式写的)优先;空字符串视为未配置。
|
|
129
|
+
*/
|
|
130
|
+
function resolveGuardConfig(hostConfig) {
|
|
131
|
+
const file = readBrainConfig()
|
|
132
|
+
const fileGuard = file?.guard && typeof file.guard === 'object' ? file.guard : {}
|
|
133
|
+
const host = hostConfig && typeof hostConfig === 'object' ? hostConfig : {}
|
|
134
|
+
const pick = (key) => {
|
|
135
|
+
const h = host[key]
|
|
136
|
+
if (h !== undefined && h !== null && h !== '') return h
|
|
137
|
+
return fileGuard[key]
|
|
138
|
+
}
|
|
139
|
+
const enabled = pick('enabled') === undefined ? DEFAULT_GUARD.enabled : pick('enabled') !== false
|
|
140
|
+
const shadow = pick('shadow') === undefined ? DEFAULT_GUARD.shadow : pick('shadow') !== false
|
|
141
|
+
// owners:guard 段没配/为空时回退同文件顶层 owners(CLI 用的那份名单)。
|
|
142
|
+
let owners = stringList(pick('owners'))
|
|
143
|
+
if (!owners.length) owners = stringList(file?.owners)
|
|
144
|
+
// readOnlyAllow:配了数组就照用(显式 [] = 一个只读工具都不放),否则用默认表。
|
|
145
|
+
const allowRaw = pick('readOnlyAllow')
|
|
146
|
+
const readOnlyAllow = Array.isArray(allowRaw) ? stringList(allowRaw) : DEFAULT_READ_ONLY
|
|
147
|
+
const logPathRaw = pick('logPath')
|
|
148
|
+
const logPath = asText(logPathRaw) || join(memoryHome(), 'lingshu-guard.log')
|
|
149
|
+
return { enabled, shadow, owners, readOnlyAllow, logPath }
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// ---------------------------------------------------------------- 身份
|
|
153
|
+
|
|
154
|
+
/** Harness session id:agent.session.id(与 lingshu-im 一致),其余字段兜底。 */
|
|
155
|
+
function sessionIdOf(agent) {
|
|
156
|
+
const s = agent?.session
|
|
157
|
+
for (const v of [s?.id, agent?.sessionId, agent?.id]) {
|
|
158
|
+
if (typeof v === 'string' && v) return v
|
|
159
|
+
}
|
|
160
|
+
return null
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* 把绑定/服务返回的 conversation 描述归一成灵枢身份三元组(最小复刻
|
|
165
|
+
* lingshu-im 的 toIdentity,不 import 它以免循环依赖)。
|
|
166
|
+
* 返回 null 表示「有 IM 绑定但拿不到发言人身份」——调用方按 fail-closed 处理。
|
|
167
|
+
*/
|
|
168
|
+
function toIdentity(described) {
|
|
169
|
+
if (!described || typeof described !== 'object') return null
|
|
170
|
+
const channelName = asText(described.channel)
|
|
171
|
+
if (!channelName) return null
|
|
172
|
+
const botId = asText(described.botId)
|
|
173
|
+
const channel = botId ? `${enc(channelName)}@${enc(botId)}` : enc(channelName)
|
|
174
|
+
const senderId = asText(described.senderId)
|
|
175
|
+
if (!senderId) return null
|
|
176
|
+
const user = `${channel}:${enc(senderId)}`
|
|
177
|
+
const chatType = asText(described.chatType)
|
|
178
|
+
const chatId = asText(described.chatId)
|
|
179
|
+
const group = chatType && chatType !== 'dm' ? chatId : ''
|
|
180
|
+
return { channel, user, group, channelName, botId, chatType, chatId, senderId }
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** 取身份解析服务(宿主可能没装 dsh-im,或服务还没就绪)。 */
|
|
184
|
+
function dshImService(ctx) {
|
|
185
|
+
try {
|
|
186
|
+
return ctx?.get?.('dshIm') ?? null
|
|
187
|
+
} catch {
|
|
188
|
+
return null
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* 合并事件缓存与 describeConversationSync 的结果。
|
|
194
|
+
* 合并规则:服务侧字段覆盖事件侧;但服务侧的空值(null/'')不覆盖事件侧——
|
|
195
|
+
* 群聊 conversationKey 解析不出 senderId 时服务侧是 null,而 session-pre-bind
|
|
196
|
+
* 事件里的 authors 快照可能带 senderId,不能把它抹掉。
|
|
197
|
+
*/
|
|
198
|
+
function describeFor(ctx, bindings, sessionId) {
|
|
199
|
+
if (!sessionId) return null
|
|
200
|
+
let base = bindings.get(sessionId) || null
|
|
201
|
+
let live = null
|
|
202
|
+
try {
|
|
203
|
+
const svc = dshImService(ctx)
|
|
204
|
+
if (svc && typeof svc.describeConversationSync === 'function') {
|
|
205
|
+
live = svc.describeConversationSync(sessionId)
|
|
206
|
+
}
|
|
207
|
+
} catch {
|
|
208
|
+
live = null
|
|
209
|
+
}
|
|
210
|
+
if (live && typeof live !== 'object') live = null
|
|
211
|
+
if (!base) return live
|
|
212
|
+
if (!live) return base
|
|
213
|
+
const merged = { ...base, ...live }
|
|
214
|
+
for (const key of [
|
|
215
|
+
'channel', 'botId', 'chatType', 'chatId', 'threadId',
|
|
216
|
+
'conversationKey', 'senderId', 'senderName',
|
|
217
|
+
]) {
|
|
218
|
+
const v = merged[key]
|
|
219
|
+
if ((v === null || v === undefined || v === '') && base[key] !== undefined) {
|
|
220
|
+
merged[key] = base[key]
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
return merged
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* owners 匹配(v3.75 收紧):**只认完整三元组身份**。
|
|
228
|
+
*
|
|
229
|
+
* 原来还把裸 senderId、`channelName:senderId` 当 owner 候选——但 senderId
|
|
230
|
+
* 在不同通道可能相同(如 QQ 和微信都可能有 "12345"),owners 里配了裸
|
|
231
|
+
* senderId 时,任意通道撞号的成员都会被判 owner、拿到全部工具权限。
|
|
232
|
+
* 现在只匹配 CLI 口径的完整身份 `channel:user`(含 botId 的编码形态)。
|
|
233
|
+
* 老配置里若仍是裸 senderId,需要用 `brain.py channel owner list` 查到完整
|
|
234
|
+
* 身份后重新登记;启动时会对疑似裸 senderId 的 owner 打一次告警。
|
|
235
|
+
*/
|
|
236
|
+
function isOwner(owners, id) {
|
|
237
|
+
if (!owners.length || !id || !id.user) return false
|
|
238
|
+
const candidates = new Set([id.user])
|
|
239
|
+
// 完整三元组(不含 botId 的形态与含 botId 的形态——两者都是编码后的完整身份)
|
|
240
|
+
if (id.channelName) {
|
|
241
|
+
const encName = enc(id.channelName)
|
|
242
|
+
candidates.add(`${encName}:${enc(id.senderId)}`)
|
|
243
|
+
if (id.botId) candidates.add(`${encName}@${enc(id.botId)}:${enc(id.senderId)}`)
|
|
244
|
+
}
|
|
245
|
+
for (const owner of owners) {
|
|
246
|
+
if (candidates.has(owner)) return true
|
|
247
|
+
}
|
|
248
|
+
return false
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** 疑似裸 senderId 的 owner(纯数字/短 id,无通道前缀)——启动时告警用。 */
|
|
252
|
+
function suspiciousOwners(owners) {
|
|
253
|
+
return owners.filter((o) => !String(o).includes(':') && !String(o).includes('@'))
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** 日志里的身份字段(身份不完整时也尽量给出通道/群,便于排查)。 */
|
|
257
|
+
function logFields(id, described) {
|
|
258
|
+
const channelName = asText(described?.channel) || id?.channelName || ''
|
|
259
|
+
const botId = asText(described?.botId) || id?.botId || ''
|
|
260
|
+
const channel = id?.channel
|
|
261
|
+
|| (channelName ? (botId ? `${enc(channelName)}@${enc(botId)}` : enc(channelName)) : '')
|
|
262
|
+
const rawSender = asText(described?.senderId)
|
|
263
|
+
const sender = id?.user || (rawSender ? `${channel}:${enc(rawSender)}` : '')
|
|
264
|
+
const chatType = asText(described?.chatType) || id?.chatType || ''
|
|
265
|
+
const group = id?.group || (chatType && chatType !== 'dm' ? asText(described?.chatId) : '')
|
|
266
|
+
return { sender, channel, group }
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// ---------------------------------------------------------------- 日志
|
|
270
|
+
|
|
271
|
+
function appendLog(logPath, entry) {
|
|
272
|
+
try {
|
|
273
|
+
mkdirSync(dirname(logPath), { recursive: true })
|
|
274
|
+
appendFileSync(logPath, JSON.stringify(entry) + '\n', 'utf8')
|
|
275
|
+
} catch { /* 日志失败不能拖垮工具调用 */ }
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function nowIso() {
|
|
279
|
+
return new Date().toISOString()
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// ---------------------------------------------------------------- 策略
|
|
283
|
+
|
|
284
|
+
function senderLabel(id) {
|
|
285
|
+
return id.senderName ? `${id.senderName}(${id.senderId})` : id.senderId
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function denyReason(id, tool) {
|
|
289
|
+
const where = id.group ? `群 ${id.group}` : '私聊'
|
|
290
|
+
return `灵枢·guard 拒绝:IM 发言人 ${senderLabel(id)}(通道 ${id.channel},${where})`
|
|
291
|
+
+ `不在 owners 白名单,只允许只读工具(readOnlyAllow);工具 "${tool}" 有副作用,已拒绝。`
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function failClosedReason(tool) {
|
|
295
|
+
return `灵枢·guard 拒绝:这是 IM 绑定会话,但拿不到发言人身份(channel/senderId 缺失),`
|
|
296
|
+
+ `无法确认是谁在调用工具,按 fail-closed 拒绝 "${tool}"。`
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function denyOrShadow(cfg, tool, fields, reason) {
|
|
300
|
+
const action = cfg.shadow ? 'shadow-deny' : 'deny'
|
|
301
|
+
appendLog(cfg.logPath, { ts: nowIso(), action, tool, ...fields })
|
|
302
|
+
return cfg.shadow ? undefined : reason
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* 核心判定(同步):返回 string 表示拒绝原因,undefined 表示放行。
|
|
307
|
+
* 任何内部异常都 fail-closed(影子模式除外),绝不静默放行。
|
|
308
|
+
*/
|
|
309
|
+
function checkTool(ctx, bindings, hostConfig, exec, agent) {
|
|
310
|
+
let cfg
|
|
311
|
+
try {
|
|
312
|
+
cfg = resolveGuardConfig(hostConfig)
|
|
313
|
+
} catch {
|
|
314
|
+
return '灵枢·guard 拒绝:鉴权配置读取失败,按 fail-closed 拒绝。'
|
|
315
|
+
}
|
|
316
|
+
if (!cfg.enabled) return undefined
|
|
317
|
+
|
|
318
|
+
const tool = asText(exec?.name)
|
|
319
|
+
const subject = agent || exec?.agent || null
|
|
320
|
+
const sessionId = sessionIdOf(subject) || sessionIdOf(exec?.agent)
|
|
321
|
+
|
|
322
|
+
let described = null
|
|
323
|
+
let id = null
|
|
324
|
+
let resolveError = null
|
|
325
|
+
try {
|
|
326
|
+
described = describeFor(ctx, bindings, sessionId)
|
|
327
|
+
if (described) id = toIdentity(described)
|
|
328
|
+
} catch (err) {
|
|
329
|
+
resolveError = err
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
if (resolveError) {
|
|
333
|
+
const fields = { sender: '', channel: '', group: '' }
|
|
334
|
+
return denyOrShadow(cfg, tool, fields, failClosedReason(tool))
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// v3.75:区分"真桌面会话"与"IM 会话但身份解析失败"。
|
|
338
|
+
// 原来 described=null 一律放行——但 describeConversationSync 暂不可用且
|
|
339
|
+
// session-pre-bind 事件漏了时,IM 会话也会被当桌面会话,非 owner 可用
|
|
340
|
+
// shell/写文件/subagent 且无审计。现在:bindings 里有这个 session(事件侧
|
|
341
|
+
// 明确登记过 IM 绑定)却解析不出身份 → fail-closed;只有真正无任何绑定
|
|
342
|
+
// 痕迹的才当桌面会话放行。
|
|
343
|
+
if (!described) {
|
|
344
|
+
if (sessionId && bindings.has(sessionId)) {
|
|
345
|
+
const fields = { sender: '', channel: '', group: '' }
|
|
346
|
+
return denyOrShadow(cfg, tool, fields,
|
|
347
|
+
`灵枢·guard 拒绝:这是已绑定的 IM 会话,但身份解析失败(宿主只读服务不可用),`
|
|
348
|
+
+ `无法确认发言人,按 fail-closed 拒绝 "${tool}"。`)
|
|
349
|
+
}
|
|
350
|
+
return undefined
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// 有 IM 绑定但身份不完整:无法确认发言人 → fail-closed(只读工具也拒绝)。
|
|
354
|
+
if (!id) {
|
|
355
|
+
const fields = logFields(null, described)
|
|
356
|
+
return denyOrShadow(cfg, tool, fields, failClosedReason(tool))
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
const fields = logFields(id, described)
|
|
360
|
+
if (isOwner(cfg.owners, id)) {
|
|
361
|
+
appendLog(cfg.logPath, { ts: nowIso(), action: 'allow', tool, ...fields })
|
|
362
|
+
return undefined
|
|
363
|
+
}
|
|
364
|
+
if (cfg.readOnlyAllow.includes(tool)) {
|
|
365
|
+
appendLog(cfg.logPath, { ts: nowIso(), action: 'allow', tool, ...fields })
|
|
366
|
+
return undefined
|
|
367
|
+
}
|
|
368
|
+
return denyOrShadow(cfg, tool, fields, denyReason(id, tool))
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// ---------------------------------------------------------------- 插件主体
|
|
372
|
+
|
|
373
|
+
function warnOnce(ctx, message, error) {
|
|
374
|
+
try {
|
|
375
|
+
ctx?.logger?.warn?.(message, error)
|
|
376
|
+
} catch { /* logger 不可用就算了 */ }
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
export function apply(ctx, config) {
|
|
380
|
+
const hostConfig = config && typeof config === 'object' ? config : {}
|
|
381
|
+
// sessionId -> dsh-im/session-pre-bind 载荷(事件侧身份缓存)
|
|
382
|
+
const bindings = new Map()
|
|
383
|
+
let warned = false
|
|
384
|
+
const warn = (message, error) => {
|
|
385
|
+
if (warned) return
|
|
386
|
+
warned = true
|
|
387
|
+
warnOnce(ctx, message, error)
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
// shadow=true 是观察模式(只记日志不拦)。启动时明确警告一次,避免用户
|
|
391
|
+
// "以为已经开启鉴权、其实敏感命令全被放行"。默认 shadow=false 不触发。
|
|
392
|
+
try {
|
|
393
|
+
const gc = resolveGuardConfig(hostConfig)
|
|
394
|
+
if (gc.shadow) {
|
|
395
|
+
warnOnce(ctx, 'lingshu-guard: 当前处于观察模式(shadow=true),敏感命令不会被拦截,只记日志;'
|
|
396
|
+
+ '确认不会误伤后请改为 shadow=false 以启用拦截')
|
|
397
|
+
}
|
|
398
|
+
// v3.75:裸 senderId 当 owner 已失效(跨通道撞号可冒充主人),启动时告警一次。
|
|
399
|
+
if (gc.enabled && !gc.shadow) {
|
|
400
|
+
const bare = suspiciousOwners(gc.owners)
|
|
401
|
+
if (bare.length) {
|
|
402
|
+
warnOnce(ctx, 'lingshu-guard: owners 里疑似有裸 senderId(' + bare.slice(0, 5).join('、')
|
|
403
|
+
+ '),v3.75 起只认完整三元组身份(channel:user),这些条目已不再生效;'
|
|
404
|
+
+ '请用 `brain.py channel owner list` 查到完整身份后重新登记')
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
} catch { /* 配置读取异常交给 checkTool 按 fail-closed 处理,这里不重复报错 */ }
|
|
408
|
+
|
|
409
|
+
// dsh-im 绑定通告:只登记,不做 IO(事件在消息处理链路里同步发出)。
|
|
410
|
+
ctx.on('dsh-im/session-pre-bind', (payload) => {
|
|
411
|
+
try {
|
|
412
|
+
const sessionId = asText(payload?.sessionId)
|
|
413
|
+
if (!sessionId) return
|
|
414
|
+
bindings.set(sessionId, { ...payload })
|
|
415
|
+
if (bindings.size > 4096) {
|
|
416
|
+
for (const key of [...bindings.keys()].slice(0, 1024)) bindings.delete(key)
|
|
417
|
+
}
|
|
418
|
+
} catch { /* 坏载荷忽略 */ }
|
|
419
|
+
})
|
|
420
|
+
ctx.on('dsh-im/session-unbind', (payload) => {
|
|
421
|
+
try {
|
|
422
|
+
const sessionId = asText(payload?.sessionId)
|
|
423
|
+
if (sessionId) bindings.delete(sessionId)
|
|
424
|
+
} catch { /* 坏载荷忽略 */ }
|
|
425
|
+
})
|
|
426
|
+
|
|
427
|
+
const check = (exec, agent) => checkTool(ctx, bindings, hostConfig, exec, agent)
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* 给一个 agent 注册守卫。注册在 agent.ctx 上,作用域随 agent 销毁自动释放:
|
|
431
|
+
* 对话结束、会话删除、agent 重建都不会留下悬挂的守卫或重复注册。
|
|
432
|
+
*/
|
|
433
|
+
function registerFor(agent) {
|
|
434
|
+
try {
|
|
435
|
+
const agentCtx = agent?.ctx
|
|
436
|
+
if (!agentCtx || typeof agentCtx.on !== 'function') return
|
|
437
|
+
let tools = null
|
|
438
|
+
try {
|
|
439
|
+
tools = typeof agentCtx.get === 'function' ? agentCtx.get('tools') : null
|
|
440
|
+
} catch { tools = null }
|
|
441
|
+
if (tools && typeof tools.guard === 'function') {
|
|
442
|
+
try {
|
|
443
|
+
// 首选:单调执行守卫(dsh-tools 的正式 API)。
|
|
444
|
+
tools.guard((exec) => check(exec, agent))
|
|
445
|
+
return
|
|
446
|
+
} catch (error) {
|
|
447
|
+
warn('lingshu-guard: tools.guard 注册失败,退回 tools/pre-execute', error)
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
// 旧宿主降级:pre-execute waterfall 里做同样的判定。
|
|
451
|
+
agentCtx.on('tools/pre-execute', async (exec, next) => {
|
|
452
|
+
const reason = check(exec, agent)
|
|
453
|
+
if (reason) return { kind: 'deny', reason }
|
|
454
|
+
return next()
|
|
455
|
+
})
|
|
456
|
+
} catch (error) {
|
|
457
|
+
warn('lingshu-guard: 注册工具守卫失败,IM 鉴权未生效(请检查宿主 dsh-tools 版本)', error)
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
ctx.on('agent/created', (payload) => {
|
|
462
|
+
registerFor(payload?.agent)
|
|
463
|
+
})
|
|
464
|
+
|
|
465
|
+
// 热加载兜底:插件晚于 agent 创建挂载时,给已经活着的 agent 补注册。
|
|
466
|
+
try {
|
|
467
|
+
const registry = ctx.get?.('agents')
|
|
468
|
+
const live = registry && typeof registry.list === 'function' ? registry.list() : null
|
|
469
|
+
if (Array.isArray(live)) {
|
|
470
|
+
for (const agent of live) registerFor(agent)
|
|
471
|
+
}
|
|
472
|
+
} catch { /* 没有 agents 服务就只靠 agent/created */ }
|
|
473
|
+
}
|