@lark-tns/openclaw-guardian-plugin 2026.4.15
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/README.md +61 -0
- package/openclaw.plugin.json +40 -0
- package/package.json +38 -0
- package/src/common-payload.ts +27 -0
- package/src/detect-service.ts +16 -0
- package/src/hook-handler/index.ts +269 -0
- package/src/hook-payloads/index.ts +45 -0
- package/src/hook-payloads/llm-fetch-payloads.ts +26 -0
- package/src/hook-payloads/llm-payloads.ts +33 -0
- package/src/hook-payloads/shared.ts +78 -0
- package/src/hook-payloads/tool-payloads.ts +33 -0
- package/src/hostname.ts +10 -0
- package/src/http-client.ts +233 -0
- package/src/index.ts +31 -0
- package/src/llm-fetch/index.ts +485 -0
- package/src/llm-fetch/request-utils.ts +94 -0
- package/src/llm-fetch/response-utils.ts +70 -0
- package/src/llm-fetch/types.ts +34 -0
- package/src/logger.ts +84 -0
- package/src/plugin-env.ts +14 -0
- package/src/runtime-config.ts +252 -0
- package/src/skill-scan/hook-handler.ts +119 -0
- package/src/skill-scan/index.ts +173 -0
- package/src/skill-scan/skill-detect-client.ts +178 -0
- package/src/skill-scan/skill-scanner.ts +331 -0
- package/src/skill-scan/skill-storage.ts +185 -0
- package/src/token-auth.ts +227 -0
package/README.md
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# OpenClaw Guardian Plugin
|
|
2
|
+
|
|
3
|
+
This plugin uses the new OpenClaw SDK entry style and reports trust-layer payloads for the active hook points below:
|
|
4
|
+
|
|
5
|
+
- logs the payload to the official plugin logger
|
|
6
|
+
- pulls runtime toggles from `http://localhost:8001/open-apis/security_plugin/v1/openclaw_plugin/config`
|
|
7
|
+
- forwards detect requests to `http://localhost:8001/open-apis/security_plugin/v1/openclaw_plugin/detect`
|
|
8
|
+
|
|
9
|
+
- `llm_input`
|
|
10
|
+
- `llm_output`
|
|
11
|
+
- `before_tool_call`
|
|
12
|
+
- `after_tool_call`
|
|
13
|
+
|
|
14
|
+
The runtime config polling is managed by `api.registerService(...)`. The service initializes remote config on startup, keeps an in-memory snapshot for hook handlers, and disposes the refresh timer on shutdown.
|
|
15
|
+
|
|
16
|
+
## Files
|
|
17
|
+
|
|
18
|
+
- `openclaw.plugin.json`: native plugin manifest
|
|
19
|
+
- `src/index.ts`: plugin entry registered with `definePluginEntry`, hook registration, and `api.registerService(...)` wiring
|
|
20
|
+
- `src/runtime-config.ts`: remote config store plus polling service, typed against `OpenClawPluginApi` / `api.registerService(...)`
|
|
21
|
+
- `src/hook-payloads.ts`: hook-specific payload builders required by the trust-layer API
|
|
22
|
+
- `src/logger.ts`: safe payload formatter and logger helper
|
|
23
|
+
- `src/http-client.ts`: request body builder and detect/config service client
|
|
24
|
+
- `src/fetch-interceptor.ts`: optional `before_llm_fetch` / `after_llm_fetch` request-response interceptor, currently not enabled in `src/index.ts`
|
|
25
|
+
- `src/tool-effects.ts`: effect parser and hook-specific deny/rewrite handling
|
|
26
|
+
|
|
27
|
+
## Install
|
|
28
|
+
|
|
29
|
+
Link-install the plugin from this directory:
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
openclaw plugins install -l .
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Then enable it in your OpenClaw config if needed:
|
|
36
|
+
|
|
37
|
+
```json5
|
|
38
|
+
{
|
|
39
|
+
plugins: {
|
|
40
|
+
entries: {
|
|
41
|
+
"openclaw-guardian-plugin": {
|
|
42
|
+
enabled: true
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Restart the Gateway after config changes.
|
|
50
|
+
|
|
51
|
+
## Notes
|
|
52
|
+
|
|
53
|
+
- The plugin logs via `api.logger.info(...)`.
|
|
54
|
+
- The plugin registers a background service via `api.registerService(...)`; the service typing is derived from `OpenClawPluginApi`, GETs remote runtime config on startup, retries up to 3 times, defaults to all hooks disabled on first-start failure, and refreshes the config every 60 seconds.
|
|
55
|
+
- The plugin POSTs `{ hook_name, payload }` to `http://localhost:8001/open-apis/security_plugin/v1/openclaw_plugin/detect`.
|
|
56
|
+
- Hook handlers read the latest in-memory runtime-config snapshot instead of fetching `/config` inline on every hook invocation.
|
|
57
|
+
- Hook payloads are sent as the trust-layer contract requires, such as tool/session fields for tool hooks and `domain` / `path` / `origin_req` or `origin_resp` for LLM fetch hooks.
|
|
58
|
+
- `llm_input` and `llm_output` are report-only hooks; deny/rewrite responses are logged but not applied.
|
|
59
|
+
- `after_tool_call` is also observe-only in runtime; detect decisions are logged but do not rewrite the actual hook return value.
|
|
60
|
+
- Payloads are serialized defensively so circular references and `Error` objects do not break logging.
|
|
61
|
+
- `before_llm_fetch` / `after_llm_fetch` support remains in `src/fetch-interceptor.ts`, but those hooks are not active until `installFetchInterceptor(api, configStore)` is enabled in `src/index.ts`.
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "openclaw-guardian-plugin",
|
|
3
|
+
"name": "OpenClaw Guardian Plugin",
|
|
4
|
+
"description": "Reports OpenClaw hook payloads to security_plugin config and detect endpoints.",
|
|
5
|
+
"version": "2026.4.10",
|
|
6
|
+
"uiHints": {
|
|
7
|
+
"appId": {
|
|
8
|
+
"label": "Feishu App ID",
|
|
9
|
+
"placeholder": "cli_xxx"
|
|
10
|
+
},
|
|
11
|
+
"appSecret": {
|
|
12
|
+
"label": "Feishu App Secret",
|
|
13
|
+
"sensitive": true
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"configSchema": {
|
|
17
|
+
"type": "object",
|
|
18
|
+
"additionalProperties": false,
|
|
19
|
+
"properties": {
|
|
20
|
+
"env": {
|
|
21
|
+
"type": "string",
|
|
22
|
+
"enum": [
|
|
23
|
+
"online",
|
|
24
|
+
"pre",
|
|
25
|
+
"boe",
|
|
26
|
+
"dev"
|
|
27
|
+
],
|
|
28
|
+
"default": "online"
|
|
29
|
+
},
|
|
30
|
+
"appId": {
|
|
31
|
+
"type": "string",
|
|
32
|
+
"minLength": 1
|
|
33
|
+
},
|
|
34
|
+
"appSecret": {
|
|
35
|
+
"type": "string",
|
|
36
|
+
"minLength": 1
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@lark-tns/openclaw-guardian-plugin",
|
|
3
|
+
"version": "2026.4.15",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "OpenClaw plugin that reports hook payloads to the security_plugin detect service with remote hook toggles.",
|
|
6
|
+
"keywords": ["openclaw", "plugin", "security", "guardian"],
|
|
7
|
+
"files": [
|
|
8
|
+
"src/**/*.ts",
|
|
9
|
+
"openclaw.plugin.json",
|
|
10
|
+
"README.md"
|
|
11
|
+
],
|
|
12
|
+
"scripts": {
|
|
13
|
+
"typecheck": "tsc --noEmit",
|
|
14
|
+
"pack": "npm pack",
|
|
15
|
+
"upload": "node scripts/uploadManifest.mjs"
|
|
16
|
+
},
|
|
17
|
+
"openclaw": {
|
|
18
|
+
"extensions": [
|
|
19
|
+
"./src/index.ts"
|
|
20
|
+
],
|
|
21
|
+
"installDependencies": true
|
|
22
|
+
},
|
|
23
|
+
"devDependencies": {
|
|
24
|
+
"@types/yazl": "^3.3.0",
|
|
25
|
+
"typescript": "^5.8.3"
|
|
26
|
+
},
|
|
27
|
+
"dependencies": {
|
|
28
|
+
"yazl": "^3.3.1"
|
|
29
|
+
},
|
|
30
|
+
"peerDependencies": {
|
|
31
|
+
"openclaw": ">=2026.3.24"
|
|
32
|
+
},
|
|
33
|
+
"peerDependenciesMeta": {
|
|
34
|
+
"openclaw": {
|
|
35
|
+
"optional": false
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { getHostname } from './hostname';
|
|
2
|
+
|
|
3
|
+
export type CommonPayloadFields = {
|
|
4
|
+
hostname: string;
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
export function buildCommonPayloadFields(): CommonPayloadFields {
|
|
8
|
+
return {
|
|
9
|
+
hostname: getHostname(),
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function mergeCommonPayloadFields(payload: unknown): unknown {
|
|
14
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
|
|
15
|
+
return payload;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const record = payload as Record<string, unknown>;
|
|
19
|
+
if (Object.prototype.hasOwnProperty.call(record, 'hostname')) {
|
|
20
|
+
return payload;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
return {
|
|
24
|
+
...record,
|
|
25
|
+
...buildCommonPayloadFields(),
|
|
26
|
+
};
|
|
27
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { DEFAULT_TIMEOUT_MS, fetchSecurityPluginApi, getDetectUrl, createDetectRequestBody } from './http-client';
|
|
2
|
+
import { mergeCommonPayloadFields } from './common-payload';
|
|
3
|
+
import type { OpenClawPluginApi } from 'openclaw/plugin-sdk';
|
|
4
|
+
|
|
5
|
+
export async function detectHookPayload(api: OpenClawPluginApi, hookName: string, payload: unknown) {
|
|
6
|
+
const source = 'miaoda'; //TODO: Mock for now, should get from config later
|
|
7
|
+
const body = createDetectRequestBody(hookName, mergeCommonPayloadFields(payload), source);
|
|
8
|
+
|
|
9
|
+
return fetchSecurityPluginApi(api, hookName, getDetectUrl(api), {
|
|
10
|
+
method: 'POST',
|
|
11
|
+
headers: {
|
|
12
|
+
'content-type': 'application/json',
|
|
13
|
+
},
|
|
14
|
+
body: JSON.stringify(body),
|
|
15
|
+
}, DEFAULT_TIMEOUT_MS);
|
|
16
|
+
}
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
import { basename, dirname } from 'node:path';
|
|
2
|
+
import type {
|
|
3
|
+
PluginHookAfterToolCallEvent,
|
|
4
|
+
PluginHookAgentContext,
|
|
5
|
+
PluginHookBeforeToolCallEvent,
|
|
6
|
+
PluginHookBeforeToolCallResult,
|
|
7
|
+
PluginHookLlmInputEvent,
|
|
8
|
+
PluginHookLlmOutputEvent,
|
|
9
|
+
PluginHookToolContext,
|
|
10
|
+
} from 'openclaw/plugin-sdk/plugin-runtime';
|
|
11
|
+
import type { OpenClawPluginApi } from 'openclaw/plugin-sdk';
|
|
12
|
+
import { detectHookPayload } from '../detect-service';
|
|
13
|
+
import { buildHookPayload } from '../hook-payloads';
|
|
14
|
+
import { logHookPayloadWithEnv, withLogPrefix } from '../logger';
|
|
15
|
+
import { getPluginEnv } from '../plugin-env';
|
|
16
|
+
import type { RuntimeConfigStore } from '../runtime-config';
|
|
17
|
+
import { loadSkillState, resolveStoragePath } from '../skill-scan/skill-storage';
|
|
18
|
+
|
|
19
|
+
type UnknownRecord = Record<string, unknown>;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Returns the SKILL.md file path if this tool call is a skill read:
|
|
23
|
+
* tool_name === "read" and tool_args.path ends with "SKILL.md".
|
|
24
|
+
*/
|
|
25
|
+
function extractSkillFilePath(payload: UnknownRecord): string | null {
|
|
26
|
+
if (payload.tool_name !== 'read') return null;
|
|
27
|
+
const args = payload.tool_args;
|
|
28
|
+
if (!args || typeof args !== 'object' || Array.isArray(args)) return null;
|
|
29
|
+
const values = Object.values(args as UnknownRecord);
|
|
30
|
+
return (values.find((v): v is string => typeof v === 'string' && v.endsWith('SKILL.md')) ?? null);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function resolveSkillMeta(
|
|
34
|
+
api: OpenClawPluginApi,
|
|
35
|
+
skillFilePath: string,
|
|
36
|
+
agentId?: string,
|
|
37
|
+
): Promise<{ skill_name: string; skill_hash: string } | null> {
|
|
38
|
+
// dirName is the cache key in skill-detect-state.json
|
|
39
|
+
const dirName = basename(dirname(skillFilePath));
|
|
40
|
+
try {
|
|
41
|
+
let storagePath: string | undefined;
|
|
42
|
+
if (agentId) {
|
|
43
|
+
const workspaceDir = api.runtime.agent.resolveAgentWorkspaceDir(api.config, agentId);
|
|
44
|
+
storagePath = resolveStoragePath(workspaceDir);
|
|
45
|
+
}
|
|
46
|
+
const state = await loadSkillState(api, storagePath);
|
|
47
|
+
const entry = state[dirName];
|
|
48
|
+
if (!entry || !entry.zip_hash) return null;
|
|
49
|
+
return { skill_name: entry.skill_name, skill_hash: entry.zip_hash };
|
|
50
|
+
} catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
type DetectResponseLike = {
|
|
56
|
+
effect?: unknown;
|
|
57
|
+
deny_output?: unknown;
|
|
58
|
+
rewrite_output?: unknown;
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
type DetectDecision = {
|
|
62
|
+
effect: string;
|
|
63
|
+
denyOutput: string;
|
|
64
|
+
rewriteOutput: string;
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
type ReportOnlyHookName = 'llm_input' | 'llm_output' | 'after_tool_call';
|
|
68
|
+
|
|
69
|
+
type ReportOnlyHookEventMap = {
|
|
70
|
+
llm_input: PluginHookLlmInputEvent;
|
|
71
|
+
llm_output: PluginHookLlmOutputEvent;
|
|
72
|
+
after_tool_call: PluginHookAfterToolCallEvent;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
type ReportOnlyHookContextMap = {
|
|
76
|
+
llm_input: PluginHookAgentContext;
|
|
77
|
+
llm_output: PluginHookAgentContext;
|
|
78
|
+
after_tool_call: PluginHookToolContext;
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
function firstString(...values: unknown[]): string {
|
|
82
|
+
return values.find((value) => typeof value === 'string') ?? '';
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function normalizeEffect(effect: unknown): string {
|
|
86
|
+
if (typeof effect !== 'string') {
|
|
87
|
+
return 'PERMIT';
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return effect.toUpperCase();
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function parseRewriteParams(text: string): UnknownRecord | undefined {
|
|
94
|
+
if (typeof text !== 'string' || text.length === 0) {
|
|
95
|
+
return undefined;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
try {
|
|
99
|
+
const parsed = JSON.parse(text);
|
|
100
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
|
101
|
+
? (parsed as UnknownRecord)
|
|
102
|
+
: undefined;
|
|
103
|
+
} catch {
|
|
104
|
+
return undefined;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function parseDetectDecision(response: DetectResponseLike | null | undefined): DetectDecision {
|
|
109
|
+
return {
|
|
110
|
+
effect: normalizeEffect(response?.effect),
|
|
111
|
+
denyOutput: firstString(response?.deny_output),
|
|
112
|
+
rewriteOutput: firstString(response?.rewrite_output),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function applyBeforeToolCallDecision(decision: DetectDecision) {
|
|
117
|
+
const effect = normalizeEffect(decision.effect);
|
|
118
|
+
|
|
119
|
+
if (effect === 'DENY') {
|
|
120
|
+
if (!decision.denyOutput) {
|
|
121
|
+
return {
|
|
122
|
+
action: 'permit',
|
|
123
|
+
returnValue: undefined,
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
return {
|
|
128
|
+
action: 'deny',
|
|
129
|
+
output: decision.denyOutput,
|
|
130
|
+
returnValue: {
|
|
131
|
+
block: true,
|
|
132
|
+
blockReason: decision.denyOutput || 'Tool call blocked by detect service',
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (effect === 'REWRITE') {
|
|
138
|
+
if (!decision.rewriteOutput) {
|
|
139
|
+
return {
|
|
140
|
+
action: 'permit',
|
|
141
|
+
returnValue: undefined,
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const rewrittenParams = parseRewriteParams(decision.rewriteOutput);
|
|
146
|
+
if (!rewrittenParams) {
|
|
147
|
+
return {
|
|
148
|
+
action: 'rewrite_invalid',
|
|
149
|
+
returnValue: undefined,
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return {
|
|
154
|
+
action: 'rewrite',
|
|
155
|
+
returnValue: {
|
|
156
|
+
params: rewrittenParams,
|
|
157
|
+
},
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
return {
|
|
162
|
+
action: 'permit',
|
|
163
|
+
returnValue: undefined,
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async function handleReportOnlyHook<K extends ReportOnlyHookName>(
|
|
168
|
+
api: OpenClawPluginApi,
|
|
169
|
+
configStore: RuntimeConfigStore,
|
|
170
|
+
hookName: K,
|
|
171
|
+
event: ReportOnlyHookEventMap[K],
|
|
172
|
+
ctx: ReportOnlyHookContextMap[K],
|
|
173
|
+
): Promise<void> {
|
|
174
|
+
if (!(await configStore.isHookEnabled(hookName))) {
|
|
175
|
+
api.logger.info(withLogPrefix(`[${hookName}] detect skipped: hook disabled by runtime config`));
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const totalStart = Date.now();
|
|
180
|
+
const payload = buildHookPayload(hookName, event, ctx);
|
|
181
|
+
logHookPayloadWithEnv(api, hookName, payload, getPluginEnv(api));
|
|
182
|
+
|
|
183
|
+
try {
|
|
184
|
+
const detectResponse = await detectHookPayload(api, hookName, payload);
|
|
185
|
+
const decision = parseDetectDecision(detectResponse);
|
|
186
|
+
api.logger.info(
|
|
187
|
+
withLogPrefix(`[${hookName}] detect effect observed: effect=${decision.effect} (report-only hook)`),
|
|
188
|
+
);
|
|
189
|
+
} catch (error) {
|
|
190
|
+
api.logger.error(
|
|
191
|
+
withLogPrefix(
|
|
192
|
+
`[${hookName}] detect request failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
193
|
+
),
|
|
194
|
+
);
|
|
195
|
+
} finally {
|
|
196
|
+
const totalElapsed = Date.now() - totalStart;
|
|
197
|
+
api.logger.info(withLogPrefix(`[${hookName}] total_elapsed=${totalElapsed}ms`));
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async function handleBeforeToolCall(
|
|
202
|
+
api: OpenClawPluginApi,
|
|
203
|
+
configStore: RuntimeConfigStore,
|
|
204
|
+
event: PluginHookBeforeToolCallEvent,
|
|
205
|
+
ctx: PluginHookToolContext,
|
|
206
|
+
): Promise<PluginHookBeforeToolCallResult> {
|
|
207
|
+
const totalStart = Date.now();
|
|
208
|
+
if (!(await configStore.isHookEnabled('before_tool_call'))) {
|
|
209
|
+
api.logger.info(withLogPrefix('[before_tool_call] detect skipped: hook disabled by runtime config'));
|
|
210
|
+
return undefined;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const payload = buildHookPayload('before_tool_call', event, ctx);
|
|
214
|
+
|
|
215
|
+
// Enrich payload with skill metadata if this is a skill read
|
|
216
|
+
const skillFilePath = extractSkillFilePath(payload as UnknownRecord);
|
|
217
|
+
let enrichedPayload: UnknownRecord = payload as UnknownRecord;
|
|
218
|
+
if (skillFilePath) {
|
|
219
|
+
const skillMeta = await resolveSkillMeta(api, skillFilePath, ctx.agentId);
|
|
220
|
+
if (skillMeta) {
|
|
221
|
+
enrichedPayload = { ...enrichedPayload, ...skillMeta };
|
|
222
|
+
api.logger.info(
|
|
223
|
+
withLogPrefix(
|
|
224
|
+
`[before_tool_call] skill read detected: skill=${skillMeta.skill_name} hash=${skillMeta.skill_hash.slice(0, 12)}...`,
|
|
225
|
+
),
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
logHookPayloadWithEnv(api, 'before_tool_call', enrichedPayload, getPluginEnv(api));
|
|
231
|
+
|
|
232
|
+
let hookReturnValue: PluginHookBeforeToolCallResult = undefined;
|
|
233
|
+
|
|
234
|
+
try {
|
|
235
|
+
const detectResponse = await detectHookPayload(api, 'before_tool_call', enrichedPayload);
|
|
236
|
+
const decision = parseDetectDecision(detectResponse);
|
|
237
|
+
const outcome = applyBeforeToolCallDecision(decision);
|
|
238
|
+
api.logger.info(withLogPrefix(`[before_tool_call] detect effect applied: ${JSON.stringify(outcome.returnValue)}`));
|
|
239
|
+
hookReturnValue = outcome.returnValue;
|
|
240
|
+
} catch (error) {
|
|
241
|
+
api.logger.error(
|
|
242
|
+
withLogPrefix(
|
|
243
|
+
`[before_tool_call] detect request failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
244
|
+
),
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const totalElapsed = Date.now() - totalStart;
|
|
249
|
+
api.logger.info(withLogPrefix(`[before_tool_call] total_elapsed=${totalElapsed}ms`));
|
|
250
|
+
return hookReturnValue;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export function registerDetectHooks(api: OpenClawPluginApi, configStore: RuntimeConfigStore): void {
|
|
254
|
+
api.on('llm_input', async (event, ctx) => {
|
|
255
|
+
await handleReportOnlyHook(api, configStore, 'llm_input', event, ctx);
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
api.on('llm_output', async (event, ctx) => {
|
|
259
|
+
await handleReportOnlyHook(api, configStore, 'llm_output', event, ctx);
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
api.on('after_tool_call', async (event, ctx) => {
|
|
263
|
+
await handleReportOnlyHook(api, configStore, 'after_tool_call', event, ctx);
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
api.on('before_tool_call', async (event, ctx) => {
|
|
267
|
+
return handleBeforeToolCall(api, configStore, event, ctx);
|
|
268
|
+
});
|
|
269
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { ContextLike, FetchMeta, LlmEventLike, ToolEventLike } from './shared';
|
|
2
|
+
import { safeObject } from './shared';
|
|
3
|
+
import { buildAfterLlmFetchPayload, buildBeforeLlmFetchPayload } from './llm-fetch-payloads';
|
|
4
|
+
import { buildLlmInputPayload, buildLlmOutputPayload } from './llm-payloads';
|
|
5
|
+
import { buildAfterToolCallPayload, buildBeforeToolCallPayload } from './tool-payloads';
|
|
6
|
+
|
|
7
|
+
export type HookName =
|
|
8
|
+
| 'before_tool_call'
|
|
9
|
+
| 'after_tool_call'
|
|
10
|
+
| 'before_llm_fetch'
|
|
11
|
+
| 'after_llm_fetch'
|
|
12
|
+
| 'llm_input'
|
|
13
|
+
| 'llm_output';
|
|
14
|
+
|
|
15
|
+
export { buildAfterLlmFetchPayload, buildBeforeLlmFetchPayload } from './llm-fetch-payloads';
|
|
16
|
+
export { buildLlmInputPayload, buildLlmOutputPayload } from './llm-payloads';
|
|
17
|
+
export { buildAfterToolCallPayload, buildBeforeToolCallPayload } from './tool-payloads';
|
|
18
|
+
|
|
19
|
+
export function buildHookPayload(
|
|
20
|
+
hookName: HookName,
|
|
21
|
+
event: unknown,
|
|
22
|
+
ctx: unknown,
|
|
23
|
+
extra?: unknown,
|
|
24
|
+
) {
|
|
25
|
+
const toolEvent = event as ToolEventLike | null | undefined;
|
|
26
|
+
const llmEvent = event as LlmEventLike | null | undefined;
|
|
27
|
+
const safeContext = ctx as ContextLike | null | undefined;
|
|
28
|
+
|
|
29
|
+
switch (hookName) {
|
|
30
|
+
case 'before_tool_call':
|
|
31
|
+
return buildBeforeToolCallPayload(toolEvent, safeContext);
|
|
32
|
+
case 'after_tool_call':
|
|
33
|
+
return buildAfterToolCallPayload(toolEvent, safeContext);
|
|
34
|
+
case 'before_llm_fetch':
|
|
35
|
+
return buildBeforeLlmFetchPayload(extra as FetchMeta | null | undefined);
|
|
36
|
+
case 'after_llm_fetch':
|
|
37
|
+
return buildAfterLlmFetchPayload(extra as FetchMeta | null | undefined);
|
|
38
|
+
case 'llm_input':
|
|
39
|
+
return buildLlmInputPayload(llmEvent, safeContext);
|
|
40
|
+
case 'llm_output':
|
|
41
|
+
return buildLlmOutputPayload(llmEvent, safeContext);
|
|
42
|
+
default:
|
|
43
|
+
return safeObject(extra);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { FetchMeta } from './shared';
|
|
2
|
+
import { firstDefined, parseUrlParts, safeArray, safeString } from './shared';
|
|
3
|
+
|
|
4
|
+
export function buildBeforeLlmFetchPayload(meta: FetchMeta | null | undefined) {
|
|
5
|
+
const { domain, path } = parseUrlParts(safeString(meta?.url));
|
|
6
|
+
|
|
7
|
+
return {
|
|
8
|
+
request_id: safeString(meta?.request_id),
|
|
9
|
+
domain,
|
|
10
|
+
path,
|
|
11
|
+
origin_req: firstDefined(meta?.jsonBody, meta?.rawBody, ''),
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function buildAfterLlmFetchPayload(meta: FetchMeta | null | undefined) {
|
|
16
|
+
const { domain, path } = parseUrlParts(safeString(meta?.url));
|
|
17
|
+
|
|
18
|
+
return {
|
|
19
|
+
request_id: safeString(meta?.request_id),
|
|
20
|
+
domain,
|
|
21
|
+
path,
|
|
22
|
+
is_sse: meta?.isSse ? 'true' : 'false',
|
|
23
|
+
chunks: safeArray(meta?.chunks),
|
|
24
|
+
origin_resp: meta?.isSse ? '' : safeString(firstDefined(meta?.originResp, '')),
|
|
25
|
+
};
|
|
26
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { ContextLike, LlmEventLike } from './shared';
|
|
2
|
+
import { safeArray, safeString } from './shared';
|
|
3
|
+
|
|
4
|
+
function createLlmBasePayload(event: LlmEventLike | null | undefined, ctx: ContextLike | null | undefined) {
|
|
5
|
+
return {
|
|
6
|
+
agent_name: safeString(ctx?.agentId),
|
|
7
|
+
session_id: safeString(ctx?.sessionId),
|
|
8
|
+
session_key: safeString(ctx?.sessionKey),
|
|
9
|
+
channel_id: safeString(ctx?.channelId),
|
|
10
|
+
message_provider: safeString(ctx?.messageProvider),
|
|
11
|
+
trigger: safeString(ctx?.trigger),
|
|
12
|
+
model: safeString(event?.model),
|
|
13
|
+
provider: safeString(event?.provider),
|
|
14
|
+
run_id: safeString(event?.runId),
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function buildLlmInputPayload(event: LlmEventLike | null | undefined, ctx: ContextLike | null | undefined) {
|
|
19
|
+
return {
|
|
20
|
+
...createLlmBasePayload(event, ctx),
|
|
21
|
+
prompt: safeString(event?.prompt),
|
|
22
|
+
system_prompt: safeString(event?.systemPrompt),
|
|
23
|
+
history_messages: safeArray(event?.historyMessages),
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function buildLlmOutputPayload(event: LlmEventLike | null | undefined, ctx: ContextLike | null | undefined) {
|
|
28
|
+
return {
|
|
29
|
+
...createLlmBasePayload(event, ctx),
|
|
30
|
+
assistant_texts: safeArray(event?.assistantTexts),
|
|
31
|
+
last_assistant: safeString(JSON.stringify(event?.lastAssistant)),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
export type UnknownRecord = Record<string, unknown>;
|
|
2
|
+
|
|
3
|
+
export type ToolEventLike = UnknownRecord & {
|
|
4
|
+
toolCallId?: unknown;
|
|
5
|
+
toolName?: unknown;
|
|
6
|
+
params?: unknown;
|
|
7
|
+
runId?: unknown;
|
|
8
|
+
result?: unknown;
|
|
9
|
+
error?: unknown;
|
|
10
|
+
durationMs?: unknown;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export type LlmEventLike = UnknownRecord & {
|
|
14
|
+
model?: unknown;
|
|
15
|
+
provider?: unknown;
|
|
16
|
+
runId?: unknown;
|
|
17
|
+
prompt?: unknown;
|
|
18
|
+
systemPrompt?: unknown;
|
|
19
|
+
historyMessages?: unknown;
|
|
20
|
+
assistantTexts?: unknown;
|
|
21
|
+
lastAssistant?: unknown;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export type ContextLike = UnknownRecord & {
|
|
25
|
+
agentId?: unknown;
|
|
26
|
+
sessionId?: unknown;
|
|
27
|
+
sessionKey?: unknown;
|
|
28
|
+
channelId?: unknown;
|
|
29
|
+
messageProvider?: unknown;
|
|
30
|
+
trigger?: unknown;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export type FetchMeta = {
|
|
34
|
+
request_id?: unknown;
|
|
35
|
+
url?: unknown;
|
|
36
|
+
rawBody?: unknown;
|
|
37
|
+
jsonBody?: unknown;
|
|
38
|
+
isSse?: unknown;
|
|
39
|
+
chunks?: unknown;
|
|
40
|
+
originResp?: unknown;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
export function firstDefined<T>(...values: Array<T | undefined | null>): T | undefined {
|
|
44
|
+
return values.find((value) => value !== undefined && value !== null);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function safeString(value: unknown): string {
|
|
48
|
+
if (value === undefined || value === null) {
|
|
49
|
+
return '';
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return typeof value === 'string' ? value : String(value);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function safeObject(value: unknown): UnknownRecord {
|
|
56
|
+
return value && typeof value === 'object' && !Array.isArray(value)
|
|
57
|
+
? (value as UnknownRecord)
|
|
58
|
+
: {};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function safeArray(value: unknown): unknown[] {
|
|
62
|
+
return Array.isArray(value) ? value : [];
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function parseUrlParts(url: string): { domain: string; path: string } {
|
|
66
|
+
try {
|
|
67
|
+
const parsedUrl = new URL(url);
|
|
68
|
+
return {
|
|
69
|
+
domain: parsedUrl.host,
|
|
70
|
+
path: parsedUrl.pathname || '/',
|
|
71
|
+
};
|
|
72
|
+
} catch {
|
|
73
|
+
return {
|
|
74
|
+
domain: '',
|
|
75
|
+
path: '',
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { ContextLike, ToolEventLike } from './shared';
|
|
2
|
+
import { firstDefined, safeString } from './shared';
|
|
3
|
+
|
|
4
|
+
function createToolBasePayload(event: ToolEventLike | null | undefined, ctx: ContextLike | null | undefined) {
|
|
5
|
+
return {
|
|
6
|
+
agent_name: safeString(ctx?.agentId),
|
|
7
|
+
session_id: safeString(ctx?.sessionId),
|
|
8
|
+
session_key: safeString(ctx?.sessionKey),
|
|
9
|
+
tool_call_id: safeString(event?.toolCallId),
|
|
10
|
+
tool_name: safeString(event?.toolName),
|
|
11
|
+
tool_args: firstDefined(event?.params, {}),
|
|
12
|
+
run_id: safeString(event?.runId),
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function buildBeforeToolCallPayload(
|
|
17
|
+
event: ToolEventLike | null | undefined,
|
|
18
|
+
ctx: ContextLike | null | undefined,
|
|
19
|
+
) {
|
|
20
|
+
return createToolBasePayload(event, ctx);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function buildAfterToolCallPayload(
|
|
24
|
+
event: ToolEventLike | null | undefined,
|
|
25
|
+
ctx: ContextLike | null | undefined,
|
|
26
|
+
) {
|
|
27
|
+
return {
|
|
28
|
+
...createToolBasePayload(event, ctx),
|
|
29
|
+
tool_output: firstDefined(event?.result, ''),
|
|
30
|
+
tool_error: firstDefined(event?.error, ''),
|
|
31
|
+
tool_duration_ms: safeString(firstDefined(event?.durationMs, '')),
|
|
32
|
+
};
|
|
33
|
+
}
|
package/src/hostname.ts
ADDED