@shgroup/dsh-serenity-hooks 1.16.4 → 1.16.6

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.16.4",
3
+ "version": "1.16.6",
4
4
  "main": "lib/index.js",
5
5
  "description": "宁静号 ACC harness(Native Cordis 插件):真实 DSH 工具 cc_fs/session/acc_msm/eap/neat/cce/loop + 拦截缝机械约束(safe-mode/路径守卫/会话落盘)。适配 DSH 公开版(0.1.0-rc,deepseek-ai/deepseek-harness)。私有(dsh-external 组织)。",
6
6
  "engines": {
@@ -16,7 +16,8 @@
16
16
  "eap",
17
17
  "neat",
18
18
  "cce",
19
- "loop"
19
+ "loop",
20
+ "localstore"
20
21
  ],
21
22
  "skills": []
22
23
  }
package/lib/index.js CHANGED
@@ -1,13 +1,13 @@
1
1
  import z from "@deepseek-ai/schemastery";
2
2
  import { defineTool } from "@deepseek-ai/dsh-tools";
3
- import { appendFileSync, cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
+ import { appendFileSync, chmodSync, cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
4
4
  import { basename, dirname, join, relative, resolve } from "node:path";
5
- import { execFile, execFileSync, spawnSync } from "node:child_process";
5
+ import { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
6
6
  import { homedir, platform } from "node:os";
7
7
  import { promisify } from "node:util";
8
8
  import { fileURLToPath } from "node:url";
9
9
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
10
- import { randomBytes } from "node:crypto";
10
+ import { randomBytes, randomUUID } from "node:crypto";
11
11
  //#region src/ccc.ts
12
12
  /**
13
13
  * ccc.ts — CCC 纯逻辑层(零 DSH 依赖,可独立单测)
@@ -37,11 +37,29 @@ function findGitRoot(cwd) {
37
37
  current = parent;
38
38
  }
39
39
  }
40
+ /**
41
+ * 前缀判定:abs 是否位于 rootAbs 之内。
42
+ * caseInsensitive(Windows 盘符/路径大小写不敏感)由调用方按平台传入;
43
+ * 边界必须是路径分隔符(`\` 或 `/` 任一)——不依赖平台 sep,跨平台语义一致:
44
+ * - 跨盘符绝对路径(root 在 D:\、target 在 C:\)前缀不匹配 → outside
45
+ * - 兄弟目录前缀陷阱(home vs home2)边界非分隔符 → outside
46
+ * (旧实现用 path.relative().startsWith('..')——跨盘时 relative 返回绝对路径原文,
47
+ * 不以 `..` 开头 → 漏判放行,见 Windows 兼容审计问题 1。)
48
+ */
49
+ function pathInside(rootAbs, abs, caseInsensitive = process.platform === "win32") {
50
+ const r = caseInsensitive ? rootAbs.toLowerCase() : rootAbs;
51
+ const a = caseInsensitive ? abs.toLowerCase() : abs;
52
+ if (a === r) return true;
53
+ if (!a.startsWith(r)) return false;
54
+ const next = a[r.length];
55
+ return next === "\\" || next === "/";
56
+ }
40
57
  function classifyPath(p, root) {
41
- const rel = relative(resolve(root), resolve(p));
42
- if (rel === "") return "same";
43
- if (rel.startsWith("..")) return "outside";
44
- return "inside";
58
+ const rootAbs = resolve(root);
59
+ const abs = resolve(p);
60
+ const ci = process.platform === "win32";
61
+ if (ci ? abs.toLowerCase() === rootAbs.toLowerCase() : abs === rootAbs) return "same";
62
+ return pathInside(rootAbs, abs, ci) ? "inside" : "outside";
45
63
  }
46
64
  function resolveInside(root, p) {
47
65
  const abs = resolve(root, p);
@@ -221,8 +239,16 @@ function runCcFs(root, args) {
221
239
  else if (os === "linux") {
222
240
  const revealPath = statSync(abs).isDirectory() ? abs : dirname(abs);
223
241
  execFileSync("xdg-open", [revealPath], { timeout: 1e4 });
224
- } else if (os === "win32") execFileSync("explorer", ["/select,", abs], { timeout: 1e4 });
225
- else throw new Error(`unsupported platform: ${os}`);
242
+ } else if (os === "win32") {
243
+ const args = statSync(abs).isDirectory() ? [abs] : ["/select,", abs];
244
+ const child = spawn("explorer", args, {
245
+ detached: true,
246
+ stdio: "ignore",
247
+ windowsHide: false
248
+ });
249
+ child.on("error", () => {});
250
+ child.unref();
251
+ } else throw new Error(`unsupported platform: ${os}`);
226
252
  return {
227
253
  ok: true,
228
254
  revealed: safeRel(root, abs)
@@ -278,7 +304,7 @@ function runCcFs(root, args) {
278
304
  function agentCwd$6(exec) {
279
305
  return exec.agent?.session?.header?.cwd ?? process.cwd();
280
306
  }
281
- function renderText$8(value) {
307
+ function renderText$9(value) {
282
308
  return [{
283
309
  type: "text",
284
310
  text: typeof value === "string" ? value : JSON.stringify(value, null, 2)
@@ -330,7 +356,7 @@ const ccFsTool = defineTool({
330
356
  },
331
357
  output: {
332
358
  schema: { type: "json" },
333
- render: (args, value) => renderText$8(value)
359
+ render: (args, value) => renderText$9(value)
334
360
  },
335
361
  async execute(args, exec) {
336
362
  const root = findSerenityRoot(agentCwd$6(exec));
@@ -348,6 +374,12 @@ const ccFsTool = defineTool({
348
374
  */
349
375
  const execFileAsync = promisify(execFile);
350
376
  const MSM_TIMEOUT_MS = 6e5;
377
+ /**
378
+ * Windows 兼容(审计观察点 A):`.cmd` 不能直接被 CreateProcess 解析——
379
+ * `execFile('npx')` / `spawnSync('npx')` 在 Windows 必 ENOENT(需 shell 或显式 .cmd)。
380
+ * bun 无扩展名(bun.exe 可被 libuv 按 PATHEXT 解析),保持 'bun'。
381
+ */
382
+ const NPX_BIN = process.platform === "win32" ? "npx.cmd" : "npx";
351
383
  const MSM_ACTIONS = [
352
384
  "list",
353
385
  "exec",
@@ -435,7 +467,7 @@ function runMsm(root, args) {
435
467
  "pipe"
436
468
  ]
437
469
  });
438
- if (r.error && r.error.code === "ENOENT") r = spawnSync("npx", [
470
+ if (r.error && r.error.code === "ENOENT") r = spawnSync(NPX_BIN, [
439
471
  "tsx",
440
472
  entry.path,
441
473
  ...businessArgs
@@ -653,7 +685,7 @@ async function runMsmAsync(root, args) {
653
685
  } catch (e) {
654
686
  const err = e;
655
687
  if (err.code === "ENOENT") try {
656
- const r = await execFileAsync("npx", [
688
+ const r = await execFileAsync(NPX_BIN, [
657
689
  "tsx",
658
690
  entry.path,
659
691
  ...businessArgs
@@ -825,6 +857,55 @@ function readActiveSessionMd(root, scope = DEFAULT_SESSION_SCOPE) {
825
857
  if (!abs.startsWith(resolve(root))) return null;
826
858
  return abs;
827
859
  }
860
+ /** 列出全部 scope 的活动标记(含 scope / mdRel / mtime);目录不存在返回空 */
861
+ function listActiveMarkers(root) {
862
+ const dir = resolve(root, ACTIVE_SESSIONS_DIR);
863
+ if (!existsSync(dir)) return [];
864
+ const out = [];
865
+ for (const entry of readdirSync(dir)) {
866
+ const full = join(dir, entry);
867
+ if (!statSync(full).isFile()) continue;
868
+ try {
869
+ const rel = readFileSync(full, "utf-8").trim();
870
+ if (!rel) continue;
871
+ out.push({
872
+ scope: entry,
873
+ mdRel: rel,
874
+ mtime: statSync(full).mtimeMs
875
+ });
876
+ } catch {}
877
+ }
878
+ return out;
879
+ }
880
+ /**
881
+ * 重启恢复:当前 scope 无标记时,把"最近激活"(mtime 最新)且根内有效的标记
882
+ * 复制为当前 scope 标记(激活语义延续:use = 激活,重启自动恢复 = 重新激活)。
883
+ * 返回恢复的会话信息;已有标记 / 无候选 / 全部越界 → null。
884
+ * 调用方负责根会话判定(subagent / loop 牛马不恢复——见 context.ts shouldAutoRestore)。
885
+ */
886
+ function restoreActiveSession(root, scope = DEFAULT_SESSION_SCOPE) {
887
+ const marker = activeSessionMarker(root, scope);
888
+ if (existsSync(marker)) return null;
889
+ const scopeName = sanitizeScope(scope);
890
+ const candidates = listActiveMarkers(root).filter((m) => m.scope !== scopeName);
891
+ if (candidates.length === 0) return null;
892
+ const rootAbs = resolve(root);
893
+ const valid = candidates.filter((m) => pathInside(rootAbs, resolve(rootAbs, m.mdRel)));
894
+ if (valid.length === 0) return null;
895
+ const best = valid.sort((a, b) => b.mtime - a.mtime)[0];
896
+ mkdirSync(resolve(rootAbs, ACTIVE_SESSIONS_DIR), { recursive: true });
897
+ writeFileSync(marker, best.mdRel, "utf-8");
898
+ const mdPath = resolve(rootAbs, best.mdRel);
899
+ const dirName = basename(dirname(mdPath));
900
+ const idMatch = dirName.match(/S(\d{3,})/);
901
+ return {
902
+ dir: dirName,
903
+ id: idMatch ? `S${idMatch[1]}` : null,
904
+ mdPath,
905
+ restored: true,
906
+ from: best.scope
907
+ };
908
+ }
828
909
  function archiveSession(root, key) {
829
910
  const target = findSession(root, key);
830
911
  if (!target) throw new Error(`未找到会话: ${key}`);
@@ -909,7 +990,7 @@ function agentCwd$5(exec) {
909
990
  function agentScope$2(exec) {
910
991
  return exec.agent?.session?.id ?? "default";
911
992
  }
912
- function renderText$7(value) {
993
+ function renderText$8(value) {
913
994
  return [{
914
995
  type: "text",
915
996
  text: typeof value === "string" ? value : JSON.stringify(value, null, 2)
@@ -940,7 +1021,7 @@ const sessionTool = defineTool({
940
1021
  },
941
1022
  output: {
942
1023
  schema: { type: "json" },
943
- render: (args, value) => renderText$7(value)
1024
+ render: (args, value) => renderText$8(value)
944
1025
  },
945
1026
  async execute(args, exec) {
946
1027
  const root = findSerenityRoot(agentCwd$5(exec));
@@ -1211,14 +1292,15 @@ function setSafeMode(root, on) {
1211
1292
  *
1212
1293
  * health: CCC 三原则检查(P1 .serenity / P2 git / 配置)
1213
1294
  * time: ISO 8601 时间戳
1214
- * wait: 同步等待 N
1295
+ * wait: 等待 N 秒(纯 Node setTimeout——不依赖外部 sleep 可执行文件,
1296
+ * Windows 无 GNU coreutils sleep,spawn 必 ENOENT,见 Windows 兼容审计问题 3)
1215
1297
  */
1216
1298
  const KIT_ACTIONS = [
1217
1299
  "health",
1218
1300
  "time",
1219
1301
  "wait"
1220
1302
  ];
1221
- function runKit(root, args) {
1303
+ async function runKit(root, args) {
1222
1304
  switch (args.action) {
1223
1305
  case "health": {
1224
1306
  const gitRoot = findGitRoot(root);
@@ -1253,7 +1335,7 @@ function runKit(root, args) {
1253
1335
  case "wait": {
1254
1336
  const n = args.seconds ?? 0;
1255
1337
  if (!Number.isFinite(n) || n < 0) throw new Error("wait 需要非负秒数");
1256
- execFileSync("sleep", [String(n)], { stdio: "ignore" });
1338
+ await new Promise((r) => setTimeout(r, Math.round(n * 1e3)));
1257
1339
  return { waited: n };
1258
1340
  }
1259
1341
  default: throw new Error(`未知 action: ${args.action}`);
@@ -1267,7 +1349,7 @@ function runKit(root, args) {
1267
1349
  function agentCwd$4(exec) {
1268
1350
  return exec.agent?.session?.header?.cwd ?? process.cwd();
1269
1351
  }
1270
- function renderText$6(value) {
1352
+ function renderText$7(value) {
1271
1353
  return [{
1272
1354
  type: "text",
1273
1355
  text: typeof value === "string" ? value : JSON.stringify(value, null, 2)
@@ -1290,12 +1372,12 @@ const kitTool = defineTool({
1290
1372
  },
1291
1373
  output: {
1292
1374
  schema: { type: "json" },
1293
- render: (args, value) => renderText$6(value)
1375
+ render: (args, value) => renderText$7(value)
1294
1376
  },
1295
1377
  async execute(args, exec) {
1296
1378
  const root = findSerenityRoot(agentCwd$4(exec));
1297
1379
  if (!root) throw new Error("No CCC found: no .serenity file from agent cwd");
1298
- return runKit(root, args);
1380
+ return await runKit(root, args);
1299
1381
  }
1300
1382
  });
1301
1383
  //#endregion
@@ -1337,7 +1419,12 @@ function git(root, args) {
1337
1419
  function runGit(root, args) {
1338
1420
  switch (args.action) {
1339
1421
  case "status": {
1340
- const r = git(root, ["status", "--porcelain"]);
1422
+ const r = git(root, [
1423
+ "-c",
1424
+ "core.quotepath=false",
1425
+ "status",
1426
+ "--porcelain"
1427
+ ]);
1341
1428
  if (!r.ok) throw new Error(`status 失败:${r.stderr.trim()}`);
1342
1429
  return {
1343
1430
  clean: r.stdout.trim() === "",
@@ -1384,6 +1471,8 @@ function runGit(root, args) {
1384
1471
  case "log": {
1385
1472
  const n = args.count ?? 10;
1386
1473
  const r = git(root, [
1474
+ "-c",
1475
+ "core.quotepath=false",
1387
1476
  "log",
1388
1477
  "--oneline",
1389
1478
  "-n",
@@ -1403,7 +1492,7 @@ function runGit(root, args) {
1403
1492
  function agentCwd$3(exec) {
1404
1493
  return exec.agent?.session?.header?.cwd ?? process.cwd();
1405
1494
  }
1406
- function renderText$5(value) {
1495
+ function renderText$6(value) {
1407
1496
  return [{
1408
1497
  type: "text",
1409
1498
  text: typeof value === "string" ? value : JSON.stringify(value, null, 2)
@@ -1430,7 +1519,7 @@ const gitTool = defineTool({
1430
1519
  },
1431
1520
  output: {
1432
1521
  schema: { type: "json" },
1433
- render: (args, value) => renderText$5(value)
1522
+ render: (args, value) => renderText$6(value)
1434
1523
  },
1435
1524
  async execute(args, exec) {
1436
1525
  const root = findSerenityRoot(agentCwd$3(exec));
@@ -1446,7 +1535,7 @@ const gitTool = defineTool({
1446
1535
  function agentCwd$2(exec) {
1447
1536
  return exec.agent?.session?.header?.cwd ?? process.cwd();
1448
1537
  }
1449
- function renderText$4(value) {
1538
+ function renderText$5(value) {
1450
1539
  return [{
1451
1540
  type: "text",
1452
1541
  text: typeof value === "string" ? value : JSON.stringify(value, null, 2)
@@ -1490,7 +1579,7 @@ const msmTool = defineTool({
1490
1579
  },
1491
1580
  output: {
1492
1581
  schema: { type: "json" },
1493
- render: (args, value) => renderText$4(value)
1582
+ render: (args, value) => renderText$5(value)
1494
1583
  },
1495
1584
  async execute(args, exec) {
1496
1585
  const root = findSerenityRoot(agentCwd$2(exec));
@@ -1531,7 +1620,7 @@ CCC(home-serenity 等)认知内容编码为 skill/SESSION/设计文档。产
1531
1620
 
1532
1621
  ## 参考
1533
1622
  https://github.com/tellmewhattodo/theory-eap`;
1534
- function renderText$3(value) {
1623
+ function renderText$4(value) {
1535
1624
  return [{
1536
1625
  type: "text",
1537
1626
  text: typeof value === "string" ? value : JSON.stringify(value, null, 2)
@@ -1551,7 +1640,7 @@ const eapTool = defineTool({
1551
1640
  } },
1552
1641
  output: {
1553
1642
  schema: { type: "string" },
1554
- render: (_args, value) => renderText$3(value)
1643
+ render: (_args, value) => renderText$4(value)
1555
1644
  },
1556
1645
  async execute(args) {
1557
1646
  if (args.section === "variables") return EAP_CONTENT.split("## 输出前自检清单")[0];
@@ -1592,7 +1681,7 @@ const NEAT_CONTENT = `# Neat 设计协作协议
1592
1681
  2. 等待确认或修正(小步)
1593
1682
  3. 确认后记录决策(写入会话 SESSION.md 或设计文档)
1594
1683
  4. 推进到下一决策点`;
1595
- function renderText$2(value) {
1684
+ function renderText$3(value) {
1596
1685
  return [{
1597
1686
  type: "text",
1598
1687
  text: typeof value === "string" ? value : JSON.stringify(value, null, 2)
@@ -1608,7 +1697,7 @@ const neatTool = defineTool({
1608
1697
  } },
1609
1698
  output: {
1610
1699
  schema: { type: "string" },
1611
- render: (_args, value) => renderText$2(value)
1700
+ render: (_args, value) => renderText$3(value)
1612
1701
  },
1613
1702
  async execute(args) {
1614
1703
  if (args.section === "rules") return NEAT_CONTENT.match(/## 四条铁律[\s\S]*?(?=## )/)?.[0] ?? NEAT_CONTENT;
@@ -1671,7 +1760,7 @@ CCE 回答"有结构的知识应如何跨时间持续演化而不丧失连贯性
1671
1760
  ## 与 Serenity 的关系
1672
1761
  Serenity 的会话系统、会话追踪、熵管理机制(SQC 品质循环)都是 CCE 的工程实现;
1673
1762
  CCC 系统提示词中嵌入的行为约束即来自 CCE。`;
1674
- function renderText$1(value) {
1763
+ function renderText$2(value) {
1675
1764
  return [{
1676
1765
  type: "text",
1677
1766
  text: typeof value === "string" ? value : JSON.stringify(value, null, 2)
@@ -1692,7 +1781,7 @@ const cceTool = defineTool({
1692
1781
  } },
1693
1782
  output: {
1694
1783
  schema: { type: "string" },
1695
- render: (_args, value) => renderText$1(value)
1784
+ render: (_args, value) => renderText$2(value)
1696
1785
  },
1697
1786
  async execute(args) {
1698
1787
  const section = args.section;
@@ -1798,9 +1887,9 @@ function splitModel(model) {
1798
1887
  }
1799
1888
  /** 轮次 prompt(对齐老 loop 结构:回顾进度 → 自由工作 → 汇报) */
1800
1889
  function buildRoundPrompt(opts) {
1801
- const { root, session, label, round, maxRounds, stopToken, progress, task } = opts;
1890
+ const { root, session, label, round, stopToken, progress, task } = opts;
1802
1891
  const resumeNote = progress && progress.round > 0 ? `上一轮(round ${progress.round})已完成:${progress.lastResponse.slice(0, 300)}\n永远从上次停止处继续,绝不重做已完成工作。` : "这是第一轮。";
1803
- return `# ${label} — 牛马循环 round ${round}/${maxRounds}
1892
+ return `# ${label} — 牛马循环 round ${round}
1804
1893
 
1805
1894
  CCC 根:${root}
1806
1895
  ${session ? `工作会话:${session}(AGENT_SESSIONS/${session}/SESSION.md 记录进度)` : ""}
@@ -1824,11 +1913,14 @@ ${resumeNote}
1824
1913
  * label(必)任务标签 → 进度文件 loop-<label>.md/.json
1825
1914
  * session(选)工作会话 S###(上下文提示)
1826
1915
  * model(选)provider/model(如 minimax-cn-coding-plan/MiniMax-M3);缺省读 loop.defaultModel
1827
- * maxRounds(默认 100)轮次上限;每轮等待 agent **无超时**(loop 可永续,agent 工作多久等多久)
1916
+ * (S134 修正:轮次不需要调用者指定——内部 while 驱动 agent 逐轮推进,
1917
+ * 对话轮次**无上限**(不完成不返回);agent 非正常停止时自动重启,
1918
+ * 重启次数上限 LOOP_MAX_RESTARTS=100(防死循环保险阀))
1828
1919
  *
1829
1920
  * 机制:ctx.agents.create()(带 setup 钩子)创建专用 agent(进程内),
1830
- * 每轮 followup → agent/status idle → 读 session.events 响应 → 写进度 → stop token 检查 → 续跑。
1831
- * 工厂模式:apply 时闭包捕获插件 ctx(工具 execute ctx 参数)。
1921
+ * 每轮 followup → agent/status idle → 读 session.events 响应 → 写进度 → stop token 检查 →
1922
+ * 未完成继续下一轮;followup/waitIdle 抛错(非正常停止)→ dispose 并重新 create agent
1923
+ * (重启计数,≤100),同一轮重试。工厂模式:apply 时闭包捕获插件 ctx(工具 execute 无 ctx 参数)。
1832
1924
  *
1833
1925
  * preset 继承:setup 钩子里对子 agent 执行 agentPresets.composeFrom(对齐 subagent 先例),
1834
1926
  * 使 loop agent 继承发起方会话的 agent preset 工具(read/write/edit 等 preset 层工具)。
@@ -1837,7 +1929,7 @@ ${resumeNote}
1837
1929
  function agentCwd$1(exec) {
1838
1930
  return (exec.agent?.session)?.header?.cwd ?? process.cwd();
1839
1931
  }
1840
- function renderText(value) {
1932
+ function renderText$1(value) {
1841
1933
  return [{
1842
1934
  type: "text",
1843
1935
  text: typeof value === "string" ? value : JSON.stringify(value, null, 2)
@@ -1876,7 +1968,7 @@ function lastAssistantText(agent) {
1876
1968
  function createLoopTool(ctx) {
1877
1969
  return defineTool({
1878
1970
  name: "loop",
1879
- description: "牛马循环(老 loop 等效):用指定模型创建专用 agent 反复执行任务直到完成或达轮次上限。\n用法:loop 接受 task(要完成的目标)或依赖 session 上下文;模型缺省读 .dsh/serenity.json 的 loop.defaultModel(当前 minimax-cn-coding-plan/MiniMax-M3,廉价牛马)。\n行为:每轮创建全新 agent 工作(读文件/改代码/执行命令),汇报进度后进入下一轮;完成时输出停止标记即终止。**每轮等待无超时**(loop 永续:agent 工作多久等多久,不被超时打断)。\n进度:写入 AGENT_SESSIONS/loop-<label>.md/.json;同 label 再次调用从上次轮次续跑(不重做)。\n约束:loop agent 受完整 Serenity 约束(ACC 身份/入口技能系统提示词/守卫/session-keeper)。\n示例:loop 执行「扫描 SQC 并修复 DC 问题」,label: sqc-scan,maxRounds: 5",
1971
+ description: "牛马循环(老 loop 等效):用指定模型创建专用 agent 反复执行任务直到完成。\n用法:loop 接受 task(要完成的目标)或依赖 session 上下文;模型缺省读 .dsh/serenity.json 的 loop.defaultModel(当前 minimax-cn-coding-plan/MiniMax-M3,廉价牛马)。\n行为:内部硬性 while 循环驱动 agent 逐轮推进任务,每轮等待无超时(agent 工作多久等多久)。唯一完成条件 = agent 精确回显本轮随机完成码(stop token),防止低智能模型提前结束。轮次不需要调用者指定——对话轮次**无上限**(不完成不返回),agent 非正常停止时自动重启(重启 ≤100 次,防死循环保险阀)。\n进度:写入 AGENT_SESSIONS/loop-<label>.md/.json;同 label 再次调用从上次轮次续跑(不重做)。\n约束:loop agent 受完整 Serenity 约束(ACC 身份/入口技能系统提示词/守卫/session-keeper)。\n示例:loop 执行「扫描 SQC 并修复 DC 问题」,label: sqc-scan",
1880
1972
  parameters: {
1881
1973
  task: {
1882
1974
  type: "string",
@@ -1894,15 +1986,11 @@ function createLoopTool(ctx) {
1894
1986
  model: {
1895
1987
  type: "string",
1896
1988
  description: "provider/model(如 minimax-cn-coding-plan/MiniMax-M3);缺省读 loop.defaultModel"
1897
- },
1898
- maxRounds: {
1899
- type: "integer",
1900
- description: "轮次上限(默认 100)"
1901
1989
  }
1902
1990
  },
1903
1991
  output: {
1904
1992
  schema: { type: "json" },
1905
- render: (_args, value) => renderText(value)
1993
+ render: (_args, value) => renderText$1(value)
1906
1994
  },
1907
1995
  async execute(args, exec) {
1908
1996
  const root = findSerenityRoot(agentCwd$1(exec));
@@ -1910,58 +1998,71 @@ function createLoopTool(ctx) {
1910
1998
  const cfg = loadSerenityConfig(root, DEFAULT_SERENITY_CONFIG_PATHS);
1911
1999
  const model = args.model ?? cfg.loop?.defaultModel;
1912
2000
  if (!model) throw new Error("loop 需要 model:传参或配置 .dsh/serenity.json loop.defaultModel");
1913
- const maxRounds = args.maxRounds ?? 100;
1914
2001
  const label = args.label;
1915
2002
  if (!ctx.agentLoop) throw new Error("loop: ctx.agentLoop 不可用");
1916
2003
  const { provider, model: modelName } = splitModel(model);
1917
2004
  const stopToken = newStopToken();
1918
2005
  let progress = readProgress(root, label);
1919
- const startRound = progress ? Math.min(progress.round + 1, maxRounds) : 1;
2006
+ const startRound = progress ? progress.round + 1 : 1;
1920
2007
  const parentCtx = exec.agent?.ctx;
1921
2008
  const inherited = loopPresetInheritance(parentCtx);
1922
2009
  if (!ctx.agents) throw new Error("loop: ctx.agents 不可用");
1923
- const sessionId = `loop-${label}`;
1924
- const handle = await ctx.agents.create({
1925
- sessionId,
1926
- meta: {
1927
- cwd: root,
1928
- ...inherited.agentPreset === void 0 ? {} : { agentPreset: inherited.agentPreset }
1929
- },
1930
- agentOptions: {
1931
- provider,
1932
- model: modelName
1933
- },
1934
- ...inherited.setup === void 0 ? {} : { setup: inherited.setup }
1935
- });
1936
- const loopAgent = handle.agent;
2010
+ let handle;
2011
+ let loopAgent;
2012
+ const spawnAgent = async () => {
2013
+ const sessionId = `loop-${label}-${randomUUID()}`;
2014
+ handle = await ctx.agents.create({
2015
+ sessionId,
2016
+ meta: {
2017
+ cwd: root,
2018
+ ...inherited.agentPreset === void 0 ? {} : { agentPreset: inherited.agentPreset }
2019
+ },
2020
+ agentOptions: {
2021
+ provider,
2022
+ model: modelName
2023
+ },
2024
+ ...inherited.setup === void 0 ? {} : { setup: inherited.setup }
2025
+ });
2026
+ loopAgent = handle.agent;
2027
+ };
2028
+ await spawnAgent();
1937
2029
  let done = false;
1938
2030
  let lastResponse = progress?.lastResponse ?? "";
1939
2031
  let finalRound = startRound - 1;
2032
+ let restarts = 0;
1940
2033
  try {
1941
- for (let round = startRound; round <= maxRounds; round++) {
2034
+ let round = startRound;
2035
+ while (true) {
1942
2036
  finalRound = round;
1943
2037
  const prompt = buildRoundPrompt({
1944
2038
  root,
1945
2039
  session: args.session,
1946
2040
  label,
1947
2041
  round,
1948
- maxRounds,
1949
2042
  stopToken,
1950
2043
  progress,
1951
2044
  task: args.task
1952
2045
  });
1953
- loopAgent.followup(createUserMessage({
1954
- content: [{
1955
- type: "text",
1956
- text: prompt
1957
- }],
1958
- source: {
1959
- kind: "plugin",
1960
- plugin: "dsh-serenity-hooks"
1961
- }
1962
- }));
1963
- await waitIdle(ctx, loopAgent);
1964
- lastResponse = lastAssistantText(loopAgent);
2046
+ try {
2047
+ loopAgent.followup(createUserMessage({
2048
+ content: [{
2049
+ type: "text",
2050
+ text: prompt
2051
+ }],
2052
+ source: {
2053
+ kind: "plugin",
2054
+ plugin: "dsh-serenity-hooks"
2055
+ }
2056
+ }));
2057
+ await waitIdle(ctx, loopAgent);
2058
+ lastResponse = lastAssistantText(loopAgent);
2059
+ } catch {
2060
+ restarts++;
2061
+ if (restarts > 100) break;
2062
+ await handle.dispose().catch(() => {});
2063
+ await spawnAgent();
2064
+ continue;
2065
+ }
1965
2066
  progress = {
1966
2067
  round,
1967
2068
  done: false,
@@ -1975,6 +2076,7 @@ function createLoopTool(ctx) {
1975
2076
  done = true;
1976
2077
  break;
1977
2078
  }
2079
+ round++;
1978
2080
  }
1979
2081
  writeProgress(root, label, {
1980
2082
  round: finalRound,
@@ -1991,21 +2093,371 @@ function createLoopTool(ctx) {
1991
2093
  return {
1992
2094
  done,
1993
2095
  rounds: finalRound,
2096
+ restarts,
1994
2097
  model,
1995
2098
  label,
1996
2099
  progressFile: json,
1997
2100
  lastResponse: lastResponse.slice(0, 2e3),
1998
2101
  usage: {
1999
- how: "loop 用指定模型(默认 M3)创建专用 agent 每轮独立执行任务,完成时输出停止标记即终止",
2102
+ how: "loop 内部硬性 while 驱动 agent 逐轮推进,agent 精确回显随机完成码即终止;对话轮次无上限(不完成不返回),agent 非正常停止时自动重启(≤100 次)",
2000
2103
  progress: `进度在 AGENT_SESSIONS/loop-${label}.md 与 .json;同 label 再调 loop 会从下一轮续跑(不重做)`,
2001
2104
  constraints: "loop agent 受完整 Serenity 约束(ACC 身份/入口技能系统提示词/守卫)",
2002
- next: done ? "任务已完成;可查看进度文件收尾" : `任务未完成(${finalRound}/${maxRounds} 轮);可同 label 续跑或调整 maxRounds`
2105
+ next: done ? "任务已完成;可查看进度文件收尾" : `任务未完成(已达内部 100 次重启保险阀);可同 label 续跑`
2003
2106
  }
2004
2107
  };
2005
2108
  }
2006
2109
  });
2007
2110
  }
2008
2111
  //#endregion
2112
+ //#region src/localstore-ops.ts
2113
+ /**
2114
+ * localstore-ops.ts — localstore 纯逻辑层(零 DSH 依赖,可独立单测)
2115
+ *
2116
+ * ACC 标准本地凭据/配置存储(S133 设计):
2117
+ * - 一个工具管理两个命名空间:credential(凭据,0600)+ config(偏好,0644)
2118
+ * - 存储于 ~/.serenity/(平台感知:win %USERPROFILE%\.serenity\)
2119
+ * - 两个 YAML 文件:credentials.yaml(扁平 REF→value)+ settings.yaml(命名空间分节)
2120
+ * - 目录 0700
2121
+ *
2122
+ * YAML 用轻量自实现子集(零依赖):扁平 `KEY: value` 映射 + `#` 注释。
2123
+ * 凭据/配置本质是给 MSM/agent 用的普通 YAML 文件——agent 可按 doc 子命令
2124
+ * 说明直接用 fs 工具(read/write)操作;本工具是管理入口 + 规范文档。
2125
+ */
2126
+ const LOCALSTORE_SCOPES = ["credential", "config"];
2127
+ /** 根目录名(~/.serenity) */
2128
+ const STORE_DIR_NAME = ".serenity";
2129
+ /** 凭据文件(0600) */
2130
+ const CREDENTIALS_FILENAME = "credentials.yaml";
2131
+ /** 配置文件(0644) */
2132
+ const SETTINGS_FILENAME = "settings.yaml";
2133
+ /** 凭据 key 规范:大写蛇形(命名空间前缀),如 HOME_GITLAB_TOKEN */
2134
+ const CREDENTIAL_KEY_RE = /^[A-Z][A-Z0-9_]*$/;
2135
+ /** 配置节名规范:小写字母数字连字符 */
2136
+ const CONFIG_SECTION_RE = /^[a-z][a-z0-9-]*$/;
2137
+ /** 配置 key 规范(节内):小驼峰(首字母小写,可含大写),如 defaultModel */
2138
+ const CONFIG_KEY_RE = /^[a-z][a-zA-Z0-9_]*$/;
2139
+ /** 解析 ~/.serenity 根(平台感知:os.homedir() 三平台统一) */
2140
+ function serenityDir() {
2141
+ return join(homedir(), STORE_DIR_NAME);
2142
+ }
2143
+ /** 各命名空间的文件绝对路径 */
2144
+ function storeFilePath(scope) {
2145
+ return scope === "credential" ? join(serenityDir(), CREDENTIALS_FILENAME) : join(serenityDir(), SETTINGS_FILENAME);
2146
+ }
2147
+ /** 确保目录存在并设 0700 */
2148
+ function ensureDir(dir) {
2149
+ mkdirSync(dir, { recursive: true });
2150
+ try {
2151
+ chmodSync(dir, 448);
2152
+ } catch {}
2153
+ }
2154
+ /** 设置文件权限:credential 0600 / config 0644 */
2155
+ function applyFileMode(scope, path) {
2156
+ try {
2157
+ chmodSync(path, scope === "credential" ? 384 : 420);
2158
+ } catch {}
2159
+ }
2160
+ /** 解析扁平映射 YAML → Record<string,string>(忽略 # 注释与空行;值去引号) */
2161
+ function parseFlatYaml(text) {
2162
+ const out = {};
2163
+ for (const rawLine of text.split("\n")) {
2164
+ const line = rawLine.trim();
2165
+ if (line === "" || line.startsWith("#")) continue;
2166
+ const idx = line.indexOf(":");
2167
+ if (idx <= 0) continue;
2168
+ const key = line.slice(0, idx).trim();
2169
+ let value = line.slice(idx + 1).trim();
2170
+ if (value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
2171
+ out[key] = value;
2172
+ }
2173
+ return out;
2174
+ }
2175
+ /** 序列化扁平映射 YAML(保持 key 顺序,值引号包裹含特殊字符的) */
2176
+ function renderFlatYaml(entries) {
2177
+ const lines = [];
2178
+ for (const [key, value] of Object.entries(entries)) {
2179
+ const rendered = /[:#\n]/.test(value) || value === "" || /^\s/.test(value) || /\s$/.test(value) ? JSON.stringify(value) : value;
2180
+ lines.push(`${key}: ${rendered}`);
2181
+ }
2182
+ return lines.join("\n") + (lines.length > 0 ? "\n" : "");
2183
+ }
2184
+ /** 解析分节 YAML(config):节 → key → value */
2185
+ function parseSectionedYaml(text) {
2186
+ const out = {};
2187
+ let section = "";
2188
+ for (const rawLine of text.split("\n")) {
2189
+ const line = rawLine.trim();
2190
+ if (line === "" || line.startsWith("#")) continue;
2191
+ if (rawLine.length - rawLine.trimStart().length === 0 && line.endsWith(":")) {
2192
+ section = line.slice(0, -1).trim();
2193
+ if (!out[section]) out[section] = {};
2194
+ continue;
2195
+ }
2196
+ if (section === "") continue;
2197
+ const idx = line.indexOf(":");
2198
+ if (idx <= 0) continue;
2199
+ const key = line.slice(0, idx).trim();
2200
+ let value = line.slice(idx + 1).trim();
2201
+ if (value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
2202
+ const sectionMap = out[section] ??= {};
2203
+ sectionMap[key] = value;
2204
+ }
2205
+ return out;
2206
+ }
2207
+ /** 序列化分节 YAML(config):节 → key → value */
2208
+ function renderSectionedYaml(sections) {
2209
+ const lines = [];
2210
+ for (const [section, entries] of Object.entries(sections)) {
2211
+ lines.push(`${section}:`);
2212
+ for (const [key, value] of Object.entries(entries)) {
2213
+ const rendered = /[:#\n]/.test(value) || value === "" || /^\s/.test(value) || /\s$/.test(value) ? JSON.stringify(value) : value;
2214
+ lines.push(` ${key}: ${rendered}`);
2215
+ }
2216
+ }
2217
+ return lines.join("\n") + (lines.length > 0 ? "\n" : "");
2218
+ }
2219
+ /** 读取命名空间全部条目(文件不存在返回空) */
2220
+ function readStore(scope) {
2221
+ const path = storeFilePath(scope);
2222
+ if (!existsSync(path)) return scope === "credential" ? {} : {};
2223
+ const text = readFileSync(path, "utf-8");
2224
+ return scope === "credential" ? parseFlatYaml(text) : parseSectionedYaml(text);
2225
+ }
2226
+ /** 校验凭据 key 合法(大写蛇形);不合法抛错 */
2227
+ function assertCredentialKey(key) {
2228
+ if (!CREDENTIAL_KEY_RE.test(key)) throw new Error(`credential key "${key}" 必须匹配大写蛇形 ^[A-Z][A-Z0-9_]*$(如 HOME_GITLAB_TOKEN)`);
2229
+ }
2230
+ /** 校验 config 路径(节.key);不合法抛错 */
2231
+ function assertConfigPath(path) {
2232
+ const idx = path.indexOf(".");
2233
+ if (idx <= 0 || idx === path.length - 1) throw new Error(`config path "${path}" 必须为 section.key(如 loop.defaultModel)`);
2234
+ const section = path.slice(0, idx);
2235
+ const key = path.slice(idx + 1);
2236
+ if (!CONFIG_SECTION_RE.test(section)) throw new Error(`config 节 "${section}" 必须匹配 ^[a-z][a-z0-9-]*$`);
2237
+ if (!CONFIG_KEY_RE.test(key)) throw new Error(`config key "${key}" 必须匹配小驼峰 ^[a-z][a-zA-Z0-9_]*$(如 defaultModel)`);
2238
+ return {
2239
+ section,
2240
+ key
2241
+ };
2242
+ }
2243
+ /** 写入单个条目(自动建目录/设权限;保留其他条目与注释行外内容) */
2244
+ function writeEntry(scope, name, value) {
2245
+ const path = storeFilePath(scope);
2246
+ ensureDir(serenityDir());
2247
+ if (scope === "credential") {
2248
+ assertCredentialKey(name);
2249
+ const entries = parseFlatYaml(existsSync(path) ? readFileSync(path, "utf-8") : "");
2250
+ entries[name] = value;
2251
+ writeFileSync(path, renderFlatYaml(entries), "utf-8");
2252
+ } else {
2253
+ const { section, key } = assertConfigPath(name);
2254
+ const sections = parseSectionedYaml(existsSync(path) ? readFileSync(path, "utf-8") : "");
2255
+ if (!sections[section]) sections[section] = {};
2256
+ sections[section][key] = value;
2257
+ writeFileSync(path, renderSectionedYaml(sections), "utf-8");
2258
+ }
2259
+ applyFileMode(scope, path);
2260
+ }
2261
+ /** 删除单个条目(不存在返回 false) */
2262
+ function unsetEntry(scope, name) {
2263
+ const path = storeFilePath(scope);
2264
+ if (!existsSync(path)) return false;
2265
+ if (scope === "credential") {
2266
+ assertCredentialKey(name);
2267
+ const entries = parseFlatYaml(readFileSync(path, "utf-8"));
2268
+ if (!(name in entries)) return false;
2269
+ delete entries[name];
2270
+ writeFileSync(path, renderFlatYaml(entries), "utf-8");
2271
+ return true;
2272
+ }
2273
+ const { section, key } = assertConfigPath(name);
2274
+ const sections = parseSectionedYaml(readFileSync(path, "utf-8"));
2275
+ const sectionMap = sections[section];
2276
+ if (!sectionMap || !(key in sectionMap)) return false;
2277
+ delete sectionMap[key];
2278
+ if (Object.keys(sectionMap).length === 0) delete sections[section];
2279
+ writeFileSync(path, renderSectionedYaml(sections), "utf-8");
2280
+ return true;
2281
+ }
2282
+ /** 读取单个条目值;不存在返回 null */
2283
+ function getEntry(scope, name) {
2284
+ const path = storeFilePath(scope);
2285
+ if (!existsSync(path)) return null;
2286
+ if (scope === "credential") {
2287
+ assertCredentialKey(name);
2288
+ return parseFlatYaml(readFileSync(path, "utf-8"))[name] ?? null;
2289
+ }
2290
+ const { section, key } = assertConfigPath(name);
2291
+ return parseSectionedYaml(readFileSync(path, "utf-8"))[section]?.[key] ?? null;
2292
+ }
2293
+ /** 列出 key(凭据只返回 key 名,不返回值) */
2294
+ function listKeys(scope) {
2295
+ const data = readStore(scope);
2296
+ if (scope === "credential") return Object.keys(data);
2297
+ return Object.entries(data).flatMap(([section, entries]) => Object.keys(entries).map((key) => `${section}.${key}`));
2298
+ }
2299
+ /**
2300
+ * doc 说明文本:输出存储位置/格式/key 规范/权限/读写方法/安全边界。
2301
+ * agent 据此可直接用 fs 工具(read/write)自己读写凭据/配置。
2302
+ */
2303
+ function docText() {
2304
+ const dir = serenityDir();
2305
+ const credPath = storeFilePath("credential");
2306
+ const cfgPath = storeFilePath("config");
2307
+ return [
2308
+ "# localstore — ACC 本地凭据/配置存储(标准)",
2309
+ "",
2310
+ "一个工具管理两个命名空间:credential(凭据,0600)+ config(偏好,0644)。",
2311
+ "存储于用户主目录,不在任何 CCC git 仓库内。",
2312
+ "",
2313
+ "## 存储位置(平台感知)",
2314
+ `- 根目录: ${dir} (0700)`,
2315
+ `- 凭据: ${credPath} (0600)`,
2316
+ `- 配置: ${cfgPath} (0644)`,
2317
+ "- Windows: %USERPROFILE%\\.serenity\\...(与 Linux/macOS 的 $HOME/.serenity 同构)",
2318
+ "",
2319
+ "## 格式",
2320
+ "credentials.yaml(扁平映射,key = 大写蛇形命名空间前缀):",
2321
+ "```yaml",
2322
+ "HOME_GITLAB_TOKEN: xxx",
2323
+ "SSH_UBUNTU_PASSWORD: xxx",
2324
+ "ANYSEARCH_API_KEY: xxx",
2325
+ "```",
2326
+ "settings.yaml(命名空间分节):",
2327
+ "```yaml",
2328
+ "loop:",
2329
+ " defaultModel: minimax-cn-coding-plan/MiniMax-M3",
2330
+ "ui:",
2331
+ " theme: dark",
2332
+ "```",
2333
+ "",
2334
+ "## key 规范",
2335
+ "- credential key: ^[A-Z][A-Z0-9_]*$(如 HOME_GITLAB_TOKEN)",
2336
+ "- config path: section.key(节 ^[a-z][a-z0-9-]*$,key 小驼峰 ^[a-z][a-zA-Z0-9_]*$,如 loop.defaultModel)",
2337
+ "",
2338
+ "## 读取方法(agent 可直接用 fs 工具)",
2339
+ "- 用 read 工具读对应文件 → 按上面格式解析 YAML",
2340
+ "- 或用 localstore get <name> [--scope credential|config]",
2341
+ "",
2342
+ "## 写入方法",
2343
+ "- 推荐:localstore set <name> <value> [--scope ...](自动建目录/设权限/保留其他条目)",
2344
+ "- 或直接用 write/edit 工具修改文件,保持 YAML 合法(键值冒号分隔)",
2345
+ "",
2346
+ "## 安全边界",
2347
+ "- list/show 对 credential 只返回 key 名,不返回值",
2348
+ "- 凭据值应在 agent 内部使用,不要写入对话/日志",
2349
+ "- 文件权限不符(非 0600/0644)时 get/set 会提示 chmod 修复",
2350
+ "- 文件在用户主目录,天然不进入任何 git 仓库",
2351
+ ""
2352
+ ].join("\n");
2353
+ }
2354
+ /** 运行 localstore 操作(纯逻辑;返回 JSON 值供工具 render) */
2355
+ function runLocalStore(args) {
2356
+ const scope = args.scope === "config" ? "config" : "credential";
2357
+ switch (args.action) {
2358
+ case "list": return {
2359
+ scope,
2360
+ keys: listKeys(scope)
2361
+ };
2362
+ case "get": {
2363
+ if (!args.name) throw new Error("get 需要 name");
2364
+ const value = getEntry(scope, args.name);
2365
+ if (value === null) throw new Error(`not found: ${args.name}(scope=${scope})`);
2366
+ return {
2367
+ scope,
2368
+ name: args.name,
2369
+ value,
2370
+ source: scope
2371
+ };
2372
+ }
2373
+ case "set":
2374
+ if (!args.name) throw new Error("set 需要 name");
2375
+ if (args.value === void 0) throw new Error("set 需要 value");
2376
+ writeEntry(scope, args.name, args.value);
2377
+ return {
2378
+ scope,
2379
+ name: args.name,
2380
+ set: true
2381
+ };
2382
+ case "unset": {
2383
+ if (!args.name) throw new Error("unset 需要 name");
2384
+ const removed = unsetEntry(scope, args.name);
2385
+ return {
2386
+ scope,
2387
+ name: args.name,
2388
+ removed
2389
+ };
2390
+ }
2391
+ case "show": {
2392
+ if (!args.name) throw new Error("show 需要 name");
2393
+ const exists = getEntry(scope, args.name) !== null;
2394
+ return {
2395
+ scope,
2396
+ name: args.name,
2397
+ exists,
2398
+ path: storeFilePath(scope)
2399
+ };
2400
+ }
2401
+ case "doc": return { doc: docText() };
2402
+ default: throw new Error(`未知子命令: ${args.action}(可用 list/get/set/unset/show/doc)`);
2403
+ }
2404
+ }
2405
+ //#endregion
2406
+ //#region src/tools/localstore.ts
2407
+ /**
2408
+ * localstore.ts — localstore 真实 DSH 工具定义(defineTool)
2409
+ *
2410
+ * ACC 标准本地凭据/配置存储(S133 设计)。进程内注册,零 DSH 依赖逻辑在
2411
+ * localstore-ops.ts(可单测)。doc 子命令输出存储规范,agent 可直接用 fs
2412
+ * 工具(read/write)自己读写。
2413
+ */
2414
+ const ACTIONS = [
2415
+ "list",
2416
+ "get",
2417
+ "set",
2418
+ "unset",
2419
+ "show",
2420
+ "doc"
2421
+ ];
2422
+ function renderText(value) {
2423
+ return [{
2424
+ type: "text",
2425
+ text: typeof value === "string" ? value : JSON.stringify(value, null, 2)
2426
+ }];
2427
+ }
2428
+ const localstoreTool = defineTool({
2429
+ name: "localstore",
2430
+ description: "ACC 标准本地凭据/配置存储:一个工具管理两个命名空间 credential(凭据,0600)与 config(本地偏好,0644)。存储于用户主目录 ~/.serenity/(平台感知,不在任何 git 仓库内)。子命令:list(列 key,凭据不返回值)/ get <name>(读值)/ set <name> <value>(写)/ unset <name>(删)/ show <name>(元数据,凭据不打印值)/ doc(输出存储规范——路径/格式/key 规范/权限,agent 可按说明直接用 read/write 操作文件)。默认 scope=credential;config 需传 --scope config(路径为 section.key,如 loop.defaultModel)。",
2431
+ parameters: {
2432
+ action: {
2433
+ type: "string",
2434
+ enum: [...ACTIONS],
2435
+ required: true,
2436
+ description: "子命令:list/get/set/unset/show/doc"
2437
+ },
2438
+ name: {
2439
+ type: "string",
2440
+ description: "条目名(credential 用大写蛇形;config 用 section.key)"
2441
+ },
2442
+ value: {
2443
+ type: "string",
2444
+ description: "set 的值"
2445
+ },
2446
+ scope: {
2447
+ type: "string",
2448
+ enum: [...LOCALSTORE_SCOPES],
2449
+ description: "命名空间 credential|config(默认 credential)"
2450
+ }
2451
+ },
2452
+ output: {
2453
+ schema: { type: "json" },
2454
+ render: (args, value) => renderText(value)
2455
+ },
2456
+ async execute(args) {
2457
+ return runLocalStore(args);
2458
+ }
2459
+ });
2460
+ //#endregion
2009
2461
  //#region src/seams/loop.ts
2010
2462
  /** 解析当前 dsh 会话 scope 的活跃会话 SESSION.md 绝对路径;无标记/越界返回 null */
2011
2463
  function resolveActiveSession(root, scope = DEFAULT_SESSION_SCOPE) {
@@ -2209,13 +2661,14 @@ function accBlock(root) {
2209
2661
  "",
2210
2662
  " cc_fs — CCC 内文件系统操作(root/resolve/exists/list/tree/relative/mkdir/rm/mv/cp/touch/append/reveal/info/find)",
2211
2663
  " session — session lifecycle(list/show/create/health/qa/archive/summary)",
2212
- " acc_kit — ACC utility kit(health: CCC three principles / time: now / wait: sleep N seconds)",
2664
+ " acc_kit — ACC utility kit(health: CCC three principles / time: now / wait: wait N seconds)",
2213
2665
  " cc_git — git operations(status/commit/push/log)",
2214
2666
  " acc_msm — MSM framework(list/exec/register/deregister/check/guide)",
2215
2667
  " eap — return the full EAP cognitive quality framework",
2216
2668
  " neat — return the full Neat design collaboration protocol",
2217
2669
  " cce — return the full Cognitive Continuity Engineering framework",
2218
2670
  " loop — 牛马循环:指定模型专用 agent 反复执行",
2671
+ " localstore — ACC 本地凭据/配置存储(credential 0600 + config 0644,~/.serenity/);doc 子命令输出规范",
2219
2672
  "",
2220
2673
  "The DSH platform tools remain available too (read/write/edit/glob/grep/web_search/ask_user_question/subagent/workflow/goal and more) — the ACC tools above are the serenity-native layer, not the only tools.",
2221
2674
  "",
@@ -2508,6 +2961,22 @@ function agentKey(agent) {
2508
2961
  function agentScope(agent) {
2509
2962
  return agent.session.id ?? "default";
2510
2963
  }
2964
+ /**
2965
+ * 重启恢复的根会话判定(S134 需求):
2966
+ * 只有"conversation 根会话"才自动恢复最近激活的宁静号会话——
2967
+ * - subagent:session header `origin === 'subagent'`(DSH 路由语义,agent-lookup.ts)
2968
+ * - 派生会话:`parentSession` 存在(任何子会话)
2969
+ * - loop 牛马:sessionId 固定 `loop-` 前缀(tools/loop.ts 生成)
2970
+ * 三者都不恢复(避免把主会话激活注入子上下文,违背 v1.16.2 scope 隔离)。
2971
+ */
2972
+ function shouldAutoRestore(agent) {
2973
+ const session = agent.session;
2974
+ if (!session) return false;
2975
+ if (session.header?.origin === "subagent") return false;
2976
+ if (session.header?.parentSession) return false;
2977
+ if (session.id?.startsWith("loop-")) return false;
2978
+ return true;
2979
+ }
2511
2980
  function registerContext(ctx, opts = {}) {
2512
2981
  const configPaths = opts.configPaths ?? DEFAULT_SERENITY_CONFIG_PATHS;
2513
2982
  const entrySkillMaxChars = opts.entrySkillMaxChars ?? 3e4;
@@ -2516,6 +2985,12 @@ function registerContext(ctx, opts = {}) {
2516
2985
  if (!root) return;
2517
2986
  const key = agentKey(agent);
2518
2987
  registerEntrySkillSection(agent, root);
2988
+ if (shouldAutoRestore(agent)) try {
2989
+ if (loadSerenityConfig(root, configPaths).hooks?.autoRestoreSession ?? true) {
2990
+ const restored = restoreActiveSession(root, agentScope(agent));
2991
+ if (restored) console.log(`[serenity-hooks] ↻ 自动恢复激活会话: ${restored.dir}(from scope ${restored.from})`);
2992
+ }
2993
+ } catch {}
2519
2994
  if (injected.has(key)) return;
2520
2995
  injected.add(key);
2521
2996
  agent.inject(accMessage(root, configPaths, entrySkillMaxChars, agentScope(agent)));
@@ -2833,6 +3308,7 @@ function apply(ctx, config) {
2833
3308
  ctx.tools.register(neatTool);
2834
3309
  ctx.tools.register(cceTool);
2835
3310
  ctx.tools.register(createLoopTool(ctx));
3311
+ ctx.tools.register(localstoreTool);
2836
3312
  }
2837
3313
  if (config.guards) registerGuards(ctx, { configPaths: config.serenityConfigPaths });
2838
3314
  if (config.turnFlush) registerTurnFlush(ctx);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shgroup/dsh-serenity-hooks",
3
- "version": "1.16.4",
3
+ "version": "1.16.6",
4
4
  "description": "宁静号 ACC harness — Native Cordis 插件(DeepSeek Harness 运行时)。真实 DSH 工具注册(cc_fs/session/acc_msm 等 9 工具)+ 拦截缝机械约束(safe-mode/路径守卫/会话落盘)+ 系统提示词注入(ACC/CCE/Constraints/SKILL/Session 五块)。适配 DSH 公开版(deepseek-ai/deepseek-harness 0.1.0-rc)。",
5
5
  "license": "MIT",
6
6
  "repository": {