@shgroup/dsh-serenity-hooks 1.139.1 → 1.139.2
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/dsh.plugin.json +1 -1
- package/lib/{contract-Mxgh_fl4.js → contract-DXaIXQvh.js} +3 -640
- package/lib/guards-is79hFAc.js +1405 -0
- package/lib/index.js +17 -19
- package/lib/{observation-8iVgMHVC.js → observation-BMS74GF_.js} +2 -2
- package/lib/{rebuild-DVVb82zf.js → rebuild-bySH_ZPq.js} +1 -1
- package/lib/{route-DcUo9alz.js → route-BGKbuE3M.js} +279 -2
- package/lib/seams/guards.d.ts +46 -0
- package/lib/{service-CWNPCS5c.js → service-BYIKwXsG.js} +1 -1
- package/lib/{session-BMaTNjK1.js → session-BTOngenk.js} +5 -4
- package/package.json +1 -1
- package/lib/channels-Covd8vLQ.js +0 -458
- package/lib/rules-BYeykzys.js +0 -261
- package/lib/service-BRUHmVFn.js +0 -282
|
@@ -0,0 +1,1405 @@
|
|
|
1
|
+
import { r as cccRootForCwd } from "./ccc-roots-B6dJON2X.js";
|
|
2
|
+
import { c as matchBlacklist, d as readCccName, g as resolveInside, h as readUtf8, l as pathInside, o as isSafeModeOn, u as readBlacklist } from "./ccc-DSMqTrRU.js";
|
|
3
|
+
import { c as readWeixinSettings, o as readImSettings } from "./route-BGKbuE3M.js";
|
|
4
|
+
import { l as trajectoryCodeForSession, u as trajectoryConstraintForSession } from "./profile-CRcW3ifg.js";
|
|
5
|
+
import { REGISTERED_TOOLS } from "./invariant.js";
|
|
6
|
+
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
7
|
+
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
//#region src/kernel/constants.ts
|
|
10
|
+
/** 常量(纯模块,零 DSH 依赖) */
|
|
11
|
+
/** 本包名 —— 上溯定位包根时的**身份核对**(同名目录家的邻居不会误命中) */
|
|
12
|
+
const PACKAGE_NAME = "@shgroup/dsh-serenity-hooks";
|
|
13
|
+
/** 上溯层数上限(源码态最深 `src/<域>/<子域>/` / 发布态 `lib/` ⇒ 8 层足够,且**保证有界**) */
|
|
14
|
+
const MAX_ROOT_ASCENT = 8;
|
|
15
|
+
/**
|
|
16
|
+
* 包根 = 含**本包** `package.json` 的目录。
|
|
17
|
+
*
|
|
18
|
+
* 🔴 为什么不写 `join(here, '..')`:本模块自身的位置**随目录重构变化**
|
|
19
|
+
* (曾 `src/`,现 `src/kernel/`),而发布态是从打包入口 `lib/index.js` 反推 ——
|
|
20
|
+
* 两种布局的深度不同,写死层数**必然在其中一个布局下静默错位**。
|
|
21
|
+
* 实测代价:`src/` → `src/kernel/` 之后,`join(here,'..')` 指到 `src/`(无 package.json)
|
|
22
|
+
* ⇒ `ACC_VERSION` 落进 catch 分支变 `0.0.0`,**没有任何门禁报警**。
|
|
23
|
+
*
|
|
24
|
+
* ⇒ 判据改成**内容**(找带本包名的 package.json)而不是**层数**。
|
|
25
|
+
*
|
|
26
|
+
* @param start 起点目录(缺省 = 本模块所在目录;测试可注入)
|
|
27
|
+
*/
|
|
28
|
+
function findPackageRoot(start) {
|
|
29
|
+
let dir = start ?? dirname(fileURLToPath(import.meta.url));
|
|
30
|
+
for (let i = 0; i < MAX_ROOT_ASCENT; i += 1) {
|
|
31
|
+
try {
|
|
32
|
+
if (JSON.parse(readFileSync(join(dir, "package.json"), "utf-8")).name === PACKAGE_NAME) return dir;
|
|
33
|
+
} catch {}
|
|
34
|
+
const parent = dirname(dir);
|
|
35
|
+
if (parent === dir) return null;
|
|
36
|
+
dir = parent;
|
|
37
|
+
}
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* ACC 版本:自动从 package.json 读取(单一真相源,消除与 CHANGELOG 的漂移)。
|
|
42
|
+
* 发布时只需改 package.json 的 version。
|
|
43
|
+
*/
|
|
44
|
+
const ACC_VERSION = (() => {
|
|
45
|
+
try {
|
|
46
|
+
const root = findPackageRoot();
|
|
47
|
+
if (root === null) return "0.0.0";
|
|
48
|
+
return JSON.parse(readFileSync(join(root, "package.json"), "utf-8")).version ?? "0.0.0";
|
|
49
|
+
} catch {
|
|
50
|
+
return "0.0.0";
|
|
51
|
+
}
|
|
52
|
+
})();
|
|
53
|
+
//#endregion
|
|
54
|
+
//#region src/trajectory/policy/rules.ts
|
|
55
|
+
/**
|
|
56
|
+
* trajectory/policy/rules.ts — 轨迹约束面的**纯逻辑助手**(零 DSH 依赖,可独立单测)
|
|
57
|
+
*
|
|
58
|
+
* ## 2026-10-19 重做后的职责边界(R↓,别再混起来)
|
|
59
|
+
*
|
|
60
|
+
* | 模块 | 管什么 |
|
|
61
|
+
* |---|---|
|
|
62
|
+
* | `./profile.ts` | **判据 + 读盘**("这是不是 轨迹约束"、"约束面是什么") |
|
|
63
|
+
* | `./rules.ts`(本文件) | **从约束面派生出的纯函数**(白名单集合、提示词读取器、基础提示词文本) |
|
|
64
|
+
* | `../session-create.ts` | 会话创建/复用、提问、守门查询 |
|
|
65
|
+
*
|
|
66
|
+
* ⇒ 本文件**不再读 `serenity.json`**:`轨迹约束.roles` 整段已退役(owner 2026-10-19 重做)。
|
|
67
|
+
* 它只接收一个已解析好的 `TrajectoryConstraint`,因此**不涉及任何 IO**(除提示词文件,那是刻意懒读的)。
|
|
68
|
+
*
|
|
69
|
+
* ## S12(2026-10-19,轨迹中心重构)
|
|
70
|
+
*
|
|
71
|
+
* 原名 `role/轨迹约束/config.ts`。改名理由(框架 §6.3「角色不是一个概念,是一段历史」):
|
|
72
|
+
* 它派生的是**某条轨迹的约束面**,与"配置读取"无关(本文件零配置读取,见上一段)
|
|
73
|
+
* ⇒ `config` 这个名字描述的是**它曾经的样子**,`rules` 描述它**现在做的事**。
|
|
74
|
+
*/
|
|
75
|
+
/** 白名单推导 ────────────────────────────────────────────────────────────── */
|
|
76
|
+
/** 提示词来源提示串(`apply` 回执与面板共用;避免两处措辞漂) */
|
|
77
|
+
const TRAJECTORY_CONSTRAINT_HINT = "systemPromptFile hot-reloads by mtime; the rest of trajectory-constraint.json is re-read every turn";
|
|
78
|
+
/**
|
|
79
|
+
* 该轨迹会话**可见**的工具面(tools ∪ `msm`)。
|
|
80
|
+
*
|
|
81
|
+
* 🔴 **返回值 `null` 有专门含义(D181,owner 2026-10-20 裁「不写当然不收窄」)**:
|
|
82
|
+
*
|
|
83
|
+
* | `tools` | `msms` | 返回 | 语义 |
|
|
84
|
+
* |---|---|---|---|
|
|
85
|
+
* | 缺省 | 缺省 | **`null`** | **不收窄任何工具面**(这条轨迹要的是别的设定,如只写 `resident`) |
|
|
86
|
+
* | `[]` | 缺省 | `{'msm'?}` 空/仅 msm | **全隐藏**(除恒可用的 `skill`) |
|
|
87
|
+
* | `['a']` | … | `{'a', …}` | 只给这些 |
|
|
88
|
+
*
|
|
89
|
+
* ⛔ **调用方不许把 `null` 当空集处理** —— 那正是 S196 被锁死的形态(D179(b))。
|
|
90
|
+
* 判据是**字段在不在**,不是数组空不空。
|
|
91
|
+
*
|
|
92
|
+
* 🔴 `msm` 为什么自动加入:`msms` 非空意味着这个轨迹 **有 MSM 通道**,
|
|
93
|
+
* 而 MSM 的唯一合法调用入口是 `msm` 工具(单入口纪律)——不给它 `msm` 就等于
|
|
94
|
+
* 声明了一堆调不动的能力。⚠️ 这是**并集**,不是覆盖:`tools` 里显式写的照旧生效。
|
|
95
|
+
*
|
|
96
|
+
* @returns 白名单集合;**`null` = 不收窄**(调用方须显式判 `null`)
|
|
97
|
+
*/
|
|
98
|
+
function profileToolWhitelist(profile) {
|
|
99
|
+
if (!profile) return null;
|
|
100
|
+
if (profile.tools === void 0 && profile.msms === void 0) return null;
|
|
101
|
+
const out = /* @__PURE__ */ new Set();
|
|
102
|
+
for (const t of profile.tools ?? []) out.add(t);
|
|
103
|
+
if ((profile.msms?.length ?? 0) > 0) out.add("msm");
|
|
104
|
+
return out;
|
|
105
|
+
}
|
|
106
|
+
/** 该轨迹会话可 exec 的 MSM 白名单(`msm` 工具内部再过滤;独立于工具白名单) */
|
|
107
|
+
function profileMsmWhitelist(profile) {
|
|
108
|
+
return new Set(profile?.msms ?? []);
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* 该轨迹可**写**的路径前缀(owner 2026-10-20 令:「轨迹设定自己的写白名单」)。
|
|
112
|
+
*
|
|
113
|
+
* 🔴 与 `profileToolWhitelist` 共用同一条判据(D181/D183):**字段在不在,不是数组空不空**。
|
|
114
|
+
*
|
|
115
|
+
* | `writes` | 返回 | 语义 |
|
|
116
|
+
* |---|---|---|
|
|
117
|
+
* | 缺省 | **`null`** | 不收窄(写权限 = 路径守卫那几条,与今天一致) |
|
|
118
|
+
* | `[]` | `[]`(空数组) | **一个写都落不下**(显式意图) |
|
|
119
|
+
* | `['a/']` | `['a/']` | 写目标必须落在 `a/` 之内 |
|
|
120
|
+
*
|
|
121
|
+
* ⛔ **调用方不许把 `null` 当 `[]`** —— 那会把"我没想到这件事"读成"我不许写任何东西",
|
|
122
|
+
* 正是 S196 被静默锁死的形态(D179(b))。
|
|
123
|
+
*
|
|
124
|
+
* ⚠️ 返回的是**原始条目**(相对 CCC 根或绝对路径都可),解析成绝对路径由调用方按自己的 root 做 ——
|
|
125
|
+
* 本模块不持有 root(判据在 `seams/guards.ts`)。
|
|
126
|
+
*/
|
|
127
|
+
function profileWriteWhitelist(profile) {
|
|
128
|
+
if (!profile) return null;
|
|
129
|
+
if (profile.writes === void 0) return null;
|
|
130
|
+
return profile.writes;
|
|
131
|
+
}
|
|
132
|
+
/** 轨迹纪律参与项(`profile` 缺省已在 `readTrajectoryConstraintAt` 归一为全 true) */
|
|
133
|
+
function constraintCognitiveTrajectory(profile) {
|
|
134
|
+
return {
|
|
135
|
+
session: profile?.cognitiveTrajectory.session === true,
|
|
136
|
+
keeper: profile?.cognitiveTrajectory.keeper === true,
|
|
137
|
+
rebuild: profile?.cognitiveTrajectory.rebuild === true
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* 解析约束面声明的**系统提示词全文**(一次性读取;`create` / `validate` / `list` 用)。
|
|
142
|
+
*
|
|
143
|
+
* 顺序:`systemPromptFile`(**推荐**:超长提示词在 JSON 里内嵌不可读)→ 内嵌 `systemPrompt` → 空串。
|
|
144
|
+
* 文件缺失/逃逸 ⇒ **抛错**(调用方 catch 降级;`validate` 据此报 issue)。
|
|
145
|
+
*
|
|
146
|
+
* ⚠️ 热路径**不用**它(那会用每次工具调用去读盘)——热路径用 `createProfilePromptReader`。
|
|
147
|
+
*/
|
|
148
|
+
function resolveConstraintSystemPrompt(root, profile) {
|
|
149
|
+
if (!profile) return "";
|
|
150
|
+
const file = profile.systemPromptFile?.trim();
|
|
151
|
+
if (file) {
|
|
152
|
+
const abs = resolveInside(root, file);
|
|
153
|
+
if (!existsSync(abs)) throw new Error(`轨迹约束 "${profile.code}": systemPromptFile "${file}" not found (resolved: ${abs})`);
|
|
154
|
+
return readUtf8(abs).trim();
|
|
155
|
+
}
|
|
156
|
+
return profile.systemPrompt ?? "";
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* 提示词来源(`list`/`validate` 展示用)。
|
|
160
|
+
*
|
|
161
|
+
* 🔴 **2026-10-19 修(T4 的漏网面)**:v1.72.0 起提示词有两代来源——**新形态**
|
|
162
|
+
* 是轨迹目录里的 `PROMPT.md`(`trajectory/prompt.ts`,**优先**),旧形态才是
|
|
163
|
+
* `systemPromptFile` / `systemPrompt`。本函数原先只认旧形态 ⇒ 两条只写了 `PROMPT.md`
|
|
164
|
+
* 的轨迹在 `container_admin config list` 里恒显示 `promptSource: 'none'`。
|
|
165
|
+
*
|
|
166
|
+
* 那是**读数器过时**,不是配置缺失:`validate` 侧早已按两条来源判(见
|
|
167
|
+
* `trajectory-constraint-admin.ts` 的 `hasTrajectoryPromptOrLegacy`),而 `list` 侧漏了。
|
|
168
|
+
* ⇒ 返 **四种**值,把"有章程但来源是新形态"这一格单独说出来。
|
|
169
|
+
*
|
|
170
|
+
* @param hasPromptFile 该轨迹目录下**是否真有** `PROMPT.md`(调用方查,本函数不做 IO)
|
|
171
|
+
*/
|
|
172
|
+
function constraintSystemPromptSource(profile, hasPromptFile = false) {
|
|
173
|
+
if (hasPromptFile) return "trajectory-file";
|
|
174
|
+
if (profile?.systemPromptFile?.trim()) return "file";
|
|
175
|
+
if (profile?.systemPrompt?.trim()) return "inline";
|
|
176
|
+
return "none";
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* 提示词**读取器**(长期热更新;改文件即生效,无需重启)。
|
|
180
|
+
*
|
|
181
|
+
* 为什么返回函数而不是字符串(R↓,实证代价):旧实现在创建时把提示词**快照**进系统提示词段闭包
|
|
182
|
+
* ⇒ CCC 改了提示词文件必须重启 dsh web 才生效(实测:改完 18KB 提示词,live agent 仍用旧文本)。
|
|
183
|
+
* 现形态由系统提示词段的 `text()` **每轮调用**本读取器:
|
|
184
|
+
* - `systemPromptFile`:按 **mtime + size** 缓存重读(命中缓存零 IO;未变不解析)
|
|
185
|
+
* - 内嵌 `systemPrompt`:静态(改 JSON 仍需重载配置,这与文件热更的差别是**必然**的 —— 文件有 mtime,JSON 没有)
|
|
186
|
+
* - 读取失败:返回**上次成功内容**(⛔ 绝不返回空——空提示词会让角色失去人格与纪律),并按标签去重告警一次
|
|
187
|
+
*
|
|
188
|
+
* @param root CCC 根
|
|
189
|
+
* @param profile 约束面
|
|
190
|
+
*/
|
|
191
|
+
function createProfilePromptReader(root, profile) {
|
|
192
|
+
const file = profile?.systemPromptFile?.trim();
|
|
193
|
+
if (!file) {
|
|
194
|
+
const inline = profile?.systemPrompt ?? "";
|
|
195
|
+
return () => inline;
|
|
196
|
+
}
|
|
197
|
+
let abs = null;
|
|
198
|
+
try {
|
|
199
|
+
abs = resolveInside(root, file);
|
|
200
|
+
} catch (err) {
|
|
201
|
+
console.warn(`[serenity-hooks] ✗ 轨迹约束提示词路径非法(${file}): ${String(err?.message ?? err)}`);
|
|
202
|
+
}
|
|
203
|
+
if (abs === null) return () => "";
|
|
204
|
+
const absPath = abs;
|
|
205
|
+
let cachedMtime = -1;
|
|
206
|
+
let cachedSize = -1;
|
|
207
|
+
let cachedText = "";
|
|
208
|
+
let warned = false;
|
|
209
|
+
return () => {
|
|
210
|
+
try {
|
|
211
|
+
const st = statSync(absPath);
|
|
212
|
+
if (st.mtimeMs === cachedMtime && st.size === cachedSize) return cachedText;
|
|
213
|
+
const text = readUtf8(absPath).trim();
|
|
214
|
+
const isReload = cachedMtime !== -1;
|
|
215
|
+
cachedMtime = st.mtimeMs;
|
|
216
|
+
cachedSize = st.size;
|
|
217
|
+
cachedText = text;
|
|
218
|
+
warned = false;
|
|
219
|
+
if (isReload) console.info(`[serenity-hooks] ↻ 轨迹约束提示词已热重载(${file},${text.length} 字符)`);
|
|
220
|
+
return text;
|
|
221
|
+
} catch (err) {
|
|
222
|
+
if (!warned) {
|
|
223
|
+
warned = true;
|
|
224
|
+
console.warn(`[serenity-hooks] ✗ 轨迹约束提示词读取失败(${file})——沿用上次成功内容: ${String(err?.message ?? err)}`);
|
|
225
|
+
}
|
|
226
|
+
return cachedText;
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* 轨迹约束 基础提示词(dsp 只给这部分;CCC 的 `systemPrompt` 段由调用方拼接)。
|
|
232
|
+
*
|
|
233
|
+
* ## 🔴 为什么**不再枚举**清单(owner 2026-10-19 令)
|
|
234
|
+
*
|
|
235
|
+
* 旧版在这里抄了两份清单(`MSMs: a, b, c` / `Tools: read, grep, …`)。那是**第二真相源**,
|
|
236
|
+
* 而真相源本来就在模型自己手里:
|
|
237
|
+
* · **工具清单** = 这一轮实际注册给它的 tool schema —— 模型已经看得见,抄一遍只会漂
|
|
238
|
+
* · **MSM 清单** = `msm()` 无参调用返回的目录 —— 已按白名单过滤,且**每次实时读配置**
|
|
239
|
+
*
|
|
240
|
+
* ⚠️ **漂移不是理论风险,是已发生的缺陷**(2026-10-19):角色配置早就长到 8 个工具,
|
|
241
|
+
* 而这个函数是从**创建时冻结的快照**求值的 ⇒ 提示词里一直写着旧的 4 个
|
|
242
|
+
* ⇒ 模型照着提示词办事,**它自己以为没有的能力就不去调** ⇒ 症状是"工具用不了",
|
|
243
|
+
* 而守卫那边(每调用实时读配置)其实是放行的。两个真相源打架,输的总是提示词。
|
|
244
|
+
*
|
|
245
|
+
* ⇒ 现在只声明**边界与发现路径**,不抄内容:清单在哪,怎么取,越界会怎样。
|
|
246
|
+
*
|
|
247
|
+
* @param code 轨迹编码(轨迹约束的身份 —— 不是"角色名",那个概念已退役)
|
|
248
|
+
*/
|
|
249
|
+
function buildTrajectoryBasePrompt(code) {
|
|
250
|
+
return [
|
|
251
|
+
"=== Serenity 轨迹约束 ===",
|
|
252
|
+
`Cognitive trajectory: ${code} (this is the trajectory you ARE, not a role you play)`,
|
|
253
|
+
"Your capability boundary is enforced mechanically by this CCC — anything outside it is rejected at the call site, not by your judgment.",
|
|
254
|
+
"Discover your surface, do not memorize it (both are generated from the live config on every turn):",
|
|
255
|
+
" · Your tools are exactly the tool schemas you see in this session — if a tool is not in your schema, it is not available.",
|
|
256
|
+
" · Your MSMs are listed by calling msm() with no arguments — that directory is already filtered to this trajectory.",
|
|
257
|
+
" · Usage for any MSM: msm(\"<name>\", [], inspect=true) or pass \"--help\" as the first argument.",
|
|
258
|
+
"Do not infer unavailability from anything you remember or from an earlier list: this surface changes when the CCC configuration changes, and it takes effect without restarting.",
|
|
259
|
+
"",
|
|
260
|
+
"---",
|
|
261
|
+
""
|
|
262
|
+
].join("\n");
|
|
263
|
+
}
|
|
264
|
+
//#endregion
|
|
265
|
+
//#region src/im/log-scan.ts
|
|
266
|
+
/**
|
|
267
|
+
* im/log-scan.ts — 读聊天记录落盘,汇总出「与谁有过往来」(`contacts` 的数据源)
|
|
268
|
+
*
|
|
269
|
+
* ## 这个文件解决什么
|
|
270
|
+
*
|
|
271
|
+
* owner 2026-10-22:「配路由需要的是**账户到轨迹**,轨迹 CCC 知道,**账户 CCC 不知道**,
|
|
272
|
+
* 需要有个能力让 CCC 查询用户配好的账户」。这里的"账户"= **通道用户**(对方是谁),
|
|
273
|
+
* 不是 IM 账号(我们自己登录的身份,`status` 早就能查)。
|
|
274
|
+
*
|
|
275
|
+
* 那个 id(微信 `xxx@im.wechat` / 飞书 `ou_…`)不在任何配置文件里 ——
|
|
276
|
+
* 它**只在聊天记录里出现过**。⇒ 本文件把记录读成联系人表。
|
|
277
|
+
*
|
|
278
|
+
* ## 🔴 两条硬边界
|
|
279
|
+
*
|
|
280
|
+
* 1. **只读**:本文件不写任何东西。真相源仍是那些 jsonl(append-only 事件流),
|
|
281
|
+
* 本文件只是它的一次投影 —— ⛔ 不产生第二真相源。
|
|
282
|
+
* 2. **不猜渠道**:事件的 `channel` 字段为准;缺它(存量事件)⇒ 按
|
|
283
|
+
* `accountId → im.accounts[].channel` 回填,仍取不到才落 `weixin`
|
|
284
|
+
* (那是该字段存在之前唯一的渠道)。⛔ **绝不按 userId 的形状猜**
|
|
285
|
+
* (`ou_` 前缀 / `@im.wechat` 后缀都是命名习惯,不是判据 —— D167 认族不认名)。
|
|
286
|
+
*/
|
|
287
|
+
/** 日志根目录族(**新旧两代并存**:`_im-logs/<channel>/` 与存量 `_weixin-logs/`) */
|
|
288
|
+
const IM_LOG_DIR_NEW = "_im-logs";
|
|
289
|
+
const IM_LOG_DIR_LEGACY = "_weixin-logs";
|
|
290
|
+
/** 某 CCC 下**存在**的日志目录(相对根),新代在前 */
|
|
291
|
+
function imLogRoots(root) {
|
|
292
|
+
const out = [];
|
|
293
|
+
const newBase = join(root, "AGENT_SESSIONS", IM_LOG_DIR_NEW);
|
|
294
|
+
const legacy = join(root, "AGENT_SESSIONS", IM_LOG_DIR_LEGACY);
|
|
295
|
+
if (existsSync(newBase)) out.push(join("AGENT_SESSIONS", IM_LOG_DIR_NEW));
|
|
296
|
+
if (existsSync(legacy)) out.push(join("AGENT_SESSIONS", IM_LOG_DIR_LEGACY));
|
|
297
|
+
return out;
|
|
298
|
+
}
|
|
299
|
+
/** 收集某个日志根下所有 `*.jsonl`(含 `_im-logs/<channel>/` 一层;按文件名排序) */
|
|
300
|
+
function jsonlFilesIn(root, rel) {
|
|
301
|
+
const abs = join(root, rel);
|
|
302
|
+
const out = [];
|
|
303
|
+
let entries = [];
|
|
304
|
+
try {
|
|
305
|
+
entries = readdirSync(abs, { withFileTypes: true }).map((d) => d.name);
|
|
306
|
+
} catch {
|
|
307
|
+
return out;
|
|
308
|
+
}
|
|
309
|
+
for (const name of entries.sort()) {
|
|
310
|
+
if (name.startsWith(".")) continue;
|
|
311
|
+
if (name.endsWith(".jsonl")) {
|
|
312
|
+
out.push(join(rel, name));
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
315
|
+
if (rel === join("AGENT_SESSIONS", "_im-logs")) {
|
|
316
|
+
const sub = join(rel, name);
|
|
317
|
+
try {
|
|
318
|
+
for (const child of readdirSync(join(root, sub)).sort()) if (child.endsWith(".jsonl")) out.push(join(sub, child));
|
|
319
|
+
} catch {}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
return out;
|
|
323
|
+
}
|
|
324
|
+
/** 从文件名 / 所在目录猜渠道(**只作为回填的最后一级**,不是判据) */
|
|
325
|
+
function channelFromPath(rel) {
|
|
326
|
+
const parts = rel.split("/");
|
|
327
|
+
const idx = parts.indexOf(IM_LOG_DIR_NEW);
|
|
328
|
+
const candidate = idx >= 0 && parts.length > idx + 2 ? parts[idx + 1] : void 0;
|
|
329
|
+
return candidate !== void 0 && candidate !== "" ? candidate : null;
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* 扫描本 CCC 的全部聊天记录,按 `(channel, userId)` 汇总。
|
|
333
|
+
*
|
|
334
|
+
* @param root CCC 根
|
|
335
|
+
* @param accountChannel 存量事件缺 `channel` 时的回填表(`accountId → channel`)
|
|
336
|
+
* @returns 汇总结果 + **扫描域** + 读取错误(三者都不可省)
|
|
337
|
+
*/
|
|
338
|
+
function scanImContacts(root, accountChannel = {}) {
|
|
339
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
340
|
+
const sources = [];
|
|
341
|
+
const errors = [];
|
|
342
|
+
for (const rel of imLogRoots(root)) for (const fileRel of jsonlFilesIn(root, rel)) {
|
|
343
|
+
sources.push(fileRel);
|
|
344
|
+
let text = "";
|
|
345
|
+
try {
|
|
346
|
+
text = readFileSync(join(root, fileRel), "utf8");
|
|
347
|
+
} catch (err) {
|
|
348
|
+
errors.push(`${fileRel}: ${err instanceof Error ? err.message : String(err)}`);
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
const pathChannel = channelFromPath(fileRel);
|
|
352
|
+
for (const line of text.split("\n")) {
|
|
353
|
+
const trimmed = line.trim();
|
|
354
|
+
if (trimmed === "") continue;
|
|
355
|
+
let ev;
|
|
356
|
+
try {
|
|
357
|
+
ev = JSON.parse(trimmed);
|
|
358
|
+
} catch {
|
|
359
|
+
errors.push(`${fileRel}: 有 1 行不是合法 JSON(已跳过)`);
|
|
360
|
+
continue;
|
|
361
|
+
}
|
|
362
|
+
const userId = typeof ev.userId === "string" ? ev.userId.trim() : "";
|
|
363
|
+
if (userId === "") continue;
|
|
364
|
+
const accountId = typeof ev.accountId === "string" ? ev.accountId.trim() : "";
|
|
365
|
+
const channel = (typeof ev.channel === "string" && ev.channel.trim() !== "" ? ev.channel.trim() : null) ?? pathChannel ?? (accountId !== "" ? accountChannel[accountId] ?? null : null) ?? "weixin";
|
|
366
|
+
const key = `${channel}\u0000${userId}`;
|
|
367
|
+
let entry = byKey.get(key);
|
|
368
|
+
if (!entry) {
|
|
369
|
+
entry = {
|
|
370
|
+
channel,
|
|
371
|
+
userId,
|
|
372
|
+
accountIds: [],
|
|
373
|
+
roleAtEvent: null,
|
|
374
|
+
firstSeen: null,
|
|
375
|
+
lastSeen: null,
|
|
376
|
+
messages: 0
|
|
377
|
+
};
|
|
378
|
+
byKey.set(key, entry);
|
|
379
|
+
}
|
|
380
|
+
if (accountId !== "" && !entry.accountIds.includes(accountId)) entry.accountIds.push(accountId);
|
|
381
|
+
if (typeof ev.role === "string" && ev.role.trim() !== "") entry.roleAtEvent = ev.role.trim();
|
|
382
|
+
const ts = typeof ev.ts === "number" && Number.isFinite(ev.ts) ? ev.ts : null;
|
|
383
|
+
if (ts !== null) {
|
|
384
|
+
if (entry.firstSeen === null || ts < entry.firstSeen) entry.firstSeen = ts;
|
|
385
|
+
if (entry.lastSeen === null || ts > entry.lastSeen) entry.lastSeen = ts;
|
|
386
|
+
}
|
|
387
|
+
entry.messages += 1;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
return {
|
|
391
|
+
contacts: [...byKey.values()].sort((a, b) => (b.lastSeen ?? 0) - (a.lastSeen ?? 0)),
|
|
392
|
+
sources,
|
|
393
|
+
errors
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
//#endregion
|
|
397
|
+
//#region src/im/channels.ts
|
|
398
|
+
/**
|
|
399
|
+
* im/channels.ts — IM 发送能力层(v1.31.0,S142 用户洞察)
|
|
400
|
+
*
|
|
401
|
+
* 用户原话:「既然微信桥是我们 ACC 提供的,那么 weixin-send 应该是我们 ACC 提供的能力,
|
|
402
|
+
* 当用户配置了微信桥则可用,不配置则不可见」+「设定一个复杂的多层工具,叫 im-bridge,
|
|
403
|
+
* 里面有微信,然后保留后续可能兼容别的 im 的空间」。
|
|
404
|
+
*
|
|
405
|
+
* 分层(E↑):
|
|
406
|
+
* `tools/im/channels.ts`(工具面:参数 → 结果渲染)
|
|
407
|
+
* → **本模块**(通道注册表 + 可见性判据 + 动作分发 + 错误码翻译)
|
|
408
|
+
* → 通道实现(`im/weixin-channel.ts`:协议/凭据/账号/记录)
|
|
409
|
+
*
|
|
410
|
+
* 边界(R↓):
|
|
411
|
+
* - **本模块零宿主依赖**(不 import cordis/agent)——可见性判定与分发都是纯逻辑,可独立单测。
|
|
412
|
+
* - **通道只提供机制**:本模块不认识"微信";新增 IM 只需注册一个通道实现(R3 家族式扩展)。
|
|
413
|
+
* - **只能操作本会话 CCC**(R4):`root` 由调用方(工具面)从 agent cwd 解析后传入,
|
|
414
|
+
* 本模块不接受"目标 CCC"参数——跨 CCC 发送不在能力面。
|
|
415
|
+
* - **记录归通道**(R5):通道实现负责让每次发送都落既有 hook。
|
|
416
|
+
*/
|
|
417
|
+
/** 文本长度上限(微信侧单条实践上限;超限拒绝而非静默截断——与 HTTP 入口同值) */
|
|
418
|
+
const IM_SEND_MAX_TEXT = 4e3;
|
|
419
|
+
/** 文件大小上限(20MB,与媒体接收上限一致) */
|
|
420
|
+
const IM_FILE_MAX_BYTES = 20971520;
|
|
421
|
+
const channels = /* @__PURE__ */ new Map();
|
|
422
|
+
/** 注册通道(index.ts apply 调用;重复 id 覆盖——测试与热重载友好) */
|
|
423
|
+
function registerImChannel(channel) {
|
|
424
|
+
channels.set(channel.id, channel);
|
|
425
|
+
}
|
|
426
|
+
/** 已注册通道 id(工具 `channel` 参数枚举) */
|
|
427
|
+
function imChannelIds() {
|
|
428
|
+
return [...channels.keys()];
|
|
429
|
+
}
|
|
430
|
+
/**
|
|
431
|
+
* 可见性判据:本 CCC 是否**有任何可用的 IM 账号**。
|
|
432
|
+
* 未启用 → 工具面对该 agent **不可见**(`tools.restrict` 移除,而非调用时报错)。
|
|
433
|
+
*
|
|
434
|
+
* ## 🔴 2026-10-22 判据修正(owner 令:「把开关升级为有任意账号即可,而不是盯着微信」)
|
|
435
|
+
*
|
|
436
|
+
* **旧判据** = 遍历已注册通道、任一 `channel.isEnabled(root)` 为真即可见。
|
|
437
|
+
* **旧判据的缺陷**(实测于一个只配飞书的 CCC):`feishuChannel.isEnabled()` 首行是
|
|
438
|
+
* `if (settings.enabled !== true) return false` —— 总开关一关,**后面的账号判断根本不执行**
|
|
439
|
+
* ⇒ 账号明明配了、`enabled:true`,却因为一个**渠道无关的总开关**被永久判成"未启用"
|
|
440
|
+
* ⇒ `im-bridge` 在模型清单里彻底消失,而配置面看上去是对的(`accounts[]` 里躺着一条 feishu)。
|
|
441
|
+
* 这正是 D179 的形态:**配置说它有,行为说它没有**,且零报错。
|
|
442
|
+
*
|
|
443
|
+
* **新判据** = **账号即事实**:`readImSettings(root).accounts` 里存在
|
|
444
|
+
* 「`enabled !== false` 的账号」即视为可见。理由三条:
|
|
445
|
+
* ① **可见性问的是"这个 CCC 有没有 IM 能力"**,而能力的载体是**账号**,不是总开关;
|
|
446
|
+
* ② 总开关的语义是"**要不要让桥跑起来**",把它当成可见性上限,会让"配好了但暂时不想让它跑"
|
|
447
|
+
* 这种合法状态变成"工具凭空消失";
|
|
448
|
+
* ③ 判**按账号判**后,微信与飞书不再各有一套"总开关 + 账号"的双重判据 ⇒ 消除同族漂移。
|
|
449
|
+
*
|
|
450
|
+
* ⚠️ **不放宽的部分**:没有账号 ⇒ 仍然不可见(`accounts` 为空即 false)。
|
|
451
|
+
* ⚠️ 单个通道自己的 `isEnabled` 仍是**发送/启停**判据(那是通道自己的事),
|
|
452
|
+
* 只是**不再兼任**工具可见性判据 —— 两件事被这次修正分开了。
|
|
453
|
+
*
|
|
454
|
+
* @param root 本会话 CCC 根(由调用方解析)
|
|
455
|
+
*/
|
|
456
|
+
function hasEnabledImChannel(root) {
|
|
457
|
+
let settings;
|
|
458
|
+
try {
|
|
459
|
+
settings = readImSettings(root);
|
|
460
|
+
} catch {
|
|
461
|
+
return false;
|
|
462
|
+
}
|
|
463
|
+
return (settings.accounts ?? []).some((a) => a.enabled !== false);
|
|
464
|
+
}
|
|
465
|
+
/**
|
|
466
|
+
* 可见性判据(**轨迹级**,2026-10-23 owner 令):
|
|
467
|
+
* 这个 dsh 会话所属的认知轨迹,是否**被 IM 路由表点名**(= 它才是那个"接线人")。
|
|
468
|
+
*
|
|
469
|
+
* ## 它解决的问题(owner 原话的**去标识改写**,原文含私有角色名,按 D145 不入仓库)
|
|
470
|
+
*
|
|
471
|
+
* > 「很多轨迹发消息给我,但是我没空回,它们就会等待我,其实并不是,我希望他们继续工作;
|
|
472
|
+
* > 所以只有 IM 桥绑定了任意账户的认知轨迹才拥有 `im-bridge` 这个 tool,
|
|
473
|
+
* > 这样可以确保只有一个接线角色和我联系,其它轨迹和它联系即可,它会自行回复它们的」
|
|
474
|
+
*
|
|
475
|
+
* ⇒ 旧判据是 **CCC 级**({@link hasEnabledImChannel}:本 CCC 有任一启用账号 ⇒ 全体可见)。
|
|
476
|
+
* 它的后果不是"少一个工具",而是**一条错误的工作流**:每条轨迹都以为自己该直接对 owner 说话,
|
|
477
|
+
* 于是发完就**停下来等人回**——而 owner 根本没空逐条回。**工具在,就把等待也带上了。**
|
|
478
|
+
*
|
|
479
|
+
* ## 判据(两条,缺一不可)
|
|
480
|
+
*
|
|
481
|
+
* 1. 本 CCC 有可用账号({@link hasEnabledImChannel})—— 没有账号时路由表也没有意义;
|
|
482
|
+
* 2. 本会话**绑定的轨迹编码**出现在 `routes[].trajectory` 里。
|
|
483
|
+
*
|
|
484
|
+
* ⚠️ **为什么不看 `routes[].user`**:那是"对端是谁"(owner 的通道 id),
|
|
485
|
+
* 判"这条轨迹能不能说话"只跟**轨迹**有关,与哪个对端无关。
|
|
486
|
+
*
|
|
487
|
+
* ⚠️ **`*` 通配也算点名**:`{ user:"*", trajectory:"<某轨迹>" }` 这条路由的含义就是
|
|
488
|
+
* "**没人认领的消息都归那条轨迹**" ⇒ 它确实是一条被授权的接线轨迹,必须算可见。
|
|
489
|
+
* 这与 `matchWeixinRoute` 的通配兜底语义**同源**,不另立规则。
|
|
490
|
+
*
|
|
491
|
+
* ## 拿不到轨迹编码时怎么办(fail-closed,与 `exclusive` 同向)
|
|
492
|
+
*
|
|
493
|
+
* 会话 → 轨迹编码要读绑定。**取不到就判不可见**:
|
|
494
|
+
* - 与 `exclusive`(未声明 ⇒ 隐藏)同向;
|
|
495
|
+
* - 反向(取不到就放行)会让"绑定坏了"表现成"工具还在",
|
|
496
|
+
* 而那正是本判据要防的形态(D179:配置说它有、行为说它没有,且零报错)。
|
|
497
|
+
* ⚠️ 代价明示:绑定读取若短暂失败,该轮会少一个工具;下一轮绑定恢复即回。
|
|
498
|
+
* 这比"误给一条轨迹发消息的权限"便宜 —— 后者会让它**停下来等 owner**。
|
|
499
|
+
*
|
|
500
|
+
* @param root CCC 根
|
|
501
|
+
* @param trajectoryCode 本会话所属认知轨迹的编码(**由调用方解析**,见 `trajectory/policy/profile.ts`)
|
|
502
|
+
* @returns true = 该轨迹接线,`im-bridge` 可见
|
|
503
|
+
*/
|
|
504
|
+
function isImWiredTrajectory(root, trajectoryCode) {
|
|
505
|
+
if (typeof trajectoryCode !== "string" || trajectoryCode.trim() === "") return false;
|
|
506
|
+
if (!hasEnabledImChannel(root)) return false;
|
|
507
|
+
let settings;
|
|
508
|
+
try {
|
|
509
|
+
settings = readImSettings(root);
|
|
510
|
+
} catch {
|
|
511
|
+
return false;
|
|
512
|
+
}
|
|
513
|
+
const wanted = trajectoryCode.trim();
|
|
514
|
+
for (const route of settings.routes ?? []) {
|
|
515
|
+
const target = typeof route.trajectory === "string" ? route.trajectory.trim() : "";
|
|
516
|
+
if (target !== "" && target === wanted) return true;
|
|
517
|
+
}
|
|
518
|
+
return false;
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
521
|
+
* 错误码 → 可行动提示(模型视角:说清怎么改)。
|
|
522
|
+
*
|
|
523
|
+
* 🔴 `CHANNEL_NOT_CONFIGURED` 的提示**不能写死某一个渠道的字段名**(2026-10-20 Q4 真机验收踩到):
|
|
524
|
+
* 首版逐字写「enable it in … (weixin.enabled)」,而接第二个渠道后,**飞书能不能用不取决于
|
|
525
|
+
* 这个开关**(它取决于有没有一条启用中的飞书账号)⇒ 按那句提示去改 `weixin.enabled`
|
|
526
|
+
* **不会生效**,而错误码又指向"没配置" ⇒ 用户据此改完还是同一句报错。
|
|
527
|
+
* ⇒ 提示按**渠道是否带自己的启用判据**分岔:带 `channelHint` 的就用它自己的说法。
|
|
528
|
+
*/
|
|
529
|
+
function remediationFor(code, channelHint) {
|
|
530
|
+
switch (code) {
|
|
531
|
+
case "CHANNEL_UNKNOWN": return "Use a registered channel id (see the tool description)";
|
|
532
|
+
case "CHANNEL_NOT_CONFIGURED": return channelHint ?? "This CCC has not configured that channel — check .opencode/serenity.json (the channel's own enabled flag / accounts) or the settings panel";
|
|
533
|
+
case "ACTION_UNKNOWN": return "Use send / send-file / users / status";
|
|
534
|
+
case "ACTION_UNSUPPORTED": return "This channel does not support that action";
|
|
535
|
+
case "ALIAS_UNKNOWN": return "Use a configured alias (see action=users) or a raw channel user id";
|
|
536
|
+
case "TEXT_REQUIRED": return "Provide text";
|
|
537
|
+
case "TEXT_TOO_LONG": return `Shorten the text to <= ${IM_SEND_MAX_TEXT} characters`;
|
|
538
|
+
case "USER_REQUIRED": return "Provide user";
|
|
539
|
+
case "FILE_REQUIRED": return "Provide file (a path inside this CCC)";
|
|
540
|
+
case "FILE_ESCAPE": return "Use a path inside this CCC";
|
|
541
|
+
case "FILE_NOT_FOUND": return "Check the path exists inside this CCC";
|
|
542
|
+
case "FILE_TOO_LARGE": return `Use a file <= ${Math.round(IM_FILE_MAX_BYTES / 1048576)} MB`;
|
|
543
|
+
default: return;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
function fail(code, error, remediation) {
|
|
547
|
+
return {
|
|
548
|
+
ok: false,
|
|
549
|
+
code,
|
|
550
|
+
error,
|
|
551
|
+
...remediation ?? remediationFor(code) ? { remediation: remediation ?? remediationFor(code) } : {}
|
|
552
|
+
};
|
|
553
|
+
}
|
|
554
|
+
/** CCC 内文件读取(路径逃逸/缺失/超限一律拒绝,返回稳定码) */
|
|
555
|
+
function readCccFile(root, relOrAbs) {
|
|
556
|
+
const abs = isAbsolute(relOrAbs) ? resolve(relOrAbs) : resolve(root, relOrAbs);
|
|
557
|
+
const rel = relative(resolve(root), abs);
|
|
558
|
+
if (rel.startsWith("..") || isAbsolute(rel)) return {
|
|
559
|
+
ok: false,
|
|
560
|
+
code: "FILE_ESCAPE",
|
|
561
|
+
error: `file escapes the CCC root: ${relOrAbs}`
|
|
562
|
+
};
|
|
563
|
+
if (!existsSync(abs)) return {
|
|
564
|
+
ok: false,
|
|
565
|
+
code: "FILE_NOT_FOUND",
|
|
566
|
+
error: `file not found: ${relOrAbs}`
|
|
567
|
+
};
|
|
568
|
+
let size = 0;
|
|
569
|
+
try {
|
|
570
|
+
size = statSync(abs).size;
|
|
571
|
+
} catch (err) {
|
|
572
|
+
return {
|
|
573
|
+
ok: false,
|
|
574
|
+
code: "FILE_NOT_FOUND",
|
|
575
|
+
error: `cannot stat file: ${relOrAbs} (${err instanceof Error ? err.message : String(err)})`
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
if (size > 20971520) return {
|
|
579
|
+
ok: false,
|
|
580
|
+
code: "FILE_TOO_LARGE",
|
|
581
|
+
error: `file is ${size} bytes (> ${IM_FILE_MAX_BYTES})`
|
|
582
|
+
};
|
|
583
|
+
try {
|
|
584
|
+
return {
|
|
585
|
+
ok: true,
|
|
586
|
+
data: readFileSync(abs),
|
|
587
|
+
fileName: abs.split("/").pop() ?? "file"
|
|
588
|
+
};
|
|
589
|
+
} catch (err) {
|
|
590
|
+
return {
|
|
591
|
+
ok: false,
|
|
592
|
+
code: "FILE_NOT_FOUND",
|
|
593
|
+
error: `cannot read file: ${relOrAbs} (${err instanceof Error ? err.message : String(err)})`
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
/**
|
|
598
|
+
* 执行一次 IM 动作(工具面唯一入口)。
|
|
599
|
+
*
|
|
600
|
+
* 顺序:通道解析 → 动作校验 → 用户解析(别名 → id)→ 输入校验 → 调用通道实现。
|
|
601
|
+
* 任何一步失败都返回**稳定错误码 + 可行动提示**(不抛错——工具面统一渲染)。
|
|
602
|
+
*
|
|
603
|
+
* @param root 本会话 CCC 根(调用方从 agent cwd 解析;本函数不接受目标 CCC)
|
|
604
|
+
* @param req 工具参数
|
|
605
|
+
*/
|
|
606
|
+
async function runImBridge(root, req) {
|
|
607
|
+
const channelId = (req.channel ?? "").trim();
|
|
608
|
+
const action = (req.action ?? "").trim();
|
|
609
|
+
if (channelId === "") return fail("CHANNEL_REQUIRED", "channel is required", "Provide channel (e.g. \"weixin\")");
|
|
610
|
+
const channel = channels.get(channelId);
|
|
611
|
+
if (!channel) return fail("CHANNEL_UNKNOWN", `unknown channel "${channelId}" (registered: ${imChannelIds().join(", ") || "(none)"})`);
|
|
612
|
+
if (!channel.isEnabled(root)) return fail("CHANNEL_NOT_CONFIGURED", `channel "${channelId}" is not configured for this CCC (${root})`, channel.notEnabledReason?.(root));
|
|
613
|
+
if (action === "users") return {
|
|
614
|
+
ok: true,
|
|
615
|
+
channel: channelId,
|
|
616
|
+
action,
|
|
617
|
+
detail: { users: channel.listUsers(root) }
|
|
618
|
+
};
|
|
619
|
+
if (action === "contacts") {
|
|
620
|
+
if (!channel.listContacts) return fail("ACTION_UNSUPPORTED", `channel "${channelId}" has no record source for contacts`);
|
|
621
|
+
const settings = readWeixinSettings(root);
|
|
622
|
+
const accountChannel = {};
|
|
623
|
+
for (const account of settings.accounts ?? []) if (typeof account.accountId === "string" && account.accountId !== "") accountChannel[account.accountId] = typeof account.channel === "string" && account.channel !== "" ? account.channel : "weixin";
|
|
624
|
+
const scanned = scanImContacts(root, accountChannel);
|
|
625
|
+
const mine = scanned.contacts.filter((c) => c.channel === channelId);
|
|
626
|
+
/** 当前路由表(`user → trajectory`);同一 user 多条时后者覆盖 */
|
|
627
|
+
const routeMap = /* @__PURE__ */ new Map();
|
|
628
|
+
for (const route of settings.routes ?? []) if (typeof route.user === "string" && route.user !== "") routeMap.set(route.user, typeof route.trajectory === "string" ? route.trajectory : "");
|
|
629
|
+
const contacts = mine.map((c) => ({
|
|
630
|
+
channel: c.channel,
|
|
631
|
+
userId: c.userId,
|
|
632
|
+
accountIds: c.accountIds,
|
|
633
|
+
route: routeMap.get(c.userId) ?? null,
|
|
634
|
+
firstSeen: c.firstSeen === null ? null : new Date(c.firstSeen).toISOString(),
|
|
635
|
+
lastSeen: c.lastSeen === null ? null : new Date(c.lastSeen).toISOString(),
|
|
636
|
+
messages: c.messages
|
|
637
|
+
}));
|
|
638
|
+
const seenUsers = new Set(mine.map((c) => c.userId));
|
|
639
|
+
return {
|
|
640
|
+
ok: true,
|
|
641
|
+
channel: channelId,
|
|
642
|
+
action,
|
|
643
|
+
detail: {
|
|
644
|
+
contacts,
|
|
645
|
+
unrouted: mine.filter((c) => !routeMap.has(c.userId)).map((c) => c.userId),
|
|
646
|
+
orphanRoutes: [...routeMap.keys()].filter((user) => !seenUsers.has(user)),
|
|
647
|
+
sources: scanned.sources,
|
|
648
|
+
...scanned.errors.length > 0 ? { errors: scanned.errors } : {}
|
|
649
|
+
}
|
|
650
|
+
};
|
|
651
|
+
}
|
|
652
|
+
if (action === "status") return {
|
|
653
|
+
ok: true,
|
|
654
|
+
channel: channelId,
|
|
655
|
+
action,
|
|
656
|
+
detail: channel.status(root)
|
|
657
|
+
};
|
|
658
|
+
if (action === "send") {
|
|
659
|
+
const rawUser = (req.user ?? "").trim();
|
|
660
|
+
if (rawUser === "") return fail("USER_REQUIRED", "user is required");
|
|
661
|
+
const text = req.text ?? "";
|
|
662
|
+
if (text === "") return fail("TEXT_REQUIRED", "text is required");
|
|
663
|
+
if (text.length > 4e3) return fail("TEXT_TOO_LONG", `text is ${text.length} characters (> ${IM_SEND_MAX_TEXT})`);
|
|
664
|
+
const resolved = channel.resolveUser(root, rawUser);
|
|
665
|
+
if (!resolved) return fail("ALIAS_UNKNOWN", `unknown user "${rawUser}"`);
|
|
666
|
+
try {
|
|
667
|
+
return {
|
|
668
|
+
ok: true,
|
|
669
|
+
channel: channelId,
|
|
670
|
+
action,
|
|
671
|
+
detail: {
|
|
672
|
+
...await channel.send({
|
|
673
|
+
root,
|
|
674
|
+
userId: resolved.id,
|
|
675
|
+
text,
|
|
676
|
+
accountId: req.account
|
|
677
|
+
}),
|
|
678
|
+
user: resolved.alias ?? resolved.id
|
|
679
|
+
}
|
|
680
|
+
};
|
|
681
|
+
} catch (err) {
|
|
682
|
+
return fail("SEND_FAILED", err instanceof Error ? err.message : String(err));
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
if (action === "send-file") {
|
|
686
|
+
if (!channel.sendFile) return fail("ACTION_UNSUPPORTED", `channel "${channelId}" does not support send-file`);
|
|
687
|
+
const rawUser = (req.user ?? "").trim();
|
|
688
|
+
if (rawUser === "") return fail("USER_REQUIRED", "user is required");
|
|
689
|
+
const fileArg = (req.file ?? "").trim();
|
|
690
|
+
if (fileArg === "") return fail("FILE_REQUIRED", "file is required");
|
|
691
|
+
const resolved = channel.resolveUser(root, rawUser);
|
|
692
|
+
if (!resolved) return fail("ALIAS_UNKNOWN", `unknown user "${rawUser}"`);
|
|
693
|
+
const file = readCccFile(root, fileArg);
|
|
694
|
+
if (!file.ok) return fail(file.code, file.error);
|
|
695
|
+
try {
|
|
696
|
+
return {
|
|
697
|
+
ok: true,
|
|
698
|
+
channel: channelId,
|
|
699
|
+
action,
|
|
700
|
+
detail: {
|
|
701
|
+
...await channel.sendFile({
|
|
702
|
+
root,
|
|
703
|
+
userId: resolved.id,
|
|
704
|
+
data: file.data,
|
|
705
|
+
fileName: file.fileName,
|
|
706
|
+
caption: req.caption,
|
|
707
|
+
accountId: req.account
|
|
708
|
+
}),
|
|
709
|
+
user: resolved.alias ?? resolved.id
|
|
710
|
+
}
|
|
711
|
+
};
|
|
712
|
+
} catch (err) {
|
|
713
|
+
return fail("SEND_FAILED", err instanceof Error ? err.message : String(err));
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
return fail("ACTION_UNKNOWN", `unknown action "${action}"`);
|
|
717
|
+
}
|
|
718
|
+
//#endregion
|
|
719
|
+
//#region src/seams/tool-visibility.ts
|
|
720
|
+
/** 收集器:把各来源的 deny 合并成一个判决(**纯函数、无副作用**) */
|
|
721
|
+
function collectVisibilityDecision(sources) {
|
|
722
|
+
const deny = /* @__PURE__ */ new Set();
|
|
723
|
+
let hasError = false;
|
|
724
|
+
for (const s of sources) {
|
|
725
|
+
if (s.error !== void 0) hasError = true;
|
|
726
|
+
if (!s.ok) continue;
|
|
727
|
+
for (const name of s.deny) if (typeof name === "string" && name !== "") deny.add(name);
|
|
728
|
+
}
|
|
729
|
+
return {
|
|
730
|
+
deny: [...deny].sort(),
|
|
731
|
+
sources,
|
|
732
|
+
hasError
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
/** 判决签名(幂等判据:签名相同 ⇒ 目标态已达到 ⇒ **一次 restrict 都不发**) */
|
|
736
|
+
function decisionSignature(decision) {
|
|
737
|
+
return decision.deny.join(",");
|
|
738
|
+
}
|
|
739
|
+
/** `${sessionId}` → 已发射状态(**全模块唯一的一份**) */
|
|
740
|
+
const applied = /* @__PURE__ */ new Map();
|
|
741
|
+
/**
|
|
742
|
+
* 发射一次判决(**唯一的写点**)。
|
|
743
|
+
*
|
|
744
|
+
* 三条纪律:
|
|
745
|
+
* ① **幂等**:签名与当前已发射的一致 ⇒ 直接返回 `'unchanged'`,**不碰宿主**
|
|
746
|
+
* (这正是消除"工具清单闪动"的那一步)。
|
|
747
|
+
* ② **先撤后发**:宿主的 disposer 才是"撤销上一次",先撤再发才不会叠加旧集合。
|
|
748
|
+
* (旧集合是新集合的子集时叠不叠都看不出来,但**不是子集时**会残留 —— 必须撤。)
|
|
749
|
+
* ③ 🔴 **未注册的名字不许炸掉整次发射**:宿主契约"unknown names … fail"。
|
|
750
|
+
* 合并后集合里只要有一个不在册的名字,整次 restrict 就失败 ⇒ 六个机制**全都不生效**。
|
|
751
|
+
* ⇒ 策略 = **直接发 → 被拒时从宿主的错误文案里解析出它点名的未知名字 → 只剔那几个、其余重发一次**。
|
|
752
|
+
* 被剔掉的名字进 `dropped`(调用方决定要不要告警)。
|
|
753
|
+
* ⚠️ **不做 `tools.get` 预探活** —— 那个视图查不出 agent-plane 贡献的工具
|
|
754
|
+
* (`bash` / `schedule_*`),会把**在册的名字误判成未注册**(见下方发射段的实测记录)。
|
|
755
|
+
* 🔴 **也不按"谁注册的"降级** —— `REGISTERED_TOOLS` 只含 ACC 自己的 14 个,
|
|
756
|
+
* 用它当"在册面"会**整类丢掉宿主工具**(2026-10-24 真机缺陷,见发射段)。
|
|
757
|
+
* ⇒ 唯一合法的在册判据是**宿主自己的回答**:要么发一次成功,要么它说出哪些名字不认识。
|
|
758
|
+
*
|
|
759
|
+
* @returns `'unchanged'` / `'applied'` / `'failed'`(`failed` 时 `deny` 保持原样)
|
|
760
|
+
*/
|
|
761
|
+
function applyVisibilityDecision(agent, sessionId, decision) {
|
|
762
|
+
const signature = decisionSignature(decision);
|
|
763
|
+
const existing = applied.get(sessionId);
|
|
764
|
+
if (existing !== void 0 && existing.signature === signature) return {
|
|
765
|
+
status: "unchanged",
|
|
766
|
+
dropped: []
|
|
767
|
+
};
|
|
768
|
+
if (existing !== void 0) {
|
|
769
|
+
try {
|
|
770
|
+
existing.dispose();
|
|
771
|
+
} catch {}
|
|
772
|
+
applied.delete(sessionId);
|
|
773
|
+
}
|
|
774
|
+
const tools = agent.ctx.tools;
|
|
775
|
+
const dropped = [];
|
|
776
|
+
const names = decision.deny;
|
|
777
|
+
if (names.length === 0) {
|
|
778
|
+
applied.set(sessionId, {
|
|
779
|
+
signature,
|
|
780
|
+
deny: [],
|
|
781
|
+
dispose: () => {}
|
|
782
|
+
});
|
|
783
|
+
return {
|
|
784
|
+
status: "applied",
|
|
785
|
+
dropped
|
|
786
|
+
};
|
|
787
|
+
}
|
|
788
|
+
try {
|
|
789
|
+
const dispose = tools.restrict({ deny: [...names] });
|
|
790
|
+
applied.set(sessionId, {
|
|
791
|
+
signature,
|
|
792
|
+
deny: names,
|
|
793
|
+
dispose
|
|
794
|
+
});
|
|
795
|
+
return {
|
|
796
|
+
status: "applied",
|
|
797
|
+
dropped
|
|
798
|
+
};
|
|
799
|
+
} catch (firstError) {
|
|
800
|
+
const message = errorText(firstError);
|
|
801
|
+
const unknown = parseUnknownToolNames(message);
|
|
802
|
+
if (unknown.length === 0) return {
|
|
803
|
+
status: "failed",
|
|
804
|
+
dropped,
|
|
805
|
+
error: message
|
|
806
|
+
};
|
|
807
|
+
const unknownSet = new Set(unknown);
|
|
808
|
+
const remaining = names.filter((n) => !unknownSet.has(n));
|
|
809
|
+
dropped.push(...names.filter((n) => unknownSet.has(n)));
|
|
810
|
+
if (remaining.length === 0) return {
|
|
811
|
+
status: "failed",
|
|
812
|
+
dropped,
|
|
813
|
+
error: message
|
|
814
|
+
};
|
|
815
|
+
try {
|
|
816
|
+
const dispose = tools.restrict({ deny: remaining });
|
|
817
|
+
applied.set(sessionId, {
|
|
818
|
+
signature: decisionSignature({
|
|
819
|
+
...decision,
|
|
820
|
+
deny: remaining
|
|
821
|
+
}),
|
|
822
|
+
deny: remaining,
|
|
823
|
+
dispose
|
|
824
|
+
});
|
|
825
|
+
return {
|
|
826
|
+
status: "applied",
|
|
827
|
+
dropped
|
|
828
|
+
};
|
|
829
|
+
} catch (secondError) {
|
|
830
|
+
return {
|
|
831
|
+
status: "failed",
|
|
832
|
+
dropped,
|
|
833
|
+
error: errorText(secondError)
|
|
834
|
+
};
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
/** 取异常的可读文案(非 Error 也能取到 message;都没有则 String()) */
|
|
839
|
+
function errorText(e) {
|
|
840
|
+
if (e instanceof Error) return e.message;
|
|
841
|
+
if (typeof e === "object" && e !== null && "message" in e && typeof e.message === "string") return e.message;
|
|
842
|
+
return String(e);
|
|
843
|
+
}
|
|
844
|
+
/**
|
|
845
|
+
* 从宿主的 `tools.restrict()` 错误文案里解析出**被点名的未知工具名**。
|
|
846
|
+
*
|
|
847
|
+
* 宿主逐字形态(`dsh-tools/lib/types/index.js` 的 `restrict()`):
|
|
848
|
+
* ```
|
|
849
|
+
* tools.restrict() names unknown global tool(s) "a", "b"; known global tools: x, y, z
|
|
850
|
+
* ```
|
|
851
|
+
* 单数时是 `tool`,复数时是 `tool(s)`——两种都匹配。
|
|
852
|
+
*
|
|
853
|
+
* 🔴 **只取分号之前那一段**:分号后是 `known global tools:` 清单,**不能**误当成未知名字。
|
|
854
|
+
* 🔴 解析不出来就返回 `[]`(调用方据此走"如实失败、不记账"),**绝不猜**。
|
|
855
|
+
*/
|
|
856
|
+
function parseUnknownToolNames(message) {
|
|
857
|
+
const head = message.split(";")[0] ?? "";
|
|
858
|
+
if (!/names unknown global tool/.test(head)) return [];
|
|
859
|
+
const out = [];
|
|
860
|
+
for (const m of head.matchAll(/"([^"]+)"/g)) {
|
|
861
|
+
const name = m[1];
|
|
862
|
+
if (name !== void 0 && name !== "") out.push(name);
|
|
863
|
+
}
|
|
864
|
+
return [...new Set(out)];
|
|
865
|
+
}
|
|
866
|
+
/** 会话销毁清理(防 per-会话 Map 无界增长;lifecycle 调用) */
|
|
867
|
+
function forgetToolVisibility(sessionId) {
|
|
868
|
+
const existing = applied.get(sessionId);
|
|
869
|
+
if (existing === void 0) return;
|
|
870
|
+
try {
|
|
871
|
+
existing.dispose();
|
|
872
|
+
} catch {}
|
|
873
|
+
applied.delete(sessionId);
|
|
874
|
+
}
|
|
875
|
+
//#endregion
|
|
876
|
+
//#region src/seams/guards.ts
|
|
877
|
+
/**
|
|
878
|
+
* guards.ts — 拦截缝:安全模式 + 路径守卫(P3 语义的机械层)
|
|
879
|
+
*
|
|
880
|
+
* 纯决策逻辑(decideGuard)与 DSH 注册(registerGuards)分离:
|
|
881
|
+
* 前者零 DSH 依赖可单测,后者把决策接到 tools/pre-execute 瀑布 + ctx.tools.guard 终局。
|
|
882
|
+
*
|
|
883
|
+
* 对应 opencode-serenity-plugin 的 tool.execute.before 路径守卫 + bash 开关 + 黑名单。
|
|
884
|
+
*/
|
|
885
|
+
/** 写类工具名(黑名单/治理文件只拦这些;读工具只做路径越界检查——对齐 osp) */
|
|
886
|
+
const WRITE_TOOLS = /* @__PURE__ */ new Set([
|
|
887
|
+
"write",
|
|
888
|
+
"edit",
|
|
889
|
+
"str_replace_editor",
|
|
890
|
+
"container_fs",
|
|
891
|
+
"bash",
|
|
892
|
+
"touch"
|
|
893
|
+
]);
|
|
894
|
+
/** container_fs 的写类子命令(mkdir/rm/mv/cp/touch);其余 9 子命令(root/resolve/exists/
|
|
895
|
+
* list/tree/relative/reveal/info/find)为只读——只读子命令不查黑名单(同 read 语义)
|
|
896
|
+
* 🔴 `append` 已于 v1.101.0 退役(owner 2026-10-26),故不在此集合。 */
|
|
897
|
+
const CC_FS_WRITE_ACTIONS = /* @__PURE__ */ new Set([
|
|
898
|
+
"mkdir",
|
|
899
|
+
"rm",
|
|
900
|
+
"mv",
|
|
901
|
+
"cp",
|
|
902
|
+
"touch"
|
|
903
|
+
]);
|
|
904
|
+
/**
|
|
905
|
+
* 凭据文件硬名单(数据面守卫,v1.26.3,S142 用户:localstore.json 需要在 read 工具的黑名单里):
|
|
906
|
+
* **任何工具**(含 read/grep/glob/container_fs 只读子命令)命中这些相对 CCC 根的路径 → deny。
|
|
907
|
+
*
|
|
908
|
+
* 与 safeMode.blacklist(写黑名单,v1.18.5 决策只拦写)语义独立:
|
|
909
|
+
* - 黑名单 = 用户可配置的写保护(REPOSITORIES/ 等只读参考源不误伤读)
|
|
910
|
+
* - 凭据硬名单 = **结构性数据面边界**(不依赖 safe-mode 开关,凭据文件任何时候不可读)——
|
|
911
|
+
* 对齐 CCE Bounded Space + wardn "structural guarantee, not policy":localstore.json
|
|
912
|
+
* 含 API keys/tokens/SSH 密码,即使 prompt 纪律失败也无值可吐(机械保证)。
|
|
913
|
+
*/
|
|
914
|
+
const SENSITIVE_CREDENTIAL_FILES = /* @__PURE__ */ new Set(["localstore.json"]);
|
|
915
|
+
/**
|
|
916
|
+
* MSM 注册表写保护(需求⑤b S142 用户拍板:"msm注册的文件需要写保护起来,避免CCC意外写坏搞崩自己"):
|
|
917
|
+
* mech-registry.json 是 CCC 执行层地基(坏 → loadMsmEntries 抛 → container_admin/output-guard 全崩,
|
|
918
|
+
* register 也崩 → 自锁)。**写 deny、读 allow**(与 localstore 读 deny 语义区分 R6——注册表是
|
|
919
|
+
* 结构核心不是秘密,需被 output-guard/trajectory-constraint-admin 读取建 MSM 词表)。
|
|
920
|
+
*
|
|
921
|
+
* 单级化(需求⑤a)后**唯一合法注册表 = cccName 聚合档**
|
|
922
|
+
* `.opencode/skills/<cccName>/references/mech-registry.json`(cccName = .serenity 首行)。
|
|
923
|
+
* 历史 root 级 `mech-registry.json` 与各 skill 分散注册表已废弃:**不再保护**
|
|
924
|
+
* (review P1:保护一个永不被读的文件 = 死锁——MSM 既不可见又不可删/迁移)。
|
|
925
|
+
* 写工具命中聚合档 → deny(唯一合法写通道 = container_admin msm register/deregister
|
|
926
|
+
* 内部 writeRegistry,走工具实现不经 pre-execute → 天然豁免);读工具放行。
|
|
927
|
+
*/
|
|
928
|
+
function isProtectedRegistryRel(root, rel) {
|
|
929
|
+
const lower = (s) => process.platform === "win32" ? s.toLowerCase() : s;
|
|
930
|
+
const relCi = lower(rel);
|
|
931
|
+
try {
|
|
932
|
+
const marker = resolve(root, ".serenity");
|
|
933
|
+
if (existsSync(marker)) {
|
|
934
|
+
const line = readCccName(root);
|
|
935
|
+
if (line) {
|
|
936
|
+
if (relCi === lower(`.opencode/skills/${line}/references/mech-registry.json`)) return true;
|
|
937
|
+
if (relCi === lower(`.opencode/skills/${line}/references`)) return true;
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
} catch {}
|
|
941
|
+
return false;
|
|
942
|
+
}
|
|
943
|
+
/** 判定工具是否为写类:普通工具按名;container_fs 复合工具按子命令 action */
|
|
944
|
+
function isWriteTool(toolName, action) {
|
|
945
|
+
if (!WRITE_TOOLS.has(toolName)) return false;
|
|
946
|
+
if (toolName === "container_fs") return action !== void 0 && CC_FS_WRITE_ACTIONS.has(action);
|
|
947
|
+
return true;
|
|
948
|
+
}
|
|
949
|
+
/**
|
|
950
|
+
* 安全模式 + 黑名单 + P3 路径守卫的纯决策。
|
|
951
|
+
* 对齐 opencode-serenity-plugin 标准:安全模式 = **bash 禁用** + 写入黑名单;
|
|
952
|
+
* write/edit 等工具仅受路径逃逸与黑名单约束(不整体禁用)。
|
|
953
|
+
* 优先级:safe-mode bash > 路径越界 > 黑名单命中。
|
|
954
|
+
*/
|
|
955
|
+
function decideGuard(input) {
|
|
956
|
+
const { root, toolName, safeModeOn, blacklist, pathArg, action } = input;
|
|
957
|
+
if (input.trajectoryConstraint !== void 0 && input.trajectoryConstraint !== null) {
|
|
958
|
+
const profile = input.trajectoryConstraint;
|
|
959
|
+
if (toolName === "skill") return { kind: "allow" };
|
|
960
|
+
if ((profile.msms ?? []).includes(toolName)) return {
|
|
961
|
+
deny: `"${toolName}" is a registered MSM, not a direct tool in this trajectory — call it through the msm tool: msm("${toolName}", ["<args>"]) (pass "--help" or inspect=true for usage)`,
|
|
962
|
+
kind: "deny"
|
|
963
|
+
};
|
|
964
|
+
const whitelist = profileToolWhitelist(profile);
|
|
965
|
+
if (whitelist !== null && !whitelist.has(toolName)) return {
|
|
966
|
+
deny: "tool not allowed in this 轨迹约束 trajectory",
|
|
967
|
+
kind: "deny"
|
|
968
|
+
};
|
|
969
|
+
const writeScopes = profileWriteWhitelist(profile);
|
|
970
|
+
if (writeScopes !== null && pathArg !== void 0 && isWriteTool(toolName, action)) {
|
|
971
|
+
const abs = resolve(root, pathArg);
|
|
972
|
+
if (!writeScopes.some((scope) => pathInside(resolve(root, scope), abs))) return {
|
|
973
|
+
deny: `${toolName}: write outside this trajectory's declared write scope (allowed: ${writeScopes.length > 0 ? writeScopes.join(" / ") : "(none — \"writes\" is an empty array)"}); target: ${pathArg} — add the prefix to this trajectory's trajectory.json "writes" if the write is intended`,
|
|
974
|
+
kind: "deny"
|
|
975
|
+
};
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
if (safeModeOn && SAFE_MODE_SHELL_TOOL_NAMES.includes(toolName)) return {
|
|
979
|
+
deny: `${toolName}: no such tool`,
|
|
980
|
+
kind: "deny"
|
|
981
|
+
};
|
|
982
|
+
if (pathArg !== void 0) {
|
|
983
|
+
const abs = resolve(root, pathArg);
|
|
984
|
+
if (!pathInside(resolve(root), abs)) return {
|
|
985
|
+
deny: `path escape blocked: "${pathArg}" escapes the CCC root`,
|
|
986
|
+
kind: "deny"
|
|
987
|
+
};
|
|
988
|
+
const rel = relative(root, abs).split("\\").join("/");
|
|
989
|
+
if (SENSITIVE_CREDENTIAL_FILES.has(rel)) return {
|
|
990
|
+
deny: `access blocked: "${pathArg}" is a sensitive credential file (${rel})`,
|
|
991
|
+
kind: "deny"
|
|
992
|
+
};
|
|
993
|
+
if (isWriteTool(toolName, action)) {
|
|
994
|
+
if (rel === ".serenity-safe-on" || rel === ".serenity" || rel.startsWith(".serenity-safe-on/") || rel.startsWith(".serenity/")) return {
|
|
995
|
+
deny: `CCC governance file "${rel}" is reserved for the user — agent must not write`,
|
|
996
|
+
kind: "deny"
|
|
997
|
+
};
|
|
998
|
+
if (isProtectedRegistryRel(root, rel)) return {
|
|
999
|
+
deny: rel.endsWith("/mech-registry.json") ? `mech-registry.json is ACC-managed (${rel}) — use container_admin msm register/deregister instead of writing it directly` : `"${rel}" is an ancestor of the ACC-managed mech-registry.json — removing/moving it would destroy the registry; the registry is managed by container_admin msm register/deregister`,
|
|
1000
|
+
kind: "deny"
|
|
1001
|
+
};
|
|
1002
|
+
const hit = matchBlacklist(rel, blacklist);
|
|
1003
|
+
if (hit) return {
|
|
1004
|
+
deny: hit.message ?? `blacklist blocked: "${pathArg}" matches rule "${hit.pattern}"`,
|
|
1005
|
+
kind: "deny"
|
|
1006
|
+
};
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
return { kind: "allow" };
|
|
1010
|
+
}
|
|
1011
|
+
/**
|
|
1012
|
+
* 🔴 **工具可见性的唯一发射入口**(方案 C 的落地)。
|
|
1013
|
+
*
|
|
1014
|
+
* ## 它取代了什么
|
|
1015
|
+
*
|
|
1016
|
+
* 改之前有六条独立 sync,每条在自己的 per-会话 Map 里放一个 `restrict` disposer,
|
|
1017
|
+
* 且都由 `pre-step`(每步)与 `seed`(冷载入)各自调用 ⇒ 一次交互里可能发出多次
|
|
1018
|
+
* `tools.restrict` ⇒ 宿主每次发 `tools/change` ⇒ 模型侧看到工具清单**先进后出**
|
|
1019
|
+
* (实测症状:`新增 7 个` 紧跟 `移除 7 个`)。
|
|
1020
|
+
*
|
|
1021
|
+
* ## 为什么合并是对的(不是简化)
|
|
1022
|
+
*
|
|
1023
|
+
* 宿主 `ToolRuntime.restrict` 契约逐字:**Restrictions intersect**。
|
|
1024
|
+
* ⇒ N 次 `deny: Dᵢ` 的净效果 = `⋃Dᵢ`。先求并集只发一次,**结果相同**、只触发一次 `tools/change`。
|
|
1025
|
+
* 前提 = **只用 `deny`**(`allow` 的"交集"不满足并集律);本仓 18 处 restrict 全部只发 `deny`。
|
|
1026
|
+
*
|
|
1027
|
+
* ## 正确性怎么保住(这是本设计被质疑的那一点)
|
|
1028
|
+
*
|
|
1029
|
+
* 六源**各自独立**算自己的 deny 并**各自 catch**:某一个来源读配置抛错 ⇒ 它返回
|
|
1030
|
+
* `ok:false`(不贡献 deny),**其余五源照常生效**。⇒ 合并**不会**把一格的失败放大成六格。
|
|
1031
|
+
* 全量计算见 {@link computeVisibilitySources}(纯函数)。
|
|
1032
|
+
*
|
|
1033
|
+
* @param agent 目标会话
|
|
1034
|
+
* @param root CCC 根;`null` ⇒ 不在 CCC 内 ⇒ 隐藏**全部** ACC 工具
|
|
1035
|
+
*/
|
|
1036
|
+
function syncToolVisibility(agent, root) {
|
|
1037
|
+
const sessionId = agent.session.id ?? "global";
|
|
1038
|
+
const sources = computeVisibilitySources(sessionId, root);
|
|
1039
|
+
const decision = collectVisibilityDecision(sources);
|
|
1040
|
+
if (root !== null && decision.hasError) {
|
|
1041
|
+
const bad = sources.filter((s) => s.error !== void 0);
|
|
1042
|
+
for (const s of bad) console.error(`[serenity-hooks] 工具可见性来源「${s.id}」判据失败(其余来源照常生效): ${s.error ?? ""}`);
|
|
1043
|
+
}
|
|
1044
|
+
const r = applyVisibilityDecision(agent, sessionId, decision);
|
|
1045
|
+
if (r.status === "failed") console.error(`[serenity-hooks] 工具可见性发射失败 (session=${sessionId}): ${r.error ?? ""}`);
|
|
1046
|
+
else if (r.dropped.length > 0) console.log(`[serenity-hooks] 工具可见性:跳过 ${r.dropped.length} 个未注册名(${r.dropped.join(", ")})`);
|
|
1047
|
+
}
|
|
1048
|
+
/**
|
|
1049
|
+
* 六源 → 各自的 deny 集合(**纯函数:只读配置、不碰宿主**)。
|
|
1050
|
+
*
|
|
1051
|
+
* 每条来源**自己负责自己的失败**:抛错就 catch 在这里,转成 `ok:false + error`。
|
|
1052
|
+
* ⛔ 绝不让一个来源的异常冒泡 —— 那会让另外五源一起失效(正是合并最容易犯的错)。
|
|
1053
|
+
*/
|
|
1054
|
+
function computeVisibilitySources(sessionId, root) {
|
|
1055
|
+
const out = [];
|
|
1056
|
+
out.push(sourceOf("nonCcc", () => {
|
|
1057
|
+
if (root !== null) return { deny: [] };
|
|
1058
|
+
return { deny: [...REGISTERED_TOOLS] };
|
|
1059
|
+
}));
|
|
1060
|
+
if (root === null) {
|
|
1061
|
+
for (const id of [
|
|
1062
|
+
"safeMode",
|
|
1063
|
+
"imBridge",
|
|
1064
|
+
"hostSchedule",
|
|
1065
|
+
"trajectoryConstraint"
|
|
1066
|
+
]) out.push({
|
|
1067
|
+
id,
|
|
1068
|
+
deny: [],
|
|
1069
|
+
ok: false
|
|
1070
|
+
});
|
|
1071
|
+
return out;
|
|
1072
|
+
}
|
|
1073
|
+
out.push(sourceOf("safeMode", () => {
|
|
1074
|
+
if (!isSafeModeOn(root)) return { deny: [] };
|
|
1075
|
+
return { deny: [...SAFE_MODE_DENY_TOOLS] };
|
|
1076
|
+
}));
|
|
1077
|
+
out.push(sourceOf("imBridge", () => isImWiredTrajectory(root, trajectoryCodeForSession(root, sessionId)) ? { deny: [] } : { deny: [IM_BRIDGE_TOOL_NAME] }));
|
|
1078
|
+
out.push(sourceOf("hostSchedule", () => ({ deny: [...HOST_SCHEDULE_TOOL_NAMES] })));
|
|
1079
|
+
out.push(sourceOf("trajectoryConstraint", () => {
|
|
1080
|
+
const profile = trajectoryConstraintForSession(root, sessionId);
|
|
1081
|
+
if (profile === null) return { deny: [] };
|
|
1082
|
+
const allowed = profileToolWhitelist(profile);
|
|
1083
|
+
if (allowed === null) return { deny: [] };
|
|
1084
|
+
return { deny: REGISTERED_TOOLS.filter((n) => !allowed.has(n)) };
|
|
1085
|
+
}));
|
|
1086
|
+
out.push(sourceOf("alwaysDeny", () => ({ deny: [...ALWAYS_DENY_TOOLS] })));
|
|
1087
|
+
return out;
|
|
1088
|
+
}
|
|
1089
|
+
/**
|
|
1090
|
+
* 把一个"可能抛错的 denies 计算"包成来源(**统一在这里 catch**)。
|
|
1091
|
+
* 失败 ⇒ `ok:false`:本来源不贡献 deny,**其余来源不受影响**。
|
|
1092
|
+
*/
|
|
1093
|
+
function sourceOf(id, fn) {
|
|
1094
|
+
try {
|
|
1095
|
+
const r = fn();
|
|
1096
|
+
return {
|
|
1097
|
+
id,
|
|
1098
|
+
deny: r.deny,
|
|
1099
|
+
ok: true,
|
|
1100
|
+
...r.error !== void 0 ? { error: r.error } : {}
|
|
1101
|
+
};
|
|
1102
|
+
} catch (e) {
|
|
1103
|
+
return {
|
|
1104
|
+
id,
|
|
1105
|
+
deny: [],
|
|
1106
|
+
ok: false,
|
|
1107
|
+
error: e.message
|
|
1108
|
+
};
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
/** 从 exec 提取 agent 会话 cwd(CCC 根检测基准);无则回退进程 cwd */
|
|
1112
|
+
function resolveAgentCwd(exec) {
|
|
1113
|
+
return exec.agent?.session?.header?.cwd ?? process.cwd();
|
|
1114
|
+
}
|
|
1115
|
+
/**
|
|
1116
|
+
* 某个平台上的 **shell 工具真名** —— 安全模式拒绝面的**唯一来源**。
|
|
1117
|
+
*
|
|
1118
|
+
* ## 为什么需要它(2026-11-24 `security-serenity` owner 报障,真机缺陷)
|
|
1119
|
+
*
|
|
1120
|
+
* 判据在这里被写死成了 `'bash'`,而**宿主按平台装不同的 shell provider**,
|
|
1121
|
+
* 注册的工具名因此不同(取证:本机宿主包里 `dsh-tool-pwsh/lib/index.js` 逐字
|
|
1122
|
+
* `defineTool({ name: 'pwsh', … })`,`dsh-tool-bash` 同构但叫 `bash`):
|
|
1123
|
+
*
|
|
1124
|
+
* | 平台 | 宿主包 | 工具名 |
|
|
1125
|
+
* |---|---|---|
|
|
1126
|
+
* | win32 | `dsh-pwsh-local` / `dsh-tool-pwsh` | **`pwsh`** |
|
|
1127
|
+
* | POSIX | `dsh-bash-local` / `dsh-tool-bash` | `bash` |
|
|
1128
|
+
*
|
|
1129
|
+
* ⇒ Windows 上 `deny: ['bash']` 指向一个**从未注册的名字**:
|
|
1130
|
+
* `restrict` 要么整次失败、要么藏掉一个不存在的东西,而**`pwsh` 毫发无损**;
|
|
1131
|
+
* 守卫那句 `toolName === 'bash'` 同样**永不命中**。
|
|
1132
|
+
* 现象 = **安全模式在 Windows 上静默无效,而界面显示"已开启"**。
|
|
1133
|
+
*
|
|
1134
|
+
* ## 🔴 为什么是「按平台取单名」而不是「把两个名字都写进表」
|
|
1135
|
+
*
|
|
1136
|
+
* 宿主 `tools.restrict` 契约逐字:**未知名字会让整次调用失败**。
|
|
1137
|
+
* ⇒ `deny: ['bash','pwsh']` 在**任一**平台上都有一个未注册名 ⇒ 整次失败。
|
|
1138
|
+
* 本仓的升级路径会从错误文案里剔掉未知名再重发一次,所以**不一定**退化到失效,
|
|
1139
|
+
* 但那是**白付一次失败**,且把「本该一次成功」变成「依赖降级路径正确」。
|
|
1140
|
+
* ⇒ **拒绝表只能有本平台的真名**。
|
|
1141
|
+
*
|
|
1142
|
+
* ## 表与守卫为什么**不共用同一个集合**
|
|
1143
|
+
*
|
|
1144
|
+
* - **表**({@link SAFE_MODE_DENY_TOOLS}):必须**恰好一个真名**(上面那条契约)。
|
|
1145
|
+
* - **守卫**({@link decideGuard}):纯字符串比较、不经过 `restrict`,
|
|
1146
|
+
* 认几个候选名**没有代价**,却能补住「表发射失败」那一格
|
|
1147
|
+
* (发射失败时模型仍看得见 shell,此时守卫是**唯一的**拦截)。
|
|
1148
|
+
* ⇒ 故守卫用 {@link SAFE_MODE_SHELL_TOOL_NAMES}(全集),不是这一张。
|
|
1149
|
+
*
|
|
1150
|
+
* ⚠️ **纯函数、参数可注入**:`process.platform` 只在**缺省处**读一次,
|
|
1151
|
+
* 测试可直接喂 `'win32'`。CI 跑在 Linux 上 ⇒ win32 分支**永远走不到**,
|
|
1152
|
+
* 不给它一个可注入的入口,这条判据就**没有任何失败信号**。
|
|
1153
|
+
*/
|
|
1154
|
+
function shellToolNameFor(platform = process.platform) {
|
|
1155
|
+
return platform === "win32" ? "pwsh" : "bash";
|
|
1156
|
+
}
|
|
1157
|
+
/**
|
|
1158
|
+
* 已知的 shell 工具名全集 —— **只给守卫用**(见 {@link shellToolNameFor} 的对照说明)。
|
|
1159
|
+
*
|
|
1160
|
+
* 加名字的代价是零(纯比较);**不加**的代价是「宿主换了 provider 名,安全模式又静默失效」。
|
|
1161
|
+
*/
|
|
1162
|
+
const SAFE_MODE_SHELL_TOOL_NAMES = ["bash", "pwsh"];
|
|
1163
|
+
/**
|
|
1164
|
+
* 安全模式开启时从模型工具列表隐藏的工具 —— **安全模式唯一的开关对象**。
|
|
1165
|
+
*
|
|
1166
|
+
* 🔴 **2026-11-06 owner 令:「安全模式开关只影响 bash 开关」**。
|
|
1167
|
+
* 在此之前这里还并进了 CCC 声明的 `safeMode.hiddenTools`(v1.51.4 起的附加屏蔽面);
|
|
1168
|
+
* 该配置键**已整条退役**(见 {@link ALWAYS_DENY_TOOLS} 头的判据变更记录)。
|
|
1169
|
+
* ⇒ 本表现在**只有一个条目**,而这不是"还没补全":**安全模式管的就是它**。
|
|
1170
|
+
*
|
|
1171
|
+
* 🔴 **2026-11-24 那个"一个条目"是平台相关的**:值是 `bash` 还是 `pwsh`
|
|
1172
|
+
* 由 {@link shellToolNameFor} 决定(Windows 上宿主注册的是 `pwsh`)。
|
|
1173
|
+
* ⛔ **不要写成字面量、也不要把两个名字都塞进来** —— 理由见该函数头。
|
|
1174
|
+
*
|
|
1175
|
+
* write/edit 刻意保留:安全模式要挡的是"起 shell 做任意事",不是挡文件编辑
|
|
1176
|
+
* (编辑受路径越界与黑名单两道门约束,与本开关无关)。
|
|
1177
|
+
*/
|
|
1178
|
+
const SAFE_MODE_DENY_TOOLS = [shellToolNameFor()];
|
|
1179
|
+
/**
|
|
1180
|
+
* **CCC 内恒隐表** —— 只要会话在 CCC 目录内就隐藏,**与安全模式开关无关**。
|
|
1181
|
+
*
|
|
1182
|
+
* ## 判据(owner 2026-11-06 令)
|
|
1183
|
+
*
|
|
1184
|
+
* > 「subagent 一套 tool 常开,安全模式开关只影响 bash 开关,剩余的都是只要在 CCC 目录就关」
|
|
1185
|
+
*
|
|
1186
|
+
* 三句话对应三张表,本表是第三句的落点:
|
|
1187
|
+
*
|
|
1188
|
+
* | 范围 | 表 | 何时生效 |
|
|
1189
|
+
* |---|---|---|
|
|
1190
|
+
* | subagent 一族(`subagent` / `subagent_fork` / `send_message` / `list_agents` / `interrupt_agent` / `list_subagent_models`) | **不入任何表** | 常开 |
|
|
1191
|
+
* | shell | {@link SAFE_MODE_DENY_TOOLS} | 只随安全模式开关 |
|
|
1192
|
+
* | 其余(本表 + {@link HOST_SCHEDULE_TOOL_NAMES}) | 本表 | 只要在 CCC 内 |
|
|
1193
|
+
*
|
|
1194
|
+
* ## 🔴 判据变更记录(D184:必须说出原前提被谁取代)
|
|
1195
|
+
*
|
|
1196
|
+
* 本表原名「常驻拒绝表」,**只有一个条目** `ask_user_question`,理由是 owner 2026-11-01 那句
|
|
1197
|
+
* 「宁静号追求更高程度的自动化和轨迹协作,这种阻塞性的东西会降低效率」。
|
|
1198
|
+
* 那条老判据**没有错,只是窄**:它针对的是"阻塞",而 owner 2026-11-06 收紧成
|
|
1199
|
+
* **"凡不属于 CCC 工作流、且宿主自己会在后台驱动会话的,一律在 CCC 内关掉"**。
|
|
1200
|
+
* ⇒ 老的 `safeMode.hiddenTools` 面(10 项,其中 3 项宿主根本没注册)被**整条吸收进本表**,
|
|
1201
|
+
* 淘汰掉的是"用安全模式开关控制这些工具"的旧形态 —— 它们本来就该**一直关着**,
|
|
1202
|
+
* 跟着一个文件开关忽隐忽现反而是缺陷(安全模式关着时它们会重新出现)。
|
|
1203
|
+
*
|
|
1204
|
+
* ## 逐条为什么在这张表里
|
|
1205
|
+
*
|
|
1206
|
+
* | 工具 | 为什么在 CCC 内一律关 |
|
|
1207
|
+
* |---|---|
|
|
1208
|
+
* | `ask_user_question` | 阻塞式提问,与"轨迹自驱 + 轨迹间协作"冲突(owner 2026-11-01 原话) |
|
|
1209
|
+
* | `job_output` / `job_list` / `job_kill` | 宿主的后台作业控制面。本仓没有 ACC 侧的后台作业模型,模型看得见就会去用 ⇒ 造出"宿主自己也有一本账"的第二记账面 |
|
|
1210
|
+
* | `workflow` | 大型编排的执行器;轨迹协作走 `cognitive_trajectory send-*` 与 CRO,不走它 |
|
|
1211
|
+
* | `exit_plan_mode` | 计划模式的出口;CCC 的计划形态是 `todo_write` + `SESSION.md`,不是宿主的 plan-mode |
|
|
1212
|
+
* | `plugin_manager` | 改 profile 属**用户面**(它能装任意 Host 代码,宿主自己在提示词里也这么写);agent 不该有它 |
|
|
1213
|
+
* | `working_directory` | 🔴 **宿主 0.2.2-rc.1 新增**(owner 2026-11-06:「我们也关掉」)。它改的是**会话 cwd**,而 cwd 是 CCC 边界判定与 `cccRootForCwd` 的输入之一 ⇒ 让模型能改它,等于让模型能移动自己所在的边界。CCC 的"换目录"语义由轨迹本身表达(一条轨迹一个工作目录),不需要会话内漂移 |
|
|
1214
|
+
*
|
|
1215
|
+
* ## 与另外两张表的关系
|
|
1216
|
+
*
|
|
1217
|
+
* - **不并进** {@link SAFE_MODE_DENY_TOOLS}:那张表的名字即语义是"安全模式期间的拒绝"。
|
|
1218
|
+
* 把恒隐项塞进去会让"安全模式关着 ⇒ 这些工具全回来"—— 那正是本次要消灭的形态(D151 同族:错位零信号)。
|
|
1219
|
+
* - **不并进** {@link HOST_SCHEDULE_TOOL_NAMES}:那张表的条目**全部来自宿主包**
|
|
1220
|
+
* (`dsh-tool-schedule`),与"我们自己的工具面变更"分开登记,宿主改名时只需改那一张。
|
|
1221
|
+
*
|
|
1222
|
+
* ⚠️ **边界(诚实标注,D255)**:
|
|
1223
|
+
* - 本表是**藏**(`tools.restrict({deny})` 让模型看不见),**不是禁** —— 它不阻止经别的路径调用。
|
|
1224
|
+
* 要真禁得住需在 tool-call 层拦截,那是另一件事。
|
|
1225
|
+
* - 它**不依赖** `.serenity-safe-on`:安全模式关着也照样藏。
|
|
1226
|
+
* - 宿主若不认识某个名字,`applyVisibilityDecision` 会从它的错误里解析并只剔掉那几个
|
|
1227
|
+
* (⇒ 本表写错一个名字**不会**连累其它来源,也不会静默冻结)。
|
|
1228
|
+
* - 🔴 **非 CCC 会话本表不生效**(`computeVisibilitySources` 在非 CCC 时早返回)——
|
|
1229
|
+
* owner 的令针对的是"宁静号里",非 CCC 不是 ACC 的管辖面(见同文件 `nonCcc` 源的用例)。
|
|
1230
|
+
*/
|
|
1231
|
+
const ALWAYS_DENY_TOOLS = [
|
|
1232
|
+
"ask_user_question",
|
|
1233
|
+
"job_output",
|
|
1234
|
+
"job_list",
|
|
1235
|
+
"job_kill",
|
|
1236
|
+
"workflow",
|
|
1237
|
+
"exit_plan_mode",
|
|
1238
|
+
"plugin_manager",
|
|
1239
|
+
"working_directory"
|
|
1240
|
+
];
|
|
1241
|
+
const safeModeRestrictions = /* @__PURE__ */ new Map();
|
|
1242
|
+
const restrictDiag = {
|
|
1243
|
+
lastKey: null,
|
|
1244
|
+
lastAttemptAt: null,
|
|
1245
|
+
lastSuccess: null,
|
|
1246
|
+
lastError: null,
|
|
1247
|
+
activeKeys: [],
|
|
1248
|
+
denyByKey: {}
|
|
1249
|
+
};
|
|
1250
|
+
function getRestrictDiagnostics() {
|
|
1251
|
+
return {
|
|
1252
|
+
...restrictDiag,
|
|
1253
|
+
activeKeys: [...safeModeRestrictions.keys()],
|
|
1254
|
+
denyByKey: Object.fromEntries([...safeModeRestrictions].map(([k, v]) => [k, v.deny]))
|
|
1255
|
+
};
|
|
1256
|
+
}
|
|
1257
|
+
/** 条件可见的 IM 工具名(与 tools/im/channels.ts 的注册名一致) */
|
|
1258
|
+
const IM_BRIDGE_TOOL_NAME = "im-bridge";
|
|
1259
|
+
/**
|
|
1260
|
+
* 会话销毁清理(lifecycle 调用)。
|
|
1261
|
+
*
|
|
1262
|
+
* ⚠️ 方案 C 后撤销动作**只在** `forgetToolVisibility` 里做一次(那一次合并 restrict)。
|
|
1263
|
+
* 本函数保留为语义占位:重复撤销同一条 restrict 会抛错,故这里刻意不做动作。
|
|
1264
|
+
*/
|
|
1265
|
+
function forgetImBridgeVisibility(_sessionId) {}
|
|
1266
|
+
/** 会话销毁清理(lifecycle 调用)——方案 C 后由统一清理撤销,这里保留语义占位。 */
|
|
1267
|
+
function forgetHostScheduleToolHiding(_sessionId) {}
|
|
1268
|
+
/**
|
|
1269
|
+
* 宿主 `dsh-tool-schedule` 注册的模型可见工具名(**逐字**)。
|
|
1270
|
+
*
|
|
1271
|
+
* 🔴 **为什么要在 CCC 内屏蔽**(owner 原话:「这和 CRO 冲突,要求在宁静号激活情况下屏蔽掉」):
|
|
1272
|
+
* 宁静号的唤醒/巡航走 `cognitive_trajectory send-later` → `AGENT_SESSIONS/wake-registry.json`
|
|
1273
|
+
* → 中心调度器 5min tick(D58)。宿主这套定时器是**另一个**真相源 ⇒ 两处记账、
|
|
1274
|
+
* CRO 判据失真、且模型可能顺手排一个"不在任何账本里"的唤醒。
|
|
1275
|
+
*
|
|
1276
|
+
* 🔴🔴 **2026-11-06(S142):宿主 0.2.2-rc.1 把这套工具改了名,本表没跟上 ⇒ 屏蔽漏了一半**。
|
|
1277
|
+
* 实测(`msm sys node` 读本机装机包的 `lib/index.js`,⛔ 非推断):
|
|
1278
|
+
* | 宿主版本 | `dsh-tool-schedule` 真实注册名 |
|
|
1279
|
+
* |---|---|
|
|
1280
|
+
* | `0.2.1-rc.2` | `schedule_create` / `schedule_list` / `schedule_update` / `schedule_delete` |
|
|
1281
|
+
* | `0.2.2-rc.1` | `schedule_create` / `schedule_list` / **`schedule_view`** / **`schedule_edit`** |
|
|
1282
|
+
* ⇒ `schedule_update` / `schedule_delete` **已不存在**(写在本表里=永远剔不掉的无效名),
|
|
1283
|
+
* 而 `schedule_view` / `schedule_edit` **从未被屏蔽**(用户在会话里能直接看到并调用它们)。
|
|
1284
|
+
* **失效形态是静默的**:宿主 `restrict()` 对未知名只会**剔除**(我们那边的降级档还会打
|
|
1285
|
+
* 「跳过 N 个未注册名」),所以"旧名失效+新名漏网"在读数面上表现为**一切正常**。
|
|
1286
|
+
* ⇒ 判据:**这张表是宿主侧的名字,宿主改名必须同批改这里**;升级宿主后要**真机核一次工具面**
|
|
1287
|
+
* (会话里能不能看见 `schedule_*`),⛔ 不能只信单元测试——它测的是本表,本表错了它也绿。
|
|
1288
|
+
* ⚠️ 本清单**合并发射时不做探活**。⚠️ 现状缺口(v1.87.1 如实登记):宿主**没装**
|
|
1289
|
+
* `dsh-tool-schedule` 时,这些名字会把整次 restrict 拒掉,而退档只保留 ACC 自己的名字
|
|
1290
|
+
* ⇒ 这一格的屏蔽**不生效**(旧实现同样不生效,**未回归**;但"顺带修好了"这句是假的,已删)。
|
|
1291
|
+
*/
|
|
1292
|
+
const HOST_SCHEDULE_TOOL_NAMES = [
|
|
1293
|
+
"schedule_create",
|
|
1294
|
+
"schedule_list",
|
|
1295
|
+
"schedule_view",
|
|
1296
|
+
"schedule_edit"
|
|
1297
|
+
];
|
|
1298
|
+
/** 会话销毁清理(lifecycle 调用)。
|
|
1299
|
+
* ⚠️ 方案 C 后撤销只在 `forgetToolVisibility` 做一次;本函数保留语义占位。
|
|
1300
|
+
* 留着它的价值:lifecycle 的调用点表达"这条会话有轨迹约束可见性状态要清",
|
|
1301
|
+
* 删掉调用点会让那件事**从代码里消失**(将来有人重加机制时找不到插点)。 */
|
|
1302
|
+
function forgetTrajectoryConstraintToolVisibility(_sessionId) {}
|
|
1303
|
+
/** 会话销毁清理(lifecycle 调用)——同上,语义占位。 */
|
|
1304
|
+
function forgetExclusiveToolsVisibility(_sessionId) {}
|
|
1305
|
+
/**
|
|
1306
|
+
* 非 CCC 会话的工具隐藏状态(sessionId → restrict disposer)。
|
|
1307
|
+
*
|
|
1308
|
+
* 🔴 **为什么需要它(缺陷根因)**:工具是 `apply()` 里 `ctx.tools.register(...)` 注册到**宿主级**的
|
|
1309
|
+
* ⇒ 它们出现在**每一个**会话的工具清单里,**与会话 cwd 无关**。其余各缝(身份注入 / guards /
|
|
1310
|
+
* keeper / output-guard / bootstrap)都已有 `if (!root) return` 这道门,
|
|
1311
|
+
* **唯独"工具可见性"这一层没有** ⇒ 在非 CCC 目录开会话时,模型仍看得见这 14 个工具,
|
|
1312
|
+
* 于是会去调 —— 调了才抛 `No CCC found`。**那是运行时报错,不是事先不可见**。
|
|
1313
|
+
*
|
|
1314
|
+
* 判据(owner 原话:「宁静号所有功能在非宁静号目录不生效」):
|
|
1315
|
+
* - **在 CCC 内** → 解除隐藏(本机制**一次 restrict 都不发**,既有行为零改变)
|
|
1316
|
+
* - **不在 CCC 内** → `restrict({ deny: [...REGISTERED_TOOLS] })` ⇒ 从模型工具清单移除
|
|
1317
|
+
*
|
|
1318
|
+
* ⚠️ **与 `syncExclusiveToolsVisibility` 的分工**:那个管"CCC 内哪个工具可见"(按 CCC 配置判);
|
|
1319
|
+
* 本函数管"**这个会话配不配看到任何 ACC 工具**"(按"在不在 CCC 内"判)。二者独立、可叠加。
|
|
1320
|
+
*
|
|
1321
|
+
* ⚠️ **必须逐个名字显式列出**:宿主的 `restrict` 对**未注册的工具名**会让**整次调用失败**
|
|
1322
|
+
* (`dsh-tools` 契约逐字:"Empty filters, unknown names … fail")⇒ 不能写通配。
|
|
1323
|
+
* 但 `REGISTERED_TOOLS` 是"插件**具备**的工具面",其中 **`diagram` 是按开关注册的**
|
|
1324
|
+
* (缺省关 ⇒ 缺省**并不在册**)⇒ 直接拿全表去 deny **可能整次失败**,那样就会
|
|
1325
|
+
* **静默退回"工具照样可见"**=缺陷没修好。故此处走**两档尝试**(见 `hideAllFor`)。
|
|
1326
|
+
*/
|
|
1327
|
+
const nonCccRestrictions = /* @__PURE__ */ new Map();
|
|
1328
|
+
/** 会话销毁清理(lifecycle 调用;防 per-会话 Map 无界增长) */
|
|
1329
|
+
function forgetNonCccToolVisibility(sessionId) {
|
|
1330
|
+
const existing = nonCccRestrictions.get(sessionId);
|
|
1331
|
+
if (!existing) return;
|
|
1332
|
+
try {
|
|
1333
|
+
existing();
|
|
1334
|
+
} catch {}
|
|
1335
|
+
nonCccRestrictions.delete(sessionId);
|
|
1336
|
+
}
|
|
1337
|
+
/**
|
|
1338
|
+
* 从 exec 参数中提取常见路径字段(write/edit 工具);宽松读取。
|
|
1339
|
+
* container_fs 复合工具:path(单路径)/ paths(数组)/ src / dst——取第一个命中(越界检查
|
|
1340
|
+
* 逐路径由 decideGuard 单 pathArg 覆盖;多路径字段取首个,避免漏检主体路径)。
|
|
1341
|
+
*/
|
|
1342
|
+
function extractPathArg(exec) {
|
|
1343
|
+
const args = exec.arguments;
|
|
1344
|
+
if (args === null || typeof args !== "object") return void 0;
|
|
1345
|
+
const a = args;
|
|
1346
|
+
for (const key of [
|
|
1347
|
+
"path",
|
|
1348
|
+
"file_path",
|
|
1349
|
+
"target",
|
|
1350
|
+
"src",
|
|
1351
|
+
"dst"
|
|
1352
|
+
]) {
|
|
1353
|
+
const v = a[key];
|
|
1354
|
+
if (typeof v === "string") return v;
|
|
1355
|
+
}
|
|
1356
|
+
const paths = a["paths"];
|
|
1357
|
+
if (Array.isArray(paths) && paths.length > 0 && typeof paths[0] === "string") return paths[0];
|
|
1358
|
+
}
|
|
1359
|
+
/** 从 exec 参数提取 container_fs 子命令 action;无则 undefined */
|
|
1360
|
+
function extractAction(exec) {
|
|
1361
|
+
const args = exec.arguments;
|
|
1362
|
+
if (args === null || typeof args !== "object") return void 0;
|
|
1363
|
+
const a = args;
|
|
1364
|
+
return typeof a.action === "string" ? a.action : void 0;
|
|
1365
|
+
}
|
|
1366
|
+
/**
|
|
1367
|
+
* 注册守卫:tools/pre-execute 瀑布 + ctx.tools.guard 终局。
|
|
1368
|
+
* 两者都从 CCC 根实时读取配置(无状态、无缓存)。
|
|
1369
|
+
*/
|
|
1370
|
+
function registerGuards(ctx, opts = {}) {
|
|
1371
|
+
const configPaths = opts.configPaths;
|
|
1372
|
+
const evaluate = (exec) => {
|
|
1373
|
+
const cwd = resolveAgentCwd(exec);
|
|
1374
|
+
const root = cccRootForCwd(cwd);
|
|
1375
|
+
if (!root) return { kind: "allow" };
|
|
1376
|
+
const safeModeOn = isSafeModeOn(root);
|
|
1377
|
+
const blacklist = readBlacklist(root, configPaths);
|
|
1378
|
+
const pathArg = extractPathArg(exec);
|
|
1379
|
+
const action = extractAction(exec);
|
|
1380
|
+
const sessionId = exec?.agent?.session?.id;
|
|
1381
|
+
const trajectoryConstraint = trajectoryConstraintForSession(root, sessionId);
|
|
1382
|
+
return decideGuard({
|
|
1383
|
+
root,
|
|
1384
|
+
toolName: exec.name,
|
|
1385
|
+
safeModeOn,
|
|
1386
|
+
blacklist,
|
|
1387
|
+
pathArg,
|
|
1388
|
+
action,
|
|
1389
|
+
trajectoryConstraint
|
|
1390
|
+
});
|
|
1391
|
+
};
|
|
1392
|
+
ctx.on("tools/pre-execute", async (exec, next) => {
|
|
1393
|
+
const d = evaluate(exec);
|
|
1394
|
+
if (d.deny) return {
|
|
1395
|
+
kind: "deny",
|
|
1396
|
+
reason: d.deny
|
|
1397
|
+
};
|
|
1398
|
+
return next();
|
|
1399
|
+
});
|
|
1400
|
+
ctx.tools.guard((exec) => {
|
|
1401
|
+
return evaluate(exec).deny;
|
|
1402
|
+
});
|
|
1403
|
+
}
|
|
1404
|
+
//#endregion
|
|
1405
|
+
export { findPackageRoot as C, ACC_VERSION as S, constraintCognitiveTrajectory as _, forgetTrajectoryConstraintToolVisibility as a, profileMsmWhitelist as b, shellToolNameFor as c, imChannelIds as d, isImWiredTrajectory as f, buildTrajectoryBasePrompt as g, TRAJECTORY_CONSTRAINT_HINT as h, forgetNonCccToolVisibility as i, syncToolVisibility as l, runImBridge as m, forgetHostScheduleToolHiding as n, getRestrictDiagnostics as o, registerImChannel as p, forgetImBridgeVisibility as r, registerGuards as s, forgetExclusiveToolsVisibility as t, forgetToolVisibility as u, constraintSystemPromptSource as v, resolveConstraintSystemPrompt as x, createProfilePromptReader as y };
|