@carfiedli/runtime-guardrail 0.1.19

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 (86) hide show
  1. package/README.fe.md +256 -0
  2. package/README.hooks-security.md +1017 -0
  3. package/README.md +1316 -0
  4. package/dist/adapters/index.d.ts +1 -0
  5. package/dist/adapters/persistence/file-store.d.ts +18 -0
  6. package/dist/adapters/persistence/index.d.ts +4 -0
  7. package/dist/adapters/persistence/json-event-log.d.ts +31 -0
  8. package/dist/adapters/persistence/queue-store.d.ts +19 -0
  9. package/dist/adapters/persistence/snapshot-store.d.ts +14 -0
  10. package/dist/approval/approval-service.d.ts +27 -0
  11. package/dist/approval/approval-state-machine.d.ts +5 -0
  12. package/dist/approval/hitl/hitl-connector.d.ts +9 -0
  13. package/dist/approval/index.d.ts +4 -0
  14. package/dist/approval/run-hold-service.d.ts +16 -0
  15. package/dist/audit/audit-event-store.d.ts +12 -0
  16. package/dist/audit/audit-read-model-builder.d.ts +17 -0
  17. package/dist/audit/audit-service.d.ts +18 -0
  18. package/dist/audit/incident-query-service.d.ts +7 -0
  19. package/dist/audit/index.d.ts +5 -0
  20. package/dist/audit/metrics-projection.d.ts +10 -0
  21. package/dist/bootstrap/create-runtime-guardrail-plugin.d.ts +3 -0
  22. package/dist/bootstrap/dependency-container.d.ts +2 -0
  23. package/dist/bootstrap/index.d.ts +3 -0
  24. package/dist/bootstrap/runtime-facade.d.ts +31 -0
  25. package/dist/compat/index.d.ts +1 -0
  26. package/dist/compat/legacy-types.d.ts +29 -0
  27. package/dist/contracts/core.d.ts +277 -0
  28. package/dist/contracts/events.d.ts +35 -0
  29. package/dist/contracts/host.d.ts +239 -0
  30. package/dist/contracts/index.d.ts +6 -0
  31. package/dist/contracts/operator.d.ts +110 -0
  32. package/dist/execution/egress-mediator.d.ts +7 -0
  33. package/dist/execution/execution-broker.d.ts +13 -0
  34. package/dist/execution/execution-plan-builder.d.ts +12 -0
  35. package/dist/execution/index.d.ts +4 -0
  36. package/dist/execution/model-governance-service.d.ts +7 -0
  37. package/dist/index.d.ts +29 -0
  38. package/dist/index.js +23 -0
  39. package/dist/openclaw/hooks/egress-adapter.d.ts +9 -0
  40. package/dist/openclaw/hooks/hook-registry.d.ts +21 -0
  41. package/dist/openclaw/hooks/hook-result-mapper.d.ts +43 -0
  42. package/dist/openclaw/hooks/hook-types.d.ts +31 -0
  43. package/dist/openclaw/hooks/index.d.ts +8 -0
  44. package/dist/openclaw/hooks/ingress-adapter.d.ts +14 -0
  45. package/dist/openclaw/hooks/llm-request-adapter.d.ts +9 -0
  46. package/dist/openclaw/hooks/persist-adapter.d.ts +30 -0
  47. package/dist/openclaw/hooks/tool-call-adapter.d.ts +7 -0
  48. package/dist/openclaw/index.d.ts +4 -0
  49. package/dist/openclaw/plugin-runtime.d.ts +103 -0
  50. package/dist/openclaw/rpc-handlers.d.ts +20 -0
  51. package/dist/openclaw/skills-availability.d.ts +10 -0
  52. package/dist/openclaw/skills-upload.d.ts +17 -0
  53. package/dist/openclaw/testing/index.d.ts +1 -0
  54. package/dist/openclaw/testing/mock-openclaw-api.d.ts +74 -0
  55. package/dist/operator/cli/register-cli.d.ts +4 -0
  56. package/dist/operator/command-service.d.ts +15 -0
  57. package/dist/operator/index.d.ts +5 -0
  58. package/dist/operator/query-service.d.ts +21 -0
  59. package/dist/operator/reporting/report-service.d.ts +9 -0
  60. package/dist/operator/rpc/register-rpc.d.ts +5 -0
  61. package/dist/policy/detectors/detector-port.d.ts +23 -0
  62. package/dist/policy/finding-normalizer.d.ts +3 -0
  63. package/dist/policy/index.d.ts +4 -0
  64. package/dist/policy/policy-engine.d.ts +8 -0
  65. package/dist/policy/stage-resolver.d.ts +7 -0
  66. package/dist/runtime-core/device-id.d.ts +15 -0
  67. package/dist/runtime-core/evaluate-service.d.ts +91 -0
  68. package/dist/runtime-core/index.d.ts +10 -0
  69. package/dist/runtime-core/memory-audit-logger.d.ts +55 -0
  70. package/dist/runtime-core/memory-store.d.ts +141 -0
  71. package/dist/runtime-core/remote-guard-request-builder.d.ts +15 -0
  72. package/dist/runtime-core/remote-guard-transport.d.ts +79 -0
  73. package/dist/runtime-core/remote-guard-types.d.ts +183 -0
  74. package/dist/runtime-core/remote-policy-evaluator.d.ts +51 -0
  75. package/dist/runtime-core/skill-name-resolver.d.ts +31 -0
  76. package/dist/runtime-core/sync-remote-evaluate.d.ts +29 -0
  77. package/dist/runtime-core/sync-remote-worker.d.ts +14 -0
  78. package/dist/runtime-core/sync-remote-worker.js +2 -0
  79. package/dist/runtime-core/telemetry-service.d.ts +94 -0
  80. package/dist/runtime-core/telemetry-types.d.ts +181 -0
  81. package/dist/types.d.ts +224 -0
  82. package/dist/version.d.ts +1 -0
  83. package/openclaw.plugin.json +76 -0
  84. package/package.json +71 -0
  85. package/remote-guard-config.json +30 -0
  86. package/scripts/runtime-guardrailctl.mjs +864 -0
@@ -0,0 +1,183 @@
1
+ /**
2
+ * 远端安全检测服务请求/响应类型定义
3
+ * 基于 iwiki 文档:https://iwiki.woa.com/p/4018637975
4
+ */
5
+ /** Hook 类型枚举 */
6
+ export type RemoteGuardHookType = "message_received" | "before_prompt_build" | "llm_input" | "before_tool_call" | "tool_result_persist" | "before_message_write" | "message_sending";
7
+ /** message_received 事件数据 */
8
+ export type MessageReceivedEvents = {
9
+ from?: string;
10
+ content: string;
11
+ metadata: {
12
+ provider: string;
13
+ surface: string;
14
+ originatingChannel: string;
15
+ messageId: string;
16
+ senderId: string;
17
+ };
18
+ };
19
+ /** before_prompt_build 事件数据 */
20
+ export type BeforePromptBuildEvents = {
21
+ prompt: string;
22
+ };
23
+ /** llm_input 事件数据 */
24
+ export type LlmInputEvents = {
25
+ runId: string;
26
+ sessionId: string;
27
+ provider: string;
28
+ model: string;
29
+ prompt: string;
30
+ imagesCount: number;
31
+ };
32
+ /** before_tool_call 事件数据 */
33
+ export type BeforeToolCallEvents = {
34
+ toolName: string;
35
+ params: Record<string, unknown>;
36
+ runId: string;
37
+ toolCallId: string;
38
+ /** Skill 名称(当检测到读取 SKILL.md 时填充,否则为空字符串) */
39
+ skillName: string;
40
+ };
41
+ /** tool_result_persist 事件数据 */
42
+ export type ToolResultPersistEvents = {
43
+ toolName: string;
44
+ toolCallId: string;
45
+ content: string;
46
+ isError: boolean;
47
+ isSynthetic: boolean;
48
+ };
49
+ /** Token 使用统计 */
50
+ export type UsageInfo = {
51
+ input: number;
52
+ output: number;
53
+ cacheRead: number;
54
+ cacheWrite: number;
55
+ totalTokens: number;
56
+ cost: {
57
+ input: number;
58
+ output: number;
59
+ cacheRead: number;
60
+ cacheWrite: number;
61
+ total: number;
62
+ };
63
+ };
64
+ /** before_message_write 事件数据 */
65
+ export type BeforeMessageWriteEvents = {
66
+ role: "user" | "assistant" | "toolResult";
67
+ content: string;
68
+ stopReason?: string;
69
+ usage?: UsageInfo;
70
+ toolName?: string;
71
+ isError?: boolean;
72
+ };
73
+ /** message_sending 事件数据 */
74
+ export type MessageSendingEvents = {
75
+ to: string;
76
+ content: string;
77
+ metadata?: Record<string, unknown>;
78
+ };
79
+ /** 事件数据按 hook 类型分组 */
80
+ export type RemoteGuardEventsData = {
81
+ message_received: MessageReceivedEvents | Record<string, never>;
82
+ before_prompt_build: BeforePromptBuildEvents | Record<string, never>;
83
+ llm_input: LlmInputEvents | Record<string, never>;
84
+ before_tool_call: BeforeToolCallEvents | Record<string, never>;
85
+ tool_result_persist: ToolResultPersistEvents | Record<string, never>;
86
+ before_message_write: BeforeMessageWriteEvents | Record<string, never>;
87
+ message_sending: MessageSendingEvents | Record<string, never>;
88
+ };
89
+ /** 上下文数据 */
90
+ export type RemoteGuardContextData = {
91
+ agentId?: string;
92
+ sessionId?: string;
93
+ sessionKey?: string;
94
+ channelId?: string;
95
+ runId?: string;
96
+ workspaceDir?: string;
97
+ messageProvider?: string;
98
+ trigger?: string;
99
+ toolName?: string;
100
+ toolCallId?: string;
101
+ };
102
+ /** 安全检测数据(Data 字段内容) */
103
+ export type RemoteGuardSecurityCheckData = {
104
+ hook: RemoteGuardHookType;
105
+ timestamp: number;
106
+ events: RemoteGuardEventsData;
107
+ ctx: RemoteGuardContextData;
108
+ };
109
+ /** 远端安全检测请求体(最外层) */
110
+ export type RemoteGuardRequest = {
111
+ Type: number;
112
+ AgentId: string;
113
+ DeviceId: string;
114
+ Data: RemoteGuardSecurityCheckData;
115
+ };
116
+ /** 远端安全检测响应体 */
117
+ export type RemoteGuardResponse = {
118
+ RequestId?: string;
119
+ /**
120
+ * 响应动作:
121
+ * - allow: 放行
122
+ * - deny: 阻断,停止当前会话
123
+ * - approval: 需要审批,暂停当前会话等待审批
124
+ * - redact: 脱敏
125
+ * - permit: 放行(与 allow 等效,不做任何处理,不记录 incident)
126
+ * - log: 记录日志后放行(不做任何处理,不记录 incident,正常继续)
127
+ */
128
+ Action: "allow" | "deny" | "approval" | "redact" | "permit" | "log";
129
+ RuleId?: string;
130
+ Message?: string;
131
+ RedactedContent?: string;
132
+ };
133
+ /** 远端服务配置 */
134
+ export type RemoteGuardServerConfig = {
135
+ ip: string;
136
+ port: number;
137
+ path: string;
138
+ corPresignPath?: string;
139
+ /** skills 上传完成后提交检测任务的接口路径 */
140
+ detectPath?: string;
141
+ };
142
+ /** WebSocket 配置 */
143
+ export type RemoteGuardWebSocketConfig = {
144
+ /** WebSocket 端口(默认 8081) */
145
+ port?: number;
146
+ /** 连接协议(ws 或 wss,默认 ws) */
147
+ protocol?: "ws" | "wss";
148
+ };
149
+ /** 远端认证配置 */
150
+ export type RemoteGuardAuthConfig = {
151
+ key: string;
152
+ };
153
+ /** 远端身份配置 */
154
+ export type RemoteGuardIdentityConfig = {
155
+ agentId: string;
156
+ };
157
+ /** 遥测上报配置 */
158
+ export type RemoteGuardTelemetryConfig = {
159
+ /** 是否启用遥测上报 */
160
+ enabled?: boolean;
161
+ /** 心跳间隔(毫秒),默认 30000 */
162
+ heartbeatIntervalMs?: number;
163
+ /** 数据上报间隔(毫秒),默认 600000(10分钟) */
164
+ dataReportIntervalMs?: number;
165
+ };
166
+ /** 远端选项配置 */
167
+ export type RemoteGuardOptionsConfig = {
168
+ timeoutMs: number;
169
+ /** 同步 hook(before_message_write / tool_result_persist)远端调用超时(毫秒),默认 500 */
170
+ syncHookTimeoutMs?: number;
171
+ /** skills 上传产物落盘目录(支持绝对路径或相对 workspace 的路径) */
172
+ skillsStateDir?: string;
173
+ };
174
+ /** 完整的远端配置 */
175
+ export type RemoteGuardConfig = {
176
+ enabled: boolean;
177
+ server: RemoteGuardServerConfig;
178
+ websocket?: RemoteGuardWebSocketConfig;
179
+ auth: RemoteGuardAuthConfig;
180
+ identity: RemoteGuardIdentityConfig;
181
+ telemetry?: RemoteGuardTelemetryConfig;
182
+ options: RemoteGuardOptionsConfig;
183
+ };
@@ -0,0 +1,51 @@
1
+ import type { PolicyEvaluator } from "./evaluate-service";
2
+ import type { CompiledShieldRule, ShieldApprovalRequest, ShieldHookModification, ShieldMatch, ShieldPolicyFinding, ShieldPolicyInput, ShieldPolicyResult, ShieldRedaction, ShieldRuleAction, ShieldRunHold, ShieldSeverity, ShieldStage } from "../types";
3
+ /** 远端评估请求体(可直接对接安全服务) */
4
+ export type RemotePolicyRequest = {
5
+ input: ShieldPolicyInput;
6
+ stage: ShieldStage;
7
+ };
8
+ /** 远端评估响应体(允许部分字段,骨架会补齐默认值) */
9
+ export type RemotePolicyResponse = Partial<ShieldPolicyResult> & {
10
+ rawAction?: ShieldRuleAction;
11
+ effectiveAction?: ShieldRuleAction;
12
+ severity?: ShieldSeverity;
13
+ blockReason?: string;
14
+ redactions?: ShieldRedaction[];
15
+ redactedTexts?: Record<string, string>;
16
+ matched?: ShieldMatch[];
17
+ appliedExceptions?: string[];
18
+ redactionRules?: CompiledShieldRule[];
19
+ tags?: string[];
20
+ durationMs?: number;
21
+ findings?: ShieldPolicyFinding[];
22
+ modifications?: ShieldHookModification[];
23
+ approvalRequest?: ShieldApprovalRequest;
24
+ runHold?: ShieldRunHold;
25
+ };
26
+ /** 远端调用函数签名:由接入方注入(HTTP/gRPC/SDK 均可) */
27
+ export type RemotePolicyTransport = (request: RemotePolicyRequest) => Promise<RemotePolicyResponse | undefined>;
28
+ /** 远端评估器配置 */
29
+ export type RemotePolicyEvaluatorConfig = {
30
+ /** 真实对接时由业务方注入远端调用逻辑 */
31
+ transport?: RemotePolicyTransport;
32
+ /** 远端失败时是否打印日志(默认 true) */
33
+ enableWarnLog?: boolean;
34
+ /** 远端失败时回退动作(默认 allow) */
35
+ fallbackAction?: ShieldRuleAction;
36
+ };
37
+ /**
38
+ * 远端策略评估器骨架:
39
+ * - 未配置 transport 时,默认返回 allow(确保内置 demo 策略不生效)
40
+ * - 配置 transport 后,可直接对接安全团队远端接口
41
+ */
42
+ export declare class RemotePolicyEvaluator implements PolicyEvaluator {
43
+ private readonly transport?;
44
+ private readonly enableWarnLog;
45
+ private readonly fallbackAction;
46
+ constructor(config?: RemotePolicyEvaluatorConfig);
47
+ evaluate(input: ShieldPolicyInput, stage: ShieldStage): Promise<ShieldPolicyResult>;
48
+ evaluateSync(_input: ShieldPolicyInput, _stage: ShieldStage): ShieldPolicyResult;
49
+ }
50
+ /** 工厂函数:创建远端策略评估器骨架 */
51
+ export declare const createRemotePolicyEvaluator: (config?: RemotePolicyEvaluatorConfig) => PolicyEvaluator;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Skill 名称解析器
3
+ * 用于从 SKILL.md 文件路径中识别和提取 skill 名称
4
+ */
5
+ /** Skill 名称解析结果 */
6
+ export type SkillNameResolveResult = {
7
+ /** 是否检测到 SKILL.md 读取操作 */
8
+ isSkillRead: boolean;
9
+ /** Skill 名称(如果识别到) */
10
+ skillName: string;
11
+ /** 解析来源:'frontmatter' 表示从文件内容解析,'path' 表示从路径提取 */
12
+ source: "frontmatter" | "path" | "none";
13
+ };
14
+ /**
15
+ * 解析 skill 名称
16
+ * 优先从 SKILL.md 文件内容的 frontmatter 中解析,解析失败则从路径中提取
17
+ *
18
+ * @param toolName 工具名称
19
+ * @param params 工具参数
20
+ * @returns 解析结果
21
+ */
22
+ export declare const resolveSkillName: (toolName: string, params: Record<string, unknown>) => Promise<SkillNameResolveResult>;
23
+ /**
24
+ * 同步版本:仅从路径提取 skill 名称(不读取文件)
25
+ * 用于无法执行异步操作的场景
26
+ *
27
+ * @param toolName 工具名称
28
+ * @param params 工具参数
29
+ * @returns 解析结果
30
+ */
31
+ export declare const resolveSkillNameSync: (toolName: string, params: Record<string, unknown>) => SkillNameResolveResult;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * 同步远端安全评估模块
3
+ *
4
+ * 通过 SharedArrayBuffer + Atomics.wait + Worker 线程实现:
5
+ * 在同步 hook(before_message_write / tool_result_persist)中
6
+ * 同步等待远端 HTTP 安全检测结果,根据返回做阻断/脱敏决策。
7
+ *
8
+ * 超时后 fallback allow,避免冻结 openclaw 进程。
9
+ */
10
+ import type { GuardrailDecision, HookEnvelope } from "../contracts";
11
+ import type { RemoteGuardConfig } from "./remote-guard-types";
12
+ /**
13
+ * 同步执行远端安全检测
14
+ *
15
+ * 在同步 hook 中调用,通过 Worker + SharedArrayBuffer + Atomics.wait
16
+ * 同步等待远端 HTTP 检测结果并返回 GuardrailDecision。
17
+ *
18
+ * @param envelope 钩子信封
19
+ * @param config 远端配置
20
+ * @returns 护栏决策(超时/错误时返回 fallback allow 决策)
21
+ */
22
+ export declare const syncRemoteEvaluate: (envelope: HookEnvelope, config: RemoteGuardConfig) => GuardrailDecision;
23
+ /**
24
+ * 创建绑定了配置的同步远端评估函数
25
+ *
26
+ * @param config 远端配置(为 null 时返回 undefined,表示远端不可用)
27
+ * @returns 同步评估函数,或 undefined(远端不可用)
28
+ */
29
+ export declare const createSyncRemoteEvaluateFn: (config: RemoteGuardConfig | null | undefined) => ((envelope: HookEnvelope) => GuardrailDecision) | undefined;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Worker 线程脚本:执行同步远端 HTTP 调用
3
+ *
4
+ * 通过 SharedArrayBuffer + Atomics 与主线程通信:
5
+ * - 主线程通过 workerData 传入 SAB 和请求参数
6
+ * - Worker 异步执行 fetch,将结果写入 SAB
7
+ * - 完成后 Atomics.notify 通知主线程
8
+ *
9
+ * SharedArrayBuffer 布局:
10
+ * [0..3] Int32 — status (0=pending, 1=success, 2=http_error, 3=network_error)
11
+ * [4..7] Int32 — result length in bytes
12
+ * [8..] Uint8Array — result data (response body or error message, UTF-8)
13
+ */
14
+ export {};
@@ -0,0 +1,2 @@
1
+ /* @tencent/runtime-guardrail worker - UNLICENSED */
2
+ "use strict";var c=require("worker_threads"),{sab:i,url:m,method:d,headers:l,body:g,timeoutMs:u}=c.workerData,o=new Int32Array(i,0,2),s=new Uint8Array(i,8),a=(t,r)=>{let e=new TextEncoder().encode(r),n=Math.min(e.length,s.length);s.set(e.subarray(0,n)),Atomics.store(o,1,n),Atomics.store(o,0,t),Atomics.notify(o,0)};(async()=>{try{let t=new AbortController,r=setTimeout(()=>t.abort(),u),e=await fetch(m,{method:d,headers:l,body:g,signal:t.signal});clearTimeout(r);let n=await e.text();a(e.ok?1:2,n)}catch(t){let r=t instanceof Error?t.message:String(t);a(3,r)}})();
@@ -0,0 +1,94 @@
1
+ /**
2
+ * 遥测上报后台服务
3
+ * 实现心跳上报(30秒一次)和数据上报(10分钟一次)
4
+ * 基于 iwiki 文档:https://iwiki.woa.com/p/4018670075
5
+ */
6
+ import type { OpenClawApi } from "../contracts";
7
+ import type { MemoryStore } from "./memory-store";
8
+ import type { TelemetryServiceConfig, TelemetryServiceStatus } from "./telemetry-types";
9
+ import type { RemoteGuardConfig } from "./remote-guard-types";
10
+ /** 遥测服务实例 */
11
+ export declare class TelemetryService {
12
+ private config;
13
+ private readonly store;
14
+ private readonly logger?;
15
+ private ws;
16
+ private heartbeatInterval;
17
+ private dataReportInterval;
18
+ private reconnectTimeout;
19
+ private authTimeout;
20
+ private authRetryInterval;
21
+ private isRunning;
22
+ private isAuthenticated;
23
+ private pendingAuthRequestId;
24
+ private status;
25
+ /** 已发送但未收到 ACK 的数据上报,key 为 request_id,value 为 incident IDs */
26
+ private readonly pendingReports;
27
+ constructor(config: TelemetryServiceConfig, store: MemoryStore, logger?: {
28
+ info: (msg: string) => void;
29
+ warn: (msg: string) => void;
30
+ error: (msg: string) => void;
31
+ } | undefined);
32
+ /** 获取当前状态 */
33
+ getStatus(): TelemetryServiceStatus;
34
+ /** 启动遥测服务 */
35
+ start(): Promise<void>;
36
+ /** 停止遥测服务 */
37
+ stop(): Promise<void>;
38
+ /** 使用新配置重新加载遥测服务 */
39
+ reload(config: TelemetryServiceConfig | undefined): Promise<void>;
40
+ /** 建立 WebSocket 连接 */
41
+ private connect;
42
+ /** 创建 WebSocket 连接 */
43
+ private createWebSocketConnection;
44
+ /** WebSocket 连接成功 */
45
+ private handleOpen;
46
+ /** 发送认证消息 */
47
+ private sendAuth;
48
+ /** 安排认证重试 */
49
+ private scheduleAuthRetry;
50
+ /** 停止认证重试 */
51
+ private stopAuthRetry;
52
+ /** 启动心跳和数据上报定时器 */
53
+ private startHeartbeatAndDataReport;
54
+ /** 认证成功后的处理 */
55
+ private onAuthenticationSuccess;
56
+ /** WebSocket 接收消息 */
57
+ private handleMessage;
58
+ /** 处理消息数据 */
59
+ private processMessageData;
60
+ /** WebSocket 连接关闭 */
61
+ private handleClose;
62
+ /** WebSocket 错误 */
63
+ private handleError;
64
+ /** 计划重连 */
65
+ private scheduleReconnect;
66
+ /** 发送心跳 */
67
+ private sendHeartbeat;
68
+ /** 发送数据上报 */
69
+ private sendDataReport;
70
+ /** 日志输出 */
71
+ private log;
72
+ }
73
+ /** 从 RemoteGuardConfig 构建 TelemetryServiceConfig */
74
+ export declare const buildTelemetryConfigFromRemoteGuard: (remoteConfig: RemoteGuardConfig) => TelemetryServiceConfig;
75
+ /** 遥测服务注册选项 */
76
+ export type TelemetryServiceOptions = {
77
+ /** 是否启用遥测上报 */
78
+ enabled?: boolean;
79
+ /** 自定义配置(优先于从 remote-guard-config.json 加载) */
80
+ config?: Partial<TelemetryServiceConfig>;
81
+ /** 心跳间隔(毫秒),默认 30000 */
82
+ heartbeatIntervalMs?: number;
83
+ /** 数据上报间隔(毫秒),默认 600000 */
84
+ dataReportIntervalMs?: number;
85
+ /** 指向用户侧下发的 remote-guard-config.json */
86
+ remoteGuardConfigPath?: string;
87
+ /** 直接注入远端配置(优先于 remoteGuardConfigPath) */
88
+ remoteGuardConfig?: RemoteGuardConfig;
89
+ };
90
+ export declare const resolveTelemetryServiceConfig: (options?: TelemetryServiceOptions) => TelemetryServiceConfig | undefined;
91
+ /**
92
+ * 注册遥测服务到 OpenClaw 插件
93
+ */
94
+ export declare const registerTelemetryService: (api: OpenClawApi, store: MemoryStore, options?: TelemetryServiceOptions) => TelemetryService | undefined;
@@ -0,0 +1,181 @@
1
+ /**
2
+ * 遥测上报服务类型定义
3
+ * 基于 iwiki 文档:https://iwiki.woa.com/p/4018670075
4
+ */
5
+ /** WebSocket 消息基础结构 */
6
+ export type TelemetryMessageBase = {
7
+ /** 消息类型 */
8
+ type: "heartbeat" | "data_report" | "config_push" | "device_push" | "error" | "auth" | "auth_ack";
9
+ /** 请求唯一标识 */
10
+ request_id: string;
11
+ /** Unix 时间戳(秒) */
12
+ timestamp: number;
13
+ /** 消息体 */
14
+ payload?: unknown;
15
+ };
16
+ /** WebSocket 发送消息基础结构(客户端 → 服务端,已认证连接无需 api_key) */
17
+ export type TelemetrySendMessageBase = TelemetryMessageBase;
18
+ /** 心跳消息 Payload(客户端 → 服务端) */
19
+ export type HeartbeatPayload = {
20
+ /** 插件 ID(同时作为 appid 使用) */
21
+ plugin_id: string;
22
+ /** 设备唯一标识 */
23
+ device_id: string;
24
+ /** Agent 标识(当前使用 deviceId 值) */
25
+ agent_id?: string;
26
+ /** 插件版本号 */
27
+ plugin_version: string;
28
+ /** 运行状态 */
29
+ running_status: "healthy" | "warning" | "error" | "offline";
30
+ };
31
+ /** 心跳消息(客户端 → 服务端) */
32
+ export type HeartbeatMessage = TelemetryMessageBase & {
33
+ type: "heartbeat";
34
+ payload: HeartbeatPayload;
35
+ };
36
+ /** 心跳发送消息(客户端 → 服务端,已认证连接无需 api_key) */
37
+ export type HeartbeatSendMessage = TelemetrySendMessageBase & {
38
+ type: "heartbeat";
39
+ payload: HeartbeatPayload;
40
+ };
41
+ /** 心跳响应 Payload(服务端 → 客户端) */
42
+ export type HeartbeatAckPayload = {
43
+ server_time: number;
44
+ };
45
+ /** 心跳响应消息 */
46
+ export type HeartbeatAckMessage = TelemetryMessageBase & {
47
+ type: "heartbeat";
48
+ payload: HeartbeatAckPayload;
49
+ };
50
+ /** 数据上报 Payload */
51
+ export type DataReportPayload = {
52
+ /** 插件 ID */
53
+ plugin_id: string;
54
+ /** 上报数据类型 */
55
+ report_type: string;
56
+ /** 上报数据体 */
57
+ data: unknown;
58
+ };
59
+ /** 数据上报消息(客户端 → 服务端) */
60
+ export type DataReportMessage = TelemetryMessageBase & {
61
+ type: "data_report";
62
+ payload: DataReportPayload;
63
+ };
64
+ /** 数据上报发送消息(客户端 → 服务端,已认证连接无需 api_key) */
65
+ export type DataReportSendMessage = TelemetrySendMessageBase & {
66
+ type: "data_report";
67
+ payload: DataReportPayload;
68
+ };
69
+ /** 数据上报响应 Payload */
70
+ export type DataReportAckPayload = {
71
+ accepted: boolean;
72
+ message: string;
73
+ };
74
+ /** 数据上报响应消息 */
75
+ export type DataReportAckMessage = TelemetryMessageBase & {
76
+ type: "data_report";
77
+ payload: DataReportAckPayload;
78
+ };
79
+ /** 配置推送 Payload(服务端 → 客户端) */
80
+ export type ConfigPushPayload = {
81
+ config_version: string;
82
+ config_type: string;
83
+ config: Record<string, unknown>;
84
+ };
85
+ /** 配置推送消息 */
86
+ export type ConfigPushMessage = TelemetryMessageBase & {
87
+ type: "config_push";
88
+ payload: ConfigPushPayload;
89
+ };
90
+ /** 设备推送 Payload */
91
+ export type DevicePushPayload = {
92
+ message_type: string;
93
+ data: unknown;
94
+ };
95
+ /** 设备推送消息 */
96
+ export type DevicePushMessage = TelemetryMessageBase & {
97
+ type: "device_push";
98
+ payload: DevicePushPayload;
99
+ };
100
+ /** 错误消息 Payload */
101
+ export type ErrorPayload = {
102
+ message: string;
103
+ };
104
+ /** 错误消息 */
105
+ export type ErrorMessage = TelemetryMessageBase & {
106
+ type: "error";
107
+ payload: ErrorPayload;
108
+ };
109
+ /** 认证消息(客户端 → 服务端) */
110
+ export type AuthSendMessage = {
111
+ type: "auth";
112
+ request_id: string;
113
+ timestamp: number;
114
+ api_key: string;
115
+ };
116
+ /** 认证响应 Payload(服务端 → 客户端) */
117
+ export type AuthAckPayload = {
118
+ success: boolean;
119
+ message: string;
120
+ };
121
+ /** 认证响应消息(服务端 → 客户端) */
122
+ export type AuthAckMessage = TelemetryMessageBase & {
123
+ type: "auth_ack";
124
+ payload: AuthAckPayload;
125
+ };
126
+ /** 所有消息类型的联合类型 */
127
+ export type TelemetryMessage = HeartbeatMessage | HeartbeatAckMessage | DataReportMessage | DataReportAckMessage | ConfigPushMessage | DevicePushMessage | ErrorMessage | AuthAckMessage;
128
+ /** 遥测服务配置 */
129
+ export type TelemetryServiceConfig = {
130
+ /** 是否启用遥测上报 */
131
+ enabled: boolean;
132
+ /** WebSocket 服务器配置 */
133
+ websocket: {
134
+ /** 服务器 IP */
135
+ ip: string;
136
+ /** WebSocket 端口(默认 8081) */
137
+ port: number;
138
+ /** 连接协议(ws 或 wss) */
139
+ protocol?: "ws" | "wss";
140
+ };
141
+ /** 身份配置 */
142
+ identity: {
143
+ agentId: string;
144
+ };
145
+ /** 认证配置 */
146
+ auth: {
147
+ /** API 密钥 */
148
+ apiKey: string;
149
+ };
150
+ /** 上报间隔配置 */
151
+ intervals: {
152
+ /** 心跳间隔(毫秒),默认 30000 */
153
+ heartbeatMs: number;
154
+ /** 数据上报间隔(毫秒),默认 600000(10分钟) */
155
+ dataReportMs: number;
156
+ };
157
+ /** 重连配置 */
158
+ reconnect: {
159
+ /** 最大重连次数 */
160
+ maxAttempts: number;
161
+ /** 基础重连延迟(毫秒) */
162
+ baseDelayMs: number;
163
+ /** 最大重连延迟(毫秒) */
164
+ maxDelayMs: number;
165
+ };
166
+ };
167
+ /** 遥测服务状态 */
168
+ export type TelemetryServiceStatus = {
169
+ /** 是否已连接 */
170
+ connected: boolean;
171
+ /** 最后心跳时间 */
172
+ lastHeartbeatAt?: number;
173
+ /** 最后数据上报时间 */
174
+ lastDataReportAt?: number;
175
+ /** 重连次数 */
176
+ reconnectAttempts: number;
177
+ /** 最后错误信息 */
178
+ lastError?: string;
179
+ /** 服务启动时间 */
180
+ startedAt?: number;
181
+ };