@shgroup/dsh-serenity-hooks 1.137.18 → 1.138.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/dsh.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "dsh-serenity-hooks",
3
- "version": "1.137.18",
3
+ "version": "1.138.0",
4
4
  "main": "lib/index.js",
5
5
  "description": "宁静号 ACC harness(Native Cordis 插件):给 DSH 装一个「AI 工作区」——13 个工具(container_fs/cognitive_trajectory/dashboard/container_git/msm/praxis/ontology/serenity-skill-creator/localstore/container_admin/browser_slot;另两个 im-bridge/diagram 按条件出现)+ 机械约束(安全模式/工作区围墙/密钥守卫)+ 认知轨迹日志与原地重建 + 网页登录入口/IM 桥/认知轨迹唤醒注册表 + 浏览器槽位管理(≤20 个独立 profile 的 Chrome 槽位,带占用归属与异常时向所属会话反向注入提醒)。轨迹声明 = 轨迹目录下的 trajectory.json(约束面 + 旧标识 uid + CRO 机器绑定 cro.host;旧名 trajectory-constraint.json / skiff.json 仍在读取族里);轨迹提示词 = 轨迹目录下的 PROMPT.md(一条轨迹「是谁、按什么章程工作」,所有轨迹通用,追加在容器层与质量层之后,不替换它们)。适配 DSH 0.1.7-rc.1 / 0.2.0-rc.1 / 0.2.1-rc.1(三档,deepseek-ai/deepseek-harness)。",
6
6
  "engines": {
@@ -51,6 +51,25 @@ export interface Ledger {
51
51
  failures: number;
52
52
  nextAt: number;
53
53
  }>;
54
+ /**
55
+ * 🔴 **最近被强关的槽位**(最多 20 条,新在前)。
56
+ *
57
+ * 为什么必须有:强关会**删掉租约** ⇒ 事后"这槽刚才为什么被关"在台账上**无从回答**。
58
+ * 而强关会**中断别人正在做的事** ⇒ 那种事必须可追溯,否则下一个人只看到"槽位突然空了"。
59
+ */
60
+ recentKills: RecentKill[];
61
+ }
62
+ /** 一次强关的留痕 */
63
+ export interface RecentKill {
64
+ slot: number;
65
+ trajectory: string;
66
+ /** 强关时的闲置分钟数 */
67
+ idleMin: number;
68
+ /** 强关前已提醒过几次(证明"先提醒后强关"确实发生过) */
69
+ nudges: number;
70
+ /** 杀进程是否成功(owner 裁「不会 kill 不掉」⇒ 正常应为 true;若不是,这就是那条异常的证据) */
71
+ ok: boolean;
72
+ at: number;
54
73
  }
55
74
  /** 读台账。文件缺失/损坏 ⇒ 返回空台账(⛔ 不抛错:一次坏文件不该炸掉所有槽位操作) */
56
75
  export declare function readLedger(): Ledger;
@@ -31,7 +31,7 @@ import { type HitVerdict } from './hit-test.js';
31
31
  * 裸端口会让「这是谁的浏览器」变成一个隐含状态。
32
32
  * 先例 `browser` MSM 收 `--port=` —— 那正是它和槽位体系断开的那个口子。
33
33
  */
34
- export declare const SLOT_ACTIONS: readonly ["acquire", "release", "list", "status", "reap", "doctor", "targets", "open", "goto", "eval", "text", "html", "shot", "reload", "close", "click", "ax", "press", "type", "fill", "scroll", "wait", "drag", "upload", "downloads", "dialog", "ext-list", "ext"];
34
+ export declare const SLOT_ACTIONS: readonly ["acquire", "release", "list", "status", "reap", "hold", "doctor", "targets", "open", "goto", "eval", "text", "html", "shot", "reload", "close", "click", "ax", "press", "type", "fill", "scroll", "wait", "drag", "upload", "downloads", "dialog", "ext-list", "ext"];
35
35
  export type SlotAction = (typeof SLOT_ACTIONS)[number];
36
36
  /** 哪些动作需要 `--slot`(页面层 + ext 需要,槽位层不需要) */
37
37
  export declare const ACTIONS_NEED_SLOT: ReadonlySet<SlotAction>;
@@ -119,10 +119,61 @@ export interface NudgeOutcome {
119
119
  delivered: boolean;
120
120
  detail: string;
121
121
  }
122
+ /** 强关结果(与 NudgeOutcome 分开:一件事是"提醒了",另一件是"关掉了",⛔ 不可混) */
123
+ export interface ForceReapOutcome {
124
+ slot: number;
125
+ trajectory: string;
126
+ idleMin: number;
127
+ killed: boolean;
128
+ killDetail: string;
129
+ delivered: boolean;
130
+ deliverDetail: string;
131
+ }
122
132
  export type Injector = (root: string, target: string, message: string) => Promise<{
123
133
  ok: boolean;
124
134
  detail: string;
125
135
  }>;
136
+ /**
137
+ * 🔴 **强关扫描(owner 2026-11-24 令:「浏览器一直不关的现象严重」)**。
138
+ *
139
+ * 与 {@link nudgeStaleSlots} **分两个函数**,⛔ 不合并:
140
+ * 前者是"告诉它还活着",后者是"真的关掉它" —— 两件事的失败面与后果完全不同,
141
+ * 合进一个函数会让"提醒了没关"与"该关没关"在回执上同形。
142
+ *
143
+ * ## 顺序(由调用方保证,⛔ 不可换)
144
+ *
145
+ * 调用方先跑 `nudgeStaleSlots`(提醒),**再**跑本函数(强关)。
146
+ * 而本函数内部还有第二道闸:`lease.nudges >= 1`(见 shouldForceReap ③)
147
+ * ⇒ 即使调用顺序被写错,**也不会出现"没提醒过就杀掉"**。
148
+ *
149
+ * ## 一辆车能做两件事,但账要分开记
150
+ *
151
+ * 强关后:① 杀进程 + 删租约 + 清 identity(复用 `reapSlot`,它是既有生产路径);
152
+ * ② 向占用者注入**告知**(不是提醒 —— 提醒是"请你做",告知是"我已经做了")。
153
+ */
154
+ export declare function forceReapIdleSlots(root: string, inject: Injector, policy?: SlotPolicy): Promise<{
155
+ reaped: ForceReapOutcome[];
156
+ scanned: number;
157
+ }>;
158
+ /**
159
+ * 🔴 **保活**(owner 2026-11-24 裁:同意)—— 长下载/慢查询的唯一逃生阀。
160
+ *
161
+ * ## 它为什么必须存在
162
+ *
163
+ * 强关的判据是「30 分钟静默 ⇒ 你肯定不在用它」。而**长下载恰好合法地静默**。
164
+ * 没有这条通道,强关就是粗糙的 —— 会把正在下载 2GB 镜像的人一脚踢掉。
165
+ *
166
+ * ## 🔴 它**不推进 `lastActionAt`**
167
+ *
168
+ * 那是关键设计:`lastActionAt` 的语义是「我刚做了一个动作」(**事实**),
169
+ * 而 `holdUntil` 是「我预知接下来不动,别判我闲置」(**声明**)。
170
+ * 若用推进 `lastActionAt` 来实现保活,那么「真的在干活」与「申请了豁免」在读数上**同形** ——
171
+ * `status` 的读者(和看守自己)就会据此做错动作。⇒ 两个字段,⛔ 不合流。
172
+ */
173
+ export declare function holdSlot(root: string, sessionId: string, target: number, minutes: number, reason: string): {
174
+ ok: boolean;
175
+ detail: string;
176
+ };
126
177
  export declare function nudgeStaleSlots(root: string, inject: Injector, policy?: SlotPolicy): Promise<{
127
178
  nudged: NudgeOutcome[];
128
179
  scanned: number;
@@ -73,6 +73,17 @@ export interface SlotLease {
73
73
  lastNudgeAt: number;
74
74
  /** 该槽位对应的 chrome 主进程 pid;0 = 尚未启动 */
75
75
  pid: number;
76
+ /**
77
+ * 保活截止时刻(ms);0 = 未申请保活(owner 2026-11-24 裁:同意 `hold`)。
78
+ *
79
+ * 🔴 **它与 `lastActionAt` 是两件事,⛔ 不许合流**:
80
+ * `lastActionAt` = 「我刚做了一个动作」(事实);
81
+ * `holdUntil` = 「我预知接下来一段时间不会有动作,别判我闲置」(声明)。
82
+ * 若用推进 `lastActionAt` 来实现保活,那么"真的在干活"与"申请了豁免"在读数上**同形** ——
83
+ * 读它的人(包括看守自己、以及 `status` 的读者)会据此做错动作。
84
+ * 本仓这条判据立过多次:一个读数在两种相反情况下取同一个值,报它等于报假。
85
+ */
86
+ holdUntil: number;
76
87
  }
77
88
  /** 槽位对外状态(四个,互相穷尽) */
78
89
  export type SlotState =
@@ -98,8 +109,29 @@ export interface SlotPolicy {
98
109
  nudgeCooldownMs: number;
99
110
  /** 提醒几次后升级为"建议直接回收"(默认 2) */
100
111
  nudgeEscalateAt: number;
112
+ /**
113
+ * 🔴 **强制回收阈值**(owner 2026-11-24 令:「浏览器一直不关的现象严重」)。
114
+ *
115
+ * 闲置超过它 ⇒ **真的关掉**(destroySlot + 删租约),并向占用者注入一条告知。
116
+ * `0` = **关闭强关**(留一个彻底不杀的开关)。
117
+ *
118
+ * ## 为什么这条可以破「提醒不代它释放」那条老判据
119
+ *
120
+ * 老判据防的是「代为释放可能中断一个正在取的证」。而强关的前提是
121
+ * **30 分钟一次操作都没有** —— `lastActionAt` 只由**成功的操作**推进(见 touchSlot),
122
+ * 所以一个正在取证的浏览器**不可能**静默 30 分钟。
123
+ * ⇒ 判据从「我不知道它还要不要」变成「**30 分钟的静默本身就是证据**」。
124
+ *
125
+ * ⚠️ 真实例外是长下载/慢查询 ⇒ 由 `hold`(见 SlotLease.holdUntil)提供逃生阀。
126
+ */
127
+ idleKillMs: number;
101
128
  }
102
129
  export declare const DEFAULT_POLICY: SlotPolicy;
130
+ /**
131
+ * `hold` 单次可申请的上限(分钟)。
132
+ * 理由:⛔ 不让 `hold` 变成"永久豁免" —— 那等于把强关架空,而强关正是 owner 要的东西。
133
+ */
134
+ export declare const HOLD_MAX_MINUTES = 240;
103
135
  /** 从环境变量读策略(缺省回落 DEFAULT_POLICY;非法值静默回落,⛔ 不抛错) */
104
136
  export declare function policyFromEnv(env?: Record<string, string | undefined>): SlotPolicy;
105
137
  /** 进程读数(由调用方采集;纯函数只消费,不采集) */
@@ -143,6 +175,39 @@ export declare function shouldNudge(lease: SlotLease, state: SlotState, now: num
143
175
  * 而它真正该做的是 `release`。⇒ 每条文本都把**具体动作**写明。
144
176
  */
145
177
  export declare function nudgeText(slot: number, state: SlotState, reasons: string[], policy: SlotPolicy): string;
178
+ /**
179
+ * 🔴 **强关判定(纯函数,owner 2026-11-24 令)**。
180
+ *
181
+ * 「浏览器一直不关的现象严重」⇒ 把"劝"改成"劝不动就关"。
182
+ *
183
+ * ## 三条**必须同时成立**(⛔ 少一条就退化成误杀)
184
+ *
185
+ * | # | 条件 | 为什么 |
186
+ * |---|---|---|
187
+ * | ① | 闲置 ≥ `idleKillMs`(默认 30 min) | owner 裁的阈值 |
188
+ * | ② | 进程**仍活着** | 进程都没了走 `orphaned` 那条既有路径,⛔ 不走强关 |
189
+ * | ③ | `nudges ≥ 1`(**至少提醒过一次**) | 🔴 **公平**:不能因为刚拍到它闲置就直接杀 —— 它可能一直在跑长任务、根本没看到提醒。**先提醒、后强关,顺序不可换** |
190
+ *
191
+ * 另外两条闸门:
192
+ * - `idleKillMs === 0` ⇒ **永不强关**(owner 可整体关闭);
193
+ * - `holdUntil > now` ⇒ **不动**(保活期内)。
194
+ *
195
+ * @returns `null` = 不该强关;否则返回强关原因(用于注入文案与台账留痕)
196
+ */
197
+ export declare function shouldForceReap(lease: SlotLease | null, proc: SlotProcReading | null, now: number, policy?: SlotPolicy): {
198
+ idleMin: number;
199
+ nudges: number;
200
+ } | null;
201
+ /**
202
+ * 强关后的**告知**文本(注入给占用者)。
203
+ *
204
+ * 🔴 判据:**必须三件事都给** ——
205
+ * ① 发生了什么(被强制回收了,多少分钟没动作);
206
+ * ② 损失了什么/没损失什么(浏览器关了;**profile 保留、登录态还在**);
207
+ * ③ 下次怎么避免(`hold` 保活),以及怎么继续(重新 acquire)。
208
+ * ⛔ 不写"你的槽位异常了" —— 那是无法行动的话。
209
+ */
210
+ export declare function forceReapText(slot: number, idleMin: number, nudges: number, policy?: SlotPolicy): string;
146
211
  /**
147
212
  * 选一个空槽。⛔ 不做"最久未用优先"这类聪明事 —— 20 个槽位装得下,选择规则越简单越可预测。
148
213
  * 返回 0 = 满。
package/lib/index.js CHANGED
@@ -18195,7 +18195,8 @@ const DEFAULT_POLICY = {
18195
18195
  cpuPct: 80,
18196
18196
  rssMb: 2500,
18197
18197
  nudgeCooldownMs: 12e5,
18198
- nudgeEscalateAt: 2
18198
+ nudgeEscalateAt: 2,
18199
+ idleKillMs: 18e5
18199
18200
  };
18200
18201
  /** 从环境变量读策略(缺省回落 DEFAULT_POLICY;非法值静默回落,⛔ 不抛错) */
18201
18202
  function policyFromEnv(env = process.env) {
@@ -18211,7 +18212,8 @@ function policyFromEnv(env = process.env) {
18211
18212
  cpuPct: num("SERENITY_SLOT_CPU_PCT", DEFAULT_POLICY.cpuPct),
18212
18213
  rssMb: num("SERENITY_SLOT_RSS_MB", DEFAULT_POLICY.rssMb),
18213
18214
  nudgeCooldownMs: Math.max(num("SERENITY_SLOT_NUDGE_COOLDOWN_MS", DEFAULT_POLICY.nudgeCooldownMs), 6e4),
18214
- nudgeEscalateAt: num("SERENITY_SLOT_NUDGE_ESCALATE_AT", DEFAULT_POLICY.nudgeEscalateAt)
18215
+ nudgeEscalateAt: num("SERENITY_SLOT_NUDGE_ESCALATE_AT", DEFAULT_POLICY.nudgeEscalateAt),
18216
+ idleKillMs: env["SERENITY_SLOT_IDLE_KILL_MS"] === "0" ? 0 : num("SERENITY_SLOT_IDLE_KILL_MS", DEFAULT_POLICY.idleKillMs)
18215
18217
  };
18216
18218
  }
18217
18219
  /**
@@ -18234,7 +18236,7 @@ function deriveSlotState(lease, proc, now, policy = DEFAULT_POLICY) {
18234
18236
  reasons: ["进程已退出"]
18235
18237
  };
18236
18238
  const idle = now - lease.lastActionAt;
18237
- if (idle > policy.idleMs) reasons.push(`已 ${Math.round(idle / 6e4)} 分钟无动作`);
18239
+ if (!(lease.holdUntil > now) && idle > policy.idleMs) reasons.push(`已 ${Math.round(idle / 6e4)} 分钟无动作`);
18238
18240
  if (now - lease.leasedAt > policy.leaseMaxMs) reasons.push(`占用已超 ${Math.round(policy.leaseMaxMs / 6e4)} 分钟上限`);
18239
18241
  if (proc && proc.cpuPct >= policy.cpuPct) reasons.push(`CPU ${proc.cpuPct.toFixed(0)}% 超阈值`);
18240
18242
  if (proc && proc.rssMb >= policy.rssMb) reasons.push(`内存 ${proc.rssMb.toFixed(0)}MB 超阈值`);
@@ -18275,6 +18277,50 @@ function nudgeText(slot, state, reasons, policy) {
18275
18277
  return `${head}\n 现象:${reasons.length > 0 ? reasons.join(";") : "状态异常"}\n${` 判据(你越了哪条线):闲置 ${Math.round(policy.idleMs / 6e4)} 分钟 / CPU ${policy.cpuPct}% / 内存 ${policy.rssMb}MB / 占用上限 ${Math.round(policy.leaseMaxMs / 6e4)} 分钟。`}\n 为什么找你:这个槽位是**你**租的,只有你知道它还有没有用。\n ⇒ 还在用:把闲置阈值以下的动作做一次,或先 release 再重新租(会刷新计时)。\n ⇒ 不用了:若你已不再需要它,release 即可 —— 这是最省事的一步。\n${rel}`;
18276
18278
  }
18277
18279
  /**
18280
+ * 🔴 **强关判定(纯函数,owner 2026-11-24 令)**。
18281
+ *
18282
+ * 「浏览器一直不关的现象严重」⇒ 把"劝"改成"劝不动就关"。
18283
+ *
18284
+ * ## 三条**必须同时成立**(⛔ 少一条就退化成误杀)
18285
+ *
18286
+ * | # | 条件 | 为什么 |
18287
+ * |---|---|---|
18288
+ * | ① | 闲置 ≥ `idleKillMs`(默认 30 min) | owner 裁的阈值 |
18289
+ * | ② | 进程**仍活着** | 进程都没了走 `orphaned` 那条既有路径,⛔ 不走强关 |
18290
+ * | ③ | `nudges ≥ 1`(**至少提醒过一次**) | 🔴 **公平**:不能因为刚拍到它闲置就直接杀 —— 它可能一直在跑长任务、根本没看到提醒。**先提醒、后强关,顺序不可换** |
18291
+ *
18292
+ * 另外两条闸门:
18293
+ * - `idleKillMs === 0` ⇒ **永不强关**(owner 可整体关闭);
18294
+ * - `holdUntil > now` ⇒ **不动**(保活期内)。
18295
+ *
18296
+ * @returns `null` = 不该强关;否则返回强关原因(用于注入文案与台账留痕)
18297
+ */
18298
+ function shouldForceReap(lease, proc, now, policy = DEFAULT_POLICY) {
18299
+ if (!lease) return null;
18300
+ if (policy.idleKillMs <= 0) return null;
18301
+ if (lease.holdUntil > now) return null;
18302
+ if (proc && !proc.alive) return null;
18303
+ if (lease.nudges < 1) return null;
18304
+ const idle = now - lease.lastActionAt;
18305
+ if (idle < policy.idleKillMs) return null;
18306
+ return {
18307
+ idleMin: Math.round(idle / 6e4),
18308
+ nudges: lease.nudges
18309
+ };
18310
+ }
18311
+ /**
18312
+ * 强关后的**告知**文本(注入给占用者)。
18313
+ *
18314
+ * 🔴 判据:**必须三件事都给** ——
18315
+ * ① 发生了什么(被强制回收了,多少分钟没动作);
18316
+ * ② 损失了什么/没损失什么(浏览器关了;**profile 保留、登录态还在**);
18317
+ * ③ 下次怎么避免(`hold` 保活),以及怎么继续(重新 acquire)。
18318
+ * ⛔ 不写"你的槽位异常了" —— 那是无法行动的话。
18319
+ */
18320
+ function forceReapText(slot, idleMin, nudges, policy = DEFAULT_POLICY) {
18321
+ return `[浏览器槽位看守] 槽位 ${slotLabel(slot)} 已被**强制回收**(闲置 ${idleMin} 分钟,之前已提醒 ${nudges} 次)。\n · 你的浏览器已关闭。**profile 目录保留** ⇒ 登录态还在,重新 acquire 不需要重登。\n · 若这次是被误杀(例如在做长下载、等一个慢查询),下次请先保活:\n \`browser_slot hold --slot ${slotLabel(slot)} --reason "<在做什么>" --holdFor <分钟>\`\n · 要接着用:重新 \`acquire\` 即可。\n 为什么是我:闲置阈值 ${Math.round(policy.idleKillMs / 6e4)} 分钟 —— 一个真在干活的浏览器不会静默这么久。`;
18322
+ }
18323
+ /**
18278
18324
  * 选一个空槽。⛔ 不做"最久未用优先"这类聪明事 —— 20 个槽位装得下,选择规则越简单越可预测。
18279
18325
  * 返回 0 = 满。
18280
18326
  */
@@ -18412,10 +18458,11 @@ const LOCK_STALE_MS = 1e4;
18412
18458
  /** 持锁自旋:最多等这么久(超过即放弃并报错,⛔ 不无限等) */
18413
18459
  const LOCK_WAIT_MS = 8e3;
18414
18460
  const EMPTY = {
18415
- version: 2,
18461
+ version: 3,
18416
18462
  leases: {},
18417
18463
  updatedAt: 0,
18418
- backoff: {}
18464
+ backoff: {},
18465
+ recentKills: []
18419
18466
  };
18420
18467
  /** 读台账。文件缺失/损坏 ⇒ 返回空台账(⛔ 不抛错:一次坏文件不该炸掉所有槽位操作) */
18421
18468
  function readLedger() {
@@ -18441,7 +18488,8 @@ function readLedger() {
18441
18488
  lastActionAt: Number(l.lastActionAt) || Number(l.leasedAt) || 0,
18442
18489
  nudges: Number(l.nudges) || 0,
18443
18490
  lastNudgeAt: Number(l.lastNudgeAt) || 0,
18444
- pid: Number(l.pid) || 0
18491
+ pid: Number(l.pid) || 0,
18492
+ holdUntil: Number(l.holdUntil) || 0
18445
18493
  };
18446
18494
  }
18447
18495
  const backoff = {};
@@ -18455,16 +18503,31 @@ function readLedger() {
18455
18503
  nextAt: Number(b?.nextAt) || 0
18456
18504
  };
18457
18505
  }
18506
+ const recentKills = [];
18507
+ if (Array.isArray(raw.recentKills)) for (const item of raw.recentKills) {
18508
+ const n = Number(item?.slot);
18509
+ if (!Number.isInteger(n) || n < 1 || n > 20) continue;
18510
+ recentKills.push({
18511
+ slot: n,
18512
+ trajectory: typeof item?.trajectory === "string" ? item.trajectory : "",
18513
+ idleMin: Number(item?.idleMin) || 0,
18514
+ nudges: Number(item?.nudges) || 0,
18515
+ ok: item?.ok === true,
18516
+ at: Number(item?.at) || 0
18517
+ });
18518
+ }
18458
18519
  return {
18459
- version: Number(raw.version) || 2,
18520
+ version: Number(raw.version) || 3,
18460
18521
  leases,
18461
18522
  updatedAt: Number(raw.updatedAt) || 0,
18462
- backoff
18523
+ backoff,
18524
+ recentKills: recentKills.slice(0, 20)
18463
18525
  };
18464
18526
  } catch {
18465
18527
  return {
18466
18528
  ...EMPTY,
18467
- leases: {}
18529
+ leases: {},
18530
+ recentKills: []
18468
18531
  };
18469
18532
  }
18470
18533
  }
@@ -21464,6 +21527,7 @@ const SLOT_ACTIONS = [
21464
21527
  "list",
21465
21528
  "status",
21466
21529
  "reap",
21530
+ "hold",
21467
21531
  "doctor",
21468
21532
  "targets",
21469
21533
  "open",
@@ -21585,7 +21649,8 @@ async function acquireSlot(input) {
21585
21649
  lastActionAt: now,
21586
21650
  nudges: 0,
21587
21651
  lastNudgeAt: 0,
21588
- pid: 0
21652
+ pid: 0,
21653
+ holdUntil: 0
21589
21654
  };
21590
21655
  return {
21591
21656
  ledger: lg,
@@ -21819,6 +21884,138 @@ function reapSlot(root, target, reason) {
21819
21884
  detail: `已回收槽位 ${slotLabel(target)}(原因:${reason})。${destroyed.detail}`
21820
21885
  };
21821
21886
  }
21887
+ /**
21888
+ * 🔴 **强关扫描(owner 2026-11-24 令:「浏览器一直不关的现象严重」)**。
21889
+ *
21890
+ * 与 {@link nudgeStaleSlots} **分两个函数**,⛔ 不合并:
21891
+ * 前者是"告诉它还活着",后者是"真的关掉它" —— 两件事的失败面与后果完全不同,
21892
+ * 合进一个函数会让"提醒了没关"与"该关没关"在回执上同形。
21893
+ *
21894
+ * ## 顺序(由调用方保证,⛔ 不可换)
21895
+ *
21896
+ * 调用方先跑 `nudgeStaleSlots`(提醒),**再**跑本函数(强关)。
21897
+ * 而本函数内部还有第二道闸:`lease.nudges >= 1`(见 shouldForceReap ③)
21898
+ * ⇒ 即使调用顺序被写错,**也不会出现"没提醒过就杀掉"**。
21899
+ *
21900
+ * ## 一辆车能做两件事,但账要分开记
21901
+ *
21902
+ * 强关后:① 杀进程 + 删租约 + 清 identity(复用 `reapSlot`,它是既有生产路径);
21903
+ * ② 向占用者注入**告知**(不是提醒 —— 提醒是"请你做",告知是"我已经做了")。
21904
+ */
21905
+ async function forceReapIdleSlots(root, inject, policy = policyFromEnv()) {
21906
+ const ledger = readLedger();
21907
+ const now = Date.now();
21908
+ const out = [];
21909
+ let scanned = 0;
21910
+ for (const lease of listLeases(ledger)) {
21911
+ scanned += 1;
21912
+ const verdict = shouldForceReap(lease, readProcFor(root, lease.slot, now, lease.pid), now, policy);
21913
+ if (!verdict) continue;
21914
+ const res = reapSlot(root, lease.slot, `闲置 ${verdict.idleMin} 分钟(已提醒 ${verdict.nudges} 次)`);
21915
+ recordRecentKill(lease.slot, lease.trajectory, verdict.idleMin, verdict.nudges, res.ok);
21916
+ const target = lease.trajectory || lease.sessionId;
21917
+ let delivered = false;
21918
+ let deliverDetail = "";
21919
+ if (target) {
21920
+ const text = forceReapText(lease.slot, verdict.idleMin, verdict.nudges, policy);
21921
+ try {
21922
+ const r = await inject(root, target, text);
21923
+ delivered = r.ok;
21924
+ deliverDetail = r.detail;
21925
+ } catch (err) {
21926
+ deliverDetail = String(err?.message ?? err);
21927
+ }
21928
+ } else deliverDetail = "该槽位没有归属轨迹(sessionId/trajectory 皆空)⇒ 无法告知,已在台账留痕";
21929
+ out.push({
21930
+ slot: lease.slot,
21931
+ trajectory: lease.trajectory,
21932
+ idleMin: verdict.idleMin,
21933
+ killed: res.ok,
21934
+ killDetail: res.detail,
21935
+ delivered,
21936
+ deliverDetail
21937
+ });
21938
+ }
21939
+ return {
21940
+ reaped: out,
21941
+ scanned
21942
+ };
21943
+ }
21944
+ /**
21945
+ * 🔴 **保活**(owner 2026-11-24 裁:同意)—— 长下载/慢查询的唯一逃生阀。
21946
+ *
21947
+ * ## 它为什么必须存在
21948
+ *
21949
+ * 强关的判据是「30 分钟静默 ⇒ 你肯定不在用它」。而**长下载恰好合法地静默**。
21950
+ * 没有这条通道,强关就是粗糙的 —— 会把正在下载 2GB 镜像的人一脚踢掉。
21951
+ *
21952
+ * ## 🔴 它**不推进 `lastActionAt`**
21953
+ *
21954
+ * 那是关键设计:`lastActionAt` 的语义是「我刚做了一个动作」(**事实**),
21955
+ * 而 `holdUntil` 是「我预知接下来不动,别判我闲置」(**声明**)。
21956
+ * 若用推进 `lastActionAt` 来实现保活,那么「真的在干活」与「申请了豁免」在读数上**同形** ——
21957
+ * `status` 的读者(和看守自己)就会据此做错动作。⇒ 两个字段,⛔ 不合流。
21958
+ */
21959
+ function holdSlot(root, sessionId, target, minutes, reason) {
21960
+ if (!Number.isFinite(minutes) || minutes <= 0) return {
21961
+ ok: false,
21962
+ detail: `hold 需要正的分钟数(收到 ${minutes})`
21963
+ };
21964
+ if (minutes > 240) return {
21965
+ ok: false,
21966
+ detail: `hold 单次最多 240 分钟(收到 ${minutes})。\n ⛔ 不让它变成"永久豁免" —— 那等于把闲置强关架空。需要更久就到期前再续一次。`
21967
+ };
21968
+ const lease = readLedger().leases[String(target)];
21969
+ if (!lease) return {
21970
+ ok: false,
21971
+ detail: `槽位 ${slotLabel(target)} 无人占用(没有可保活的租约)。`
21972
+ };
21973
+ if (sessionId && lease.sessionId && lease.sessionId !== sessionId) return {
21974
+ ok: false,
21975
+ detail: `槽位 ${slotLabel(target)} 不属于你,⛔ 不能替别人保活。`
21976
+ };
21977
+ const until = Date.now() + minutes * 6e4;
21978
+ withLedger((lg) => {
21979
+ const cur = lg.leases[String(target)];
21980
+ if (cur) cur.holdUntil = until;
21981
+ return {
21982
+ ledger: lg,
21983
+ result: null
21984
+ };
21985
+ });
21986
+ return {
21987
+ ok: true,
21988
+ detail: `已保活槽位 ${slotLabel(target)} 至 ${new Date(until).toLocaleTimeString("zh-CN")}(${minutes} 分钟)。\n · 保活期内**不判闲置**,但仍判进程死活/CPU/内存。\n · 原因:${reason || "(未填)"}\n · 到期后若仍无动作,照常进入提醒→强关流程。`
21989
+ };
21990
+ }
21991
+ /**
21992
+ * 强关留痕(台账里的 `recentKills`,最多保留 20 条)。
21993
+ *
21994
+ * 🔴 **为什么必须有它**:强关删掉了租约 ⇒ 事后问"刚才那槽为什么被关"在台账上**无从回答**。
21995
+ * 而强关会**中断别人正在做的事**,那种事必须有可追溯的记录,否则下一个人只会看到"槽位突然空了"。
21996
+ */
21997
+ function recordRecentKill(slot, trajectory, idleMin, nudges, ok) {
21998
+ try {
21999
+ withLedger((lg) => {
22000
+ const list = Array.isArray(lg.recentKills) ? lg.recentKills : [];
22001
+ list.unshift({
22002
+ slot,
22003
+ trajectory,
22004
+ idleMin,
22005
+ nudges,
22006
+ ok,
22007
+ at: Date.now()
22008
+ });
22009
+ lg.recentKills = list.slice(0, 20);
22010
+ return {
22011
+ ledger: lg,
22012
+ result: null
22013
+ };
22014
+ });
22015
+ } catch (err) {
22016
+ console.warn(`[serenity-hooks] ⚠️ 强关留痕写入失败(槽位 ${slotLabel(slot)}):${String(err?.message ?? err)}`);
22017
+ }
22018
+ }
21822
22019
  async function nudgeStaleSlots(root, inject, policy = policyFromEnv()) {
21823
22020
  const ledger = readLedger();
21824
22021
  const now = Date.now();
@@ -22445,6 +22642,14 @@ async function run(ctx, root, sessionId, trajectory, action, args) {
22445
22642
  if (n === 0) return "⛔ 需要槽位号:reap 需要 --slot <b1..b20>";
22446
22643
  return reapSlot(root, n, typeof args.reason === "string" && args.reason ? args.reason : "manual reaping").detail;
22447
22644
  }
22645
+ case "hold": {
22646
+ const n = normalizeSlotId(String(args.slot ?? ""));
22647
+ if (n === 0) return "⛔ 需要槽位号:hold 需要 --slot <b1..b20>";
22648
+ const mins = num(args.holdFor);
22649
+ if (mins === void 0) return "⛔ 需要 --holdFor=<分钟>(保活多久)。例:--holdFor 60\n ⛔ 不接受\"永久保活\" —— 那会把闲置强关架空。";
22650
+ const r = holdSlot(root, sessionId, n, mins, typeof args.reason === "string" ? args.reason : "");
22651
+ return r.ok ? r.detail : `⛔ ${r.detail}`;
22652
+ }
22448
22653
  case "status": {
22449
22654
  const n = normalizeSlotId(String(args.slot ?? ""));
22450
22655
  const v = n > 0 ? slotStatus(root, n) : null;
@@ -22648,7 +22853,7 @@ async function run(ctx, root, sessionId, trajectory, action, args) {
22648
22853
  function createBrowserSlotTool(ctx) {
22649
22854
  return defineTool({
22650
22855
  name: "browser_slot",
22651
- description: "Browser slot manager (ACC-level, max 20 Chrome slots). Each slot = one isolated Chrome process with its own profile dir, fixed resolution, and a CDP port (9301+). Slots carry state: free / leased / stale (idle too long, CPU or memory over threshold, lease expired) / orphaned (process died). Actions: acquire (lease a slot; reuses your existing lease instead of leasing a second one) / release (REQUIRED when done — a background watchman nudges you if you forget) / list (all slots + occupancy) / status --slot <bN> / reap --slot <bN> (force-reclaim an abandoned slot, records a reason) / doctor (self-check, read-only). PAGE: targets / open / goto / eval / text / html / shot / reload / close / click (text or xy, real mouse events). HIGH-LEVEL (v1.130.0): ax (accessibility-tree snapshot -> stable `ref` like e12345; the only honest answer to \"is this control clickable\") / press (semantic keys & chords: Enter, Escape, Control+A; non-ASCII text must use `type`) / type (browser text input at the focused element) / fill --ref --value (native setter + input/change so React/Vue actually see it; receipt reports the READ-BACK value) / scroll (real wheel events, so lazy-loading and virtual lists fire) / wait --for <selector:|text:|url:|gone:|js:> (in-page polling; timeout says WHAT it waited for and what it last read) / drag --from --to (multi-step mouseMoved; one-jump drags are ignored by sortablejs & friends) / upload --ref --file (paths must stay inside the CCC root) / downloads (pins the capture dir to _tmp/browser-downloads/<slot>) / dialog (default DISMISS — OK often means delete/pay/publish). 🔴 Lease before you drive a browser for evidence, and ALWAYS release when finished — an unreleased slot keeps a Chrome process alive and burns power.",
22856
+ description: "Browser slot manager (ACC-level, max 20 Chrome slots). Each slot = one isolated Chrome process with its own profile dir, fixed resolution, and a CDP port (9301+). Slots carry state: free / leased / stale (idle too long, CPU or memory over threshold, lease expired) / orphaned (process died). Actions: acquire (lease a slot; reuses your existing lease instead of leasing a second one) / release (REQUIRED when done — a background watchman nudges you if you forget, and **force-reclaims after ~30 min of silence**) / list (all slots + occupancy) / status --slot <bN> / hold --slot <bN> --holdFor <minutes> [--reason] (keep-alive: the idle reclaim skips a held slot; use it before long downloads or slow queries — no permanent hold) / reap --slot <bN> (force-reclaim an abandoned slot, records a reason) / doctor (self-check, read-only). PAGE: targets / open / goto / eval / text / html / shot / reload / close / click (text or xy, real mouse events). HIGH-LEVEL (v1.130.0): ax (accessibility-tree snapshot -> stable `ref` like e12345; the only honest answer to \"is this control clickable\") / press (semantic keys & chords: Enter, Escape, Control+A; non-ASCII text must use `type`) / type (browser text input at the focused element) / fill --ref --value (native setter + input/change so React/Vue actually see it; receipt reports the READ-BACK value) / scroll (real wheel events, so lazy-loading and virtual lists fire) / wait --for <selector:|text:|url:|gone:|js:> (in-page polling; timeout says WHAT it waited for and what it last read) / drag --from --to (multi-step mouseMoved; one-jump drags are ignored by sortablejs & friends) / upload --ref --file (paths must stay inside the CCC root) / downloads (pins the capture dir to _tmp/browser-downloads/<slot>) / dialog (default DISMISS — OK often means delete/pay/publish). 🔴 Lease before you drive a browser for evidence, and ALWAYS release when finished — an unreleased slot keeps a Chrome process alive and burns power.",
22652
22857
  parameters: {
22653
22858
  action: {
22654
22859
  type: "string",
@@ -22666,7 +22871,11 @@ function createBrowserSlotTool(ctx) {
22666
22871
  },
22667
22872
  reason: {
22668
22873
  type: "string",
22669
- description: "reap: why this slot is being force-reclaimed (recorded)."
22874
+ description: "reap / hold: why this slot is being force-reclaimed, or why it must stay alive (recorded)."
22875
+ },
22876
+ holdFor: {
22877
+ type: "number",
22878
+ description: "hold: keep-alive minutes (max 240). Use before a long download / slow query, or the idle guard will force-reclaim the slot after ~30 min of silence. No permanent hold — renew it instead."
22670
22879
  },
22671
22880
  url: {
22672
22881
  type: "string",
@@ -22895,6 +23104,14 @@ function registerSlotWatchman(ctx) {
22895
23104
  };
22896
23105
  });
22897
23106
  for (const n of res.nudged) console.log(`[serenity-hooks] 槽位看守:${slotLabel(n.slot)} (${n.state}) → ${n.trajectory || "(无归属)"} ${n.delivered ? "已注入" : "注入失败"}:${n.detail}`);
23107
+ const killed = await forceReapIdleSlots(root, async (r, target, message) => {
23108
+ const out = await sendToCognitiveTrajectory(ctx, r, target, message, "浏览器槽位看守");
23109
+ return {
23110
+ ok: out.ok,
23111
+ detail: out.detail
23112
+ };
23113
+ });
23114
+ for (const k of killed.reaped) console.warn(`[serenity-hooks] 槽位强关:${slotLabel(k.slot)} → ${k.trajectory || "(无归属)"} 闲置 ${k.idleMin} 分钟:${k.killDetail}|告知 ${k.delivered ? "已注入" : "未注入"}:${k.deliverDetail}`);
22898
23115
  } catch (err) {
22899
23116
  console.warn(`[serenity-hooks] ✗ 槽位看守异常(${root}): ${String(err?.message ?? err)}`);
22900
23117
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shgroup/dsh-serenity-hooks",
3
- "version": "1.137.18",
3
+ "version": "1.138.0",
4
4
  "description": "宁静号 ACC harness(Native Cordis 插件)——给 DeepSeek Harness 装一个「AI 工作区」:13 个工具(container_fs/cognitive_trajectory/dashboard/container_git/msm/praxis/ontology/serenity-skill-creator/localstore/container_admin/browser_slot;另两个 im-bridge/diagram 按条件出现)+ 机械约束(安全模式/工作区围墙/密钥守卫/对外输出守卫)+ 认知轨迹日志与原地重建 + 网页登录入口/IM 桥/认知轨迹唤醒注册表 + 浏览器槽位管理(≤20 个独立 profile 的 Chrome 槽位,带占用归属与异常时向所属会话反向注入提醒)。轨迹声明 = 轨迹目录下的 trajectory.json(约束面 + 旧标识 uid + CRO 机器绑定 cro.host;旧名 trajectory-constraint.json / skiff.json 仍在读取族里);轨迹提示词 = 轨迹目录下的 PROMPT.md(一条轨迹「是谁、按什么章程工作」,所有轨迹通用,追加在容器层与质量层之后,不替换它们)。适配 DSH 0.1.7-rc.1 / 0.2.0-rc.1 / 0.2.1-rc.1(三档)。",
5
5
  "license": "MIT",
6
6
  "repository": {