dsh-workbench-host 0.7.0 → 0.8.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.
@@ -0,0 +1,102 @@
1
+ /**
2
+ * 宿主元 action 的纯文本渲染:审计列表/记录/统计、action 列表、action 帮助。
3
+ *
4
+ * 单独成文件的原因:actions.ts 已贴近单文件 600 行上限,而这些函数只做字符串拼装,
5
+ * 不读库、不发事件、不依赖注册表,拆出来后既便于单测,也让动作注册表保持可读。
6
+ */
7
+ import { schemaChoices } from "./action-output.js";
8
+ export function renderAuditList(meta) {
9
+ const lines = [
10
+ "审计日志 " + meta.total + " 条(返回 " + meta.returned + " 条 · 第 " + meta.page + " 页 · 每页 " + meta.pageSize + ")",
11
+ ];
12
+ if (!meta.records.length)
13
+ lines.push("(没有符合条件的记录)");
14
+ for (const r of meta.records) {
15
+ lines.push("");
16
+ lines.push("#" + r.id + " " + r.time + " · " + r.actor + " · " + r.action + (r.ok ? "" : " ✗ 失败") +
17
+ (r.durationMs ? " · " + r.durationMs + "ms" : ""));
18
+ if (r.target)
19
+ lines.push(" 目标:" + r.target);
20
+ if (r.error)
21
+ lines.push(" 错误:" + String(r.error).slice(0, 500));
22
+ if (r.args)
23
+ lines.push(" 参数:" + String(r.args).slice(0, 300));
24
+ }
25
+ return lines.join("\n");
26
+ }
27
+ export function renderAuditRecord(r) {
28
+ const lines = [
29
+ "#" + r.id + " " + r.time,
30
+ "入口:" + r.actor + " · 域:" + (r.domain || "(未知)") + " · " + (r.ok ? "成功" : "失败") + " · " + r.durationMs + "ms",
31
+ "action:" + r.action,
32
+ ];
33
+ if (r.target)
34
+ lines.push("目标:" + r.target);
35
+ if (r.error)
36
+ lines.push("错误:" + r.error);
37
+ lines.push("", "参数:", r.args ? prettyJson(r.args) : "(无)", "", "结果:", r.result ? prettyJson(r.result) : "(无)");
38
+ return lines.join("\n");
39
+ }
40
+ function prettyJson(text) {
41
+ try {
42
+ return JSON.stringify(JSON.parse(text), null, 2);
43
+ }
44
+ catch {
45
+ return String(text);
46
+ }
47
+ }
48
+ export function renderAuditStats(s) {
49
+ const lines = ["最近 " + s.rangeDays + " 天:共 " + s.total + " 条,失败 " + s.failed + " 条"];
50
+ if (s.byAction.length) {
51
+ lines.push("", "按 action:");
52
+ for (const a of s.byAction)
53
+ lines.push(" " + a.action + " × " + a.count + (a.failed ? "(失败 " + a.failed + ")" : ""));
54
+ }
55
+ if (s.byActor.length) {
56
+ lines.push("", "按入口:");
57
+ for (const a of s.byActor)
58
+ lines.push(" " + a.actor + " × " + a.count);
59
+ }
60
+ if (s.byDay.length) {
61
+ lines.push("", "按天:");
62
+ for (const d of s.byDay)
63
+ lines.push(" " + d.day + " × " + d.count + (d.failed ? "(失败 " + d.failed + ")" : ""));
64
+ }
65
+ return lines.join("\n");
66
+ }
67
+ export function renderActionList(meta) {
68
+ const lines = ["工作台 " + meta.shellVersion + " · " + meta.domains.length + " 个域 · " + meta.actions.length + " 个 action"];
69
+ for (const d of meta.domains) {
70
+ lines.push("", "[" + d.id + "] " + d.title + " v" + d.version + (d.enabled ? "" : "(未启用:" + d.error + ")"));
71
+ for (const a of meta.actions) {
72
+ if (a.domain !== d.id)
73
+ continue;
74
+ lines.push(" " + a.name + (a.description ? " — " + a.description : ""));
75
+ const params = a.params ?? [];
76
+ lines.push(" 参数:" +
77
+ (params.length
78
+ ? params.map((p) => (a.required.indexOf(p) >= 0 ? p : p + "?")).join(", ")
79
+ : "无(直接调用即可)"));
80
+ }
81
+ }
82
+ lines.push("", '查看完整 JSON Schema 与示例:Workbench({ action: "actions.help", args: { action: "<name>" } })');
83
+ return lines.join("\n");
84
+ }
85
+ export function renderActionHelp(help) {
86
+ const lines = [help.name + " · " + help.domain, help.description || "(无描述)", "", "参数:"];
87
+ if (!help.params.length)
88
+ lines.push(" 无");
89
+ for (const p of help.params) {
90
+ lines.push(" " + p.name + (p.required ? "*" : "") + " (" + p.type + ")" + (p.description ? " — " + p.description : "") +
91
+ (Array.isArray(p.enum) ? ";可选值:" + p.enum.join(" / ") : ""));
92
+ }
93
+ lines.push(...schemaChoices(help.input));
94
+ lines.push("", "JSON Schema:", JSON.stringify(help.input, null, 2));
95
+ if (help.examples.length) {
96
+ lines.push("", "示例:");
97
+ for (const ex of help.examples) {
98
+ lines.push(" Workbench(" + JSON.stringify({ action: help.name, args: ex }) + ")");
99
+ }
100
+ }
101
+ return lines.join("\n");
102
+ }
@@ -1,9 +1,46 @@
1
- import { actionErrorText, schemaChoices } from "./action-output.js";
1
+ import { actionErrorText } from "./action-output.js";
2
+ import { renderActionHelp, renderActionList, renderAuditList, renderAuditRecord, renderAuditStats } from "./action-render.js";
2
3
  import { createTaskTargets } from "./task-targets.js";
3
4
  import { createCapabilities } from "./capabilities.js";
5
+ import { AGENT_LOCKED_ACTIONS, createAgentAccess } from "./agent-access.js";
6
+ import { BUILTIN_ACTIONS } from "./builtin-actions.js";
4
7
  export function createActions({ domains, SHELL_VERSION, publicInfo, audit, clock, emit, db, search }) {
5
8
  /** 宿主内置的元 action 归属域(不参与备份,也不是业务插件)。 */
6
9
  const META_DOMAIN = "wb-shell";
10
+ /** agent 可调用开关:声明默认值 + 本机 meta 覆盖(只在本机生效,不进备份/同步)。 */
11
+ const agentAccess = createAgentAccess(db);
12
+ /** 权限开关拦下的错误:都要进审计,且即使 action 属于「默认不记」的类别也不例外。 */
13
+ function isPolicyDenied(error) {
14
+ const code = String(error?.code ?? "");
15
+ return code === "ACTION_AGENT_DISABLED" || code === "ACTION_UI_ONLY";
16
+ }
17
+ /** 被本机关闭的 action,agent 硬调时的结构化错误。 */
18
+ function agentDisabledError(action) {
19
+ const error = new Error("该 action 已被本机设置禁止 agent 调用(界面仍可执行):" + action);
20
+ error.code = "ACTION_AGENT_DISABLED";
21
+ error.details = { action };
22
+ return error;
23
+ }
24
+ /** 开关只能从界面改:agent 调用一律拒绝,保证它没法给自己解锁。 */
25
+ function uiOnlyError() {
26
+ const error = new Error("该 action 只允许在界面中执行;agent 不能修改 action 的调用权限");
27
+ error.code = "ACTION_UI_ONLY";
28
+ return error;
29
+ }
30
+ /** agent 视角下某个 action 是否可见/可调(ui 恒为 true,不受开关影响)。 */
31
+ function agentVisible(name, def) {
32
+ return agentAccess.effective(name, def);
33
+ }
34
+ /** 分发前拦截:agent 调不到被关闭的 action;未知 action 仍走原来的报错。 */
35
+ function assertAgentAllowed(action, origin) {
36
+ if (origin !== "agent")
37
+ return;
38
+ if (AGENT_LOCKED_ACTIONS.has(action))
39
+ throw agentDisabledError(action);
40
+ const found = findActionDef(action);
41
+ if (found && !agentVisible(action, found.def))
42
+ throw agentDisabledError(action);
43
+ }
7
44
  /**
8
45
  * 宿主元 action:与业务域共用同一套 schema 发现(actions.list/help)与分发、审计链路,
9
46
  * 但不需要注册成插件域,统一归在 wb-shell 下。
@@ -73,71 +110,75 @@ export function createActions({ domains, SHELL_VERSION, publicInfo, audit, clock
73
110
  execute: (args) => audit.prune(args.retentionDays),
74
111
  render: (result) => "已清理 " + result.deleted + " 条审计(保留 " + result.retentionDays + " 天,截止 " + new Date(result.cutoff).toISOString() + ")",
75
112
  });
76
- function renderAuditList(meta) {
77
- const lines = [
78
- "审计日志 " + meta.total + " 条(返回 " + meta.returned + " 条 · 第 " + meta.page + " 页 · 每页 " + meta.pageSize + ")",
79
- ];
80
- if (!meta.records.length)
81
- lines.push("(没有符合条件的记录)");
82
- for (const r of meta.records) {
83
- lines.push("");
84
- lines.push("#" + r.id + " " + r.time + " · " + r.actor + " · " + r.action + (r.ok ? "" : " ✗ 失败") +
85
- (r.durationMs ? " · " + r.durationMs + "ms" : ""));
86
- if (r.target)
87
- lines.push(" 目标:" + r.target);
88
- if (r.error)
89
- lines.push(" 错误:" + String(r.error).slice(0, 500));
90
- if (r.args)
91
- lines.push(" 参数:" + String(r.args).slice(0, 300));
92
- }
93
- return lines.join("\n");
94
- }
95
- function renderAuditRecord(r) {
96
- const lines = [
97
- "#" + r.id + " " + r.time,
98
- "入口:" + r.actor + " · 域:" + (r.domain || "(未知)") + " · " + (r.ok ? "成功" : "失败") + " · " + r.durationMs + "ms",
99
- "action:" + r.action,
100
- ];
101
- if (r.target)
102
- lines.push("目标:" + r.target);
103
- if (r.error)
104
- lines.push("错误:" + r.error);
105
- lines.push("", "参数:", r.args ? prettyJson(r.args) : "(无)", "", "结果:", r.result ? prettyJson(r.result) : "(无)");
106
- return lines.join("\n");
107
- }
108
- function prettyJson(text) {
109
- try {
110
- return JSON.stringify(JSON.parse(text), null, 2);
111
- }
112
- catch {
113
- return String(text);
114
- }
115
- }
116
- function renderAuditStats(s) {
117
- const lines = ["最近 " + s.rangeDays + " 天:共 " + s.total + " 条,失败 " + s.failed + " 条"];
118
- if (s.byAction.length) {
119
- lines.push("", "按 action:");
120
- for (const a of s.byAction)
121
- lines.push(" " + a.action + " × " + a.count + (a.failed ? "(失败 " + a.failed + ")" : ""));
122
- }
123
- if (s.byActor.length) {
124
- lines.push("", "按入口:");
125
- for (const a of s.byActor)
126
- lines.push(" " + a.actor + " × " + a.count);
127
- }
128
- if (s.byDay.length) {
129
- lines.push("", "按天:");
130
- for (const d of s.byDay)
131
- lines.push(" " + d.day + " × " + d.count + (d.failed ? "(失败 " + d.failed + ")" : ""));
132
- }
133
- return lines.join("\n");
134
- }
113
+ META_ACTIONS.set("actions.setAgentAccess", {
114
+ description: "(仅界面)打开/关闭某个 action 的 agent 可调用开关。开关只存本机 meta,不参与备份与云同步;" +
115
+ "关闭后 agent 在 actions.list / actions.help / capabilities.* / *.actionSchema 中都看不到该 action," +
116
+ "硬调会得到 ACTION_AGENT_DISABLED;界面(origin=ui)的调用完全不受影响。agent 永远不能调用本 action。",
117
+ // 开关自身永久对 agent 关闭:否则「先解锁开关、再解锁一切」就绕过了整套限制。
118
+ agentEnabled: false,
119
+ input: {
120
+ type: "object",
121
+ properties: {
122
+ action: { type: "string", description: "要调整的 action 名,如 tasks.update / mail.messageBody" },
123
+ agentEnabled: { type: "boolean", description: "true=允许 agent 调用;false=只允许界面调用" },
124
+ domain: { type: "string", description: "可选:所属业务域 id(wb-addon-tasks 或 tasks),传了就校验归属" },
125
+ },
126
+ required: ["action", "agentEnabled"],
127
+ },
128
+ examples: [{ action: "tasks.update", agentEnabled: false }],
129
+ execute: (args, ctx) => {
130
+ if (ctx.origin !== "ui")
131
+ throw uiOnlyError();
132
+ const name = String(args.action ?? "").trim();
133
+ if (!name)
134
+ throw new Error("缺少 action");
135
+ if (typeof args.agentEnabled !== "boolean")
136
+ throw new Error("agentEnabled 必须是布尔值 true / false");
137
+ const found = findActionDef(name);
138
+ if (!found)
139
+ throw new Error("没有该 action:" + name);
140
+ const domain = args.domain === undefined || args.domain === null ? "" : String(args.domain).trim();
141
+ if (domain && domain !== found.domainId && domain !== found.domainId.replace(/^wb-addon-/, "")) {
142
+ throw new Error("action " + name + " 属于 " + found.domainId + ",不是 " + domain);
143
+ }
144
+ const changed = agentAccess.set(name, found.def, args.agentEnabled);
145
+ const out = {
146
+ action: name,
147
+ domain: found.domainId,
148
+ agentEnabled: changed.agentEnabled,
149
+ source: changed.source,
150
+ declared: agentAccess.declaredValue(name, found.def),
151
+ locked: agentAccess.locked(name, found.def),
152
+ };
153
+ // 开关本身是安全相关操作:actions.* 默认不进审计,这里显式留一条。
154
+ audit.record({
155
+ action: "actions.setAgentAccess",
156
+ domain: META_DOMAIN,
157
+ actor: ctx.origin,
158
+ ok: true,
159
+ args: { action: name, agentEnabled: args.agentEnabled },
160
+ result: out,
161
+ durationMs: 0,
162
+ force: true,
163
+ });
164
+ return out;
165
+ },
166
+ render: (result) => (result.agentEnabled ? "已允许" : "已禁止") +
167
+ " agent 调用 " +
168
+ result.action +
169
+ "(来源:" +
170
+ (result.source === "meta" ? "本机覆盖" : "action 定义的默认值") +
171
+ ")",
172
+ });
135
173
  /** 旧版 Workbench 顶层 schema 里的“通用字段”,多数 action 并不接受。 */
136
174
  const TRAP_FIELDS = ["due_at", "note", "tags", "tagIds", "dirIds", "parentId", "deadline", "start_at", "assignee", "limit"];
137
175
  const taskTargets = createTaskTargets(db, domains, invoke);
138
176
  META_ACTIONS.set("capabilities.setTaskTarget", taskTargets.setAction);
139
- const { capabilityListMeta, renderCapabilityList, capabilityGetMeta, renderCapability } = createCapabilities({ domains, SHELL_VERSION, actionEntry, taskTargets });
177
+ const { capabilityListMeta, renderCapabilityList, capabilityGetMeta, renderCapability } = createCapabilities({ domains, SHELL_VERSION, actionEntry, taskTargets, agentVisible });
140
178
  function findActionDef(name) {
179
+ const builtin = BUILTIN_ACTIONS.get(name);
180
+ if (builtin)
181
+ return { def: builtin, domainId: META_DOMAIN };
141
182
  const meta = META_ACTIONS.get(name);
142
183
  if (meta)
143
184
  return { def: meta, domainId: META_DOMAIN };
@@ -165,21 +206,35 @@ export function createActions({ domains, SHELL_VERSION, publicInfo, audit, clock
165
206
  required,
166
207
  params: Object.keys(props),
167
208
  input: def.input ?? { type: "object", properties: {} },
209
+ // UI 的 Action 页据此区分三种状态:允许 / 默认关闭(可开)/ 永远关闭(agentLocked 安全锁定)。
210
+ agentEnabled: agentAccess.effective(name, def),
211
+ agentLocked: agentAccess.locked(name, def),
168
212
  };
169
213
  }
170
214
  /** actions.list:把已注册 action 的“真实入参”暴露给 agent,避免按顶层通用 schema 猜字段。 */
171
- function listActionsMeta(args) {
215
+ function listActionsMeta(args, origin = "ui") {
172
216
  const raw = args.domain === undefined || args.domain === null ? "" : String(args.domain).trim();
173
217
  const matchDomain = (domainId) => !raw || domainId === raw || domainId === "wb-addon-" + raw;
174
218
  const matchAction = (name, domainId) => !raw || matchDomain(domainId) || name === raw || name.split(".")[0] === raw;
175
219
  const all = [];
176
220
  for (const rec of domains.values()) {
177
221
  for (const [name, def] of rec.actions) {
222
+ // agent 视图只列出它真能调用的 action;被本机关闭的不出现(ui 仍看全量)。
223
+ if (origin === "agent" && !agentVisible(name, def))
224
+ continue;
178
225
  if (matchAction(name, rec.def.id))
179
226
  all.push(actionEntry(name, rec.def.id, def));
180
227
  }
181
228
  }
182
229
  for (const [name, def] of META_ACTIONS) {
230
+ if (origin === "agent" && !agentVisible(name, def))
231
+ continue;
232
+ if (matchAction(name, META_DOMAIN))
233
+ all.push(actionEntry(name, META_DOMAIN, def));
234
+ }
235
+ for (const [name, def] of BUILTIN_ACTIONS) {
236
+ if (origin === "agent" && !agentVisible(name, def))
237
+ continue;
183
238
  if (matchAction(name, META_DOMAIN))
184
239
  all.push(actionEntry(name, META_DOMAIN, def));
185
240
  }
@@ -194,7 +249,8 @@ export function createActions({ domains, SHELL_VERSION, publicInfo, audit, clock
194
249
  version: info.version,
195
250
  enabled: info.enabled,
196
251
  error: info.error,
197
- actionCount: rec.actions.size,
252
+ // agent 视图只数它看得到的;ui 保持原有的域内 action 总数。
253
+ actionCount: origin === "agent" ? all.filter((a) => a.domain === info.id).length : rec.actions.size,
198
254
  };
199
255
  });
200
256
  if (ids.has(META_DOMAIN)) {
@@ -204,7 +260,7 @@ export function createActions({ domains, SHELL_VERSION, publicInfo, audit, clock
204
260
  version: SHELL_VERSION,
205
261
  enabled: true,
206
262
  error: null,
207
- actionCount: 4 + META_ACTIONS.size,
263
+ actionCount: all.filter((a) => a.domain === META_DOMAIN).length,
208
264
  });
209
265
  }
210
266
  const detail = args.detail === true;
@@ -213,33 +269,27 @@ export function createActions({ domains, SHELL_VERSION, publicInfo, audit, clock
213
269
  domains: domainsOut,
214
270
  actions: detail
215
271
  ? all
216
- : all.map((a) => ({ name: a.name, domain: a.domain, description: a.description, required: a.required, params: a.params })),
272
+ : all.map((a) => ({
273
+ name: a.name,
274
+ domain: a.domain,
275
+ description: a.description,
276
+ required: a.required,
277
+ params: a.params,
278
+ agentEnabled: a.agentEnabled,
279
+ agentLocked: a.agentLocked,
280
+ })),
217
281
  };
218
282
  }
219
- function renderActionList(meta) {
220
- const lines = ["工作台 " + meta.shellVersion + " · " + meta.domains.length + " 个域 · " + meta.actions.length + " 个 action"];
221
- for (const d of meta.domains) {
222
- lines.push("", "[" + d.id + "] " + d.title + " v" + d.version + (d.enabled ? "" : "(未启用:" + d.error + ")"));
223
- for (const a of meta.actions) {
224
- if (a.domain !== d.id)
225
- continue;
226
- lines.push(" " + a.name + (a.description ? " — " + a.description : ""));
227
- const params = a.params ?? [];
228
- lines.push(" 参数:" +
229
- (params.length
230
- ? params.map((p) => (a.required.indexOf(p) >= 0 ? p : p + "?")).join(", ")
231
- : "无(直接调用即可)"));
232
- }
233
- }
234
- lines.push("", '查看完整 JSON Schema 与示例:Workbench({ action: "actions.help", args: { action: "<name>" } })');
235
- return lines.join("\n");
236
- }
237
283
  /** actions.help:单个 action 的完整 schema + 参数说明 + 示例。 */
238
- function helpActionMeta(args) {
284
+ function helpActionMeta(args, origin = "ui") {
239
285
  const name = String(args.action ?? args.name ?? "").trim();
240
286
  if (!name)
241
287
  throw new Error("缺少 action;先用 actions.list 查看可用 action");
242
288
  const found = findActionDef(name);
289
+ // help 也是 agent 的发现入口:关掉的 action 连参数都不给它看,和调用保持同一套错误。
290
+ if (origin === "agent" && (AGENT_LOCKED_ACTIONS.has(name) || (found && !agentVisible(name, found.def)))) {
291
+ throw agentDisabledError(name);
292
+ }
243
293
  if (!found)
244
294
  throw new Error("没有该 action:" + name + ";先用 actions.list 查看可用 action");
245
295
  const entry = actionEntry(name, found.domainId, found.def);
@@ -260,24 +310,6 @@ export function createActions({ domains, SHELL_VERSION, publicInfo, audit, clock
260
310
  examples: found.def.examples ?? [],
261
311
  };
262
312
  }
263
- function renderActionHelp(help) {
264
- const lines = [help.name + " · " + help.domain, help.description || "(无描述)", "", "参数:"];
265
- if (!help.params.length)
266
- lines.push(" 无");
267
- for (const p of help.params) {
268
- lines.push(" " + p.name + (p.required ? "*" : "") + " (" + p.type + ")" + (p.description ? " — " + p.description : "") +
269
- (Array.isArray(p.enum) ? ";可选值:" + p.enum.join(" / ") : ""));
270
- }
271
- lines.push(...schemaChoices(help.input));
272
- lines.push("", "JSON Schema:", JSON.stringify(help.input, null, 2));
273
- if (help.examples.length) {
274
- lines.push("", "示例:");
275
- for (const ex of help.examples) {
276
- lines.push(" Workbench(" + JSON.stringify({ action: help.name, args: ex }) + ")");
277
- }
278
- }
279
- return lines.join("\n");
280
- }
281
313
  function actionNames() {
282
314
  const out = [];
283
315
  for (const rec of domains.values()) {
@@ -285,13 +317,16 @@ export function createActions({ domains, SHELL_VERSION, publicInfo, audit, clock
285
317
  out.push({ name: action, domainId: rec.def.id, description: def.description });
286
318
  }
287
319
  }
288
- for (const [name, def] of META_ACTIONS) {
289
- out.push({ name, domainId: META_DOMAIN, description: def.description });
320
+ // 元 action 与内置 action 按名字去重后一起暴露:界面路由据此找到归属域。
321
+ const seen = new Set(out.map((entry) => entry.name));
322
+ for (const map of [META_ACTIONS, BUILTIN_ACTIONS]) {
323
+ for (const [name, def] of map) {
324
+ if (seen.has(name))
325
+ continue;
326
+ seen.add(name);
327
+ out.push({ name, domainId: META_DOMAIN, description: def.description });
328
+ }
290
329
  }
291
- out.push({ name: "capabilities.list", domainId: META_DOMAIN, description: "列出各业务插件记录什么、首选哪个 action" });
292
- out.push({ name: "capabilities.get", domainId: META_DOMAIN, description: "查看单个业务插件的完整能力清单与 action 列表" });
293
- out.push({ name: "actions.list", domainId: META_DOMAIN, description: "列出已安装业务域的 action、参数与必填项" });
294
- out.push({ name: "actions.help", domainId: META_DOMAIN, description: "查看单个 action 的完整 JSON Schema、参数说明与示例" });
295
330
  return out;
296
331
  }
297
332
  async function invoke(action, args, origin) {
@@ -315,7 +350,9 @@ export function createActions({ domains, SHELL_VERSION, publicInfo, audit, clock
315
350
  return out;
316
351
  }
317
352
  catch (e) {
318
- if (audited) {
353
+ // 被权限开关拦下的调用一律留痕(即使 action 本身属于「默认不记」的那几类)。
354
+ const deniedByPolicy = isPolicyDenied(e);
355
+ if (audited || deniedByPolicy) {
319
356
  const target = findActionDef(action);
320
357
  audit.record({
321
358
  action,
@@ -325,26 +362,30 @@ export function createActions({ domains, SHELL_VERSION, publicInfo, audit, clock
325
362
  error: String((e && e.message) || e),
326
363
  args,
327
364
  durationMs: clock.now() - started,
365
+ force: deniedByPolicy || undefined,
328
366
  });
329
367
  }
330
368
  throw e;
331
369
  }
332
370
  }
333
371
  async function invokeAction(action, args, origin) {
372
+ // 入口一处拦截:agent 调不到被本机关闭的 action(含永久锁死的开关自身);
373
+ // ui/sync/plugin 的语义完全不变。拦截失败同样会进 invoke() 的审计。
374
+ assertAgentAllowed(action, origin);
334
375
  if (action === "capabilities.list") {
335
- const result = await capabilityListMeta(args);
376
+ const result = await capabilityListMeta(args, origin);
336
377
  return { result, text: renderCapabilityList(result), domainId: META_DOMAIN };
337
378
  }
338
379
  if (action === "capabilities.get") {
339
- const result = await capabilityGetMeta(args);
380
+ const result = await capabilityGetMeta(args, origin);
340
381
  return { result, text: renderCapability(result), domainId: META_DOMAIN };
341
382
  }
342
383
  if (action === "actions.list") {
343
- const result = listActionsMeta(args);
384
+ const result = listActionsMeta(args, origin);
344
385
  return { result, text: renderActionList(result), domainId: META_DOMAIN };
345
386
  }
346
387
  if (action === "actions.help") {
347
- const result = helpActionMeta(args);
388
+ const result = helpActionMeta(args, origin);
348
389
  return { result, text: renderActionHelp(result), domainId: META_DOMAIN };
349
390
  }
350
391
  const meta = META_ACTIONS.get(action);
@@ -363,10 +404,11 @@ export function createActions({ domains, SHELL_VERSION, publicInfo, audit, clock
363
404
  const def = rec.actions.get(action);
364
405
  if (!def)
365
406
  continue;
366
- const result = await def.execute(args, {
407
+ const raw = await def.execute(args, {
367
408
  origin,
368
409
  emit: (event, data) => emit("domain-event", { domainId: rec.def.id, event, data: data ?? null }),
369
410
  });
411
+ const result = decorateSchemaResult(action, raw, origin);
370
412
  return {
371
413
  result,
372
414
  text: def.render ? def.render(result) : JSON.stringify(result),
@@ -375,6 +417,42 @@ export function createActions({ domains, SHELL_VERSION, publicInfo, audit, clock
375
417
  }
376
418
  throw new Error("没有业务插件注册 action:" + action);
377
419
  }
420
+ /**
421
+ * 插件自己的 `<域>.actionSchema` 结果由宿主补齐 agent 开关状态:
422
+ * ui 看全量并带 agentEnabled(Action 页据此渲染开关),agent 只看到自己仍能调用的。
423
+ */
424
+ function decorateSchemaResult(action, result, origin) {
425
+ if (!/\.actionSchema$/.test(action))
426
+ return result;
427
+ if (!result || typeof result !== "object" || !Array.isArray(result.actions))
428
+ return result;
429
+ const found = findActionDef(action);
430
+ const rec = found && found.domainId !== META_DOMAIN ? domains.get(found.domainId) : null;
431
+ const actions = result.actions.map((entry) => {
432
+ const name = entry && typeof entry.name === "string" ? entry.name : "";
433
+ const def = name && rec ? (rec.actions.get(name) ?? META_ACTIONS.get(name)) : name ? META_ACTIONS.get(name) : null;
434
+ if (!name || !def)
435
+ return entry;
436
+ return {
437
+ ...entry,
438
+ agentEnabled: agentAccess.effective(name, def),
439
+ agentLocked: agentAccess.locked(name, def),
440
+ };
441
+ });
442
+ // 插件自己列的 schema 常常漏掉 actionSchema 自身等条目:宿主补全,UI 才能逐个配置开关。
443
+ if (origin !== "agent" && rec) {
444
+ const domainId = found ? found.domainId : rec.def.id;
445
+ const listed = new Set(actions.map((entry) => entry?.name));
446
+ for (const [name, def] of rec.actions) {
447
+ if (!listed.has(name))
448
+ actions.push(actionEntry(name, domainId, def));
449
+ }
450
+ }
451
+ return {
452
+ ...result,
453
+ actions: origin === "agent" ? actions.filter((entry) => entry.agentEnabled !== false) : actions,
454
+ };
455
+ }
378
456
  function installTool(ctx) {
379
457
  // ── Agent 工具:Workbench(单工具多 action,action 由已注册业务域动态提供)──
380
458
  ctx.tools?.register({
@@ -386,6 +464,7 @@ export function createActions({ domains, SHELL_VERSION, publicInfo, audit, clock
386
464
  "actions.list / actions.help 用于自举:先 actions.list 看有哪些 action,再 actions.help 看真实字段。" +
387
465
  "审计留痕可直接查 audit.list / audit.get / audit.stats(本机行为账本:谁在何时调了什么、成功与否,参数已脱敏)。" +
388
466
  "入参统一放进 args;不要再按旧版顶层字段(due_at / tags / parentId 等)猜参数。" +
467
+ "被本机在 Action 页关闭 agent 访问的 action 不会出现在 actions.list 中,直接调用返回 ACTION_AGENT_DISABLED(界面仍可正常使用);" +
389
468
  "安装或卸载业务插件请使用 DSH 的插件管理,不在本工具里做。",
390
469
  parameters: {
391
470
  type: "object",
@@ -463,11 +542,17 @@ export function createActions({ domains, SHELL_VERSION, publicInfo, audit, clock
463
542
  */
464
543
  function schemaSnapshot(domain) {
465
544
  const wanted = String(domain ?? "").trim();
466
- const meta = listActionsMeta({ detail: true, ...(wanted ? { domain: wanted } : {}) });
545
+ // 只读快照给 Action 页调试用:界面要看到全量 action 及每个的 agent 开关状态。
546
+ const meta = listActionsMeta({ detail: true, ...(wanted ? { domain: wanted } : {}) }, "ui");
467
547
  const actions = meta.actions.map((entry) => {
468
548
  const found = findActionDef(entry.name);
469
549
  const examples = found && Array.isArray(found.def.examples) ? found.def.examples : [];
470
- return { ...entry, examples };
550
+ return {
551
+ ...entry,
552
+ examples,
553
+ agentEnabled: entry.agentEnabled ?? (found ? agentVisible(entry.name, found.def) : true),
554
+ agentLocked: found ? agentAccess.locked(entry.name, found.def) : false,
555
+ };
471
556
  });
472
557
  return { shellVersion: meta.shellVersion, domains: meta.domains, actions };
473
558
  }
@@ -0,0 +1,84 @@
1
+ /** meta 键前缀:一个 action 一行,值只允许 "1"(开)/ "0"(关)。 */
2
+ export const AGENT_ACCESS_KEY_PREFIX = "config.wb-shell.actionAgent.";
3
+ /**
4
+ * 永久锁死的 action:无论 meta 怎么写都不允许 agent 调用。
5
+ * 开关自身必须在里面,否则「先解锁开关、再解锁一切」就绕过了整套限制。
6
+ */
7
+ export const AGENT_LOCKED_ACTIONS = new Set(["actions.setAgentAccess"]);
8
+ export function agentAccessKey(action) {
9
+ return AGENT_ACCESS_KEY_PREFIX + action;
10
+ }
11
+ const ON_VALUES = new Set(["1", "true", "on", "yes"]);
12
+ const OFF_VALUES = new Set(["0", "false", "off", "no"]);
13
+ /**
14
+ * 读本机覆盖。返回 failed=true 表示「读不到/值无效」,调用方必须按关闭处理(fail closed):
15
+ * 数据库故障时宁可 agent 调不到,也不能把用户关掉的 action 静默放行。
16
+ * db 为空只出现在纯 schema 测试里,此时按「没有覆盖」回默认值。
17
+ */
18
+ function readOverride(db, action) {
19
+ if (!db)
20
+ return { value: null, failed: false };
21
+ try {
22
+ const row = db.prepare("SELECT v FROM meta WHERE k = ?").get(agentAccessKey(action));
23
+ const raw = row && row.v !== undefined && row.v !== null ? String(row.v).trim().toLowerCase() : "";
24
+ if (raw === "")
25
+ return { value: null, failed: false };
26
+ if (ON_VALUES.has(raw))
27
+ return { value: true, failed: false };
28
+ if (OFF_VALUES.has(raw))
29
+ return { value: false, failed: false };
30
+ return { value: null, failed: true };
31
+ }
32
+ catch {
33
+ return { value: null, failed: true };
34
+ }
35
+ }
36
+ function writeMeta(db, key, value) {
37
+ if (value === null) {
38
+ db.prepare("DELETE FROM meta WHERE k = ?").run(key);
39
+ return;
40
+ }
41
+ db.prepare("INSERT INTO meta(k, v) VALUES(?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(key, value);
42
+ }
43
+ export function createAgentAccess(db) {
44
+ /**
45
+ * 硬锁:安全约束,agent 永远不可调用、界面也不能打开。
46
+ * 两个来源:宿主内置的永久锁定清单,或 action 自己声明 agentLocked:true。
47
+ */
48
+ function locked(action, def) {
49
+ return AGENT_LOCKED_ACTIONS.has(action) || Boolean(def && def.agentLocked === true);
50
+ }
51
+ /** action 定义的默认值:没声明 agentEnabled 就是允许 agent 调用;硬锁恒为关闭。 */
52
+ function declaredValue(action, def) {
53
+ if (locked(action, def))
54
+ return false;
55
+ return !def || def.agentEnabled !== false;
56
+ }
57
+ /** 本机覆盖;没写过返回 null,读失败/值无效返回 failed(调用方按关闭处理)。 */
58
+ function override(action) {
59
+ return readOverride(db, action);
60
+ }
61
+ /** 生效值:硬锁恒为 false;读不到覆盖时 fail closed;最后才是声明默认值。 */
62
+ function effective(action, def) {
63
+ if (locked(action, def))
64
+ return false;
65
+ const own = override(action);
66
+ if (own.failed)
67
+ return false;
68
+ return own.value === null ? declaredValue(action, def) : own.value;
69
+ }
70
+ /** 改开关:硬锁直接拒绝;与声明默认值相同时删掉覆盖行(不留脏 meta),否则写 "1"/"0"。 */
71
+ function set(action, def, agentEnabled) {
72
+ if (locked(action, def)) {
73
+ throw new Error("该 action 的 agent 调用被永久禁止(安全约束),界面也不能解锁:" + action);
74
+ }
75
+ const base = declaredValue(action, def);
76
+ if (agentEnabled === base) {
77
+ writeMeta(db, agentAccessKey(action), null);
78
+ return { agentEnabled: base, source: "declared" };
79
+ }
80
+ writeMeta(db, agentAccessKey(action), agentEnabled ? "1" : "0");
81
+ return { agentEnabled, source: "meta" };
82
+ }
83
+ return { locked, declaredValue, override, effective, set };
84
+ }