@shgroup/dsh-serenity-hooks 1.139.1 → 1.139.3

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.
@@ -22,3 +22,28 @@ export declare function __resetDisposerWarningsForTest(): void;
22
22
  * @returns 是否成功装配(false = 宿主无 `ctx.effect`,已告警)
23
23
  */
24
24
  export declare function registerDisposer(ctx: unknown, label: string, cleanup: () => void): boolean;
25
+ /**
26
+ * 把一个 HTTP 路由注册器包成「注册即撤销」。
27
+ *
28
+ * ## 为什么必须有这一层(2026-11-24 真机事故)
29
+ *
30
+ * 宿主 `WebServer.register()` 只把 disposer **返回**给调用方,**自己不代管**
31
+ * (`dsh-host-webserver` 逐字:同路径第二次注册 `throw new Error('webserver: duplicate … route')`;
32
+ * 同类的 `listen()` 反而走 `ctx.effect` ⇒ **拆卸登记是调用方的责任**)。
33
+ *
34
+ * 我们此前 11 处注册**全部丢弃返回值** ⇒ 路由挂在宿主表上、插件卸下时无人摘除。
35
+ * 后果不是"泄漏一点内存":同一进程内再装配一次就撞上那条 throw,
36
+ * 而宿主对插件抛错的处理是**整份插件判失败** ⇒ 工具面与附带服务面一起消失,
37
+ * 而宿主本身照常运行(现象:ACC「突然没了」)。
38
+ *
39
+ * ## 形态
40
+ *
41
+ * 返回一个与 `ctx.webServer` 同形的对象,`register()` 内部照旧调用真宿主并把
42
+ * disposer 交给 `registerDisposer`。既有调用点**只改传入的对象**,路由定义一个字不动。
43
+ *
44
+ * @param ctx 宿主插件上下文(交给 `registerDisposer` 登记拆卸)
45
+ * @param label 日志标签,指明是哪一面
46
+ * @param webServer 真宿主服务(可能是测试替身)
47
+ * @returns 同形对象;`effect` 不可用时仍照常注册(响亮降级,见 `registerDisposer`)
48
+ */
49
+ export declare function withRouteDisposal<T extends object>(ctx: unknown, label: string, webServer: T): T;
package/lib/index.js CHANGED
@@ -2,18 +2,16 @@ import { i as __toESM, n as __exportAll } from "./rolldown-runtime-B4iAMlE-.js";
2
2
  import { d as hostSessions, f as hostSettings, i as cccRootForExec, m as hostWebServer, n as agentCwdFor, o as listCccs, p as hostWeb, r as cccRootForCwd, t as NO_CCC_FROM_AGENT_CWD, u as hostService } from "./ccc-roots-B6dJON2X.js";
3
3
  import { a as findSerenityRoot$1, d as readCccName, g as resolveInside, l as pathInside, m as readUserQuotesEnabled, p as readTrajectorySubscriptions, s as loadSerenityConfig, t as DEFAULT_SERENITY_CONFIG_PATHS } from "./ccc-DSMqTrRU.js";
4
4
  import { A as useSession, C as resolveSessionByTitle, D as showSession, E as setActiveSessionInfo, F as isoLocal, I as localFileStamp, M as TRAJECTORY_LEGACY_FILENAMES, O as summarize, S as readTrajectoryUid, T as sessionsRoot, _ as listSessions, b as parseTrajectoryCode, c as UID_FILENAME, d as createSession, j as TRAJECTORY_FILENAME, k as trajectoryDescOf, l as archiveSession, m as getActiveSessionInfo, o as COGNITIVE_TRAJECTORY_ACTIONS, p as findSession, u as clearActiveSessionInfo, v as namingTitleFor, w as sessionEvents, y as parseSessionContextFromEvents } from "./bind-file-Dy6Qmm7z.js";
5
- import { n as checkLocalstoreGitCompliance, o as readStore, s as runLocalStore, t as LOCALSTORE_SCOPES } from "./service-BRUHmVFn.js";
6
- import { d as findPackageRoot, i as constraintSystemPromptSource, l as resolveConstraintSystemPrompt, r as constraintCognitiveTrajectory, t as TRAJECTORY_CONSTRAINT_HINT, u as ACC_VERSION } from "./rules-BYeykzys.js";
7
- import { C as docsPointer, S as runMsmAsync, _ as CCC_CONFIG_REFERENCE, a as setSafeMode, b as loadMsmEntries, d as forgetNonCccToolVisibility, g as ACC_CATALOG, h as forgetToolVisibility, i as readDshVersion, m as syncToolVisibility, n as summarizeHostContract, o as listOpencodeSkillDirs, p as registerGuards, r as getStatus, s as loadOpencodeSkill, t as hostContractReport, w as setWeixinSendEndpoint, x as runMsm, y as findEntry } from "./contract-Mxgh_fl4.js";
5
+ import { _ as readStore, a as readFeishuCredential, c as readWeixinSettings, d as weixinInboundDir, f as weixinSessionIdForTrajectory, i as matchWeixinRoute, m as checkLocalstoreGitCompliance, n as extractWeixinText, p as LOCALSTORE_SCOPES, r as hasVoiceItem, s as readWeixinCredential, t as extractWeixinMedia, u as sanitizeFileName$1, v as runLocalStore } from "./route-BGKbuE3M.js";
6
+ import { C as findPackageRoot, S as ACC_VERSION, _ as constraintCognitiveTrajectory, d as imChannelIds, f as isImWiredTrajectory, h as TRAJECTORY_CONSTRAINT_HINT, i as forgetNonCccToolVisibility, l as syncToolVisibility, m as runImBridge, p as registerImChannel, s as registerGuards, u as forgetToolVisibility, v as constraintSystemPromptSource, x as resolveConstraintSystemPrompt } from "./guards-is79hFAc.js";
7
+ import { a as setSafeMode, c as ACC_CATALOG, d as findEntry, f as loadMsmEntries, g as setWeixinSendEndpoint, h as docsPointer, i as readDshVersion, l as CCC_CONFIG_REFERENCE, m as runMsmAsync, n as summarizeHostContract, o as listOpencodeSkillDirs, p as runMsm, r as getStatus, s as loadOpencodeSkill, t as hostContractReport } from "./contract-DXaIXQvh.js";
8
8
  import { c as replacesDefaultIdentity, i as listTrajectoryConstraints, l as trajectoryCodeForSession, n as findDirNameByCode, o as readTrajectoryConstraintAt, r as isTrajectoryConstrained, s as readTrajectoryConstraintByCode, t as TRAJECTORY_CONSTRAINT_FILENAME } from "./profile-CRcW3ifg.js";
9
- import { A as TRAJECTORY_PROMPT_FILENAME, C as recordToolUsage, D as buildResourceNameSuffix, E as buildResourceIndex, O as isSafeSkillName, S as verifyTotpCode, T as SKILL_ONTOLOGY_FILE, _ as projectKnownWorkspaces, a as trajectoryConstraintFor, b as FACE_PORTS, c as trajectoryWorkspaceMdPath, d as splitModel, f as registerCognitiveTrajectorySkillSection, g as migrateLegacyLocalstore, h as applyWirePatch, i as getTrajectoryAgent, j as hasTrajectoryPrompt, k as truncateContent, l as unregisterTrajectorySession, m as registerEntrySkillSectionGlobal, n as deliverToTrajectory, o as trajectoryConstraintMsmGate, p as registerEntrySkillSection, r as ensureWorkspacePromptSection, s as trajectoryConstraintParticipates, t as createTrajectoryAgent, u as workspaceCognitiveTrajectoryLine, v as readAdvancedSettings, w as REFERENCE_DIR, x as MECHANISM_PORTS, y as toWire } from "./session-BMaTNjK1.js";
9
+ import { A as TRAJECTORY_PROMPT_FILENAME, C as recordToolUsage, D as buildResourceNameSuffix, E as buildResourceIndex, O as isSafeSkillName, S as verifyTotpCode, T as SKILL_ONTOLOGY_FILE, _ as projectKnownWorkspaces, a as trajectoryConstraintFor, b as FACE_PORTS, c as trajectoryWorkspaceMdPath, d as splitModel, f as registerCognitiveTrajectorySkillSection, g as migrateLegacyLocalstore, h as applyWirePatch, i as getTrajectoryAgent, j as hasTrajectoryPrompt, k as truncateContent, l as unregisterTrajectorySession, m as registerEntrySkillSectionGlobal, n as deliverToTrajectory, o as trajectoryConstraintMsmGate, p as registerEntrySkillSection, r as ensureWorkspacePromptSection, s as trajectoryConstraintParticipates, t as createTrajectoryAgent, u as workspaceCognitiveTrajectoryLine, v as readAdvancedSettings, w as REFERENCE_DIR, x as MECHANISM_PORTS, y as toWire } from "./session-BTOngenk.js";
10
10
  import { d as readLastBound, f as resolveSessionCognitiveTrajectoryLabel, i as toMessage, l as findTrajectoryOfSession, n as deliver, o as PLUGIN_SOURCE, r as makeInjection, s as appendBound, u as listBoundSessionIds } from "./injection-ME-aoZVl.js";
11
- import { c as buildCroSnapshot, d as WAKE_CATCH_UP_MS, f as addWake, i as sendToCognitiveTrajectory, n as registerWakeScheduler, o as registerCroTurnTracking, s as registerDisposer, t as createAndBindTarget, u as CARRIER_OPENING_MARK } from "./scheduler-pOtONqPy.js";
11
+ import { c as withRouteDisposal, d as CARRIER_OPENING_MARK, f as WAKE_CATCH_UP_MS, i as sendToCognitiveTrajectory, l as buildCroSnapshot, n as registerWakeScheduler, o as registerCroTurnTracking, p as addWake, s as registerDisposer, t as createAndBindTarget } from "./scheduler-4EvElf11.js";
12
12
  import { i as hostAliveProbe, n as readSimpleSettings, r as registerSettingsSection } from "./settings-YC-csZus.js";
13
- import { a as readFeishuCredential, c as readWeixinSettings, d as weixinInboundDir, f as weixinSessionIdForTrajectory, i as matchWeixinRoute, n as extractWeixinText, r as hasVoiceItem, s as readWeixinCredential, t as extractWeixinMedia, u as sanitizeFileName$1 } from "./route-DcUo9alz.js";
14
- import { i as runImBridge, n as isImWiredTrajectory, r as registerImChannel, t as imChannelIds } from "./channels-Covd8vLQ.js";
15
- import { a as ACK_PREFIX, c as eventToken, i as resolveSessionMdPath, l as DEFAULT_FAKE_INITIAL_MESSAGES, o as ASSISTANT_PREFIX, r as registerRebuildTurnHook, s as LOG_FILE_REL, t as buildRebuildAnchor, u as registerBootstrap } from "./rebuild-DVVb82zf.js";
16
- import { i as subscriptionStats, n as registerTrajectorySubscriptions, r as subscriptionEval, t as defaultSubscriptionDeps } from "./subscriptions-DBoO0GSO.js";
13
+ import { a as ACK_PREFIX, c as eventToken, i as resolveSessionMdPath, l as DEFAULT_FAKE_INITIAL_MESSAGES, o as ASSISTANT_PREFIX, r as registerRebuildTurnHook, s as LOG_FILE_REL, t as buildRebuildAnchor, u as registerBootstrap } from "./rebuild-bySH_ZPq.js";
14
+ import { i as subscriptionStats, n as registerTrajectorySubscriptions, r as subscriptionEval, t as defaultSubscriptionDeps } from "./subscriptions-BlxA1n2N.js";
17
15
  import { c as sendTextMessage, i as getUpdates, l as sendTyping, n as downloadMedia, o as markdownToPlainText, r as getConfig, s as sendFileMessage, t as TypingStatus, u as sniffImageExt } from "./ilink-CsZ-f64q.js";
18
16
  import { a as registerImAccountImpl, i as normalizeAccountChannel, n as getImAccountImpl, r as imAccountChannels } from "./accounts-BHQbakUh.js";
19
17
  import { createRequire } from "node:module";
@@ -514,7 +512,7 @@ const KIT_ACTIONS = [
514
512
  async function runKit(root, args, hostCtx) {
515
513
  switch (args.action) {
516
514
  case "health": {
517
- const { containerStatus } = await import("./observation-8iVgMHVC.js");
515
+ const { containerStatus } = await import("./observation-BU6BZjsW.js");
518
516
  const s = containerStatus({
519
517
  root,
520
518
  hostCtx
@@ -560,7 +558,7 @@ async function runKit(root, args, hostCtx) {
560
558
  }
561
559
  case "diag": {
562
560
  if (hostCtx === void 0) throw new Error("diag requires the plugin context (live session data unavailable without it)");
563
- const { runDiag, renderDiag } = await import("./service-CWNPCS5c.js");
561
+ const { runDiag, renderDiag } = await import("./service-C3vpKGcT.js");
564
562
  return renderDiag(await runDiag(hostCtx, root ?? ""));
565
563
  }
566
564
  default: throw new Error(`Unknown action: ${args.action}`);
@@ -6700,7 +6698,7 @@ function createCognitiveTrajectoryTool(ctx) {
6700
6698
  } catch {}
6701
6699
  }
6702
6700
  }
6703
- const { queueRebuild } = await import("./rebuild-DVVb82zf.js").then((n) => n.n);
6701
+ const { queueRebuild } = await import("./rebuild-bySH_ZPq.js").then((n) => n.n);
6704
6702
  const result = await queueRebuild(ctx, {
6705
6703
  root,
6706
6704
  note: args.note,
@@ -9674,7 +9672,8 @@ function resolveWorkspace(ctx, params) {
9674
9672
  }
9675
9673
  function registerStatusApi(ctx, opts = {}) {
9676
9674
  const configPaths = opts.configPaths ?? DEFAULT_SERENITY_CONFIG_PATHS;
9677
- ctx.webServer.register({
9675
+ const webServer = withRouteDisposal(ctx, "serenity status api routes", ctx.webServer);
9676
+ webServer.register({
9678
9677
  kind: "exact",
9679
9678
  path: UPLOAD_PATH,
9680
9679
  handler: async (req, res) => {
@@ -9701,7 +9700,7 @@ function registerStatusApi(ctx, opts = {}) {
9701
9700
  }
9702
9701
  }
9703
9702
  });
9704
- ctx.webServer.register({
9703
+ webServer.register({
9705
9704
  kind: "exact",
9706
9705
  path: FILE_UPLOAD_PATH,
9707
9706
  handler: async (req, res) => {
@@ -9728,7 +9727,7 @@ function registerStatusApi(ctx, opts = {}) {
9728
9727
  }
9729
9728
  }
9730
9729
  });
9731
- ctx.webServer.register({
9730
+ webServer.register({
9732
9731
  kind: "exact",
9733
9732
  path: ROUTE_PATH,
9734
9733
  handler: async (req, res) => {
@@ -9777,7 +9776,7 @@ function registerStatusApi(ctx, opts = {}) {
9777
9776
  }
9778
9777
  }
9779
9778
  });
9780
- ctx.webServer.register({
9779
+ webServer.register({
9781
9780
  kind: "exact",
9782
9781
  path: CONFIG_PATH,
9783
9782
  handler: async (req, res) => {
@@ -9812,7 +9811,7 @@ function registerStatusApi(ctx, opts = {}) {
9812
9811
  }
9813
9812
  }
9814
9813
  });
9815
- ctx.webServer.register({
9814
+ webServer.register({
9816
9815
  kind: "exact",
9817
9816
  path: CCCS_PATH,
9818
9817
  handler: async (req, res) => {
@@ -9836,7 +9835,7 @@ function registerStatusApi(ctx, opts = {}) {
9836
9835
  }
9837
9836
  }
9838
9837
  });
9839
- ctx.webServer.register({
9838
+ webServer.register({
9840
9839
  kind: "exact",
9841
9840
  path: SUBSCRIPTIONS_PATH,
9842
9841
  handler: async (req, res) => {
@@ -9873,7 +9872,7 @@ function registerStatusApi(ctx, opts = {}) {
9873
9872
  }
9874
9873
  }
9875
9874
  });
9876
- ctx.webServer.register({
9875
+ webServer.register({
9877
9876
  kind: "exact",
9878
9877
  path: WEIXIN_PATH,
9879
9878
  handler: async (req, res) => {
@@ -9886,11 +9885,11 @@ function registerStatusApi(ctx, opts = {}) {
9886
9885
  sendJson$2(res, 400, { error: chk.error });
9887
9886
  return;
9888
9887
  }
9889
- const { readWeixinSettings } = await import("./route-DcUo9alz.js").then((n) => n.l);
9888
+ const { readWeixinSettings } = await import("./route-BGKbuE3M.js").then((n) => n.l);
9890
9889
  const { weixinBridgeStatus } = await Promise.resolve().then(() => bridge_exports);
9891
9890
  const settings = readWeixinSettings(chk.root);
9892
9891
  const bridge = weixinBridgeStatus().find((b) => b.ccc === chk.root);
9893
- const { imCredentialBound } = await import("./route-DcUo9alz.js").then((n) => n.l);
9892
+ const { imCredentialBound } = await import("./route-BGKbuE3M.js").then((n) => n.l);
9894
9893
  const { normalizeAccountChannel } = await import("./accounts-BHQbakUh.js").then((n) => n.t);
9895
9894
  const accounts = (settings.accounts ?? []).map((a) => {
9896
9895
  const channel = normalizeAccountChannel(a.channel);
@@ -9927,7 +9926,7 @@ function registerStatusApi(ctx, opts = {}) {
9927
9926
  const { fetchQRCode } = await import("./ilink-CsZ-f64q.js").then((n) => n.a);
9928
9927
  const { randomUUID } = await import("node:crypto");
9929
9928
  for (const [key, v] of weixinLogins) if (Date.now() - v.startedAt > WEIXIN_LOGIN_TTL_MS) weixinLogins.delete(key);
9930
- const { readWeixinSettings } = await import("./route-DcUo9alz.js").then((n) => n.l);
9929
+ const { readWeixinSettings } = await import("./route-BGKbuE3M.js").then((n) => n.l);
9931
9930
  const qr = await fetchQRCode({ botType: readWeixinSettings(root).botType ?? void 0 });
9932
9931
  const loginKey = randomUUID();
9933
9932
  weixinLogins.set(loginKey, {
@@ -9948,7 +9947,7 @@ function registerStatusApi(ctx, opts = {}) {
9948
9947
  sendJson$2(res, 400, { error: "missing accountId" });
9949
9948
  return;
9950
9949
  }
9951
- const { removeWeixinAccount } = await import("./route-DcUo9alz.js").then((n) => n.l);
9950
+ const { removeWeixinAccount } = await import("./route-BGKbuE3M.js").then((n) => n.l);
9952
9951
  const { syncCccBridge } = await Promise.resolve().then(() => bridge_exports);
9953
9952
  removeWeixinAccount(root, body.accountId);
9954
9953
  syncCccBridge(ctx, root);
@@ -9974,7 +9973,7 @@ function registerStatusApi(ctx, opts = {}) {
9974
9973
  trajectory: code
9975
9974
  });
9976
9975
  }
9977
- const { saveWeixinRoutes } = await import("./route-DcUo9alz.js").then((n) => n.l);
9976
+ const { saveWeixinRoutes } = await import("./route-BGKbuE3M.js").then((n) => n.l);
9978
9977
  const { findDirNameByCode } = await import("./profile-CRcW3ifg.js").then((n) => n.a);
9979
9978
  for (const r of routes) if (findDirNameByCode(root, r.trajectory) === null) {
9980
9979
  sendJson$2(res, 400, { error: `unknown trajectory: ${r.trajectory} (no such trajectory code in ${root})` });
@@ -9986,7 +9985,7 @@ function registerStatusApi(ctx, opts = {}) {
9986
9985
  }
9987
9986
  if (body.action === "set-enabled") {
9988
9987
  const enabled = body.enabled === true;
9989
- const { readWeixinSettings, setWeixinEnabled } = await import("./route-DcUo9alz.js").then((n) => n.l);
9988
+ const { readWeixinSettings, setWeixinEnabled } = await import("./route-BGKbuE3M.js").then((n) => n.l);
9990
9989
  const { syncCccBridge } = await Promise.resolve().then(() => bridge_exports);
9991
9990
  const settings = readWeixinSettings(root);
9992
9991
  if (enabled && (settings.accounts ?? []).length === 0) {
@@ -10009,7 +10008,7 @@ function registerStatusApi(ctx, opts = {}) {
10009
10008
  sendJson$2(res, 400, { error: "appId 与 appSecret 都必须填(只填一个等于没绑)" });
10010
10009
  return;
10011
10010
  }
10012
- const { readWeixinSettings, upsertWeixinAccount, writeFeishuCredential, nextFeishuAccountId } = await import("./route-DcUo9alz.js").then((n) => n.l);
10011
+ const { readWeixinSettings, upsertWeixinAccount, writeFeishuCredential, nextFeishuAccountId } = await import("./route-BGKbuE3M.js").then((n) => n.l);
10013
10012
  const { syncCccBridge } = await Promise.resolve().then(() => bridge_exports);
10014
10013
  const before = readWeixinSettings(root);
10015
10014
  const accountId = (body.accountId ?? "").trim() !== "" ? body.accountId.trim() : nextFeishuAccountId(before);
@@ -10037,7 +10036,7 @@ function registerStatusApi(ctx, opts = {}) {
10037
10036
  }
10038
10037
  }
10039
10038
  });
10040
- ctx.webServer.register({
10039
+ webServer.register({
10041
10040
  kind: "exact",
10042
10041
  path: `${WEIXIN_PATH}/login`,
10043
10042
  handler: async (req, res) => {
@@ -10059,7 +10058,7 @@ function registerStatusApi(ctx, opts = {}) {
10059
10058
  return;
10060
10059
  }
10061
10060
  const { pollQRStatus } = await import("./ilink-CsZ-f64q.js").then((n) => n.a);
10062
- const { readWeixinSettings } = await import("./route-DcUo9alz.js").then((n) => n.l);
10061
+ const { readWeixinSettings } = await import("./route-BGKbuE3M.js").then((n) => n.l);
10063
10062
  const settings = readWeixinSettings(login.root);
10064
10063
  const status = await pollQRStatus({
10065
10064
  baseUrl: void 0,
@@ -10074,7 +10073,7 @@ function registerStatusApi(ctx, opts = {}) {
10074
10073
  });
10075
10074
  return;
10076
10075
  }
10077
- const { upsertWeixinAccount, writeWeixinCredential, nextWeixinAccountId } = await import("./route-DcUo9alz.js").then((n) => n.l);
10076
+ const { upsertWeixinAccount, writeWeixinCredential, nextWeixinAccountId } = await import("./route-BGKbuE3M.js").then((n) => n.l);
10078
10077
  const { syncCccBridge } = await Promise.resolve().then(() => bridge_exports);
10079
10078
  const accountId = nextWeixinAccountId(settings);
10080
10079
  upsertWeixinAccount(login.root, {
@@ -10109,7 +10108,7 @@ function registerStatusApi(ctx, opts = {}) {
10109
10108
  }
10110
10109
  }
10111
10110
  });
10112
- ctx.webServer.register({
10111
+ webServer.register({
10113
10112
  kind: "exact",
10114
10113
  path: "/serenity/session-cleanup",
10115
10114
  handler: async (req, res) => {
@@ -10371,7 +10370,7 @@ function sendJson$1(res, status, body) {
10371
10370
  * 显示的还是 home-serenity 的信息」)。不传 ⇒ 不注入(保持资产原样 = 旧行为)。
10372
10371
  */
10373
10372
  function registerVoyageApi(ctx, opts = {}) {
10374
- ctx.webServer.register({
10373
+ withRouteDisposal(ctx, "serenity voyage api route", ctx.webServer).register({
10375
10374
  kind: "exact",
10376
10375
  path: VOYAGE_PATH,
10377
10376
  handler: (req, res) => {
@@ -1,7 +1,7 @@
1
1
  import { d as readCccName, i as findGitRoot, l as pathInside, s as loadSerenityConfig, t as DEFAULT_SERENITY_CONFIG_PATHS } from "./ccc-DSMqTrRU.js";
2
- import { u as ACC_VERSION } from "./rules-BYeykzys.js";
3
- import { i as readDshVersion, t as hostContractReport, v as checkRegistryQuality } from "./contract-Mxgh_fl4.js";
4
- import { a as wakeSchedulerState, p as listWakes } from "./scheduler-pOtONqPy.js";
2
+ import { S as ACC_VERSION } from "./guards-is79hFAc.js";
3
+ import { i as readDshVersion, t as hostContractReport, u as checkRegistryQuality } from "./contract-DXaIXQvh.js";
4
+ import { a as wakeSchedulerState, m as listWakes } from "./scheduler-4EvElf11.js";
5
5
  import { resolve } from "node:path";
6
6
  import { existsSync, readFileSync, statSync } from "node:fs";
7
7
  //#region src/surface/observation.ts
@@ -2,7 +2,7 @@ import { n as __exportAll } from "./rolldown-runtime-B4iAMlE-.js";
2
2
  import { n as agentCwdFor, r as cccRootForCwd, u as hostService } from "./ccc-roots-B6dJON2X.js";
3
3
  import { F as isoLocal, b as parseTrajectoryCode, f as extractSessionMdPathFromText, m as getActiveSessionInfo, v as namingTitleFor, w as sessionEvents, y as parseSessionContextFromEvents } from "./bind-file-Dy6Qmm7z.js";
4
4
  import { c as replacesDefaultIdentity } from "./profile-CRcW3ifg.js";
5
- import { a as trajectoryConstraintFor } from "./session-BMaTNjK1.js";
5
+ import { a as trajectoryConstraintFor } from "./session-BTOngenk.js";
6
6
  import { a as ACC_MESSAGE_KIND, d as readLastBound, n as deliver, r as makeInjection, s as appendBound } from "./injection-ME-aoZVl.js";
7
7
  import { basename, dirname, join, resolve } from "node:path";
8
8
  import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
@@ -1,9 +1,286 @@
1
1
  import { n as __exportAll } from "./rolldown-runtime-B4iAMlE-.js";
2
2
  import { s as loadSerenityConfig, t as DEFAULT_SERENITY_CONFIG_PATHS } from "./ccc-DSMqTrRU.js";
3
- import { c as unsetEntry, l as writeEntry, r as getEntry } from "./service-BRUHmVFn.js";
4
3
  import { join, resolve } from "node:path";
5
4
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
5
  import { createHash } from "node:crypto";
6
+ //#region src/tools/localstore/service.ts
7
+ /**
8
+ * tools/localstore/service.ts — localstore 纯逻辑层(零 DSH 依赖,可独立单测)
9
+ *
10
+ * S134 重设计(v1.16.7):存储从 ~/.serenity/ 迁到 **CCC 根根目录 localstore.json**
11
+ * (JSON 格式——方便 MSM 直接 read + JSON.parse 读取,零解析依赖)。
12
+ *
13
+ * git 提交策略(可靠机制 × 用户自由):
14
+ * - 配置:.opencode/serenity.json `localstore.gitTrack`: "allow"(可提交)| "deny"(禁提交)
15
+ * - **缺省 deny(没配就是不提交)**;且 deny 的保证**不依赖 dsh 运行**——
16
+ * 写入时自动确保 .gitignore 含 localstore.json(物理保证:即使 dsh 不在、
17
+ * 用户手动 git commit 也不会误提交),container_git 检查为第二道防线(拒绝 + 提示)
18
+ * - allow:放行(文件可提交,用户自行管理 .gitignore)
19
+ *
20
+ * 存储结构(JSON 顶层分节):
21
+ * { "credentials": { "HOME_GITLAB_TOKEN": "xxx" }, "<config节>": { "<key>": "v" } }
22
+ * credentials 为保留节(credential 命名空间,key 大写蛇形);其余节归 config 命名空间
23
+ * (path = section.key,如 my-feature.someKey)。
24
+ */
25
+ const LOCALSTORE_SCOPES = ["credential", "config"];
26
+ /** 存储文件名(CCC 根根目录) */
27
+ const LOCALSTORE_FILENAME = "localstore.json";
28
+ /** 凭据保留节名(JSON 顶层) */
29
+ const CREDENTIALS_SECTION = "credentials";
30
+ /** 凭据 key 规范:大写蛇形,如 HOME_GITLAB_TOKEN */
31
+ const CREDENTIAL_KEY_RE = /^[A-Z][A-Z0-9_]*$/;
32
+ /** 配置节名规范:小写字母数字连字符 */
33
+ const CONFIG_SECTION_RE = /^[a-z][a-z0-9-]*$/;
34
+ /** 配置 key 规范(节内):小驼峰,如 defaultModel */
35
+ const CONFIG_KEY_RE = /^[a-z][a-zA-Z0-9_]*$/;
36
+ /** 存储文件绝对路径(CCC 根根目录) */
37
+ function localstorePath(root) {
38
+ return join(root, LOCALSTORE_FILENAME);
39
+ }
40
+ /** git 策略:serenity.json localstore.gitTrack,缺省 deny(不提交) */
41
+ function readGitTrack(root, paths = DEFAULT_SERENITY_CONFIG_PATHS) {
42
+ return loadSerenityConfig(root, paths).localstore?.gitTrack === "allow" ? "allow" : "deny";
43
+ }
44
+ /** .gitignore 是否已覆盖 localstore 文件(非空非注释行含文件名即算) */
45
+ function isLocalstoreGitignored(root) {
46
+ const gi = join(root, ".gitignore");
47
+ if (!existsSync(gi)) return false;
48
+ return readFileSync(gi, "utf-8").split("\n").some((l) => {
49
+ const t = l.trim();
50
+ return t !== "" && !t.startsWith("#") && t.includes("localstore.json");
51
+ });
52
+ }
53
+ /**
54
+ * 确保 .gitignore 含 localstore 文件(deny 时的物理保证,不依赖 dsh 运行):
55
+ * 写入 localstore 时调用——deny(含缺省)且 .gitignore 未覆盖 → 自动追加一行。
56
+ * allow → 不写入(放行,文件可提交)。
57
+ */
58
+ function ensureLocalstoreGitignored(root) {
59
+ if (readGitTrack(root) === "allow") return { status: "allow" };
60
+ if (isLocalstoreGitignored(root)) return { status: "ignored" };
61
+ const gi = join(root, ".gitignore");
62
+ const existing = existsSync(gi) ? readFileSync(gi, "utf-8") : "";
63
+ const line = `${LOCALSTORE_FILENAME} # ACC localstore (localstore.gitTrack defaults to deny — do not commit)`;
64
+ writeFileSync(gi, (existing.endsWith("\n") || existing === "" ? existing : existing + "\n") + line + "\n", "utf-8");
65
+ return { status: "appended" };
66
+ }
67
+ /**
68
+ * container_git 联动检查(第二道防线):文件存在 && deny && .gitignore 未覆盖 → 不通过。
69
+ * 调用方(container_git commit)据此拒绝提交;status 可输出 warning。
70
+ */
71
+ function checkLocalstoreGitCompliance(root) {
72
+ if (!existsSync(localstorePath(root))) return { ok: true };
73
+ if (readGitTrack(root) === "allow") return { ok: true };
74
+ if (isLocalstoreGitignored(root)) return { ok: true };
75
+ return {
76
+ ok: false,
77
+ reason: `localstore.json must not be committed (localstore.gitTrack=deny default) but .gitignore does not cover it — add ${LOCALSTORE_FILENAME} to .gitignore (or set localstore.gitTrack=allow to explicitly permit)`
78
+ };
79
+ }
80
+ /** 已告警的坏 localstore 路径(进程级去重;F-07:凭据文件损坏不得静默) */
81
+ const warnedBrokenStores = /* @__PURE__ */ new Set();
82
+ /** 读取全文件(顶层分节);文件不存在 → 空;**坏 JSON → 空 + 响亮告警**(每路径一次) */
83
+ function readAll(root) {
84
+ const p = localstorePath(root);
85
+ if (!existsSync(p)) return {};
86
+ try {
87
+ const v = JSON.parse(readFileSync(p, "utf-8").replace(/^\uFEFF/, ""));
88
+ if (v && typeof v === "object" && !Array.isArray(v)) return v;
89
+ return {};
90
+ } catch (err) {
91
+ if (!warnedBrokenStores.has(p)) {
92
+ warnedBrokenStores.add(p);
93
+ console.warn(`[serenity-hooks] ✗ localstore 解析失败,已按空存储继续(其中凭据/配置对工具表现为"未设置",请修 JSON): ${p} — ${String(err?.message ?? err)}`);
94
+ }
95
+ return {};
96
+ }
97
+ }
98
+ /** 写回全文件(2 空格缩进 + 尾换行,方便 MSM 直接读取) */
99
+ function writeAll(root, data) {
100
+ writeFileSync(localstorePath(root), JSON.stringify(data, null, 2) + "\n", "utf-8");
101
+ }
102
+ /** 读取命名空间全部条目:credential → 扁平;config → 分节(剔除 credentials 保留节) */
103
+ function readStore(root, scope) {
104
+ const all = readAll(root);
105
+ if (scope === "credential") return all[CREDENTIALS_SECTION] ?? {};
106
+ const { [CREDENTIALS_SECTION]: _cred, ...rest } = all;
107
+ return rest;
108
+ }
109
+ /** 校验凭据 key 合法(大写蛇形);不合法抛错 */
110
+ function assertCredentialKey(key) {
111
+ if (!CREDENTIAL_KEY_RE.test(key)) throw new Error(`credential key "${key}" must match UPPER_SNAKE ^[A-Z][A-Z0-9_]*$ (e.g. HOME_GITLAB_TOKEN)`);
112
+ }
113
+ /** 校验 config 路径(节.key);不合法抛错 */
114
+ function assertConfigPath(path) {
115
+ const idx = path.indexOf(".");
116
+ if (idx <= 0 || idx === path.length - 1) throw new Error(`config path "${path}" must be section.key (e.g. my-feature.someKey)`);
117
+ const section = path.slice(0, idx);
118
+ const key = path.slice(idx + 1);
119
+ if (!CONFIG_SECTION_RE.test(section)) throw new Error(`config section "${section}" must match ^[a-z][a-z0-9-]*$`);
120
+ if (!CONFIG_KEY_RE.test(key)) throw new Error(`config key "${key}" must match lowerCamel ^[a-z][a-zA-Z0-9_]*$ (e.g. defaultModel)`);
121
+ return {
122
+ section,
123
+ key
124
+ };
125
+ }
126
+ /** 写入单个条目(自动建文件;deny 默认时同步确保 .gitignore 物理保证) */
127
+ function writeEntry(root, scope, name, value) {
128
+ const all = readAll(root);
129
+ if (scope === "credential") {
130
+ assertCredentialKey(name);
131
+ all[CREDENTIALS_SECTION] ??= {};
132
+ all[CREDENTIALS_SECTION][name] = value;
133
+ } else {
134
+ const { section, key } = assertConfigPath(name);
135
+ all[section] ??= {};
136
+ all[section][key] = value;
137
+ }
138
+ writeAll(root, all);
139
+ ensureLocalstoreGitignored(root);
140
+ }
141
+ /** 删除单个条目(不存在返回 false);空节自动移除 */
142
+ function unsetEntry(root, scope, name) {
143
+ const all = readAll(root);
144
+ if (scope === "credential") {
145
+ assertCredentialKey(name);
146
+ const sec = all[CREDENTIALS_SECTION];
147
+ if (!sec || !(name in sec)) return false;
148
+ delete sec[name];
149
+ if (Object.keys(sec).length === 0) delete all[CREDENTIALS_SECTION];
150
+ } else {
151
+ const { section, key } = assertConfigPath(name);
152
+ const sec = all[section];
153
+ if (!sec || !(key in sec)) return false;
154
+ delete sec[key];
155
+ if (Object.keys(sec).length === 0) delete all[section];
156
+ }
157
+ writeAll(root, all);
158
+ return true;
159
+ }
160
+ /** 读取单个条目值;不存在返回 null */
161
+ function getEntry(root, scope, name) {
162
+ const all = readAll(root);
163
+ if (scope === "credential") {
164
+ assertCredentialKey(name);
165
+ return all[CREDENTIALS_SECTION]?.[name] ?? null;
166
+ }
167
+ const { section, key } = assertConfigPath(name);
168
+ return all[section]?.[key] ?? null;
169
+ }
170
+ /** 列出 key(凭据只返回 key 名,不返回值) */
171
+ function listKeys(root, scope) {
172
+ const data = readStore(root, scope);
173
+ if (scope === "credential") return Object.keys(data);
174
+ return Object.entries(data).flatMap(([section, entries]) => Object.keys(entries).map((key) => `${section}.${key}`));
175
+ }
176
+ /**
177
+ * doc 说明文本:输出存储位置/格式/key 规范/git 策略/读写方法。
178
+ * agent 据此可直接用 fs 工具(read/write)自己读写凭据/配置。
179
+ */
180
+ function docText(root) {
181
+ const path = localstorePath(root);
182
+ return [
183
+ "# localstore — ACC local credential/config storage (standard, S134 redesign)",
184
+ "",
185
+ "One tool manages two namespaces: credential (credentials) + config (preferences).",
186
+ `Stored at the CCC root in ${path} (JSON format; MSMs can read + JSON.parse directly).`,
187
+ "",
188
+ "## Git commit policy",
189
+ "- Config: .opencode/serenity.json `localstore.gitTrack`: `\"allow\"` (may commit) | `\"deny\"` (must not commit; .dsh fallback)",
190
+ "- **Default deny (unset = not committed)**; when deny, writes automatically ensure .gitignore contains localstore.json",
191
+ " (physical guarantee, independent of dsh runtime); container_git commit checks and refuses",
192
+ "- To commit: set `\"localstore\": { \"gitTrack\": \"allow\" }` and remove localstore.json from .gitignore",
193
+ "",
194
+ "## Format (JSON top-level sections)",
195
+ "```json",
196
+ "{",
197
+ " \"credentials\": {",
198
+ " \"HOME_GITLAB_TOKEN\": \"xxx\"",
199
+ " },",
200
+ " \"my-feature\": {",
201
+ " \"someKey\": \"some-value\"",
202
+ " }",
203
+ "}",
204
+ "```",
205
+ "- credentials is a reserved section (credentials, UPPER_SNAKE keys); other sections = config (path = section.key)",
206
+ "",
207
+ "## Key conventions",
208
+ "- credential key: ^[A-Z][A-Z0-9_]*$ (e.g. HOME_GITLAB_TOKEN)",
209
+ "- config path: section.key (section ^[a-z][a-z0-9-]*$, key lowerCamel ^[a-z][a-zA-Z0-9_]*$, e.g. my-feature.someKey)",
210
+ "",
211
+ "## Reading (agents may use fs tools directly)",
212
+ `- Read ${path} with the read tool → JSON.parse`,
213
+ "- Or use localstore get <name> [--scope credential|config]",
214
+ "",
215
+ "## Writing",
216
+ "- Recommended: localstore set <name> <value> [--scope ...] (auto-creates file / preserves other entries / syncs .gitignore)",
217
+ "- Or modify the file directly with write/edit, keeping the JSON valid",
218
+ "",
219
+ "## Security boundary",
220
+ "- list/show return only key names for credentials, never values",
221
+ "- Credential values should be used internally by the agent; never write them into conversation or logs",
222
+ "- Default deny: the file is not committed to git (.gitignore physical guarantee + container_git check fallback)",
223
+ ""
224
+ ].join("\n");
225
+ }
226
+ /** 运行 localstore 操作(纯逻辑;返回 JSON 值供工具 render) */
227
+ function runLocalStore(root, args) {
228
+ const scope = args.scope === "config" ? "config" : "credential";
229
+ switch (args.action) {
230
+ case "list": return {
231
+ scope,
232
+ keys: listKeys(root, scope)
233
+ };
234
+ case "get": {
235
+ if (!args.name) throw new Error("get requires name");
236
+ const value = getEntry(root, scope, args.name);
237
+ if (value === null) throw new Error(`not found: ${args.name} (scope=${scope})`);
238
+ return {
239
+ scope,
240
+ name: args.name,
241
+ value,
242
+ source: scope
243
+ };
244
+ }
245
+ case "set": {
246
+ if (!args.name) throw new Error("set requires name");
247
+ if (args.value === void 0) throw new Error("set requires value");
248
+ writeEntry(root, scope, args.name, args.value);
249
+ const git = checkLocalstoreGitCompliance(root);
250
+ return {
251
+ scope,
252
+ name: args.name,
253
+ set: true,
254
+ path: localstorePath(root),
255
+ gitTrack: readGitTrack(root),
256
+ gitOk: git.ok,
257
+ git: git.reason ? { warning: git.reason } : null
258
+ };
259
+ }
260
+ case "unset": {
261
+ if (!args.name) throw new Error("unset requires name");
262
+ const removed = unsetEntry(root, scope, args.name);
263
+ return {
264
+ scope,
265
+ name: args.name,
266
+ removed
267
+ };
268
+ }
269
+ case "show": {
270
+ if (!args.name) throw new Error("show requires name");
271
+ const exists = getEntry(root, scope, args.name) !== null;
272
+ return {
273
+ scope,
274
+ name: args.name,
275
+ exists,
276
+ path: localstorePath(root)
277
+ };
278
+ }
279
+ case "doc": return { doc: docText(root) };
280
+ default: throw new Error(`Unknown subcommand: ${args.action} (available: list/get/set/unset/show/doc)`);
281
+ }
282
+ }
283
+ //#endregion
7
284
  //#region src/im/route.ts
8
285
  /**
9
286
  * im/route.ts — 微信桥 CCC 配置层纯逻辑(F4c-3,v1.27.0 实验性)
@@ -430,4 +707,4 @@ function setWeixinEnabled(root, enabled) {
430
707
  return next;
431
708
  }
432
709
  //#endregion
433
- export { readFeishuCredential as a, readWeixinSettings as c, weixinInboundDir as d, weixinSessionIdForTrajectory as f, matchWeixinRoute as i, route_exports as l, extractWeixinText as n, readImSettings as o, hasVoiceItem as r, readWeixinCredential as s, extractWeixinMedia as t, sanitizeFileName as u };
710
+ export { readStore as _, readFeishuCredential as a, readWeixinSettings as c, weixinInboundDir as d, weixinSessionIdForTrajectory as f, readGitTrack as g, localstorePath as h, matchWeixinRoute as i, route_exports as l, checkLocalstoreGitCompliance as m, extractWeixinText as n, readImSettings as o, LOCALSTORE_SCOPES as p, hasVoiceItem as r, readWeixinCredential as s, extractWeixinMedia as t, sanitizeFileName as u, runLocalStore as v };
@@ -1167,6 +1167,49 @@ function registerDisposer(ctx, label, cleanup) {
1167
1167
  return false;
1168
1168
  }
1169
1169
  }
1170
+ /**
1171
+ * 把一个 HTTP 路由注册器包成「注册即撤销」。
1172
+ *
1173
+ * ## 为什么必须有这一层(2026-11-24 真机事故)
1174
+ *
1175
+ * 宿主 `WebServer.register()` 只把 disposer **返回**给调用方,**自己不代管**
1176
+ * (`dsh-host-webserver` 逐字:同路径第二次注册 `throw new Error('webserver: duplicate … route')`;
1177
+ * 同类的 `listen()` 反而走 `ctx.effect` ⇒ **拆卸登记是调用方的责任**)。
1178
+ *
1179
+ * 我们此前 11 处注册**全部丢弃返回值** ⇒ 路由挂在宿主表上、插件卸下时无人摘除。
1180
+ * 后果不是"泄漏一点内存":同一进程内再装配一次就撞上那条 throw,
1181
+ * 而宿主对插件抛错的处理是**整份插件判失败** ⇒ 工具面与附带服务面一起消失,
1182
+ * 而宿主本身照常运行(现象:ACC「突然没了」)。
1183
+ *
1184
+ * ## 形态
1185
+ *
1186
+ * 返回一个与 `ctx.webServer` 同形的对象,`register()` 内部照旧调用真宿主并把
1187
+ * disposer 交给 `registerDisposer`。既有调用点**只改传入的对象**,路由定义一个字不动。
1188
+ *
1189
+ * @param ctx 宿主插件上下文(交给 `registerDisposer` 登记拆卸)
1190
+ * @param label 日志标签,指明是哪一面
1191
+ * @param webServer 真宿主服务(可能是测试替身)
1192
+ * @returns 同形对象;`effect` 不可用时仍照常注册(响亮降级,见 `registerDisposer`)
1193
+ */
1194
+ function withRouteDisposal(ctx, label, webServer) {
1195
+ const real = webServer;
1196
+ const disposers = [];
1197
+ registerDisposer(ctx, label, () => {
1198
+ for (let i = disposers.length - 1; i >= 0; i--) try {
1199
+ disposers[i]?.();
1200
+ } catch (err) {
1201
+ console.warn(`[serenity-hooks] ✗ 路由摘除失败(${label} #${i}): ${String(err?.message ?? err)}`);
1202
+ }
1203
+ disposers.length = 0;
1204
+ });
1205
+ const proxy = Object.create(webServer);
1206
+ proxy.register = ((route) => {
1207
+ const dispose = real.register(route);
1208
+ if (typeof dispose === "function") disposers.push(dispose);
1209
+ return dispose;
1210
+ });
1211
+ return proxy;
1212
+ }
1170
1213
  //#endregion
1171
1214
  //#region src/cro/turns.ts
1172
1215
  /**
@@ -3787,4 +3830,4 @@ function registerWakeScheduler(ctx) {
3787
3830
  registerDisposer(ctx, "认知轨迹唤醒调度器", () => clock.dispose());
3788
3831
  }
3789
3832
  //#endregion
3790
- export { wakeSchedulerState as a, buildCroSnapshot as c, WAKE_CATCH_UP_MS as d, addWake as f, sendToCognitiveTrajectory as i, listCroCognitiveTrajectories as l, registerWakeScheduler as n, registerCroTurnTracking as o, listWakes as p, scheduler_exports as r, registerDisposer as s, createAndBindTarget as t, CARRIER_OPENING_MARK as u };
3833
+ export { wakeSchedulerState as a, withRouteDisposal as c, CARRIER_OPENING_MARK as d, WAKE_CATCH_UP_MS as f, sendToCognitiveTrajectory as i, buildCroSnapshot as l, listWakes as m, registerWakeScheduler as n, registerCroTurnTracking as o, addWake as p, scheduler_exports as r, registerDisposer as s, createAndBindTarget as t, listCroCognitiveTrajectories as u };