dlinkclaw-openclaw 2026.10.23 → 2026.10.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{emptyPluginConfigSchema as e}from"openclaw/plugin-sdk/core";import{channelMeta as s,dlChannel as n,LOG_TAG as r}from"./src/channel.js";import{setDLLogger as t,setDLRuntime as o,isRunStopped as i}from"./src/runtime.js";import{loadPersonaBlock as a,currentPersonaAgent as l}from"./src/persona.js";const p=s;p.isDebug&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0",process.env.NODE_ENV="dev");const c={id:p.id,name:p.label,description:p.blurb,configSchema:e(),register(e){o(e.runtime),t(e.logger,r),e.registerChannel({plugin:n}),e.on("before_tool_call",(e,s)=>{const n=p.id;if(s.channelId===n)return e.runId&&i(e.runId)?{block:!0,blockReason:"用户已点击停止,任务终止执行"}:void 0}),e.on("before_prompt_build",async(s,n)=>{const r=p.id;if(n.channel!==r&&n.channelId!==r)return;const t=["[AGENT CODE OF CONDUCT - ALWAYS FOLLOW]","1. ASK BEFORE GUESSING: If the task is incomplete or has multiple reasonable interpretations, send a one-line confirmation first. Never guess.",'2. STOP ON FAILURE: If the same problem fails 2-3 times in a row, stop and report: "I am stuck: <reason>. Please advise." Never retry endlessly.','3. ALWAYS REPORT COMPLETION: Every task must end with a completion signal. After sending media/files, always follow up with a short text confirmation (e.g. "✅ Sent 3 files: a.png / b.pdf / c.txt"). The client shows a spinner until it receives the final text reply.',"4. LANGUAGE: write your reply AND any intermediate/progress text (tool narration, status lines, preamble) in the same language as the user's latest message. Never default to English when the user writes in another language."],o=l(n.sessionKey);!o&&String(n.sessionKey??"").includes(":group:")&&e.logger.warn(`persona group scope missing: session=${n.sessionKey}`);const i=await a(n.sessionKey,o);return i&&t.push(i),{prependSystemContext:t.join("\n\n")}})}};export default c;
1
+ import{emptyPluginConfigSchema as e}from"openclaw/plugin-sdk/core";import{channelMeta as n,dlChannel as s,LOG_TAG as r}from"./src/channel.js";import{setDLLogger as t,setDLRuntime as o,isRunStopped as i}from"./src/runtime.js";import{loadPersonaBlock as a,currentPersonaAgent as l}from"./src/persona.js";const p=n;p.isDebug&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0",process.env.NODE_ENV="dev");const c={id:p.id,name:p.label,description:p.blurb,configSchema:e(),register(e){o(e.runtime),t(e.logger,r),e.registerChannel({plugin:s}),e.on("before_tool_call",(e,n)=>{const s=p.id;if(n.channelId===s)return e.runId&&i(e.runId)?{block:!0,blockReason:"用户已点击停止,任务终止执行"}:void 0}),e.on("before_prompt_build",async(n,s)=>{const r=p.id;if(s.channel!==r&&s.channelId!==r)return;const t=["[AGENT CODE OF CONDUCT - ALWAYS FOLLOW]","1. ASK BEFORE GUESSING: If the task is incomplete or has multiple reasonable interpretations, send a one-line confirmation first. Never guess.",'2. STOP ON FAILURE: If the same problem fails 2-3 times in a row, stop and report: "I am stuck: <reason>. Please advise." Never retry endlessly.','3. ALWAYS REPORT COMPLETION: Every task must end with a completion signal. After sending media/files, always follow up with a short text confirmation (e.g. "✅ Sent 3 files: a.png / b.pdf / c.txt"). The client shows a spinner until it receives the final text reply.',"4. LANGUAGE: write your reply, any intermediate/progress text (tool narration, status lines, preamble), AND your reasoning/thinking in the same language as the user's latest message. Never default to English when the user writes in another language."],o=l(s.sessionKey);!o&&String(s.sessionKey??"").includes(":group:")&&e.logger.warn(`persona group scope missing: session=${s.sessionKey}`);const i=await a(s.sessionKey,o);return i&&t.push(i),{prependSystemContext:t.join("\n\n")}})}};export default c;
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dlinkclaw-openclaw",
3
- "version": "2026.10.23",
3
+ "version": "2026.10.26",
4
4
  "description": "DLinkClaw OpenClaw channel plugin — 朵联 OpenClaw 接入通道",
5
5
  "keywords": [
6
6
  "DLinkClaw",
@@ -0,0 +1 @@
1
+ export declare function createDLApprovalCapability(): any;
@@ -0,0 +1,80 @@
1
+ import { DEFAULT_ACCOUNT_ID } from 'openclaw/plugin-sdk/core';
2
+ import { getDLClient } from './client/client-manager.js';
3
+ import { getDLLogger } from './runtime.js';
4
+ function firstString(...vals) {
5
+ for (const v of vals) {
6
+ if (typeof v === 'string' && v.length > 0) {
7
+ return v;
8
+ }
9
+ }
10
+ return '';
11
+ }
12
+ function pickRequest(ctx) {
13
+ const req = ctx?.request ?? {};
14
+ const view = ctx?.view ?? {};
15
+ const payload = ctx?.pendingPayload ?? {};
16
+ return {
17
+ approvalId: firstString(payload.approvalId, req.id, req.approvalId),
18
+ kind: firstString(ctx?.approvalKind, req.kind, 'exec'),
19
+ agentId: firstString(req.agentId, view.agentId, req.sessionKey ? '' : ''),
20
+ sessionKey: firstString(req.sessionKey, view.sessionKey),
21
+ command: firstString(payload.command, view.command, req.command, req.payload?.command),
22
+ cwd: firstString(payload.cwd, view.cwd, req.cwd),
23
+ expiresAtMs: Number(payload.expiresAtMs ?? view.expiresAtMs ?? req.expiresAtMs ?? 0)
24
+ };
25
+ }
26
+ export function createDLApprovalCapability() {
27
+ return {
28
+ availability: {
29
+ // dlink 是唯一通道;账号已配置即可承接审批
30
+ isConfigured: () => true,
31
+ shouldHandle: () => true
32
+ },
33
+ presentation: {
34
+ buildPendingPayload: (ctx) => {
35
+ const info = pickRequest(ctx);
36
+ return {
37
+ ...info,
38
+ text: firstString(ctx?.view?.summary, info.command)
39
+ };
40
+ },
41
+ buildResolvedResult: () => ({ kind: 'leave' }),
42
+ buildExpiredResult: () => ({ kind: 'leave' })
43
+ },
44
+ transport: {
45
+ prepareTarget: (ctx) => ctx?.plannedTarget ?? null,
46
+ deliverPending: async (ctx) => {
47
+ const logger = getDLLogger();
48
+ const info = pickRequest(ctx);
49
+ if (!info.approvalId) {
50
+ logger.warn?.('approval deliver skipped: no approvalId');
51
+ return null;
52
+ }
53
+ const dlClient = getDLClient(ctx?.accountId || DEFAULT_ACCOUNT_ID);
54
+ if (!dlClient) {
55
+ logger.warn?.('approval deliver skipped: no dlink client');
56
+ return null;
57
+ }
58
+ try {
59
+ await dlClient.pushApprovalEvent({
60
+ approvalId: info.approvalId,
61
+ kind: info.kind,
62
+ agentId: info.agentId,
63
+ sessionKey: info.sessionKey,
64
+ command: info.command,
65
+ cwd: info.cwd,
66
+ expiresAtMs: info.expiresAtMs
67
+ });
68
+ logger.info?.(`approval forwarded to relay: id=${info.approvalId} agent=${info.agentId} kind=${info.kind}`);
69
+ }
70
+ catch (e) {
71
+ logger.warn?.(`approval forward failed: ${String(e)}`);
72
+ }
73
+ return { approvalId: info.approvalId, deliveredAt: Date.now() };
74
+ },
75
+ updateEntry: async () => { },
76
+ deleteEntry: async () => { }
77
+ },
78
+ interactions: {}
79
+ };
80
+ }
@@ -4,6 +4,7 @@ import { checkConfigured, deleteDLAccount, listDLConfiguredAccountIds, resolveDe
4
4
  import { formatPairingApproveHint } from "openclaw/plugin-sdk/core";
5
5
  import { getDLLogger } from "./runtime.js";
6
6
  import { dlOutbound, dlPairing } from "./outbound.js";
7
+ import { createDLApprovalCapability } from "./approval-native.js";
7
8
  export const channelMeta = pkg.openclaw.channel;
8
9
  export const LOG_TAG = channelMeta.selectionLabel;
9
10
  const channelId = channelMeta.id;
@@ -142,6 +143,8 @@ export const dlChannel = {
142
143
  },
143
144
  pairing: dlPairing(channelId),
144
145
  outbound: dlOutbound(),
146
+ // 2026-10-27 原生审批投递:core 把请求交给插件,插件转交中继扇出
147
+ approvalCapability: createDLApprovalCapability(),
145
148
  gateway: {
146
149
  startAccount: async (ctx) => {
147
150
  ctx.setStatus({
@@ -25,6 +25,7 @@ export declare const REPLY_SEND_TIMEOUT_MS = 15000;
25
25
  */
26
26
  export declare const AUTO_RELAY_API = "/guest/relayBot/sendNotification";
27
27
  export declare const AUTO_RELAY_PERSONA = "/guest/relayBot/persona";
28
+ export declare const AUTO_RELAY_APPROVAL_EVENT = "/guest/relayBot/approvalEvent";
28
29
  export declare const AUTO_RELAY_UPLOAD = "/guest/relayBot/uploadMediaFiles";
29
30
  export declare const FILE_LIMITS: {
30
31
  image: {
@@ -26,6 +26,7 @@ export const REPLY_SEND_TIMEOUT_MS = 15_000;
26
26
  export const AUTO_RELAY_API = '/guest/relayBot/sendNotification';
27
27
  // 2026-10-26 人设注入:按 sessionKey 拉取 agent 人格与生效约定
28
28
  export const AUTO_RELAY_PERSONA = '/guest/relayBot/persona';
29
+ export const AUTO_RELAY_APPROVAL_EVENT = '/guest/relayBot/approvalEvent';
29
30
  export const AUTO_RELAY_UPLOAD = "/guest/relayBot/uploadMediaFiles";
30
31
  // ====== 上传文件配置常量(根据服务器性能调整)=======
31
32
  export const FILE_LIMITS = {
@@ -53,6 +53,8 @@ export declare class DLClient extends EventEmitter {
53
53
  * 失败返回 null,调用方降级为不注入,不影响正常对话。
54
54
  */
55
55
  fetchPersona(sessionKey: string, agentId?: string): Promise<any | null>;
56
+ /** 2026-10-27 把审批请求交给中继(由中继扇出给最多三人) */
57
+ pushApprovalEvent(payload: Record<string, unknown>): Promise<any>;
56
58
  private fetchConfig;
57
59
  private changeConnectStatus;
58
60
  private connect;
@@ -3,7 +3,7 @@ import { buildDLReplyMessage, messagePreviewHandler } from './message.js';
3
3
  import mqtt from 'mqtt';
4
4
  import { DLHttp } from './dl-http.js';
5
5
  import { decryptAesEcbPkcs5 } from './crypto.js';
6
- import { AUTO_RELAY_API, AUTO_RELAY_PERSONA, AUTO_RELAY_UPLOAD } from './const.js';
6
+ import { AUTO_RELAY_API, AUTO_RELAY_PERSONA, AUTO_RELAY_APPROVAL_EVENT, AUTO_RELAY_UPLOAD } from './const.js';
7
7
  import { createCmdHandler } from '../services/index.js';
8
8
  import { uuidStr } from '../utils.js';
9
9
  export class DLClient extends EventEmitter {
@@ -66,6 +66,17 @@ export class DLClient extends EventEmitter {
66
66
  return null;
67
67
  }
68
68
  }
69
+ /** 2026-10-27 把审批请求交给中继(由中继扇出给最多三人) */
70
+ async pushApprovalEvent(payload) {
71
+ try {
72
+ const data = await this.http.post(AUTO_RELAY_APPROVAL_EVENT, payload);
73
+ return data ?? null;
74
+ }
75
+ catch (e) {
76
+ this.logger.warn(`pushApprovalEvent failed: ${e}`);
77
+ return null;
78
+ }
79
+ }
69
80
  async fetchConfig() {
70
81
  const url = `/guest/mqtt/getConfig/${this.ctx.account.config.apiKey}`;
71
82
  const res = await this.http.get(url);
@@ -946,16 +946,57 @@ export async function routeAndDispatchMessage(ctx) {
946
946
  kind: 'in_process'
947
947
  });
948
948
  }
949
+ // 2026-10-27 terminal guard: hoisted so the finally block can always settle the stream
950
+ const mediaFiles = [];
951
+ // 2026-10-27 terminal guard: normal end, empty reply, abort and error must all send finish=true exactly once.
952
+ // Otherwise client runState.status.finish stays false and the UI spins forever.
953
+ let terminalSent = false;
954
+ let scopeEnded = false;
955
+ let personaScopeKey = '';
956
+ const endScopeOnce = () => {
957
+ if (scopeEnded) {
958
+ return;
959
+ }
960
+ scopeEnded = true;
961
+ if (personaAgentId) {
962
+ endPersonaScope(personaScopeKey, personaAgentId);
963
+ }
964
+ };
965
+ // send terminal state once; tag_status_completed is parsed as a state message, not a chat bubble
966
+ const settleOnce = async (content, kind = 'block') => {
967
+ if (terminalSent) {
968
+ return;
969
+ }
970
+ terminalSent = true;
971
+ try {
972
+ await client.publishProcessingState({
973
+ streamId,
974
+ content: '[tag_status_completed]',
975
+ status: 'read',
976
+ kind: 'in_process'
977
+ });
978
+ }
979
+ catch (e) {
980
+ logger.warn?.(`account[${accountId}] publish terminal status failed: ${String(e)}`);
981
+ }
982
+ try {
983
+ if (messageAccumulators.has(streamId)) {
984
+ await client.publishToServer({ streamId, content, finish: true, kind, mediaFiles }, chatOpts);
985
+ }
986
+ }
987
+ catch (e) {
988
+ logger.error(`account[${accountId}] publish terminal reply failed: ${String(e)}`);
989
+ }
990
+ };
949
991
  try {
950
992
  const ctx = await ctxPayload;
951
993
  // 2026-10-26 群聊人设作用域:分发期间绑定被 @ 的 agent,整轮(含工具循环)都能读到正确值
952
994
  // 2026-10-26 OpenClaw 的消息上下文字段名是 SessionKey(大写),兼容两种写法
953
- const personaScopeKey = ((ctx.SessionKey ?? ctx.sessionKey) || '');
995
+ personaScopeKey = ((ctx.SessionKey ?? ctx.sessionKey) || '');
954
996
  logger.debug?.(`persona scope: session=${personaScopeKey} agent=${personaAgentId ?? '-'}`);
955
997
  if (personaAgentId) {
956
998
  beginPersonaScope(personaScopeKey, personaAgentId);
957
999
  }
958
- const mediaFiles = [];
959
1000
  await core.channel.reply.dispatchReplyWithBufferedBlockDispatcher({
960
1001
  ctx,
961
1002
  cfg,
@@ -997,9 +1038,7 @@ export async function routeAndDispatchMessage(ctx) {
997
1038
  }
998
1039
  },
999
1040
  onSettled: async () => {
1000
- if (personaAgentId) {
1001
- endPersonaScope(personaScopeKey, personaAgentId);
1002
- }
1041
+ endScopeOnce();
1003
1042
  if ((accStatus.accumulatedPayload && accStatus.accumulatedPayload.length > 0) || mediaFiles.length > 0) {
1004
1043
  //发送结束状态
1005
1044
  await client.publishProcessingState({
@@ -1009,6 +1048,7 @@ export async function routeAndDispatchMessage(ctx) {
1009
1048
  kind: 'in_process'
1010
1049
  });
1011
1050
  //处理完成整体回复
1051
+ terminalSent = true;
1012
1052
  await client.publishToServer({
1013
1053
  streamId,
1014
1054
  content: accStatus.accumulatedPayload,
@@ -1017,11 +1057,13 @@ export async function routeAndDispatchMessage(ctx) {
1017
1057
  mediaFiles
1018
1058
  }, chatOpts);
1019
1059
  }
1060
+ else {
1061
+ // 2026-10-27 空回复(含被中止、模型未产出正文)也必须收尾,否则客户端一直转圈
1062
+ await settleOnce('[tag_status_completed]');
1063
+ }
1020
1064
  },
1021
1065
  onError: async (err, info) => {
1022
- if (personaAgentId) {
1023
- endPersonaScope(personaScopeKey, personaAgentId);
1024
- }
1066
+ endScopeOnce();
1025
1067
  const errorStr = String(err);
1026
1068
  await client.publishProcessingState({
1027
1069
  streamId,
@@ -1029,7 +1071,10 @@ export async function routeAndDispatchMessage(ctx) {
1029
1071
  status: 'read',
1030
1072
  kind: 'in_process'
1031
1073
  });
1032
- client.publishToServer({
1074
+ if (info.kind === 'final') {
1075
+ terminalSent = true;
1076
+ }
1077
+ await client.publishToServer({
1033
1078
  streamId,
1034
1079
  content: `[tag_error_pross]\n${errorStr}`,
1035
1080
  finish: info.kind === 'final',
@@ -1113,10 +1158,13 @@ export async function routeAndDispatchMessage(ctx) {
1113
1158
  }
1114
1159
  },
1115
1160
  async onItemEvent(payload) {
1116
- const kind = payload.kind;
1161
+ let kind = payload.kind;
1117
1162
  if (!kind) {
1118
1163
  return;
1119
1164
  }
1165
+ if (kind === 'preamble') {
1166
+ kind = 'commentary'; //适配前端中间文本气泡显示
1167
+ }
1120
1168
  const content = [];
1121
1169
  if (payload.name) {
1122
1170
  content.push(payload.name);
@@ -1130,18 +1178,28 @@ export async function routeAndDispatchMessage(ctx) {
1130
1178
  if (payload.summary) {
1131
1179
  content.push(payload.summary);
1132
1180
  }
1133
- const messages = [
1134
- `[tag_status_call_${kind}]`,
1135
- `[tag_status_phase_${payload.phase}]`,
1136
- `[tag_status_${payload.status}]`,
1137
- ...content
1138
- ];
1139
- await client.publishProcessingState({
1140
- streamId,
1141
- content: messages.join('>'),
1142
- status: 'read',
1143
- kind: kind
1144
- });
1181
+ if (kind === 'commentary') {
1182
+ await client.publishProcessingState({
1183
+ streamId,
1184
+ content: content.join('<br/>'),
1185
+ status: 'read',
1186
+ kind: kind
1187
+ });
1188
+ }
1189
+ else {
1190
+ const messages = [
1191
+ `[tag_status_call_${kind}]`,
1192
+ `[tag_status_phase_${payload.phase}]`,
1193
+ `[tag_status_${payload.status}]`,
1194
+ ...content
1195
+ ];
1196
+ await client.publishProcessingState({
1197
+ streamId,
1198
+ content: messages.join('>'),
1199
+ status: 'read',
1200
+ kind: kind
1201
+ });
1202
+ }
1145
1203
  logger.info(`onItemEvent >>> kind=${payload.kind}, phase=${payload.phase}, status =${payload.status}, content=${content.join('>')}`);
1146
1204
  },
1147
1205
  onCommandOutput: async (payload) => {
@@ -1227,4 +1285,11 @@ export async function routeAndDispatchMessage(ctx) {
1227
1285
  kind: 'block'
1228
1286
  }, chatOpts);
1229
1287
  }
1288
+ finally {
1289
+ // 2026-10-27 abort 兜底:dispatch 正常返回但没走 onSettled,或异常被上层吞掉,都补发一次终态
1290
+ endScopeOnce();
1291
+ if (!terminalSent) {
1292
+ await settleOnce('[tag_status_completed]');
1293
+ }
1294
+ }
1230
1295
  }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * 2026-10-27 读取生效执行策略,把「预设」解析成实际档位。
3
+ * 直接读网关配置文件,避免依赖 exec.approvals.get RPC(该调用在插件里会静默失败)。
4
+ */
5
+ export type ExecPresetId = 'read-only' | 'guarded' | 'workspace' | 'full';
6
+ export declare function readEffectiveExecPreset(): ExecPresetId | undefined;
@@ -0,0 +1,39 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ function mapMode(mode) {
5
+ switch (mode) {
6
+ case 'full': return 'full';
7
+ case 'deny': return 'read-only';
8
+ case 'ask': return 'guarded';
9
+ case 'auto': return 'workspace';
10
+ case 'allowlist': return 'read-only';
11
+ default: return undefined;
12
+ }
13
+ }
14
+ export function readEffectiveExecPreset() {
15
+ try {
16
+ const file = process.env.OPENCLAW_CONFIG_PATH
17
+ || path.join(os.homedir(), '.openclaw', 'openclaw.json');
18
+ const cfg = JSON.parse(fs.readFileSync(file, 'utf8'));
19
+ const exec = (cfg && cfg.tools && cfg.tools.exec) || {};
20
+ const byMode = mapMode(exec.mode);
21
+ if (byMode) {
22
+ return byMode;
23
+ }
24
+ const security = exec.security;
25
+ const ask = exec.ask;
26
+ if (security === 'full')
27
+ return 'full';
28
+ if (security === 'deny')
29
+ return 'read-only';
30
+ if (security === 'allowlist') {
31
+ return ask === 'on-miss' ? 'guarded' : 'read-only';
32
+ }
33
+ // OpenClaw 未配置时默认 full(与 openclaw approvals get 的 effective 一致)
34
+ return 'full';
35
+ }
36
+ catch {
37
+ return undefined;
38
+ }
39
+ }
@@ -24,6 +24,9 @@ export class CmdHandler {
24
24
  }, (payload) => {
25
25
  // 2026-10-22:用量上报走服务端事件,由中继落库
26
26
  void this.dlClient.publishEventToServer(payload, 'onUsage', '1');
27
+ }, (payload) => {
28
+ // 2026-10-27 审批待审推送:插件发现新条目即上报中继,中继再推审批人
29
+ void this.dlClient.publishEventToServer(payload, 'onApproval', '1');
27
30
  });
28
31
  }
29
32
  log(msg, type) {
@@ -18,8 +18,13 @@ export declare class ClawServices extends EventEmitter {
18
18
  private readonly terminalManager;
19
19
  /** 2026-10-22:token 用量上报(中继落库,按同事聚合) */
20
20
  private readonly usagePublisher?;
21
+ private readonly approvalPublisher?;
22
+ private approvalTimer;
23
+ private readonly approvalSeen;
21
24
  private usageTimer;
22
- constructor(options: ClawServiceOptions, logger: PluginLogger, terminalSink?: TerminalDataSink, usagePublisher?: (payload: Record<string, unknown>) => void);
25
+ constructor(options: ClawServiceOptions, logger: PluginLogger, terminalSink?: TerminalDataSink, usagePublisher?: (payload: Record<string, unknown>) => void, approvalPublisher?: (payload: Record<string, unknown>) => void);
26
+ /** 2026-10-27 每 10 秒本地查一次审批队列,出现新条目才推中继(推模式,非中继拉取) */
27
+ private startApprovalWatcher;
23
28
  /** 2026-10-22:每 60 秒把最近一天的 token 用量上报中继(幂等 upsert) */
24
29
  private startUsageReporter;
25
30
  log(msg: string, type: 'info' | 'warn' | 'error' | 'debug'): void;
@@ -127,6 +132,16 @@ export declare class ClawServices extends EventEmitter {
127
132
  * 新增 cmd 通道 agent.stop 指令
128
133
  */
129
134
  private handleStopAgent;
135
+ /** 2026-10-27 能力协议:声明本品牌支持的能力,客户端/中继据此渲染,不硬编码品牌 */
136
+ private handleAgentCapabilities;
137
+ /** 档位 id → 品牌真实取值;default 用 null 表示清除会话级覆盖 */
138
+ private static readonly PERMISSION_PRESETS;
139
+ private handlePermissionsGet;
140
+ private handlePermissionsSet;
141
+ /** 2026-10-27 审批待办(只读):三类审批合并,归一化为品牌无关结构 */
142
+ private handleApprovalsPending;
143
+ /** 2026-10-27 审批决议:品牌无关入口,内部映射到网关 approval.resolve */
144
+ private handleApprovalsResolve;
130
145
  private handleSessionsAbort;
131
146
  private handlChatAbout;
132
147
  /**
@@ -9,6 +9,7 @@ import fs from 'fs';
9
9
  import path from 'path';
10
10
  import WSClient from './ws-client.js';
11
11
  import { getOpenclawPath, getExtCapabilitiesDir } from '../utils.js';
12
+ import { readEffectiveExecPreset } from '../exec-policy.js';
12
13
  import { applyModelOverrideToSessionEntry } from 'openclaw/plugin-sdk/model-session-runtime';
13
14
  // 2026-10-15 适配 openclaw 2026.10.3:config-runtime 子路径已被官方移除(2026-09-30 SDK owner 批准),
14
15
  // 下列符号现由 session-store-runtime 导出(同名、签名兼容:resolveStorePath/getSessionEntry/listSessionEntries 仍为同步,patchSessionEntry 为 async,调用处均已 await)
@@ -32,14 +33,66 @@ export class ClawServices extends EventEmitter {
32
33
  terminalManager;
33
34
  /** 2026-10-22:token 用量上报(中继落库,按同事聚合) */
34
35
  usagePublisher;
36
+ // 2026-10-27 审批事件推送(插件 → 中继),本地轮询发现新待审即上报
37
+ approvalPublisher;
38
+ approvalTimer = null;
39
+ approvalSeen = new Set();
35
40
  usageTimer = null;
36
- constructor(options, logger, terminalSink, usagePublisher) {
41
+ constructor(options, logger, terminalSink, usagePublisher, approvalPublisher) {
37
42
  super();
38
43
  this.options = options;
39
44
  this.logger = logger;
40
45
  this.usagePublisher = usagePublisher;
46
+ this.approvalPublisher = approvalPublisher;
41
47
  this.terminalManager = new TerminalManager(terminalSink ?? (() => { }), (msg, type) => this.log(msg, type ?? 'info'));
42
48
  }
49
+ /** 2026-10-27 每 10 秒本地查一次审批队列,出现新条目才推中继(推模式,非中继拉取) */
50
+ startApprovalWatcher() {
51
+ if (this.approvalTimer || !this.approvalPublisher) {
52
+ return;
53
+ }
54
+ const tick = async () => {
55
+ try {
56
+ const publish = this.approvalPublisher;
57
+ if (!publish) {
58
+ return;
59
+ }
60
+ if (!this.client) {
61
+ return;
62
+ }
63
+ const kinds = ['exec', 'plugin', 'system-agent'];
64
+ for (const kind of kinds) {
65
+ const res = await this.client.approvalList(kind);
66
+ const list = Array.isArray(res) ? res : (res?.approvals ?? res?.items ?? []);
67
+ for (const item of list) {
68
+ const id = item?.id ?? item?.approvalId ?? item?.approval?.id;
69
+ if (!id || this.approvalSeen.has(String(id))) {
70
+ continue;
71
+ }
72
+ this.approvalSeen.add(String(id));
73
+ publish({
74
+ approvalId: String(id),
75
+ kind,
76
+ agentId: item?.agentId ?? item?.request?.agentId ?? '',
77
+ sessionKey: item?.sessionKey ?? item?.request?.sessionKey ?? '',
78
+ command: item?.command ?? item?.request?.command ?? item?.payload?.command ?? '',
79
+ cwd: item?.cwd ?? item?.request?.cwd,
80
+ createdAtMs: item?.createdAtMs ?? 0,
81
+ expiresAtMs: item?.expiresAtMs ?? 0
82
+ });
83
+ }
84
+ }
85
+ if (this.approvalSeen.size > 500) {
86
+ this.approvalSeen.clear();
87
+ }
88
+ }
89
+ catch (e) {
90
+ this.log(`approval watch failed: ${String(e)}`, 'warn');
91
+ }
92
+ };
93
+ this.approvalTimer = setInterval(() => { void tick(); }, 10000);
94
+ this.approvalTimer.unref?.();
95
+ }
43
96
  /** 2026-10-22:每 60 秒把最近一天的 token 用量上报中继(幂等 upsert) */
44
97
  startUsageReporter() {
45
98
  if (this.usageTimer || !this.usagePublisher) {
@@ -148,6 +201,7 @@ export class ClawServices extends EventEmitter {
148
201
  this.isInitialized = true;
149
202
  // 2026-10-22:启动后开始周期上报用量
150
203
  this.startUsageReporter();
204
+ this.startApprovalWatcher();
151
205
  return true;
152
206
  }
153
207
  catch (error) {
@@ -314,6 +368,22 @@ export class ClawServices extends EventEmitter {
314
368
  // 2026-10-24:会话级中止,无 runId 时也能立即停止,并丢弃排队后续
315
369
  result = await this.handleSessionsAbort(cmdMessage.params);
316
370
  break;
371
+ // 2026-10-27 能力协议(品牌无关):能力发现 + 执行档位
372
+ case 'agent.capabilities':
373
+ result = this.handleAgentCapabilities();
374
+ break;
375
+ case 'permissions.get':
376
+ result = await this.handlePermissionsGet(cmdMessage.params ?? {});
377
+ break;
378
+ case 'permissions.set':
379
+ result = await this.handlePermissionsSet(cmdMessage.params ?? {});
380
+ break;
381
+ case 'approvals.resolve':
382
+ result = await this.handleApprovalsResolve(cmdMessage.params ?? {});
383
+ break;
384
+ case 'approvals.pending':
385
+ result = await this.handleApprovalsPending(cmdMessage.params ?? {});
386
+ break;
317
387
  // 2026-10-21:终端能力(owner-only,见 CmdHandler 校验)
318
388
  case 'terminal.open':
319
389
  result = await this.terminalManager.open(cmdMessage.params);
@@ -972,12 +1042,137 @@ export class ClawServices extends EventEmitter {
972
1042
  sessionKey
973
1043
  });
974
1044
  }
975
- async handleSessionsAbort(params) {
976
- const { sessionKey } = params;
1045
+ /** 2026-10-27 能力协议:声明本品牌支持的能力,客户端/中继据此渲染,不硬编码品牌 */
1046
+ handleAgentCapabilities() {
1047
+ return {
1048
+ permissions: {
1049
+ supported: true,
1050
+ presets: [
1051
+ { id: 'default', label: '预设', description: '遵循代理程式已设定的执行权限', level: 1 },
1052
+ { id: 'read-only', label: '唯读', description: '工具可读取工作阶段根目录内的内容,但无法写入或执行命令', level: 2 },
1053
+ { id: 'guarded', label: '防护模式', description: '超出工作阶段根目录范围的请求由人工审查', level: 3 },
1054
+ { id: 'workspace', label: '工作区', description: '超出工作阶段根目录范围的请求由 AI 审查', level: 4 },
1055
+ { id: 'full', label: '完整存取权', description: '无需审查,档案存取与命令执行皆不受限制', level: 5, requiresAdmin: true }
1056
+ ]
1057
+ },
1058
+ approvals: { supported: true, push: true, kinds: ['exec', 'plugin', 'system-agent'] },
1059
+ audit: { supported: true }
1060
+ };
1061
+ }
1062
+ /** 档位 id → 品牌真实取值;default 用 null 表示清除会话级覆盖 */
1063
+ static PERMISSION_PRESETS = {
1064
+ 'default': null,
1065
+ 'read-only': 'read-only',
1066
+ 'guarded': 'guarded',
1067
+ 'workspace': 'workspace',
1068
+ 'full': 'full'
1069
+ };
1070
+ async handlePermissionsGet(params) {
1071
+ const sessionKey = params?.sessionKey ?? params?.key;
977
1072
  if (!sessionKey) {
978
- throw new Error('sessions.abort 缺少 sessionKey 参数');
1073
+ throw new Error('permissions.get 缺少 sessionKey');
1074
+ }
1075
+ const row = await this.client?.sessionsDescribe({ key: sessionKey });
1076
+ const mode = row?.permissionMode ?? row?.session?.permissionMode ?? null;
1077
+ const presetId = Object.entries(ClawServices.PERMISSION_PRESETS).find(([, v]) => v === mode)?.[0] ?? 'default';
1078
+ // 2026-10-27 继承态:读一次生效策略,把「预设」解析成实际档位(客户端显示 预设(完整存取权))
1079
+ let effectivePresetId = presetId;
1080
+ // 2026-10-27 继承态:直接读网关配置解析实际档位(RPC exec.approvals.get 在插件里会静默失败)
1081
+ if (presetId === 'default') {
1082
+ const resolved = readEffectiveExecPreset();
1083
+ if (resolved) {
1084
+ effectivePresetId = resolved;
1085
+ }
979
1086
  }
980
- return await this.client?.sessionsAbort({ sessionKey });
1087
+ this.log(`permissions.get session=${sessionKey} mode=${mode} preset=${presetId} effective=${effectivePresetId}`, 'info');
1088
+ return { presetId, inherited: !mode, effectivePresetId };
1089
+ }
1090
+ async handlePermissionsSet(params) {
1091
+ const sessionKey = params?.sessionKey ?? params?.key;
1092
+ const presetId = String(params?.presetId ?? '');
1093
+ if (!sessionKey || !presetId) {
1094
+ throw new Error('permissions.set 缺少 sessionKey 或 presetId');
1095
+ }
1096
+ if (!(presetId in ClawServices.PERMISSION_PRESETS)) {
1097
+ throw new Error('未知档位: ' + presetId);
1098
+ }
1099
+ const mode = ClawServices.PERMISSION_PRESETS[presetId];
1100
+ // 2026-10-27 写入后校验:网关可能返回 success=false 却不抛异常,也可能接受了但没落库
1101
+ const res = await this.client?.sessionsPatch({ key: sessionKey, patch: { permissionMode: mode } });
1102
+ if (res && res.success === false) {
1103
+ throw new Error(`permissions.set failed: ${res.error ?? res.code ?? 'unknown'}`);
1104
+ }
1105
+ const row = await this.client?.sessionsDescribe({ key: sessionKey });
1106
+ const applied = row?.permissionMode ?? row?.session?.permissionMode ?? null;
1107
+ if (mode !== null && applied !== mode) {
1108
+ throw new Error(`permissions.set not applied: expected=${mode} actual=${applied}`);
1109
+ }
1110
+ this.log(`permissions.set session=${sessionKey} preset=${presetId} mode=${mode} applied=${applied}`, 'info');
1111
+ return { ok: true, presetId };
1112
+ }
1113
+ /** 2026-10-27 审批待办(只读):三类审批合并,归一化为品牌无关结构 */
1114
+ async handleApprovalsPending(params) {
1115
+ const agentId = params?.agentId ? String(params.agentId) : undefined;
1116
+ const limit = Number(params?.limit ?? 50);
1117
+ const kinds = ['exec', 'plugin', 'system-agent'];
1118
+ const lists = await Promise.all(kinds.map(async (kind) => {
1119
+ try {
1120
+ const res = await this.client?.approvalList(kind);
1121
+ const list = Array.isArray(res) ? res : (res?.approvals ?? res?.items ?? []);
1122
+ return list.map((it) => ({ ...it, __kind: kind }));
1123
+ }
1124
+ catch {
1125
+ // 某一类审批不可用不影响其余类别
1126
+ return [];
1127
+ }
1128
+ }));
1129
+ const approvals = lists.flat()
1130
+ .filter((it) => !agentId || it.agentId === agentId || it?.request?.agentId === agentId)
1131
+ .slice(0, limit)
1132
+ .map((it) => ({
1133
+ approvalId: it.id ?? it.approvalId ?? it?.approval?.id,
1134
+ kind: it.__kind,
1135
+ agentId: it.agentId ?? it?.request?.agentId ?? '',
1136
+ agentName: it.agentName ?? it?.request?.agentName,
1137
+ sessionKey: it.sessionKey ?? it?.request?.sessionKey ?? '',
1138
+ requesterEmpId: it.requesterEmpId ?? it?.request?.requesterEmpId ?? '',
1139
+ command: it.command ?? it?.request?.command ?? it?.payload?.command ?? '',
1140
+ cwd: it.cwd ?? it?.request?.cwd,
1141
+ risk: it.risk ?? it?.request?.risk,
1142
+ createdAtMs: it.createdAtMs ?? it?.request?.createdAtMs ?? 0,
1143
+ expiresAtMs: it.expiresAtMs ?? it?.request?.expiresAtMs ?? 0,
1144
+ status: it.status ?? 'pending'
1145
+ }));
1146
+ return { approvals };
1147
+ }
1148
+ /** 2026-10-27 审批决议:品牌无关入口,内部映射到网关 approval.resolve */
1149
+ async handleApprovalsResolve(params) {
1150
+ const id = params?.approvalId ?? params?.id;
1151
+ const kind = params?.kind ?? 'exec';
1152
+ const decision = params?.decision;
1153
+ if (!id || !decision) {
1154
+ throw new Error('approvals.resolve 缺少 approvalId 或 decision');
1155
+ }
1156
+ if (!['exec', 'plugin', 'system-agent'].includes(String(kind))) {
1157
+ throw new Error('未知审批类型: ' + kind);
1158
+ }
1159
+ if (!['allow-once', 'allow-always', 'deny'].includes(String(decision))) {
1160
+ throw new Error('未知决议: ' + decision);
1161
+ }
1162
+ const res = await this.client?.resolveApproval({ id: String(id), kind: kind, decision: decision });
1163
+ return { ok: true, approvalId: id, decision, upstream: res ?? null };
1164
+ }
1165
+ async handleSessionsAbort(params) {
1166
+ // 2026-10-27:兼容客户端 key / sessionKey 两种写法,统一按网关 schema 转发
1167
+ const key = params?.key ?? params?.sessionKey;
1168
+ if (!key) {
1169
+ throw new Error('sessions.abort 缺少 key 参数');
1170
+ }
1171
+ return await this.client?.sessionsAbort({
1172
+ key,
1173
+ runId: params?.runId,
1174
+ clearQueued: params?.clearQueued ?? true
1175
+ });
981
1176
  }
982
1177
  async handlChatAbout(params) {
983
1178
  const { sessionKey, runId } = params;
@@ -306,7 +306,7 @@ export interface CmdResult {
306
306
  timestamp: string | number;
307
307
  timezone: string;
308
308
  }
309
- export type CmdType = 'agent.ask' | 'agent.list' | 'agent.create' | 'agent.update' | 'agent.delete' | 'agent.get' | 'agent.stop' | 'chat.abort' | 'task.list' | 'task.create' | 'task.update' | 'task.delete' | 'task.run' | 'status.health' | 'status.system' | 'status.usage' | 'models.list' | 'sessions.list' | 'sessions.get' | 'sessions.describe' | 'sessions.resolve' | 'sessions.create' | 'sessions.archive' | 'sessions.restore' | 'sessions.delete' | 'sessions.reset' | 'sessions.patch' | 'sessions.currentModel' | 'sessions.abort' | 'terminal.open' | 'terminal.input' | 'terminal.resize' | 'terminal.close' | 'chat.history' | 'chat.trajectory' | 'skills.status' | 'skills.search' | 'skills.detail' | 'skills.install' | 'skills.update' | 'skills.securityVerdicts' | 'cancelMessage' | 'usage.cost' | 'sessions.usage' | 'sessions.usage.logs' | 'pairing.approve' | 'artifacts.list' | 'artifacts.get' | 'artifacts.download' | 'agents.files.list' | 'agents.files.get' | 'extCapabilities.status' | 'extCapabilities.check' | 'extCapabilities.install';
309
+ export type CmdType = 'agent.ask' | 'agent.list' | 'agent.create' | 'agent.update' | 'agent.delete' | 'agent.get' | 'agent.stop' | 'chat.abort' | 'agent.capabilities' | 'permissions.get' | 'permissions.set' | 'approvals.pending' | 'approvals.resolve' | 'task.list' | 'task.create' | 'task.update' | 'task.delete' | 'task.run' | 'status.health' | 'status.system' | 'status.usage' | 'models.list' | 'sessions.list' | 'sessions.get' | 'sessions.describe' | 'sessions.resolve' | 'sessions.create' | 'sessions.archive' | 'sessions.restore' | 'sessions.delete' | 'sessions.reset' | 'sessions.patch' | 'sessions.currentModel' | 'sessions.abort' | 'terminal.open' | 'terminal.input' | 'terminal.resize' | 'terminal.close' | 'chat.history' | 'chat.trajectory' | 'skills.status' | 'skills.search' | 'skills.detail' | 'skills.install' | 'skills.update' | 'skills.securityVerdicts' | 'cancelMessage' | 'usage.cost' | 'sessions.usage' | 'sessions.usage.logs' | 'pairing.approve' | 'artifacts.list' | 'artifacts.get' | 'artifacts.download' | 'agents.files.list' | 'agents.files.get' | 'extCapabilities.status' | 'extCapabilities.check' | 'extCapabilities.install';
310
310
  export type ReadlineType = Extract<CmdType, 'chat.trajectory'>;
311
311
  export interface ClawMessage {
312
312
  type: 'res' | 'event';
@@ -316,7 +316,7 @@ export interface ClawMessage {
316
316
  payload: any;
317
317
  error?: any;
318
318
  }
319
- export type EventType = 'onTick' | 'onHealth' | 'onHandshaked' | 'onConnectState' | 'onError' | 'onAgentReply' | 'onAgentChat' | 'onChatTrajectory' | 'onCron' | 'onShutdown' | 'onSessionsChanged' | 'onSkillInstalled' | 'onSkillInstalling' | 'onSkillError' | 'onPairingRequest' | 'onPairingResult'
319
+ export type EventType = 'onApproval' | 'onTick' | 'onHealth' | 'onHandshaked' | 'onConnectState' | 'onError' | 'onAgentReply' | 'onAgentChat' | 'onChatTrajectory' | 'onCron' | 'onShutdown' | 'onSessionsChanged' | 'onSkillInstalled' | 'onSkillInstalling' | 'onSkillError' | 'onPairingRequest' | 'onPairingResult'
320
320
  /** 2026-10-22:周期上报 token 用量 */
321
321
  | 'onUsage' | 'onTerminal';
322
322
  export type CmdParamsPatchSessionEntry = {
@@ -143,9 +143,22 @@ export declare class WSClient extends EventEmitter {
143
143
  sessionKey: string;
144
144
  runId?: string;
145
145
  }): Promise<any>;
146
+ /** 2026-10-27 审批决议:放行一次 / 永久放行 / 拒绝(网关 schema: id/kind/decision) */
147
+ resolveApproval(params: {
148
+ id: string;
149
+ kind: 'exec' | 'plugin' | 'system-agent';
150
+ decision: 'allow-once' | 'allow-always' | 'deny';
151
+ }): Promise<any>;
152
+ /** 2026-10-27 读取生效执行策略:把「预设」解析成实际档位 */
153
+ execApprovalsGet(): Promise<any>;
154
+ /** 2026-10-27 审批队列(只读):三类审批分别取列表,core 已做过期过滤 */
155
+ approvalList(kind: 'exec' | 'plugin' | 'system-agent'): Promise<any>;
146
156
  /** 2026-10-24:会话级中止(无 runId 时使用),同时丢弃排队后续 */
147
157
  sessionsAbort(params: {
148
- sessionKey: string;
158
+ sessionKey?: string;
159
+ key?: string;
160
+ runId?: string;
161
+ clearQueued?: boolean;
149
162
  }): Promise<any>;
150
163
  getSkillSecurityVerdicts(agentId?: string): Promise<any>;
151
164
  getUsageCost(params: Record<string, unknown>): Promise<any>;
@@ -464,13 +464,36 @@ export class WSClient extends EventEmitter {
464
464
  }
465
465
  });
466
466
  }
467
+ /** 2026-10-27 审批决议:放行一次 / 永久放行 / 拒绝(网关 schema: id/kind/decision) */
468
+ async resolveApproval(params) {
469
+ return this.sendRequest({ type: 'req', method: 'approval.resolve', params });
470
+ }
471
+ /** 2026-10-27 读取生效执行策略:把「预设」解析成实际档位 */
472
+ async execApprovalsGet() {
473
+ return this.sendRequest({ type: 'req', method: 'exec.approvals.get', params: {} });
474
+ }
475
+ /** 2026-10-27 审批队列(只读):三类审批分别取列表,core 已做过期过滤 */
476
+ async approvalList(kind) {
477
+ const method = kind === 'exec'
478
+ ? 'exec.approval.list'
479
+ : kind === 'plugin'
480
+ ? 'plugin.approval.list'
481
+ : 'openclaw.approval.list';
482
+ return this.sendRequest({ type: 'req', method, params: {} });
483
+ }
467
484
  /** 2026-10-24:会话级中止(无 runId 时使用),同时丢弃排队后续 */
468
485
  async sessionsAbort(params) {
469
- const { sessionKey } = params;
486
+ // 2026-10-27 修正:sessions.abort 的参数字段是 key(不是 sessionKey),网关 schema 为 key/runId/agentId/clearQueued;
487
+ // clearQueued 丢弃排队后续,避免中止后不到一秒又被排队任务拉起。
488
+ const key = params.key ?? params.sessionKey;
470
489
  return this.sendRequest({
471
490
  type: 'req',
472
491
  method: 'sessions.abort',
473
- params: { sessionKey }
492
+ params: {
493
+ key,
494
+ clearQueued: params.clearQueued ?? true,
495
+ ...(params.runId ? { runId: params.runId } : {})
496
+ }
474
497
  });
475
498
  }
476
499
  async getSkillSecurityVerdicts(agentId) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dlinkclaw-openclaw",
3
- "version": "2026.10.23",
3
+ "version": "2026.10.26",
4
4
  "description": "DLinkClaw OpenClaw channel plugin — 朵联 OpenClaw 接入通道",
5
5
  "keywords": [
6
6
  "DLinkClaw",