@jiyr0119/dsh-service-console 0.6.0 → 0.7.1

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.
@@ -10,10 +10,14 @@ const DEFAULT_CONFIG = {
10
10
  forceKill: false,
11
11
  autoCleanup: false
12
12
  };
13
- const CONFIG_LIMITS = {
14
- refreshInterval: [2e3, 3e4],
15
- gracefulTimeout: [1e3, 15e3]
16
- };
13
+ const REFRESH_INTERVAL_CHOICES = [
14
+ 0,
15
+ 2e3,
16
+ 5e3,
17
+ 1e4,
18
+ 3e4
19
+ ];
20
+ const CONFIG_LIMITS = { gracefulTimeout: [1e3, 15e3] };
17
21
  function configFilePath() {
18
22
  return join(homedir(), ".dsh", "plugins", "dsh-service-console", "config.json");
19
23
  }
@@ -49,6 +53,16 @@ function validateConfigPatch(patch) {
49
53
  next[key] = v;
50
54
  continue;
51
55
  }
56
+ if (key === "refreshInterval") {
57
+ if (typeof v === "number" && REFRESH_INTERVAL_CHOICES.includes(v)) {
58
+ next.refreshInterval = v;
59
+ continue;
60
+ }
61
+ return {
62
+ ok: false,
63
+ message: "invalid value for: " + key
64
+ };
65
+ }
52
66
  if (typeof v === "number" && CONFIG_LIMITS[key]) {
53
67
  if (v < CONFIG_LIMITS[key][0] || v > CONFIG_LIMITS[key][1]) return {
54
68
  ok: false,
@@ -72,4 +86,4 @@ function validateConfigPatch(patch) {
72
86
  };
73
87
  }
74
88
  //#endregion
75
- export { CONFIG_LIMITS, DEFAULT_CONFIG, loadConfigFromFile, saveConfigToFile, validateConfigPatch };
89
+ export { CONFIG_LIMITS, DEFAULT_CONFIG, REFRESH_INTERVAL_CHOICES, loadConfigFromFile, saveConfigToFile, validateConfigPatch };
@@ -41,6 +41,7 @@ async function stopService(deps, serviceId, mode) {
41
41
  async function restartService(deps, serviceId) {
42
42
  const svc = (await deps.buildSnapshot()).services.find((x) => x.id === serviceId);
43
43
  if (!svc) return err("TARGET_GONE", "该服务已结束,列表已刷新");
44
+ if (svc.protected) return err("PROTECTED_PROCESS", "该进程受保护,不能通过 Service Console 操作");
44
45
  if (!svc.restartable) return err("RESTART_UNSAFE", "缺少安全复现启动所需的信息,不能重启");
45
46
  const entry = deps.ledgerList().find((l) => svc.cwd && l.cwd && svc.cwd.indexOf(l.cwd) === 0);
46
47
  if (!entry) return err("RESTART_UNSAFE", "缺少启动命令记录,不能重启");
@@ -164,7 +164,8 @@ async function scanRaw(commandRunner = runCommand) {
164
164
  pid: r.pid,
165
165
  host,
166
166
  port,
167
- protocol: r.type === "IPv6" ? "tcp6" : "tcp"
167
+ protocol: r.type === "IPv6" ? "tcp6" : "tcp",
168
+ user: r.user || null
168
169
  });
169
170
  }
170
171
  return {
@@ -0,0 +1,41 @@
1
+ //#region src/host/protection.ts
2
+ const CRITICAL_NAMES = /* @__PURE__ */ new Set([
3
+ "launchd",
4
+ "kernel_task",
5
+ "init",
6
+ "kthreadd",
7
+ "systemd",
8
+ "sshd",
9
+ "WindowServer",
10
+ "loginwindow"
11
+ ]);
12
+ const SYSTEM_CWD_RE = /^(\/System\/|\/usr\/|\/bin\/|\/sbin\/|\/Library\/|\/private\/etc\/|\/private\/var\/(?!folders|tmp))/;
13
+ const SYSTEM_BIN_RE = /^(\/System\/|\/bin\/|\/sbin\/|\/usr\/bin\/|\/usr\/sbin\/|\/usr\/libexec\/|\/Library\/|\/private\/etc\/)/;
14
+ function basename(cmd) {
15
+ const first = String(cmd || "").trim().split(/\s+/)[0] || "";
16
+ const parts = first.split("/");
17
+ return parts[parts.length - 1] || first;
18
+ }
19
+ function executablePath(cmd) {
20
+ const first = String(cmd || "").trim().split(/\s+/)[0] || "";
21
+ return first.startsWith("/") ? first : "";
22
+ }
23
+ function classifyProtection(proc, guard = {}) {
24
+ const evidence = [];
25
+ if (guard.protectedPids && guard.protectedPids.includes(proc.pid)) evidence.push("Service Console / DSH host process (pid " + String(proc.pid) + ")");
26
+ for (const l of proc.listeners) if (guard.protectedPorts && guard.protectedPorts.includes(l.port)) evidence.push("DSH Web console listens on :" + String(l.port) + " (stopping it would disconnect this UI)");
27
+ if (proc.pid > 0 && proc.pid <= 1) evidence.push("system init process (pid " + String(proc.pid) + ")");
28
+ if (proc.listeners.some((l) => l.user === "root")) evidence.push("high-privilege process (root)");
29
+ const name = basename(proc.command) || proc.name || "";
30
+ if (name && CRITICAL_NAMES.has(name)) evidence.push("system-critical process: " + name);
31
+ if (proc.cwd && SYSTEM_CWD_RE.test(proc.cwd)) evidence.push("system directory cwd: " + proc.cwd);
32
+ const bin = executablePath(proc.command);
33
+ if (bin && SYSTEM_BIN_RE.test(bin)) evidence.push("system binary: " + bin);
34
+ const unique = [...new Set(evidence)];
35
+ return {
36
+ protected: unique.length > 0,
37
+ evidence: unique
38
+ };
39
+ }
40
+ //#endregion
41
+ export { classifyProtection };
@@ -1,6 +1,7 @@
1
1
  import { redact } from "./redaction.js";
2
2
  import { runCommand, scanRaw } from "./process-inspector.js";
3
3
  import { classifyOwnership } from "./ownership.js";
4
+ import { classifyProtection } from "./protection.js";
4
5
  import { createHash } from "node:crypto";
5
6
  //#region src/host/service-registry.ts
6
7
  function sha256Hex(input) {
@@ -9,7 +10,7 @@ function sha256Hex(input) {
9
10
  function isLocalhost(host) {
10
11
  return host === "127.0.0.1" || host === "::1" || host === "localhost";
11
12
  }
12
- async function buildSnapshot(ledgers, workspaces, commandRunner = runCommand) {
13
+ async function buildSnapshot(ledgers, workspaces, commandRunner = runCommand, guard = {}) {
13
14
  const raw = await scanRaw(commandRunner);
14
15
  const byPid = /* @__PURE__ */ new Map();
15
16
  for (const l of raw.listeners) {
@@ -17,7 +18,8 @@ async function buildSnapshot(ledgers, workspaces, commandRunner = runCommand) {
17
18
  byPid.get(l.pid).push({
18
19
  host: l.host,
19
20
  port: l.port,
20
- protocol: l.protocol
21
+ protocol: l.protocol,
22
+ user: l.user
21
23
  });
22
24
  }
23
25
  const services = [];
@@ -43,10 +45,17 @@ async function buildSnapshot(ledgers, workspaces, commandRunner = runCommand) {
43
45
  ...l,
44
46
  url: isLocalhost(l.host) ? "http://localhost:" + l.port : null
45
47
  }));
48
+ const prot = classifyProtection({
49
+ pid,
50
+ name: proc?.name,
51
+ command,
52
+ cwd,
53
+ listeners
54
+ }, guard);
46
55
  services.push({
47
56
  id: serviceId,
48
57
  status: "running",
49
- ownership: cls.ownership,
58
+ ownership: prot.protected ? "protected" : cls.ownership,
50
59
  confidence: cls.confidence,
51
60
  name: proc?.name || "unknown",
52
61
  pid,
@@ -57,8 +66,8 @@ async function buildSnapshot(ledgers, workspaces, commandRunner = runCommand) {
57
66
  startedAt,
58
67
  listeners: listenersFinal,
59
68
  restartable: !!cls.ledgerEntry,
60
- protected: false,
61
- ownershipEvidence: cls.evidence,
69
+ protected: prot.protected,
70
+ ownershipEvidence: prot.protected ? [...prot.evidence, ...cls.evidence] : cls.evidence,
62
71
  fingerprint: "sha256:" + sha256Hex(fpSource)
63
72
  });
64
73
  }
@@ -0,0 +1,158 @@
1
+ import { defineTool } from "@deepseek-ai/dsh-tools";
2
+ //#region src/host/service-tool.ts
3
+ /** 与 host/types.ts 的 Ownership 联合一致(运行时无从推导,双写靠测试对齐) */
4
+ const OWNERSHIP_LEVELS = [
5
+ "conversation-confirmed",
6
+ "workspace-inferred",
7
+ "other-local",
8
+ "unknown",
9
+ "protected"
10
+ ];
11
+ const DEFAULT_LIMIT = 50;
12
+ const MAX_LIMIT = 200;
13
+ /** 与客户端搜索框同字段:name / pid / commandSummary / cwd / 端口(不区分大小写) */
14
+ function matchesQuery(q, s) {
15
+ return s.name.toLowerCase().includes(q) || String(s.pid).includes(q) || (s.commandSummary ?? "").toLowerCase().includes(q) || (s.cwd ?? "").toLowerCase().includes(q) || s.listeners.some((l) => String(l.port).includes(q));
16
+ }
17
+ function buildServiceTool(deps) {
18
+ return defineTool({
19
+ name: "service_list",
20
+ description: "List services currently listening on this machine (process, ports, ownership). READ-ONLY: this tool never stops or restarts anything; lifecycle actions live in the Service Console panel in the UI, where system-protected processes are refused. Use query to filter by name, command, cwd, or port, and ownership to filter by how a service was attributed.",
21
+ parameters: {
22
+ query: {
23
+ type: "string",
24
+ description: "Case-insensitive substring matched against service name, pid, command, cwd, and listening ports"
25
+ },
26
+ ownership: {
27
+ type: "string",
28
+ enum: OWNERSHIP_LEVELS,
29
+ description: "Only return services attributed at this level: conversation-confirmed / workspace-inferred / other-local / unknown / protected (refused for lifecycle actions)"
30
+ },
31
+ limit: {
32
+ type: "integer",
33
+ default: DEFAULT_LIMIT,
34
+ description: `Maximum services to return, clamped to 1..${MAX_LIMIT} (default ${DEFAULT_LIMIT})`
35
+ }
36
+ },
37
+ output: {
38
+ schema: {
39
+ type: "object",
40
+ additionalProperties: false,
41
+ properties: {
42
+ scannedAt: {
43
+ type: "integer",
44
+ required: true,
45
+ description: "Epoch milliseconds of the scan"
46
+ },
47
+ total: {
48
+ type: "integer",
49
+ required: true,
50
+ description: "Services matching the filters before the limit is applied"
51
+ },
52
+ count: {
53
+ type: "integer",
54
+ required: true,
55
+ description: "Services actually returned"
56
+ },
57
+ services: {
58
+ type: "array",
59
+ required: true,
60
+ items: {
61
+ type: "object",
62
+ additionalProperties: false,
63
+ properties: {
64
+ id: {
65
+ type: "string",
66
+ required: true,
67
+ description: "Stable service id used by Service Console APIs"
68
+ },
69
+ name: {
70
+ type: "string",
71
+ required: true,
72
+ description: "Executable path or command name"
73
+ },
74
+ pid: {
75
+ type: "integer",
76
+ required: true
77
+ },
78
+ status: {
79
+ type: "string",
80
+ required: true,
81
+ description: "Lifecycle status, e.g. running"
82
+ },
83
+ ownership: {
84
+ type: "string",
85
+ required: true,
86
+ description: "Attribution level (see the ownership parameter)"
87
+ },
88
+ protected: {
89
+ type: "boolean",
90
+ required: true,
91
+ description: "True when lifecycle actions on this service are refused (system/DSH-owning processes)"
92
+ },
93
+ ports: {
94
+ type: "string",
95
+ required: true,
96
+ description: "Comma-separated listening ports"
97
+ },
98
+ cwd: {
99
+ type: "string",
100
+ required: true,
101
+ description: "Working directory of the process, empty when unknown"
102
+ },
103
+ evidence: {
104
+ type: "array",
105
+ required: true,
106
+ items: { type: "string" },
107
+ description: "Attribution/protection evidence lines, empty when none"
108
+ }
109
+ }
110
+ }
111
+ }
112
+ }
113
+ },
114
+ render: (_args, value) => {
115
+ const lines = value.services.map((s) => {
116
+ const tag = s.protected ? "[protected] " : "";
117
+ const ev = s.evidence.length > 0 ? ` · ${s.evidence.join(" | ")}` : "";
118
+ return `${tag}${s.name} :${s.ports} · pid ${s.pid} · ${s.ownership}${ev}`;
119
+ });
120
+ return [{
121
+ type: "text",
122
+ text: [`services ${value.count}/${value.total} (scanned ${new Date(value.scannedAt).toISOString()})`, ...lines].join("\n")
123
+ }];
124
+ }
125
+ },
126
+ isConcurrencySafe: () => true,
127
+ async execute(args) {
128
+ const snap = await deps.snapshot();
129
+ let rows = snap.services;
130
+ if (args.ownership !== void 0) rows = rows.filter((s) => s.ownership === args.ownership);
131
+ if (args.query) {
132
+ const q = args.query.toLowerCase();
133
+ rows = rows.filter((s) => matchesQuery(q, s));
134
+ }
135
+ const total = rows.length;
136
+ const limit = Math.min(Math.max(args.limit ?? DEFAULT_LIMIT, 1), MAX_LIMIT);
137
+ const services = rows.slice(0, limit).map((s) => ({
138
+ id: s.id,
139
+ name: s.name,
140
+ pid: s.pid,
141
+ status: s.status,
142
+ ownership: s.ownership,
143
+ protected: s.protected,
144
+ ports: s.listeners.map((l) => String(l.port)).join(", "),
145
+ cwd: s.cwd ?? "",
146
+ evidence: [...s.ownershipEvidence]
147
+ }));
148
+ return {
149
+ scannedAt: snap.scannedAt,
150
+ total,
151
+ count: services.length,
152
+ services
153
+ };
154
+ }
155
+ });
156
+ }
157
+ //#endregion
158
+ export { buildServiceTool };
package/lib/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { SessionLedger } from "./host/ledger.js";
2
2
  import { buildSnapshot } from "./host/service-registry.js";
3
3
  import { restartService, stopService } from "./host/lifecycle.js";
4
+ import { buildServiceTool } from "./host/service-tool.js";
4
5
  import { loadConfigFromFile, saveConfigToFile, validateConfigPatch } from "./host/config.js";
5
6
  //#region src/index.ts
6
7
  async function readJsonBody(req) {
@@ -43,7 +44,7 @@ var src_default = {
43
44
  const deps = {
44
45
  timer,
45
46
  config,
46
- buildSnapshot: () => buildSnapshot(ledger.list, workspaces()),
47
+ buildSnapshot: snapshot,
47
48
  ledgerList: () => ledger.list,
48
49
  logAction
49
50
  };
@@ -60,18 +61,29 @@ var src_default = {
60
61
  } catch {}
61
62
  return workspacesCache;
62
63
  }
64
+ function protectionGuard() {
65
+ const guard = { protectedPids: [process.pid] };
66
+ try {
67
+ const port = Number(ctx.webServer?.port);
68
+ if (Number.isFinite(port) && port > 0) guard.protectedPorts = [port];
69
+ } catch {}
70
+ return guard;
71
+ }
72
+ function snapshot() {
73
+ return buildSnapshot(ledger.list, workspaces(), void 0, protectionGuard());
74
+ }
63
75
  const routes = [
64
76
  {
65
77
  path: "/dsh-sc/api/services/scan",
66
78
  handler: async () => ({
67
79
  ok: true,
68
- data: await buildSnapshot(ledger.list, workspaces())
80
+ data: await snapshot()
69
81
  })
70
82
  },
71
83
  {
72
84
  path: "/dsh-sc/api/services/detail",
73
85
  handler: async (args) => {
74
- const svc = (await buildSnapshot(ledger.list, workspaces())).services.find((x) => x.id === String(args.serviceId ?? ""));
86
+ const svc = (await snapshot()).services.find((x) => x.id === String(args.serviceId ?? ""));
75
87
  if (!svc) return {
76
88
  ok: false,
77
89
  error: {
@@ -133,35 +145,54 @@ var src_default = {
133
145
  })
134
146
  }
135
147
  ];
136
- for (const route of routes) ctx.webServer.register({
137
- kind: "exact",
138
- path: route.path,
139
- handler: async (req, res) => {
140
- const body = await readJsonBody(req);
141
- if (body === null) {
142
- sendJson(res, 400, {
143
- ok: false,
144
- error: {
145
- code: "BAD_REQUEST",
146
- message: "invalid JSON body"
148
+ for (const route of routes) ctx.effect(() => {
149
+ try {
150
+ return ctx.webServer.register({
151
+ kind: "exact",
152
+ path: route.path,
153
+ handler: async (req, res) => {
154
+ const body = await readJsonBody(req);
155
+ if (body === null) {
156
+ sendJson(res, 400, {
157
+ ok: false,
158
+ error: {
159
+ code: "BAD_REQUEST",
160
+ message: "invalid JSON body"
161
+ }
162
+ });
163
+ return;
147
164
  }
148
- });
149
- return;
150
- }
151
- try {
152
- const result = await route.handler(body);
153
- sendJson(res, result.ok ? 200 : 400, result);
154
- } catch (e) {
155
- sendJson(res, 500, {
156
- ok: false,
157
- error: {
158
- code: "INTERNAL",
159
- message: String(e?.message || e)
165
+ try {
166
+ const result = await route.handler(body);
167
+ sendJson(res, result.ok ? 200 : 400, result);
168
+ } catch (e) {
169
+ sendJson(res, 500, {
170
+ ok: false,
171
+ error: {
172
+ code: "INTERNAL",
173
+ message: String(e?.message || e)
174
+ }
175
+ });
160
176
  }
161
- });
162
- }
177
+ }
178
+ });
179
+ } catch (e) {
180
+ if (process.env.DSH_SC_DEBUG === "1") console.warn(`[dsh-sc] webServer route skip ${route.path}:`, String(e));
181
+ return () => {};
182
+ }
183
+ });
184
+ const tools = ctx.get("tools");
185
+ if (tools) ctx.effect(() => {
186
+ try {
187
+ const off = tools.register(buildServiceTool({ snapshot }));
188
+ if (process.env.DSH_SC_DEBUG === "1") console.log(`[dsh-sc] service_list registered: ${String(Boolean(tools.get("service_list")))}`);
189
+ return off;
190
+ } catch (e) {
191
+ if (process.env.DSH_SC_DEBUG === "1") console.warn("[dsh-sc] tools.register skip:", String(e));
192
+ return () => {};
163
193
  }
164
194
  });
195
+ else if (process.env.DSH_SC_DEBUG === "1") console.log("[dsh-sc] tools service absent — service_list not registered");
165
196
  }
166
197
  };
167
198
  //#endregion
@@ -7,19 +7,29 @@
7
7
  * - UI: 抽屉式面板 + Tab 栏(服务 / 设置),对标 workspace-explorer 视觉风格
8
8
  */
9
9
  import * as React from 'react';
10
+ import type { ConsoleKey } from './dictionaries';
10
11
  interface TimerLike {
11
12
  timeout(callback: () => void, delay: number): () => void;
12
13
  }
13
- interface LocaleLike {
14
- getLocale(): {
15
- id?: string;
16
- };
14
+ /** 类型化翻译函数:key 为词典键(拼写错误=编译错误),params 替换 {vars}(locale 运行时完成) */
15
+ type Translate = (key: ConsoleKey, params?: Record<string, unknown>) => string;
16
+ export declare function bindTimer(t: TimerLike): void;
17
+ export declare function bindLocale(locale: {
18
+ t: Translate;
17
19
  subscribe(fn: () => void): () => void;
18
- bind(ns: string): (key: string, vars?: Record<string, string | number>) => string;
20
+ }): void;
21
+ type ServiceScope = 'conversation' | 'workspace' | 'machine';
22
+ interface ConfigData {
23
+ refreshInterval: number;
24
+ defaultScope: ServiceScope;
25
+ gracefulTimeout: number;
26
+ showUnknown: boolean;
27
+ forceKill: boolean;
19
28
  }
20
- export declare function bindTimer(t: TimerLike): void;
21
- export declare function bindLocale(locale: LocaleLike): void;
22
29
  export declare function ServiceConsoleEntry(): React.ReactElement;
23
- export declare function ServiceConsoleSettings(): React.ReactElement;
30
+ export interface SettingsProps {
31
+ onSaved?: (config: ConfigData) => void;
32
+ }
33
+ export declare function ServiceConsoleSettings({ onSaved }: SettingsProps): React.ReactElement;
24
34
  export declare function ServiceConsolePanel(): React.ReactElement | null;
25
35
  export {};
@@ -1,6 +1,157 @@
1
1
  /**
2
2
  * dsh-service-console — i18n 词典(对齐 DSH locale.register 机制)
3
3
  * 与 dsh-workspace-explorer 共享设计语言:flat key → template string with {vars}
4
+ *
5
+ * 类型化:ZH_DICT 的键集是词典权威(ConsoleKey);EN_DICT 必须同键集
6
+ * (satisfies Record<ConsoleKey, string> —— 缺键/多键都是编译错误)。
4
7
  */
5
- export declare const ZH_DICT: Record<string, string>;
6
- export declare const EN_DICT: Record<string, string>;
8
+ export declare const ZH_DICT: {
9
+ 'plugin.name': string;
10
+ 'panel.title': string;
11
+ 'panel.subtitle': string;
12
+ 'entry.label': string;
13
+ 'entry.tip': string;
14
+ 'search.ph': string;
15
+ 'status.scanning': string;
16
+ 'status.done': string;
17
+ 'status.lastScan': string;
18
+ 'status.error': string;
19
+ 'svc.noSvc': string;
20
+ 'svc.ports': string;
21
+ 'svc.pid': string;
22
+ 'svc.command': string;
23
+ 'svc.cwd': string;
24
+ 'action.stop': string;
25
+ 'action.restart': string;
26
+ 'action.detail': string;
27
+ 'action.confirm': string;
28
+ 'action.cancel': string;
29
+ 'action.pending': string;
30
+ 'confirm.stop': string;
31
+ 'confirm.restart': string;
32
+ 'confirm.txt': string;
33
+ 'result.stopped': string;
34
+ 'result.restarted': string;
35
+ 'result.error': string;
36
+ 'own.conversation': string;
37
+ 'own.workspace': string;
38
+ 'own.other': string;
39
+ 'own.unknown': string;
40
+ 'own.protected': string;
41
+ 'scope.conversation': string;
42
+ 'scope.workspace': string;
43
+ 'scope.machine': string;
44
+ 'scope.machineWarn': string;
45
+ 'detail.title': string;
46
+ 'detail.serviceRecord': string;
47
+ 'detail.serviceId': string;
48
+ 'detail.process': string;
49
+ 'detail.parent': string;
50
+ 'detail.started': string;
51
+ 'detail.evidence': string;
52
+ 'err.PERMISSION_DENIED': string;
53
+ 'err.TARGET_GONE': string;
54
+ 'err.PID_REUSED': string;
55
+ 'err.UNKNOWN_OWNERSHIP': string;
56
+ 'err.PROTECTED_PROCESS': string;
57
+ 'err.GRACEFUL_TIMEOUT': string;
58
+ 'err.RESTART_UNSAFE': string;
59
+ 'err.PORT_CONFLICT': string;
60
+ 'err.START_TIMEOUT': string;
61
+ 'tab.services': string;
62
+ 'tab.settings': string;
63
+ 'settings.title': string;
64
+ 'settings.general': string;
65
+ 'settings.refreshInterval': string;
66
+ 'settings.refresh.desc': string;
67
+ 'settings.refreshOff': string;
68
+ 'settings.refreshN': string;
69
+ 'settings.defaultScope': string;
70
+ 'settings.showUnknown': string;
71
+ 'settings.showUnknown.desc': string;
72
+ 'settings.gracefulTimeout': string;
73
+ 'settings.forceKill': string;
74
+ 'settings.forceKill.desc': string;
75
+ 'settings.restore': string;
76
+ 'settings.note': string;
77
+ 'settings.nav': string;
78
+ 'star.developer': string;
79
+ 'star.ask': string;
80
+ 'star.cta': string;
81
+ };
82
+ /** 词典键权威类型:tr() 与 LocaleNamespaceMap 合并共用(键名拼写错误=编译错误) */
83
+ export type ConsoleKey = keyof typeof ZH_DICT;
84
+ export declare const EN_DICT: {
85
+ 'plugin.name': string;
86
+ 'panel.title': string;
87
+ 'panel.subtitle': string;
88
+ 'entry.label': string;
89
+ 'entry.tip': string;
90
+ 'search.ph': string;
91
+ 'status.scanning': string;
92
+ 'status.done': string;
93
+ 'status.lastScan': string;
94
+ 'status.error': string;
95
+ 'svc.noSvc': string;
96
+ 'svc.ports': string;
97
+ 'svc.pid': string;
98
+ 'svc.command': string;
99
+ 'svc.cwd': string;
100
+ 'action.stop': string;
101
+ 'action.restart': string;
102
+ 'action.detail': string;
103
+ 'action.confirm': string;
104
+ 'action.cancel': string;
105
+ 'action.pending': string;
106
+ 'confirm.stop': string;
107
+ 'confirm.restart': string;
108
+ 'confirm.txt': string;
109
+ 'result.stopped': string;
110
+ 'result.restarted': string;
111
+ 'result.error': string;
112
+ 'own.conversation': string;
113
+ 'own.workspace': string;
114
+ 'own.other': string;
115
+ 'own.unknown': string;
116
+ 'own.protected': string;
117
+ 'scope.conversation': string;
118
+ 'scope.workspace': string;
119
+ 'scope.machine': string;
120
+ 'scope.machineWarn': string;
121
+ 'detail.title': string;
122
+ 'detail.serviceRecord': string;
123
+ 'detail.serviceId': string;
124
+ 'detail.process': string;
125
+ 'detail.parent': string;
126
+ 'detail.started': string;
127
+ 'detail.evidence': string;
128
+ 'err.PERMISSION_DENIED': string;
129
+ 'err.TARGET_GONE': string;
130
+ 'err.PID_REUSED': string;
131
+ 'err.UNKNOWN_OWNERSHIP': string;
132
+ 'err.PROTECTED_PROCESS': string;
133
+ 'err.GRACEFUL_TIMEOUT': string;
134
+ 'err.RESTART_UNSAFE': string;
135
+ 'err.PORT_CONFLICT': string;
136
+ 'err.START_TIMEOUT': string;
137
+ 'tab.services': string;
138
+ 'tab.settings': string;
139
+ 'settings.title': string;
140
+ 'settings.general': string;
141
+ 'settings.refreshInterval': string;
142
+ 'settings.refresh.desc': string;
143
+ 'settings.refreshOff': string;
144
+ 'settings.refreshN': string;
145
+ 'settings.defaultScope': string;
146
+ 'settings.showUnknown': string;
147
+ 'settings.showUnknown.desc': string;
148
+ 'settings.gracefulTimeout': string;
149
+ 'settings.forceKill': string;
150
+ 'settings.forceKill.desc': string;
151
+ 'settings.restore': string;
152
+ 'settings.note': string;
153
+ 'settings.nav': string;
154
+ 'star.developer': string;
155
+ 'star.ask': string;
156
+ 'star.cta': string;
157
+ };
@@ -0,0 +1,30 @@
1
+ /**
2
+ * i18n 注册/绑定(热挂载与双装载幂等,0.7.1)
3
+ *
4
+ * 桌面 dshmarket 热更新会把插件装载两次:第二次 locale.register 抛
5
+ * "already has locale",webServer.register 抛 "duplicate exact route"。
6
+ * 0.5–0.7.0 的初始化在异常后直接放弃绑定,导致 UI 退回原始键。
7
+ * 这里把注册做成幂等(已注册即跳过),并保证无论注册是否抛错都完成绑定。
8
+ */
9
+ import type { ConsoleKey } from './dictionaries';
10
+ /** 平台 locale 服务的最小兼容面(3 参式注册,各版本通用;对象式为 0.2.0+ 专属) */
11
+ export interface LocaleCompat {
12
+ register(ns: string, locale: string, dict: Record<string, string>): (() => void) | unknown;
13
+ bind(ns: string): (key: string, params?: Record<string, unknown>) => string;
14
+ subscribe(fn: () => void): (() => void) | void;
15
+ }
16
+ export type Translate = (key: ConsoleKey, params?: Record<string, unknown>) => string;
17
+ export interface BoundLocale {
18
+ t: Translate;
19
+ subscribe: (fn: () => void) => () => void;
20
+ }
21
+ /**
22
+ * 幂等注册词典:逐语种注册;单条失败(如 already has locale)跳过,
23
+ * 不影响其余语种与后续绑定。返回 disposer(整体可安全清理)。
24
+ */
25
+ export declare function registerDictionaries(locale: LocaleCompat, ns: string, dicts: ReadonlyArray<readonly [string, Record<string, string>]>): () => void;
26
+ /**
27
+ * 绑定翻译函数:稳定外层 + 每次取最新 bound(旧版 bind 可能缓存语种)。
28
+ * 变量插值手工兜底(旧版 bound 可能不支持 params)。
29
+ */
30
+ export declare function bindTranslator(locale: LocaleCompat, ns: string): BoundLocale;