@jiyr0119/dsh-service-console 0.9.0 → 0.11.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.
Files changed (56) hide show
  1. package/README.md +22 -6
  2. package/README.zh.md +8 -3
  3. package/assets/service-console-0.11.0.png +0 -0
  4. package/docs/DETAIL.md +1 -0
  5. package/docs/DETAIL.zh.md +1 -0
  6. package/docs/awesome-submission.yml +7 -9
  7. package/docs/compatibility.zh.md +24 -0
  8. package/docs/preview.svg +65 -0
  9. package/docs/rc5-upgrade-review.zh.md +16 -0
  10. package/docs/troubleshooting.zh.md +33 -0
  11. package/docs/user-guide.zh.md +33 -0
  12. package/icon.svg +4 -4
  13. package/lib/client/dictionaries.js +12 -0
  14. package/lib/client/locales/de.js +91 -0
  15. package/lib/client/locales/es.js +91 -0
  16. package/lib/client/locales/fr.js +91 -0
  17. package/lib/client/locales/ja.js +91 -0
  18. package/lib/client/locales/pt.js +91 -0
  19. package/lib/client/locales/ru.js +91 -0
  20. package/lib/client.js +641 -66
  21. package/lib/host/config-schema.js +45 -0
  22. package/lib/host/config.js +80 -27
  23. package/lib/host/ledger-projection.js +223 -0
  24. package/lib/host/ownership.js +2 -1
  25. package/lib/host/process-inspector.js +174 -49
  26. package/lib/host/service-registry.js +5 -4
  27. package/lib/host/service-tool.js +3 -1
  28. package/lib/host/snapshot-cache.js +59 -0
  29. package/lib/index.js +157 -24
  30. package/lib/types/client/ServiceConsole.d.ts +2 -0
  31. package/lib/types/client/dictionaries.d.ts +12 -0
  32. package/lib/types/client/locales/de.d.ts +89 -0
  33. package/lib/types/client/locales/es.d.ts +89 -0
  34. package/lib/types/client/locales/fr.d.ts +89 -0
  35. package/lib/types/client/locales/ja.d.ts +89 -0
  36. package/lib/types/client/locales/pt.d.ts +89 -0
  37. package/lib/types/client/locales/ru.d.ts +89 -0
  38. package/lib/types/host/config-schema.d.ts +52 -0
  39. package/lib/types/host/config.d.ts +27 -2
  40. package/lib/types/host/ledger-projection.d.ts +98 -0
  41. package/lib/types/host/process-inspector.d.ts +51 -2
  42. package/lib/types/host/service-registry.d.ts +1 -1
  43. package/lib/types/host/service-tool.d.ts +1 -1
  44. package/lib/types/host/snapshot-cache.d.ts +39 -0
  45. package/lib/types/host/types.d.ts +9 -0
  46. package/lib/types/index.d.ts +26 -1
  47. package/locale/de.json +7 -0
  48. package/locale/en.json +2 -1
  49. package/locale/es.json +7 -0
  50. package/locale/fr.json +7 -0
  51. package/locale/ja.json +7 -0
  52. package/locale/pt.json +7 -0
  53. package/locale/ru.json +7 -0
  54. package/locale/zh.json +2 -1
  55. package/package.json +16 -7
  56. package/assets/service-console-0.2.0.gif +0 -0
@@ -1,4 +1,4 @@
1
- import { execFileSync } from "node:child_process";
1
+ import { execFile, execFileSync } from "node:child_process";
2
2
  // src/host/process-inspector.ts
3
3
  const MONTHS = {
4
4
  Jan: 1,
@@ -14,6 +14,42 @@ const MONTHS = {
14
14
  Nov: 11,
15
15
  Dec: 12
16
16
  };
17
+ /**
18
+ * 异步命令执行(可取消):`execFile('/bin/sh', ['-c', …])` + `signal`。
19
+ *
20
+ * 扫描链路上的一切命令都必须走这里——`execFileSync` 无法响应取消,
21
+ * 面板的 8s 超时与模型的 `exec.signal` 都只能等进程自己结束。
22
+ * 取消/超时按「已结束但输出不完整」返回(code 125),由上层记为 partial。
23
+ */
24
+ function runCommandAsync(command, timeoutMs = 5e3, signal) {
25
+ return new Promise((resolve) => {
26
+ execFile("/bin/sh", ["-c", command], {
27
+ encoding: "utf8",
28
+ timeout: timeoutMs,
29
+ signal,
30
+ maxBuffer: 16777216
31
+ }, (error, stdout, stderr) => {
32
+ if (!error) {
33
+ resolve({
34
+ stdout: String(stdout ?? ""),
35
+ stderr: String(stderr ?? ""),
36
+ code: 0
37
+ });
38
+ return;
39
+ }
40
+ const e = error;
41
+ const aborted = signal?.aborted === true || e.name === "AbortError";
42
+ const timedOut = e.killed === true && aborted !== true;
43
+ const exitCode = typeof e.code === "number" ? e.code : typeof e.status === "number" ? e.status : 1;
44
+ const stderrText = String(stderr ?? "");
45
+ resolve({
46
+ stdout: String(stdout ?? ""),
47
+ stderr: stderrText !== "" ? stderrText : String(e.message ?? ""),
48
+ code: aborted || timedOut ? 125 : exitCode
49
+ });
50
+ });
51
+ });
52
+ }
17
53
  function runCommand(command, timeoutMs) {
18
54
  try {
19
55
  return {
@@ -39,6 +75,79 @@ function runCommand(command, timeoutMs) {
39
75
  };
40
76
  }
41
77
  }
78
+ /**
79
+ * 解析 `lsof -F<fields>` 输出(每条记录:p/c/f/n 前缀行)。
80
+ * @param stdout lsof 字段模式输出
81
+ */
82
+ function parseLsofFieldOutput(stdout) {
83
+ const rows = [];
84
+ let current = null;
85
+ let pendingFd = null;
86
+ for (const line of String(stdout).split("\n")) {
87
+ if (line === "") continue;
88
+ const tag = line.slice(0, 1);
89
+ const value = line.slice(1);
90
+ if (tag === "p") {
91
+ const pid = parseInt(value, 10);
92
+ if (!Number.isFinite(pid)) {
93
+ current = null;
94
+ pendingFd = null;
95
+ continue;
96
+ }
97
+ current = {
98
+ pid,
99
+ command: "",
100
+ names: [],
101
+ cwd: null
102
+ };
103
+ rows.push(current);
104
+ pendingFd = null;
105
+ continue;
106
+ }
107
+ if (current === null) continue;
108
+ if (tag === "c") current.command = value;
109
+ else if (tag === "f") pendingFd = value;
110
+ else if (tag === "n") {
111
+ if (pendingFd === "cwd") current.cwd = value;
112
+ else current.names.push(value);
113
+ }
114
+ }
115
+ return rows.filter((row) => Number.isFinite(row.pid));
116
+ }
117
+ /**
118
+ * 解析 `ps -o pid=,ppid=,pgid=,lstart=,command= -p <pids>` 的单次合并输出。
119
+ * lstart 固定占 5 个 token(Www Mmm D HH:MM:SS YYYY),command 是余下全部。
120
+ * @param stdout ps 输出
121
+ */
122
+ function parsePsCombined(stdout) {
123
+ const rows = [];
124
+ for (const line of String(stdout).split("\n")) {
125
+ const t = line.trim();
126
+ if (t === "") continue;
127
+ const parts = t.split(/\s+/);
128
+ if (parts.length < 10) continue;
129
+ const pid = parseInt(parts[0], 10);
130
+ const ppid = parseInt(parts[1], 10);
131
+ const pgid = parseInt(parts[2], 10);
132
+ if (!Number.isFinite(pid) || !Number.isFinite(ppid)) continue;
133
+ const user = parts[3] || null;
134
+ const lstart = parts.slice(4, 9).join(" ");
135
+ rows.push({
136
+ pid,
137
+ ppid,
138
+ pgid: Number.isFinite(pgid) ? pgid : null,
139
+ user,
140
+ lstart,
141
+ startedAt: parseLstart(lstart),
142
+ command: parts.slice(9).join(" ")
143
+ });
144
+ }
145
+ return rows;
146
+ }
147
+ /** 地址语法推断协议:`[::1]:80` / `[fe80::1]:80` 视为 tcp6,其余 tcp */
148
+ function protocolOfAddress(address) {
149
+ return address.startsWith("[") ? "tcp6" : "tcp";
150
+ }
42
151
  function parseLstart(str) {
43
152
  const parts = String(str).trim().split(/\s+/);
44
153
  if (parts.length < 5) return null;
@@ -112,66 +221,82 @@ function parseAddress(addr) {
112
221
  function shellQuote(s) {
113
222
  return "'" + String(s).replace(/'/g, "'\\''") + "'";
114
223
  }
115
- async function scanRaw(commandRunner = runCommand) {
224
+ async function scanRaw(commandRunner = runCommandAsync, signal, commandTimeoutMs = 5e3) {
116
225
  const partialWarnings = [];
117
- const tcp = await commandRunner("lsof -nP -iTCP -sTCP:LISTEN", 5e3);
118
- if (tcp.code !== 0 && tcp.code !== null && tcp.code !== 1) partialWarnings.push("TCP listener scan exit=" + String(tcp.code));
119
- const rows = parseListenRows(tcp.stdout);
120
- const pids = [...new Set(rows.map((r) => r.pid))];
121
- const pidList = pids.join(",");
122
- const procs = /* @__PURE__ */ new Map();
123
- if (pids.length > 0) {
124
- const psRes = await commandRunner("ps -o pid=,ppid=,lstart=,command= -p " + pidList, 5e3);
125
- const psRows = parsePsRows(psRes.stdout);
126
- if (psRes.code !== 0 && psRes.code !== null) partialWarnings.push("ps detail partial");
127
- const pgidRes = await commandRunner("ps -o pid=,pgid= -p " + pidList, 5e3);
128
- const pgidMap = /* @__PURE__ */ new Map();
129
- for (const line of String(pgidRes.stdout).split("\n")) {
130
- const parts = line.trim().split(/\s+/);
131
- if (parts.length >= 2) {
132
- const p = parseInt(parts[0], 10);
133
- const g = parseInt(parts[1], 10);
134
- if (Number.isFinite(p) && Number.isFinite(g)) pgidMap.set(p, g);
135
- }
136
- }
137
- let cwdByPid = /* @__PURE__ */ new Map();
138
- const cwdRes = await commandRunner("lsof -a -p " + pidList + " -d cwd", 5e3);
139
- for (const line of String(cwdRes.stdout).split("\n")) {
140
- const t = line.trim();
141
- if (!t || t.startsWith("COMMAND")) continue;
142
- const m = t.match(/^(\S+)\s+(\d+)\s+(\S+)\s+cwd\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.+)$/);
143
- if (m) cwdByPid.set(parseInt(m[2], 10), m[8].trim());
144
- }
145
- if (cwdRes.code !== 0 && cwdRes.code !== null) partialWarnings.push("cwd scan partial");
146
- const nameOf = (r) => {
147
- return String(r.command).split(/\s+/)[0] || null;
226
+ const run = (command) => commandRunner(command, commandTimeoutMs, signal);
227
+ const tcp = await run("lsof -nP -iTCP -sTCP:LISTEN -Fpcn");
228
+ let scanError = null;
229
+ if (tcp.code === 125) {
230
+ partialWarnings.push("TCP listener scan aborted");
231
+ scanError = {
232
+ code: "SCAN_TIMEOUT",
233
+ message: "scan aborted (timeout or cancellation)"
234
+ };
235
+ } else if (tcp.code === 1 && tcp.stderr.trim() !== "") {
236
+ partialWarnings.push("TCP listener scan exit=1 with stderr");
237
+ const denied = /permission denied|operation not permitted/i.test(tcp.stderr);
238
+ scanError = {
239
+ code: denied ? "PERMISSION_DENIED" : "SCAN_FAILED",
240
+ message: denied ? "lsof was denied permission to list sockets" : "lsof exited with 1: " + tcp.stderr.trim().slice(0, 200)
241
+ };
242
+ } else if (tcp.code !== 0 && tcp.code !== null && tcp.code !== 1) {
243
+ partialWarnings.push("TCP listener scan exit=" + String(tcp.code));
244
+ const denied = /permission denied|operation not permitted/i.test(tcp.stderr);
245
+ scanError = {
246
+ code: denied ? "PERMISSION_DENIED" : "SCAN_FAILED",
247
+ message: denied ? "lsof was denied permission to list sockets" : "lsof exited with " + String(tcp.code)
148
248
  };
149
- for (const r of psRows) procs.set(r.pid, {
150
- pid: r.pid,
151
- ppid: r.ppid,
152
- startedAt: r.startedAt,
153
- command: r.command || null,
154
- name: nameOf(r),
155
- pgid: pgidMap.get(r.pid) ?? null,
156
- cwd: cwdByPid.get(r.pid) ?? null
157
- });
158
249
  }
250
+ const groups = parseLsofFieldOutput(tcp.stdout);
159
251
  const listeners = [];
160
- for (const r of rows) {
161
- const { host, port } = parseAddress(r.address);
252
+ const pidSet = /* @__PURE__ */ new Set();
253
+ const seenListeners = /* @__PURE__ */ new Set();
254
+ for (const group of groups) for (const name of group.names) {
255
+ const { host, port } = parseAddress(name);
162
256
  if (host === null || port === null) continue;
257
+ const protocol = protocolOfAddress(name);
258
+ const key = group.pid + "|" + host + "|" + port + "|" + protocol;
259
+ if (seenListeners.has(key)) continue;
260
+ seenListeners.add(key);
163
261
  listeners.push({
164
- pid: r.pid,
262
+ pid: group.pid,
165
263
  host,
166
264
  port,
167
- protocol: r.type === "IPv6" ? "tcp6" : "tcp",
168
- user: r.user || null
265
+ protocol,
266
+ user: null
169
267
  });
268
+ pidSet.add(group.pid);
269
+ }
270
+ const procs = /* @__PURE__ */ new Map();
271
+ if (pidSet.size > 0) {
272
+ const pidList = [...pidSet].join(",");
273
+ const [cwdRes, psRes] = await Promise.all([run("lsof -a -p " + pidList + " -d cwd -Fpcn"), run("ps -ww -o pid=,ppid=,pgid=,user=,lstart=,command= -p " + pidList)]);
274
+ if (cwdRes.code === 125) partialWarnings.push("cwd scan aborted");
275
+ else if (cwdRes.code !== 0 && cwdRes.code !== null) partialWarnings.push("cwd scan partial");
276
+ const cwdByPid = /* @__PURE__ */ new Map();
277
+ for (const group of parseLsofFieldOutput(cwdRes.stdout)) if (group.cwd !== null) cwdByPid.set(group.pid, group.cwd);
278
+ if (psRes.code === 125) partialWarnings.push("ps detail aborted");
279
+ else if (psRes.code !== 0 && psRes.code !== null) partialWarnings.push("ps detail partial");
280
+ for (const row of parsePsCombined(psRes.stdout)) {
281
+ const first = String(row.command).split(/\s+/)[0];
282
+ procs.set(row.pid, {
283
+ pid: row.pid,
284
+ ppid: row.ppid,
285
+ startedAt: row.startedAt,
286
+ command: row.command || null,
287
+ name: first || null,
288
+ pgid: row.pgid,
289
+ cwd: cwdByPid.get(row.pid) ?? null,
290
+ user: row.user
291
+ });
292
+ }
293
+ for (const listener of listeners) listener.user = procs.get(listener.pid)?.user ?? null;
170
294
  }
171
295
  return {
172
296
  listeners,
173
297
  procs,
174
- partialWarnings
298
+ partialWarnings,
299
+ scanError
175
300
  };
176
301
  }
177
- export { parseAddress, parseListenRows, parseLstart, parsePsRows, runCommand, scanRaw, shellQuote };
302
+ export { parseAddress, parseListenRows, parseLsofFieldOutput, parseLstart, parsePsCombined, parsePsRows, protocolOfAddress, runCommand, runCommandAsync, scanRaw, shellQuote };
@@ -1,4 +1,4 @@
1
- import { runCommand, scanRaw } from "./process-inspector.js";
1
+ import { runCommandAsync, scanRaw } from "./process-inspector.js";
2
2
  import { redact } from "./redaction.js";
3
3
  import { classifyOwnership } from "./ownership.js";
4
4
  import { classifyProtection } from "./protection.js";
@@ -10,8 +10,8 @@ function sha256Hex(input) {
10
10
  function isLocalhost(host) {
11
11
  return host === "127.0.0.1" || host === "::1" || host === "localhost";
12
12
  }
13
- async function buildSnapshot(ledgers, workspaces, commandRunner = runCommand, guard = {}, context = {}) {
14
- const raw = await scanRaw(commandRunner);
13
+ async function buildSnapshot(ledgers, workspaces, commandRunner = runCommandAsync, guard = {}, context = {}, signal, commandTimeoutMs) {
14
+ const raw = await scanRaw(commandRunner, signal, commandTimeoutMs);
15
15
  const byPid = /* @__PURE__ */ new Map();
16
16
  for (const l of raw.listeners) {
17
17
  if (!byPid.has(l.pid)) byPid.set(l.pid, []);
@@ -77,7 +77,8 @@ async function buildSnapshot(ledgers, workspaces, commandRunner = runCommand, gu
77
77
  count: services.length,
78
78
  services,
79
79
  partialWarnings: raw.partialWarnings,
80
- ledgerCount: ledgers.length
80
+ ledgerCount: ledgers.length,
81
+ scanError: raw.scanError ?? null
81
82
  };
82
83
  }
83
84
  export { buildSnapshot };
@@ -148,6 +148,7 @@ function buildServiceTool(deps) {
148
148
  }
149
149
  },
150
150
  isConcurrencySafe: () => true,
151
+ timeoutMs: 15e3,
151
152
  presentCall: () => ({
152
153
  card: "generic",
153
154
  title: "List local services",
@@ -162,7 +163,8 @@ function buildServiceTool(deps) {
162
163
  },
163
164
  async execute(args, exec) {
164
165
  const sessionId = exec?.agent?.id ?? null;
165
- const snap = await deps.snapshot(sessionId);
166
+ const snap = await deps.snapshot(sessionId, exec?.signal);
167
+ if (snap.scanError) throw new Error(snap.scanError.code + ": " + snap.scanError.message);
166
168
  let rows = snap.services;
167
169
  if (args.ownership !== void 0) rows = rows.filter((s) => s.ownership === args.ownership);
168
170
  if (args.query) {
@@ -0,0 +1,59 @@
1
+ // src/host/snapshot-cache.ts
2
+ var SnapshotCache = class {
3
+ entries = /* @__PURE__ */ new Map();
4
+ inflight = /* @__PURE__ */ new Map();
5
+ ttlMs;
6
+ staleWhileErrorMs;
7
+ now;
8
+ constructor(options = {}) {
9
+ this.ttlMs = options.ttlMs ?? 1e3;
10
+ this.staleWhileErrorMs = options.staleWhileErrorMs ?? 5e3;
11
+ this.now = options.now ?? Date.now;
12
+ }
13
+ /**
14
+ * 取缓存或加载一次。
15
+ * @param key 缓存键(含 sessionId:归属按调用方会话收窄)
16
+ * @param load 真实加载函数
17
+ */
18
+ async get(key, load) {
19
+ const hit = this.entries.get(key);
20
+ if (hit !== void 0 && this.now() - hit.at < this.ttlMs) return {
21
+ value: hit.value,
22
+ stale: false
23
+ };
24
+ let pending = this.inflight.get(key);
25
+ if (pending === void 0) {
26
+ pending = load().then((value) => {
27
+ this.entries.set(key, {
28
+ at: this.now(),
29
+ value
30
+ });
31
+ return value;
32
+ });
33
+ this.inflight.set(key, pending);
34
+ const clear = () => {
35
+ this.inflight.delete(key);
36
+ };
37
+ pending.then(clear, clear);
38
+ }
39
+ try {
40
+ return {
41
+ value: await pending,
42
+ stale: false
43
+ };
44
+ } catch (error) {
45
+ const prev = this.entries.get(key);
46
+ if (prev !== void 0 && this.now() - prev.at < this.staleWhileErrorMs) return {
47
+ value: prev.value,
48
+ stale: true
49
+ };
50
+ throw error;
51
+ }
52
+ }
53
+ /** 失效一个键(stop/restart 后调用);不传则清空。 */
54
+ invalidate(key) {
55
+ if (key === void 0) this.entries.clear();
56
+ else this.entries.delete(key);
57
+ }
58
+ };
59
+ export { SnapshotCache };
package/lib/index.js CHANGED
@@ -1,8 +1,12 @@
1
1
  import { SessionLedger } from "./host/ledger.js";
2
+ import { createLedgerProjection, entriesOf } from "./host/ledger-projection.js";
2
3
  import { buildSnapshot } from "./host/service-registry.js";
4
+ import { redact } from "./host/redaction.js";
3
5
  import { restartService, stopService } from "./host/lifecycle.js";
4
6
  import { buildServiceTool } from "./host/service-tool.js";
5
- import { loadConfigFromFile, saveConfigToFile, validateConfigPatch } from "./host/config.js";
7
+ import { normalizeConfig, readConfigFile, saveConfigToFile, validateConfigPatch } from "./host/config.js";
8
+ import { Config } from "./host/config-schema.js";
9
+ import { SnapshotCache } from "./host/snapshot-cache.js";
6
10
  // src/index.ts
7
11
  async function readJsonBody(req) {
8
12
  try {
@@ -21,6 +25,22 @@ function sendJson(res, status, payload) {
21
25
  r.writeHead(status, { "content-type": "application/json; charset=utf-8" });
22
26
  r.end(JSON.stringify(payload));
23
27
  }
28
+ /** 错误码 → HTTP 状态(客户端只读信封,但状态码让日志/代理可读) */
29
+ function errorStatus(code) {
30
+ switch (code) {
31
+ case "TARGET_GONE": return 404;
32
+ case "FORBIDDEN_REMOTE": return 403;
33
+ case "BAD_REQUEST": return 400;
34
+ case "PROTECTED_PROCESS": return 409;
35
+ case "RESTART_UNSAFE": return 409;
36
+ case "UNKNOWN_OWNERSHIP": return 409;
37
+ case "GRACEFUL_TIMEOUT": return 504;
38
+ case "SCAN_TIMEOUT": return 504;
39
+ case "PERMISSION_DENIED": return 403;
40
+ case "SCAN_FAILED": return 503;
41
+ default: return 500;
42
+ }
43
+ }
24
44
  /**
25
45
  * 调用方是否来自本机回环。
26
46
  *
@@ -41,13 +61,69 @@ function isLoopbackCaller(remoteAddress) {
41
61
  }
42
62
  var src_default = {
43
63
  inject: ["timer", "webServer"],
44
- apply(ctx) {
64
+ /** rc.5 契约:组合行里的 `config:` 由 Loader 用这份 schema 校验 */
65
+ Config,
66
+ apply(ctx, rowConfig = {}) {
45
67
  const workspaceRegistry = ctx.get("workspaceRegistry");
46
68
  const timer = ctx.timer;
47
69
  const ledger = new SessionLedger();
70
+ let ledgerHandle = null;
71
+ ctx.inject(["sessionProjections"], (sub) => {
72
+ const projections = sub.get("sessionProjections");
73
+ if (projections === void 0) return;
74
+ sub.effect(() => {
75
+ let disposed = false;
76
+ let pending = null;
77
+ projections.register(createLedgerProjection((command) => redact(command))).then((handle) => {
78
+ if (disposed) {
79
+ handle.dispose();
80
+ return;
81
+ }
82
+ pending = handle;
83
+ ledgerHandle = handle;
84
+ if (process.env.DSH_SC_DEBUG === "1") console.log("[dsh-sc] ledger projection registered: serviceConsoleLedger");
85
+ }).catch((error) => {
86
+ console.warn("[dsh-service-console] ledger projection unavailable:", String(error));
87
+ });
88
+ return () => {
89
+ disposed = true;
90
+ ledgerHandle = null;
91
+ if (pending !== null) pending.dispose();
92
+ };
93
+ }, "service-console: ledger projection");
94
+ });
95
+ /** 已观察到的会话(扫描带 sessionId 时记录),供无会话时的合并视图使用 */
96
+ const observedSessions = /* @__PURE__ */ new Set();
97
+ /** 合并视图:所有已观察会话的投影条目 + 内存台账(有界) */
98
+ function allLedgerEntries() {
99
+ const merged = [...ledger.list];
100
+ if (ledgerHandle !== null) {
101
+ const sessions = ctx.get("sessions");
102
+ for (const id of observedSessions) try {
103
+ const session = sessions?.get(id);
104
+ if (session === void 0) continue;
105
+ const entries = entriesOf(ledgerHandle.stateOf(session));
106
+ for (const entry of entries) if (!merged.includes(entry)) merged.push(entry);
107
+ } catch {}
108
+ }
109
+ return merged.slice(-400);
110
+ }
111
+ /** 某会话的台账条目:优先投影(重启/fork 正确),否则退回内存台账 */
112
+ function ledgerEntriesFor(sessionId) {
113
+ const sessions = ctx.get("sessions");
114
+ if (sessionId === null || ledgerHandle === null || sessions === void 0) return ledger.list;
115
+ try {
116
+ const session = sessions.get(sessionId);
117
+ if (session === void 0) return ledger.list;
118
+ return entriesOf(ledgerHandle.stateOf(session));
119
+ } catch {
120
+ return ledger.list;
121
+ }
122
+ }
48
123
  const on = ctx.on;
49
124
  on("tools/result", (exec) => ledger.observe(exec));
50
- let config = loadConfigFromFile();
125
+ let overrides = readConfigFile();
126
+ let config = normalizeConfig(overrides, rowConfig);
51
127
  const actionLog = [];
52
128
  const logAction = (serviceId, action, result, code = null) => {
53
129
  actionLog.push({
@@ -63,7 +139,7 @@ var src_default = {
63
139
  timer,
64
140
  config,
65
141
  buildSnapshot: snapshot,
66
- ledgerList: () => ledger.list,
142
+ ledgerList: () => allLedgerEntries(),
67
143
  logAction
68
144
  };
69
145
  let workspacesCache = [];
@@ -87,27 +163,69 @@ var src_default = {
87
163
  } catch {}
88
164
  return guard;
89
165
  }
90
- /** 快照(可带调用方会话 id → 「本次对话」归属按 sessionKey 收窄) */
91
- function snapshot(sessionId) {
92
- return buildSnapshot(ledger.list, workspaces(), void 0, protectionGuard(), { sessionId: sessionId ?? null });
166
+ /**
167
+ * 快照(可带调用方会话 id → 「本次对话」归属按 sessionKey 收窄)。
168
+ * @param sessionId 调用方会话
169
+ * @param signal 取消信号(路由 deadline / 工具 exec.signal)
170
+ */
171
+ function snapshot(sessionId, signal) {
172
+ return buildSnapshot(ledgerEntriesFor(sessionId ?? null), workspaces(), void 0, protectionGuard(), { sessionId: sessionId ?? null }, signal, config.commandTimeoutMs);
173
+ }
174
+ /** 扫描结果缓存(两个客户端共用一次扫描;1s TTL + single-flight) */
175
+ const scanCache = new SnapshotCache({ ttlMs: 1e3 });
176
+ /** 一次 HTTP 请求的扫描 deadline(宿主命令已改为可取消,超时会真正中止子进程) */
177
+ const scanDeadlineMs = () => config.scanTimeoutMs;
178
+ async function snapshotWithDeadline(sessionId, signal) {
179
+ const controller = new AbortController();
180
+ const timer = setTimeout(() => controller.abort(), scanDeadlineMs());
181
+ const onAbort = () => controller.abort();
182
+ signal?.addEventListener("abort", onAbort, { once: true });
183
+ try {
184
+ return (await scanCache.get(sessionId ?? "__machine__", async () => {
185
+ const data = await snapshot(sessionId, controller.signal);
186
+ if (data.scanError) {
187
+ const error = new Error(data.scanError.message);
188
+ error.code = data.scanError.code;
189
+ throw error;
190
+ }
191
+ return data;
192
+ })).value;
193
+ } finally {
194
+ clearTimeout(timer);
195
+ signal?.removeEventListener("abort", onAbort);
196
+ }
93
197
  }
94
198
  /** 请求体里的会话 id(可缺省:HTTP/旧客户端保持启发式归属) */
95
199
  function sessionIdOf(args) {
96
200
  const v = args?.sessionId;
97
- return typeof v === "string" && v !== "" ? v : null;
201
+ if (typeof v !== "string" || v === "") return null;
202
+ observedSessions.add(v);
203
+ return v;
98
204
  }
99
205
  const routes = [
100
206
  {
101
207
  path: "/dsh-sc/api/services/scan",
102
- handler: async (args) => ({
103
- ok: true,
104
- data: await snapshot(sessionIdOf(args))
105
- })
208
+ handler: async (args, info) => {
209
+ try {
210
+ return {
211
+ ok: true,
212
+ data: await snapshotWithDeadline(sessionIdOf(args), info.signal)
213
+ };
214
+ } catch (error) {
215
+ return {
216
+ ok: false,
217
+ error: {
218
+ code: error.code ?? "SCAN_FAILED",
219
+ message: String(error?.message ?? error)
220
+ }
221
+ };
222
+ }
223
+ }
106
224
  },
107
225
  {
108
226
  path: "/dsh-sc/api/services/detail",
109
- handler: async (args) => {
110
- const svc = (await snapshot(sessionIdOf(args))).services.find((x) => x.id === String(args.serviceId ?? ""));
227
+ handler: async (args, info) => {
228
+ const svc = (await snapshotWithDeadline(sessionIdOf(args), info.signal)).services.find((x) => x.id === String(args.serviceId ?? ""));
111
229
  if (!svc) return {
112
230
  ok: false,
113
231
  error: {
@@ -127,12 +245,20 @@ var src_default = {
127
245
  {
128
246
  path: "/dsh-sc/api/services/stop",
129
247
  mutating: true,
130
- handler: async (args) => stopService(deps, String(args.serviceId ?? ""), String(args.mode ?? "graceful"))
248
+ handler: async (args) => {
249
+ const result = await stopService(deps, String(args.serviceId ?? ""), String(args.mode ?? "graceful"));
250
+ scanCache.invalidate();
251
+ return result;
252
+ }
131
253
  },
132
254
  {
133
255
  path: "/dsh-sc/api/services/restart",
134
256
  mutating: true,
135
- handler: async (args) => restartService(deps, String(args.serviceId ?? ""))
257
+ handler: async (args) => {
258
+ const result = await restartService(deps, String(args.serviceId ?? ""));
259
+ scanCache.invalidate();
260
+ return result;
261
+ }
136
262
  },
137
263
  {
138
264
  path: "/dsh-sc/api/config",
@@ -154,11 +280,12 @@ var src_default = {
154
280
  message: v.message
155
281
  }
156
282
  };
157
- config = {
158
- ...config,
283
+ overrides = {
284
+ ...overrides,
159
285
  ...v.next
160
286
  };
161
- saveConfigToFile(config);
287
+ config = normalizeConfig(overrides, rowConfig);
288
+ saveConfigToFile(overrides);
162
289
  return {
163
290
  ok: true,
164
291
  data: { config }
@@ -184,7 +311,12 @@ var src_default = {
184
311
  kind: "exact",
185
312
  path: route.path,
186
313
  handler: async (req, res) => {
187
- const info = { loopback: isLoopbackCaller(req?.socket?.remoteAddress) };
314
+ const abort = new AbortController();
315
+ res.once?.("close", () => abort.abort());
316
+ const info = {
317
+ loopback: isLoopbackCaller(req?.socket?.remoteAddress),
318
+ signal: abort.signal
319
+ };
188
320
  if (route.mutating === true && !info.loopback) {
189
321
  sendJson(res, 403, {
190
322
  ok: false,
@@ -208,13 +340,14 @@ var src_default = {
208
340
  }
209
341
  try {
210
342
  const result = await route.handler(body, info);
211
- sendJson(res, result.ok ? 200 : 400, result);
343
+ sendJson(res, result.ok ? 200 : errorStatus(result.error?.code ?? ""), result);
212
344
  } catch (e) {
345
+ if (process.env.DSH_SC_DEBUG === "1") console.warn("[dsh-sc] route error:", String(e));
213
346
  sendJson(res, 500, {
214
347
  ok: false,
215
348
  error: {
216
349
  code: "INTERNAL",
217
- message: String(e?.message || e)
350
+ message: "internal error"
218
351
  }
219
352
  });
220
353
  }
@@ -228,7 +361,7 @@ var src_default = {
228
361
  const tools = ctx.get("tools");
229
362
  if (tools) ctx.effect(() => {
230
363
  try {
231
- const off = tools.register(buildServiceTool({ snapshot: (sessionId) => snapshot(sessionId) }));
364
+ const off = tools.register(buildServiceTool({ snapshot: (sessionId, signal) => snapshot(sessionId, signal) }));
232
365
  if (process.env.DSH_SC_DEBUG === "1") console.log(`[dsh-sc] service_list registered: ${String(Boolean(tools.get("service_list")))}`);
233
366
  return off;
234
367
  } catch (e) {
@@ -239,4 +372,4 @@ var src_default = {
239
372
  else if (process.env.DSH_SC_DEBUG === "1") console.log("[dsh-sc] tools service absent — service_list not registered");
240
373
  }
241
374
  };
242
- export { src_default as default, isLoopbackCaller };
375
+ export { src_default as default, errorStatus, isLoopbackCaller };
@@ -26,6 +26,8 @@ interface ConfigData {
26
26
  gracefulTimeout: number;
27
27
  showUnknown: boolean;
28
28
  forceKill: boolean;
29
+ /** 宿主扫描预算(毫秒):客户端可见超时与之一致 */
30
+ scanTimeoutMs: number;
29
31
  }
30
32
  export declare function ServiceConsoleEntry({ t, openConsole }: {
31
33
  t: ConsoleT;