@dashclaw/openclaw-plugin 1.2.2
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/LICENSE +21 -0
- package/README.md +167 -0
- package/openclaw.plugin.json +62 -0
- package/package.json +55 -0
- package/src/HOOK.md +40 -0
- package/src/dashclaw.d.ts +70 -0
- package/src/index.ts +640 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 DashClaw
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
# @dashclaw/openclaw-plugin
|
|
2
|
+
|
|
3
|
+
Add DashClaw governance to OpenClaw — every tool call gets policy enforcement, human approval gates, and a verifiable decision trail.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
openclaw plugins install @dashclaw/openclaw-plugin
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Configure
|
|
12
|
+
|
|
13
|
+
The plugin accepts **three interchangeable configuration shapes** — pick whichever fits your deployment. Precedence is plugin config > env vars.
|
|
14
|
+
|
|
15
|
+
### Option A — canonical plugin-config keys
|
|
16
|
+
|
|
17
|
+
```json
|
|
18
|
+
{
|
|
19
|
+
"plugins": {
|
|
20
|
+
"entries": {
|
|
21
|
+
"dashclaw-governance": {
|
|
22
|
+
"enabled": true,
|
|
23
|
+
"config": {
|
|
24
|
+
"dashclawUrl": "https://my-dashclaw.vercel.app",
|
|
25
|
+
"dashclawApiKey": "oc_live_...",
|
|
26
|
+
"agentId": "my-openclaw-agent",
|
|
27
|
+
"failClosed": true,
|
|
28
|
+
"highRiskTools": ["bash", "exec", "write_file"]
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
### Option B — SDK-style aliases
|
|
37
|
+
|
|
38
|
+
If you prefer the same naming as the DashClaw Node SDK:
|
|
39
|
+
|
|
40
|
+
```json
|
|
41
|
+
{
|
|
42
|
+
"config": {
|
|
43
|
+
"baseUrl": "https://my-dashclaw.vercel.app",
|
|
44
|
+
"apiKey": "oc_live_...",
|
|
45
|
+
"agentId": "my-openclaw-agent"
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### Option C — environment variables (recommended for secrets)
|
|
51
|
+
|
|
52
|
+
Set these before the gateway starts and omit URL/key from plugin config entirely:
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
export DASHCLAW_BASE_URL="https://my-dashclaw.vercel.app" # DASHCLAW_URL also accepted
|
|
56
|
+
export DASHCLAW_API_KEY="oc_live_..."
|
|
57
|
+
export DASHCLAW_AGENT_ID="my-openclaw-agent" # optional
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
```json
|
|
61
|
+
{
|
|
62
|
+
"config": {
|
|
63
|
+
"failClosed": true,
|
|
64
|
+
"highRiskTools": ["bash", "exec", "write_file"]
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
This is the cleanest setup when you already keep DashClaw credentials in a `.env` / `secrets/` file shared with other tooling (CLI, local SDK scripts, MCP server).
|
|
70
|
+
|
|
71
|
+
Config changes require a gateway restart, the same as any other OpenClaw plugin.
|
|
72
|
+
|
|
73
|
+
## What happens
|
|
74
|
+
|
|
75
|
+
Every tool call your agent makes flows through DashClaw before it executes:
|
|
76
|
+
|
|
77
|
+
1. Agent decides to call a tool (e.g. `bash`, `write`, a custom HTTP tool).
|
|
78
|
+
2. The plugin **classifies the tool call** — parsing bash commands, inspecting file paths, and detecting deploy/destructive/network intents — to determine the DashClaw action type, risk score, reversibility, and systems touched.
|
|
79
|
+
3. The plugin calls DashClaw `/api/guard` with the full classification (`action_type`, `risk_score`, `declared_goal`, `reversible`, `systems_touched`). DashClaw evaluates your guard policies. If the verdict is `block`, the tool call is rejected immediately.
|
|
80
|
+
4. On `allow`, `warn`, or `require_approval`, the plugin opens a governance record via `/api/actions`. The server re-runs policy here and is the authoritative source for HITL gating — it may return `action.status === 'pending_approval'` even when guard said `allow` (for example, if the capability has `requires_approval: true`).
|
|
81
|
+
5. If the action is `pending_approval`, the plugin pauses on `waitForApproval(action.action_id)`. You approve from the DashClaw dashboard, the CLI (`dashclaw approve <id>`), or the mobile PWA — the agent is unblocked the moment the operator approves (SSE first, polling fallback).
|
|
82
|
+
6. On approval, the tool executes. The `after_tool_call` hook records the outcome (`completed` or `failed`, with the error message) so DashClaw has a full intent → policy → outcome trail.
|
|
83
|
+
|
|
84
|
+
The plugin is read-mostly: it never modifies the tool's parameters or the tool's result. It only blocks, allows, or records.
|
|
85
|
+
|
|
86
|
+
### Unified policy surface
|
|
87
|
+
|
|
88
|
+
The plugin uses the **same action type vocabulary** as the DashClaw Claude Code hooks. Policies you write for Claude Code automatically apply to OpenClaw agents — no duplication needed.
|
|
89
|
+
|
|
90
|
+
| Tool call | Action type | Risk | Reversible |
|
|
91
|
+
|---|---|---|---|
|
|
92
|
+
| `bash: git push origin main` | `deploy` | 80 | no |
|
|
93
|
+
| `bash: rm -rf /tmp/data` | `security` | 90 | no |
|
|
94
|
+
| `bash: git diff` | `review` | 10 | yes |
|
|
95
|
+
| `bash: curl https://api.example.com` | `api` | 40 | yes |
|
|
96
|
+
| `bash: npm install express` | `build` | 30 | yes |
|
|
97
|
+
| `write: .env.production` | `security` | 85 | yes |
|
|
98
|
+
| `edit: src/app.ts` | `apply` | 50 | yes |
|
|
99
|
+
| `read: config.json` | `review` | 15 | yes |
|
|
100
|
+
|
|
101
|
+
For bash/exec tools, the plugin parses the command to classify intent. For file tools, it scans the path for sensitive patterns (`.env`, `credential`, `private_key`, etc.). Unrecognized tools fall through to `other` with the default risk score.
|
|
102
|
+
|
|
103
|
+
### `action_id` distinction
|
|
104
|
+
|
|
105
|
+
`guard()` returns an `action_id` that points at the `guard_decisions` table
|
|
106
|
+
(prefix `act_gd_…`). `createAction()` returns an `action_id` that points at
|
|
107
|
+
the `action_records` table. `waitForApproval()` polls
|
|
108
|
+
`GET /api/actions/:id`, which resolves against `action_records` — so the
|
|
109
|
+
plugin always waits using the `createAction()` ID, never the `guard()` ID.
|
|
110
|
+
Plugin builds at `1.0.0` had this wrong and the PWA approval queue stayed
|
|
111
|
+
empty because the wait target didn't exist. Fixed in `1.0.1`.
|
|
112
|
+
|
|
113
|
+
## Configuration reference
|
|
114
|
+
|
|
115
|
+
| Field | Type | Default | Description |
|
|
116
|
+
|---|---|---|---|
|
|
117
|
+
| `dashclawUrl` | string | **required** | Base URL of your DashClaw instance, e.g. `https://my-dashclaw.vercel.app`. |
|
|
118
|
+
| `dashclawApiKey` | string | **required** | DashClaw API key (starts with `oc_live_`). |
|
|
119
|
+
| `agentId` | string | `"openclaw"` | Identifier this OpenClaw instance reports to DashClaw. |
|
|
120
|
+
| `failClosed` | boolean | `true` | If DashClaw is unreachable, block the tool call. Set `false` to fail open. |
|
|
121
|
+
| `riskScoreDefault` | number | `50` | Fallback risk score for tool calls the classifier doesn't recognize. Recognized commands (git, curl, rm, npm, etc.) compute their own risk score automatically. |
|
|
122
|
+
| `highRiskTools` | string[] | `[]` | Tool names that should always start at risk score 85 before classification. The classifier may raise the score further (e.g. `rm -rf` → 90) but will never lower it below 85 for tools in this list. |
|
|
123
|
+
|
|
124
|
+
## Fail-closed vs fail-open
|
|
125
|
+
|
|
126
|
+
- **`failClosed: true` (default)** — if DashClaw is unreachable for any reason (network error, 5xx, timeout), the plugin blocks the tool call with a clear reason. This is the safe default for governance: no decisions slip through unrecorded.
|
|
127
|
+
- **`failClosed: false`** — if DashClaw is unreachable, the plugin logs a warning and lets the tool call proceed. Choose this only when availability matters more than governance guarantees (e.g. a non-critical agent that should keep running through DashClaw outages).
|
|
128
|
+
|
|
129
|
+
The fail-closed branch only fires for **infrastructure failures** talking to DashClaw. Explicit `block` or denied `require_approval` decisions always block the tool call regardless of `failClosed`.
|
|
130
|
+
|
|
131
|
+
## How tool calls are classified
|
|
132
|
+
|
|
133
|
+
The plugin goes beyond tool names — it inspects the **content** of each call:
|
|
134
|
+
|
|
135
|
+
- **bash/exec**: Parses the command string against known command sets (readonly, destructive, network, package management, git subcommands) and regex patterns for deploy and destructive operations. A `git push` is classified as `deploy` (risk 80, irreversible), while `git diff` is `review` (risk 10).
|
|
136
|
+
- **write/edit/apply_patch**: Scans the file path for sensitive patterns (`.env`, `credential`, `private_key`, `.pem`). Sensitive paths get `security` (risk 85); normal paths get `apply`.
|
|
137
|
+
- **read/web_search/web_fetch**: Always `review` with low risk (capped at 15).
|
|
138
|
+
- **sessions_send**: `message`, irreversible.
|
|
139
|
+
- **Everything else**: `other` with the configured default risk.
|
|
140
|
+
|
|
141
|
+
This classification mirrors what the DashClaw Claude Code hooks do via `dashclaw_agent_intel`, so the same guard policies fire consistently across both platforms.
|
|
142
|
+
|
|
143
|
+
## Outcome recording
|
|
144
|
+
|
|
145
|
+
The plugin caches the DashClaw `action_id` from `before_tool_call` in a module-level map keyed by the call id, then resolves it in `after_tool_call` to send `updateOutcome`. If `after_tool_call` doesn't fire (process crash, hook misordering), the action stays in `running` state in DashClaw — you'll see it in the open-loops view and can resolve it manually.
|
|
146
|
+
|
|
147
|
+
If the outcome update itself fails, the plugin logs a warning but never throws — DashClaw recording is best-effort and must not break your agent's tool execution.
|
|
148
|
+
|
|
149
|
+
## Token usage and cost (v1.2.1+)
|
|
150
|
+
|
|
151
|
+
The plugin hooks OpenClaw's `llm_output` and `agent_end` events to attribute LLM token usage back to the governed tool calls that assistant response induced. Each `llm_output` reports `{input, output, cacheRead, cacheWrite}` plus the resolved `model`; when the next `llm_output` (or `agent_end`) fires, the plugin PATCHes `tokens_in`, `tokens_out`, and `model` onto every action opened since the last usage boundary. DashClaw derives `cost_estimate` server-side from its pricing table.
|
|
152
|
+
|
|
153
|
+
Accounting notes:
|
|
154
|
+
|
|
155
|
+
- Tokens are split evenly across the tool calls attributable to the same assistant response. Remainders go to the earliest buckets so the sum is preserved.
|
|
156
|
+
- Cache reads are weighted at 0.1× (Anthropic bills cache reads at ~10% of base input price) before being added to `tokens_in`. Cache writes are counted at full price. This keeps the derived cost aligned with real billing without requiring the server to model cache pricing.
|
|
157
|
+
- Failures are silent: a warning is logged but token attribution never blocks or throws. If your provider doesn't populate `usage`, nothing is patched.
|
|
158
|
+
|
|
159
|
+
## Links
|
|
160
|
+
|
|
161
|
+
- DashClaw: <https://github.com/ucsandman/DashClaw>
|
|
162
|
+
- DashClaw Node SDK: <https://www.npmjs.com/package/dashclaw>
|
|
163
|
+
- OpenClaw: <https://docs.openclaw.ai>
|
|
164
|
+
|
|
165
|
+
## License
|
|
166
|
+
|
|
167
|
+
MIT — see [LICENSE](./LICENSE).
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "dashclaw-governance",
|
|
3
|
+
"name": "DashClaw Governance",
|
|
4
|
+
"description": "Policy enforcement, human-in-the-loop approval, and decision recording for every OpenClaw tool call. Powered by DashClaw.",
|
|
5
|
+
"version": "1.2.2",
|
|
6
|
+
"entry": "src/index.ts",
|
|
7
|
+
"main": "./src/index.ts",
|
|
8
|
+
"configSchema": {
|
|
9
|
+
"type": "object",
|
|
10
|
+
"additionalProperties": false,
|
|
11
|
+
"description": "Configure the DashClaw connection via any of three shapes: (a) canonical plugin-config keys `dashclawUrl` + `dashclawApiKey` (+ optional `agentId`); (b) SDK-style aliases `baseUrl` + `apiKey`; (c) environment variables `DASHCLAW_BASE_URL` (or legacy `DASHCLAW_URL`) + `DASHCLAW_API_KEY` (+ optional `DASHCLAW_AGENT_ID`) set before the gateway starts. Precedence is plugin config > env. No field is strictly required in this schema — env vars alone are sufficient.",
|
|
12
|
+
"properties": {
|
|
13
|
+
"dashclawUrl": {
|
|
14
|
+
"type": "string",
|
|
15
|
+
"description": "URL of your DashClaw instance (e.g. https://my-dashclaw.vercel.app). Optional if DASHCLAW_BASE_URL / DASHCLAW_URL env var is set, or if baseUrl is provided."
|
|
16
|
+
},
|
|
17
|
+
"dashclawApiKey": {
|
|
18
|
+
"type": "string",
|
|
19
|
+
"description": "DashClaw API key (starts with oc_live_). Optional if DASHCLAW_API_KEY env var is set, or if apiKey is provided."
|
|
20
|
+
},
|
|
21
|
+
"baseUrl": {
|
|
22
|
+
"type": "string",
|
|
23
|
+
"description": "SDK-style alias for dashclawUrl. Use whichever you prefer."
|
|
24
|
+
},
|
|
25
|
+
"apiKey": {
|
|
26
|
+
"type": "string",
|
|
27
|
+
"description": "SDK-style alias for dashclawApiKey. Use whichever you prefer."
|
|
28
|
+
},
|
|
29
|
+
"agentId": {
|
|
30
|
+
"type": "string",
|
|
31
|
+
"default": "openclaw",
|
|
32
|
+
"description": "Agent identifier in DashClaw"
|
|
33
|
+
},
|
|
34
|
+
"failClosed": {
|
|
35
|
+
"type": "boolean",
|
|
36
|
+
"default": true,
|
|
37
|
+
"description": "If true, block tool calls when DashClaw is unreachable. If false, allow them to proceed."
|
|
38
|
+
},
|
|
39
|
+
"riskScoreDefault": {
|
|
40
|
+
"type": "number",
|
|
41
|
+
"default": 50,
|
|
42
|
+
"description": "Default risk score for tool calls that don't have a specific mapping"
|
|
43
|
+
},
|
|
44
|
+
"highRiskTools": {
|
|
45
|
+
"type": "array",
|
|
46
|
+
"items": { "type": "string" },
|
|
47
|
+
"default": [],
|
|
48
|
+
"description": "Tool names that should always get risk_score 80+ (e.g. bash, exec, deploy)"
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
"uiHints": {
|
|
53
|
+
"dashclawApiKey": { "sensitive": true, "label": "DashClaw API Key" },
|
|
54
|
+
"dashclawUrl": { "label": "DashClaw URL", "placeholder": "https://my-dashclaw.vercel.app" },
|
|
55
|
+
"baseUrl": { "label": "DashClaw URL (alias)", "advanced": true },
|
|
56
|
+
"apiKey": { "sensitive": true, "label": "DashClaw API Key (alias)", "advanced": true },
|
|
57
|
+
"agentId": { "label": "Agent ID" },
|
|
58
|
+
"failClosed": { "label": "Fail-closed when DashClaw unreachable", "advanced": true },
|
|
59
|
+
"riskScoreDefault": { "label": "Default risk score", "advanced": true },
|
|
60
|
+
"highRiskTools": { "label": "High-risk tool names", "advanced": true }
|
|
61
|
+
}
|
|
62
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@dashclaw/openclaw-plugin",
|
|
3
|
+
"version": "1.2.2",
|
|
4
|
+
"description": "DashClaw governance for OpenClaw — policy enforcement, human approval, and decision recording for every tool call.",
|
|
5
|
+
"main": "src/index.ts",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"author": "DashClaw",
|
|
9
|
+
"keywords": [
|
|
10
|
+
"openclaw",
|
|
11
|
+
"openclaw-plugin",
|
|
12
|
+
"dashclaw",
|
|
13
|
+
"governance",
|
|
14
|
+
"ai-safety",
|
|
15
|
+
"hitl",
|
|
16
|
+
"approval"
|
|
17
|
+
],
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "git+https://github.com/ucsandman/DashClaw.git",
|
|
21
|
+
"directory": "packages/openclaw-plugin"
|
|
22
|
+
},
|
|
23
|
+
"homepage": "https://github.com/ucsandman/DashClaw/tree/main/packages/openclaw-plugin#readme",
|
|
24
|
+
"files": [
|
|
25
|
+
"src/",
|
|
26
|
+
"openclaw.plugin.json",
|
|
27
|
+
"README.md",
|
|
28
|
+
"LICENSE"
|
|
29
|
+
],
|
|
30
|
+
"openclaw": {
|
|
31
|
+
"extensions": ["./src/index.ts"],
|
|
32
|
+
"hooks": ["./src/index.ts"]
|
|
33
|
+
},
|
|
34
|
+
"scripts": {
|
|
35
|
+
"build": "tsc --noEmit",
|
|
36
|
+
"typecheck": "tsc --noEmit"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"dashclaw": "^2.11.1"
|
|
40
|
+
},
|
|
41
|
+
"peerDependencies": {
|
|
42
|
+
"openclaw": ">=2025.0.0"
|
|
43
|
+
},
|
|
44
|
+
"peerDependenciesMeta": {
|
|
45
|
+
"openclaw": { "optional": false }
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"typescript": "^5.4.0",
|
|
49
|
+
"@types/node": "^20.11.0"
|
|
50
|
+
},
|
|
51
|
+
"overrides": {
|
|
52
|
+
"axios": "^1.15.0",
|
|
53
|
+
"tar": "^7.5.11"
|
|
54
|
+
}
|
|
55
|
+
}
|
package/src/HOOK.md
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: dashclaw-governance
|
|
3
|
+
description: Policy enforcement, human-in-the-loop approval, and decision recording for every OpenClaw tool call. Powered by DashClaw.
|
|
4
|
+
version: 1.2.1
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# DashClaw Governance Hook
|
|
8
|
+
|
|
9
|
+
Intercepts every OpenClaw tool call through a four-step governance loop:
|
|
10
|
+
|
|
11
|
+
1. **Guard** — `before_tool_call` sends the tool name, risk score, and a 500-character parameter summary to DashClaw `/api/guard`. Policies decide `allow`, `warn`, `block`, or `require_approval`.
|
|
12
|
+
2. **Record** — On `allow`/`warn`/`require_approval`, the hook opens a governance record via `/api/actions`. The server is authoritative — it may upgrade an `allow` decision to `pending_approval` for capabilities that require human review.
|
|
13
|
+
3. **Wait** — For `pending_approval` actions, the hook calls `waitForApproval(action_id)` using the **action_records ID from step 2**, not the `guard_decisions` ID from step 1. Operators approve from the DashClaw dashboard, CLI, or mobile PWA.
|
|
14
|
+
4. **Outcome** — `after_tool_call` records `completed` or `failed` with the error message, giving DashClaw a full intent → policy → outcome trail.
|
|
15
|
+
|
|
16
|
+
The hook never modifies tool parameters or results. It only blocks, allows, waits, or records.
|
|
17
|
+
|
|
18
|
+
## Configuration
|
|
19
|
+
|
|
20
|
+
The plugin accepts three interchangeable configuration shapes — pick whichever fits your deployment:
|
|
21
|
+
|
|
22
|
+
1. **Canonical plugin-config keys** (recommended for `openclaw.plugin.json`): `dashclawUrl` + `dashclawApiKey`.
|
|
23
|
+
2. **SDK-style aliases** (matches the DashClaw Node SDK): `baseUrl` + `apiKey`.
|
|
24
|
+
3. **Environment variables** (recommended when secrets live outside the gateway config): `DASHCLAW_BASE_URL` (or legacy `DASHCLAW_URL`) + `DASHCLAW_API_KEY`.
|
|
25
|
+
|
|
26
|
+
Precedence is `plugin config > env vars`. If env vars are set before the gateway starts, the plugin config can omit URL and API key entirely.
|
|
27
|
+
|
|
28
|
+
See the `configSchema` section in `openclaw.plugin.json` for the full list of optional fields (`agentId`, `failClosed`, `riskScoreDefault`, `highRiskTools`).
|
|
29
|
+
|
|
30
|
+
## Failure modes
|
|
31
|
+
|
|
32
|
+
- If `createAction` fails and `failClosed=true` (default), the tool call is blocked with a clear reason.
|
|
33
|
+
- If `failClosed=false`, the tool call proceeds ungoverned with a warning in the console.
|
|
34
|
+
- If the guard verdict is `block`, no action record is opened — the tool call is hard-stopped and no governance row is created.
|
|
35
|
+
|
|
36
|
+
## See also
|
|
37
|
+
|
|
38
|
+
- Canonical HITL flow: `sdk/README.md` → Human-in-the-Loop (HITL) Approval Flow
|
|
39
|
+
- Plugin source: `src/index.ts`
|
|
40
|
+
- Config schema: `openclaw.plugin.json`
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ambient type declarations for the `dashclaw` npm package.
|
|
3
|
+
*
|
|
4
|
+
* The published package ships as ESM JavaScript without `.d.ts` files, so we
|
|
5
|
+
* describe only the surface this plugin touches: the `DashClaw` client and the
|
|
6
|
+
* shapes of `guard()`, `createAction()`, `waitForApproval()`, and
|
|
7
|
+
* `updateOutcome()` responses.
|
|
8
|
+
*
|
|
9
|
+
* Shapes mirror `dashclaw@2.11.1/dashclaw.js`:
|
|
10
|
+
* - `guard()` → `{ decision, action_id, reason, signals }`
|
|
11
|
+
* - `createAction()` → API returns `{ action, action_id, decision, ... }`
|
|
12
|
+
* - `waitForApproval()` → `{ action }`
|
|
13
|
+
*/
|
|
14
|
+
declare module 'dashclaw' {
|
|
15
|
+
export interface GuardDecision {
|
|
16
|
+
decision: 'allow' | 'block' | 'warn' | 'require_approval';
|
|
17
|
+
action_id: string;
|
|
18
|
+
reason?: string;
|
|
19
|
+
signals?: string[];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface ActionRecord {
|
|
23
|
+
action_id?: string;
|
|
24
|
+
id?: string;
|
|
25
|
+
status?: string;
|
|
26
|
+
approved_by?: string | null;
|
|
27
|
+
error_message?: string | null;
|
|
28
|
+
[key: string]: unknown;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Envelope returned by `POST /api/actions`. */
|
|
32
|
+
export interface CreateActionResult {
|
|
33
|
+
action: ActionRecord;
|
|
34
|
+
action_id?: string;
|
|
35
|
+
[key: string]: unknown;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface WaitForApprovalResult {
|
|
39
|
+
action: ActionRecord;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface DashClawOptions {
|
|
43
|
+
baseUrl: string;
|
|
44
|
+
apiKey: string;
|
|
45
|
+
agentId: string;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export class DashClaw {
|
|
49
|
+
constructor(opts: DashClawOptions);
|
|
50
|
+
guard(context: Record<string, unknown>): Promise<GuardDecision>;
|
|
51
|
+
createAction(action: Record<string, unknown>): Promise<CreateActionResult>;
|
|
52
|
+
updateOutcome(
|
|
53
|
+
actionId: string,
|
|
54
|
+
outcome: Record<string, unknown>
|
|
55
|
+
): Promise<unknown>;
|
|
56
|
+
waitForApproval(
|
|
57
|
+
actionId: string,
|
|
58
|
+
opts?: { timeout?: number; interval?: number }
|
|
59
|
+
): Promise<WaitForApprovalResult>;
|
|
60
|
+
recordAssumption(assumption: Record<string, unknown>): Promise<unknown>;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export class ApprovalDeniedError extends Error {
|
|
64
|
+
status: string;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export class GuardBlockedError extends Error {
|
|
68
|
+
decision: GuardDecision;
|
|
69
|
+
}
|
|
70
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,640 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @dashclaw/openclaw-plugin
|
|
3
|
+
*
|
|
4
|
+
* OpenClaw plugin that routes every tool call through DashClaw governance:
|
|
5
|
+
* 1. `before_tool_call` → `guard()` + optional `waitForApproval()` +
|
|
6
|
+
* `createAction()` to open a governance record.
|
|
7
|
+
* 2. `after_tool_call` → `updateOutcome()` to close that record.
|
|
8
|
+
*
|
|
9
|
+
* Type accuracy notes (verified against `openclaw` plugin SDK types):
|
|
10
|
+
* - `PluginHookBeforeToolCallResult` uses `blockReason`, not `reason`.
|
|
11
|
+
* - `PluginKind` is `"memory" | "context-engine"` — neither applies to this
|
|
12
|
+
* generic hook plugin, so the manifest and `definePluginEntry` call both
|
|
13
|
+
* omit `kind`.
|
|
14
|
+
* - Event/context field shapes come from `PluginHookBeforeToolCallEvent`,
|
|
15
|
+
* `PluginHookAfterToolCallEvent`, and `PluginHookToolContext`. No
|
|
16
|
+
* defensive fallbacks for alternative field names are needed.
|
|
17
|
+
*
|
|
18
|
+
* The DashClaw client is cached at module scope and rebuilt only when the
|
|
19
|
+
* resolved config key changes, mirroring the pattern used by OpenClaw's
|
|
20
|
+
* bundled MemOS plugin.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import {
|
|
24
|
+
definePluginEntry,
|
|
25
|
+
type OpenClawPluginApi,
|
|
26
|
+
} from 'openclaw/plugin-sdk/plugin-entry';
|
|
27
|
+
import {
|
|
28
|
+
DashClaw,
|
|
29
|
+
type ActionRecord,
|
|
30
|
+
type GuardDecision,
|
|
31
|
+
} from 'dashclaw';
|
|
32
|
+
|
|
33
|
+
// ---------------------------------------------------------------------------
|
|
34
|
+
// Config
|
|
35
|
+
// ---------------------------------------------------------------------------
|
|
36
|
+
|
|
37
|
+
interface PluginConfig {
|
|
38
|
+
dashclawUrl: string;
|
|
39
|
+
dashclawApiKey: string;
|
|
40
|
+
agentId: string;
|
|
41
|
+
failClosed: boolean;
|
|
42
|
+
riskScoreDefault: number;
|
|
43
|
+
highRiskTools: ReadonlySet<string>;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Resolve the DashClaw URL from (in order of precedence):
|
|
48
|
+
* 1. `config.dashclawUrl` (canonical plugin-config key)
|
|
49
|
+
* 2. `config.baseUrl` (SDK-style alias)
|
|
50
|
+
* 3. `process.env.DASHCLAW_BASE_URL` (canonical env var — matches CLI, local scripts)
|
|
51
|
+
* 4. `process.env.DASHCLAW_URL` (legacy env var — matches MCP server docs)
|
|
52
|
+
*
|
|
53
|
+
* The same precedence applies to the API key (with DASHCLAW_API_KEY as the only env var).
|
|
54
|
+
*/
|
|
55
|
+
function firstString(...candidates: unknown[]): string {
|
|
56
|
+
for (const c of candidates) {
|
|
57
|
+
if (typeof c === 'string' && c.length > 0) return c;
|
|
58
|
+
}
|
|
59
|
+
return '';
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function resolveConfig(raw: Record<string, unknown> | undefined): PluginConfig {
|
|
63
|
+
const cfg = raw ?? {};
|
|
64
|
+
const env = typeof process !== 'undefined' && process?.env ? process.env : {};
|
|
65
|
+
|
|
66
|
+
const failClosed = cfg.failClosed !== false; // default true
|
|
67
|
+
const riskScoreDefault =
|
|
68
|
+
typeof cfg.riskScoreDefault === 'number' ? cfg.riskScoreDefault : 50;
|
|
69
|
+
const highRiskTools = new Set<string>(
|
|
70
|
+
Array.isArray(cfg.highRiskTools)
|
|
71
|
+
? cfg.highRiskTools.filter((v): v is string => typeof v === 'string')
|
|
72
|
+
: []
|
|
73
|
+
);
|
|
74
|
+
|
|
75
|
+
const dashclawUrl = firstString(
|
|
76
|
+
cfg.dashclawUrl,
|
|
77
|
+
cfg.baseUrl,
|
|
78
|
+
env.DASHCLAW_BASE_URL,
|
|
79
|
+
env.DASHCLAW_URL
|
|
80
|
+
);
|
|
81
|
+
const dashclawApiKey = firstString(
|
|
82
|
+
cfg.dashclawApiKey,
|
|
83
|
+
cfg.apiKey,
|
|
84
|
+
env.DASHCLAW_API_KEY
|
|
85
|
+
);
|
|
86
|
+
const agentId = firstString(cfg.agentId, env.DASHCLAW_AGENT_ID) || 'openclaw';
|
|
87
|
+
|
|
88
|
+
return {
|
|
89
|
+
dashclawUrl,
|
|
90
|
+
dashclawApiKey,
|
|
91
|
+
agentId,
|
|
92
|
+
failClosed,
|
|
93
|
+
riskScoreDefault,
|
|
94
|
+
highRiskTools,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// ---------------------------------------------------------------------------
|
|
99
|
+
// Module state
|
|
100
|
+
// ---------------------------------------------------------------------------
|
|
101
|
+
|
|
102
|
+
let cachedClient: DashClaw | null = null;
|
|
103
|
+
let cachedClientKey = '';
|
|
104
|
+
|
|
105
|
+
/** Maps synthetic call key → DashClaw action_id so `after_tool_call` can close it. */
|
|
106
|
+
const pendingActions = new Map<string, string>();
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Per-run state for LLM token attribution. OpenClaw's `llm_output` event
|
|
110
|
+
* fires once per assistant response with `usage.{input,output,cacheRead,
|
|
111
|
+
* cacheWrite}` and `model`. The tool calls induced by that response arrive
|
|
112
|
+
* via `before_tool_call` after the `llm_output`. We stash the most recent
|
|
113
|
+
* usage and the action_ids opened since we stashed it; on the NEXT
|
|
114
|
+
* `llm_output` (or on `agent_end`) we distribute that usage evenly across
|
|
115
|
+
* those action_ids via `updateOutcome` PATCHes. Cost is derived server-side.
|
|
116
|
+
*/
|
|
117
|
+
interface TokenTurnState {
|
|
118
|
+
pendingUsage?: { tokens_in: number; tokens_out: number; model: string };
|
|
119
|
+
turnActionIds: string[];
|
|
120
|
+
}
|
|
121
|
+
const tokenTurnByRun = new Map<string, TokenTurnState>();
|
|
122
|
+
|
|
123
|
+
// Cap for in-memory per-run state. `agent_end` deletes entries, but a crash
|
|
124
|
+
// or an agent framework that never fires `agent_end` in a long-lived gateway
|
|
125
|
+
// process would leak. At ~100 bytes/entry this cap bounds worst-case memory
|
|
126
|
+
// to ~100KB while still comfortably above typical concurrency.
|
|
127
|
+
const MAX_TURN_RUNS = 1000;
|
|
128
|
+
|
|
129
|
+
function getTokenTurn(runId: string): TokenTurnState {
|
|
130
|
+
let state = tokenTurnByRun.get(runId);
|
|
131
|
+
if (!state) {
|
|
132
|
+
if (tokenTurnByRun.size >= MAX_TURN_RUNS) {
|
|
133
|
+
// Evict oldest (Map preserves insertion order). One at a time is enough
|
|
134
|
+
// to stay at the cap under steady state — we only grow by one here.
|
|
135
|
+
const oldest = tokenTurnByRun.keys().next().value;
|
|
136
|
+
if (oldest !== undefined) tokenTurnByRun.delete(oldest);
|
|
137
|
+
}
|
|
138
|
+
state = { turnActionIds: [] };
|
|
139
|
+
tokenTurnByRun.set(runId, state);
|
|
140
|
+
}
|
|
141
|
+
return state;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Split a non-negative integer `total` into `n` buckets, putting remainders
|
|
145
|
+
* in the earliest buckets so the sum is preserved exactly. */
|
|
146
|
+
function distributeEvenly(total: number, n: number): number[] {
|
|
147
|
+
if (n <= 0 || total <= 0) return new Array<number>(Math.max(n, 0)).fill(0);
|
|
148
|
+
const base = Math.floor(total / n);
|
|
149
|
+
const remainder = total - base * n;
|
|
150
|
+
return Array.from({ length: n }, (_, i) => base + (i < remainder ? 1 : 0));
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async function distributePendingTokens(
|
|
154
|
+
client: DashClaw,
|
|
155
|
+
state: TokenTurnState,
|
|
156
|
+
): Promise<void> {
|
|
157
|
+
const usage = state.pendingUsage;
|
|
158
|
+
const ids = state.turnActionIds;
|
|
159
|
+
state.pendingUsage = undefined;
|
|
160
|
+
state.turnActionIds = [];
|
|
161
|
+
|
|
162
|
+
if (!usage || ids.length === 0) return;
|
|
163
|
+
if (usage.tokens_in === 0 && usage.tokens_out === 0) return;
|
|
164
|
+
|
|
165
|
+
const inParts = distributeEvenly(usage.tokens_in, ids.length);
|
|
166
|
+
const outParts = distributeEvenly(usage.tokens_out, ids.length);
|
|
167
|
+
|
|
168
|
+
await Promise.all(
|
|
169
|
+
ids.map((actionId, idx) =>
|
|
170
|
+
client
|
|
171
|
+
.updateOutcome(actionId, {
|
|
172
|
+
tokens_in: inParts[idx],
|
|
173
|
+
tokens_out: outParts[idx],
|
|
174
|
+
...(usage.model ? { model: usage.model } : {}),
|
|
175
|
+
})
|
|
176
|
+
.catch((err: unknown) => {
|
|
177
|
+
console.warn(
|
|
178
|
+
`[dashclaw-governance] token PATCH failed for ${actionId}: ${errorMessage(err) || 'unknown'}`
|
|
179
|
+
);
|
|
180
|
+
})
|
|
181
|
+
)
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function getClient(config: PluginConfig): DashClaw {
|
|
186
|
+
const key = `${config.dashclawUrl}|${config.dashclawApiKey}|${config.agentId}`;
|
|
187
|
+
if (cachedClient && cachedClientKey === key) return cachedClient;
|
|
188
|
+
|
|
189
|
+
if (!config.dashclawUrl || !config.dashclawApiKey) {
|
|
190
|
+
const missing: string[] = [];
|
|
191
|
+
if (!config.dashclawUrl) missing.push('dashclawUrl');
|
|
192
|
+
if (!config.dashclawApiKey) missing.push('dashclawApiKey');
|
|
193
|
+
throw new Error(
|
|
194
|
+
`dashclaw-governance plugin: missing ${missing.join(' and ')}. ` +
|
|
195
|
+
'Provide via openclaw.plugin.json config (dashclawUrl/dashclawApiKey or baseUrl/apiKey), ' +
|
|
196
|
+
'or set env vars DASHCLAW_BASE_URL and DASHCLAW_API_KEY before starting the gateway.'
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
cachedClient = new DashClaw({
|
|
201
|
+
baseUrl: config.dashclawUrl,
|
|
202
|
+
apiKey: config.dashclawApiKey,
|
|
203
|
+
agentId: config.agentId,
|
|
204
|
+
});
|
|
205
|
+
cachedClientKey = key;
|
|
206
|
+
return cachedClient;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// ---------------------------------------------------------------------------
|
|
210
|
+
// Helpers
|
|
211
|
+
// ---------------------------------------------------------------------------
|
|
212
|
+
|
|
213
|
+
function summarizeParams(params: Record<string, unknown> | undefined): string {
|
|
214
|
+
if (!params) return '';
|
|
215
|
+
let serialized: string;
|
|
216
|
+
try {
|
|
217
|
+
serialized = JSON.stringify(params);
|
|
218
|
+
} catch {
|
|
219
|
+
return '[unserializable params]';
|
|
220
|
+
}
|
|
221
|
+
if (serialized.length <= 500) return serialized;
|
|
222
|
+
return serialized.slice(0, 500) + '…[truncated]';
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function callKey(
|
|
226
|
+
toolName: string,
|
|
227
|
+
toolCallId: string | undefined,
|
|
228
|
+
runId: string | undefined
|
|
229
|
+
): string {
|
|
230
|
+
// Prefer the provider-supplied tool call ID; fall back to runId-scoped tool
|
|
231
|
+
// name so a later `after_tool_call` without a toolCallId can still find the
|
|
232
|
+
// pending record.
|
|
233
|
+
if (toolCallId) return `id:${toolCallId}`;
|
|
234
|
+
if (runId) return `run:${runId}:${toolName}`;
|
|
235
|
+
return `tool:${toolName}`;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function errorMessage(err: unknown): string {
|
|
239
|
+
if (!err) return '';
|
|
240
|
+
if (typeof err === 'string') return err;
|
|
241
|
+
if (err instanceof Error) return err.message;
|
|
242
|
+
if (typeof err === 'object' && err !== null && 'message' in err) {
|
|
243
|
+
const m = (err as { message?: unknown }).message;
|
|
244
|
+
return typeof m === 'string' ? m : '';
|
|
245
|
+
}
|
|
246
|
+
return '';
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// ---------------------------------------------------------------------------
|
|
250
|
+
// Tool classification (aligned with DashClaw hooks vocabulary so policies
|
|
251
|
+
// written for the Claude Code hooks also fire for OpenClaw tool calls)
|
|
252
|
+
// ---------------------------------------------------------------------------
|
|
253
|
+
|
|
254
|
+
interface ActionClassification {
|
|
255
|
+
actionType: string;
|
|
256
|
+
riskScore: number;
|
|
257
|
+
reversible: boolean;
|
|
258
|
+
systemsTouched: string[];
|
|
259
|
+
declaredGoal: string;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const READONLY_COMMANDS = new Set([
|
|
263
|
+
'cat', 'head', 'tail', 'less', 'more', 'wc', 'file', 'stat', 'du', 'df',
|
|
264
|
+
'ls', 'tree', 'find', 'locate', 'which', 'whereis', 'type',
|
|
265
|
+
'grep', 'rg', 'awk', 'cut', 'sort', 'uniq', 'diff', 'comm',
|
|
266
|
+
'echo', 'printf', 'date', 'uname', 'whoami', 'pwd', 'hostname',
|
|
267
|
+
'ps', 'top', 'htop', 'free', 'uptime', 'env', 'printenv',
|
|
268
|
+
]);
|
|
269
|
+
|
|
270
|
+
const GIT_READONLY = new Set([
|
|
271
|
+
'status', 'log', 'diff', 'show', 'branch', 'tag', 'remote',
|
|
272
|
+
'stash', 'describe', 'rev-parse', 'blame', 'ls-files',
|
|
273
|
+
]);
|
|
274
|
+
|
|
275
|
+
const DESTRUCTIVE_COMMANDS = new Set([
|
|
276
|
+
'rm', 'rmdir', 'shred', 'mkfs', 'dd', 'truncate',
|
|
277
|
+
]);
|
|
278
|
+
|
|
279
|
+
const NETWORK_COMMANDS = new Set([
|
|
280
|
+
'curl', 'wget', 'ssh', 'scp', 'rsync', 'ping',
|
|
281
|
+
]);
|
|
282
|
+
|
|
283
|
+
const PACKAGE_COMMANDS = new Set([
|
|
284
|
+
'npm', 'yarn', 'pnpm', 'pip', 'pip3', 'cargo', 'go', 'gem',
|
|
285
|
+
'brew', 'apt', 'apt-get', 'dnf',
|
|
286
|
+
]);
|
|
287
|
+
|
|
288
|
+
const DEPLOY_PATTERN = /(?:git\s+push|deploy|vercel|kubectl|terraform|docker\s+push|helm)/i;
|
|
289
|
+
const DESTRUCTIVE_PATTERN = /(?:rm\s+-rf|DROP\s+TABLE|DELETE\s+FROM|TRUNCATE)/i;
|
|
290
|
+
const SENSITIVE_PATH_PATTERN = /(?:\.env|secret|credential|private_key|\.pem|id_rsa|\.key)/i;
|
|
291
|
+
|
|
292
|
+
function classifyBash(
|
|
293
|
+
command: string | undefined,
|
|
294
|
+
defaultRisk: number,
|
|
295
|
+
): ActionClassification {
|
|
296
|
+
if (!command) {
|
|
297
|
+
return { actionType: 'other', riskScore: defaultRisk, reversible: true, systemsTouched: [], declaredGoal: 'Bash: (empty)' };
|
|
298
|
+
}
|
|
299
|
+
const goal = `Bash: ${command.slice(0, 120)}`;
|
|
300
|
+
|
|
301
|
+
if (DESTRUCTIVE_PATTERN.test(command)) {
|
|
302
|
+
return { actionType: 'security', riskScore: 90, reversible: false, systemsTouched: ['filesystem'], declaredGoal: goal };
|
|
303
|
+
}
|
|
304
|
+
if (DEPLOY_PATTERN.test(command)) {
|
|
305
|
+
return { actionType: 'deploy', riskScore: 80, reversible: false, systemsTouched: ['production'], declaredGoal: goal };
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const firstToken = command.trim().split(/[\s|;&]/)[0].replace(/^.*[/\\]/, '');
|
|
309
|
+
|
|
310
|
+
if (firstToken === 'git') {
|
|
311
|
+
const sub = command.match(/git\s+(\S+)/)?.[1] ?? '';
|
|
312
|
+
if (GIT_READONLY.has(sub)) {
|
|
313
|
+
return { actionType: 'review', riskScore: 10, reversible: true, systemsTouched: [], declaredGoal: goal };
|
|
314
|
+
}
|
|
315
|
+
if (sub === 'push') {
|
|
316
|
+
return { actionType: 'deploy', riskScore: 75, reversible: false, systemsTouched: [], declaredGoal: goal };
|
|
317
|
+
}
|
|
318
|
+
return { actionType: 'apply', riskScore: 30, reversible: true, systemsTouched: [], declaredGoal: goal };
|
|
319
|
+
}
|
|
320
|
+
if (READONLY_COMMANDS.has(firstToken)) {
|
|
321
|
+
return { actionType: 'review', riskScore: 10, reversible: true, systemsTouched: [], declaredGoal: goal };
|
|
322
|
+
}
|
|
323
|
+
if (DESTRUCTIVE_COMMANDS.has(firstToken)) {
|
|
324
|
+
return { actionType: 'security', riskScore: 85, reversible: false, systemsTouched: ['filesystem'], declaredGoal: goal };
|
|
325
|
+
}
|
|
326
|
+
if (NETWORK_COMMANDS.has(firstToken)) {
|
|
327
|
+
return { actionType: 'api', riskScore: 40, reversible: true, systemsTouched: [], declaredGoal: goal };
|
|
328
|
+
}
|
|
329
|
+
if (PACKAGE_COMMANDS.has(firstToken)) {
|
|
330
|
+
return { actionType: 'build', riskScore: 30, reversible: true, systemsTouched: [], declaredGoal: goal };
|
|
331
|
+
}
|
|
332
|
+
return { actionType: 'other', riskScore: defaultRisk, reversible: true, systemsTouched: ['shell'], declaredGoal: goal };
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function classifyFile(
|
|
336
|
+
toolName: string,
|
|
337
|
+
params: Record<string, unknown> | undefined,
|
|
338
|
+
defaultRisk: number,
|
|
339
|
+
): ActionClassification {
|
|
340
|
+
const filePath = String(params?.file_path ?? params?.path ?? '');
|
|
341
|
+
const goal = `${toolName}: ${filePath || '(unknown)'}`;
|
|
342
|
+
if (SENSITIVE_PATH_PATTERN.test(filePath)) {
|
|
343
|
+
return { actionType: 'security', riskScore: 85, reversible: true, systemsTouched: ['filesystem'], declaredGoal: goal };
|
|
344
|
+
}
|
|
345
|
+
return { actionType: 'apply', riskScore: defaultRisk, reversible: true, systemsTouched: ['filesystem'], declaredGoal: goal };
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
function classifyToolCall(
|
|
349
|
+
toolName: string,
|
|
350
|
+
params: Record<string, unknown> | undefined,
|
|
351
|
+
config: PluginConfig,
|
|
352
|
+
): ActionClassification {
|
|
353
|
+
const defaultRisk = config.highRiskTools.has(toolName) ? 85 : config.riskScoreDefault;
|
|
354
|
+
|
|
355
|
+
if (toolName === 'bash' || toolName === 'exec') {
|
|
356
|
+
return classifyBash(params?.command as string | undefined, defaultRisk);
|
|
357
|
+
}
|
|
358
|
+
if (toolName === 'write' || toolName === 'edit' || toolName === 'apply_patch') {
|
|
359
|
+
return classifyFile(toolName, params, defaultRisk);
|
|
360
|
+
}
|
|
361
|
+
if (['read', 'web_search', 'web_fetch', 'memory_search', 'memory_get', 'image'].includes(toolName)) {
|
|
362
|
+
const target = String(params?.file_path ?? params?.path ?? params?.query ?? '');
|
|
363
|
+
return {
|
|
364
|
+
actionType: 'review',
|
|
365
|
+
riskScore: Math.min(defaultRisk, 15),
|
|
366
|
+
reversible: true,
|
|
367
|
+
systemsTouched: [],
|
|
368
|
+
declaredGoal: `${toolName}: ${target.slice(0, 120) || '(unknown)'}`,
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
if (toolName === 'sessions_send') {
|
|
372
|
+
return {
|
|
373
|
+
actionType: 'message',
|
|
374
|
+
riskScore: defaultRisk,
|
|
375
|
+
reversible: false,
|
|
376
|
+
systemsTouched: [],
|
|
377
|
+
declaredGoal: `message: ${summarizeParams(params).slice(0, 120)}`,
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
return {
|
|
381
|
+
actionType: 'other',
|
|
382
|
+
riskScore: defaultRisk,
|
|
383
|
+
reversible: true,
|
|
384
|
+
systemsTouched: [],
|
|
385
|
+
declaredGoal: `${toolName}: ${summarizeParams(params).slice(0, 120)}`,
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function isApproved(action: ActionRecord | undefined): boolean {
|
|
390
|
+
if (!action) return false;
|
|
391
|
+
if (action.approved_by) return true;
|
|
392
|
+
return action.status === 'running' || action.status === 'completed';
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
// ---------------------------------------------------------------------------
|
|
396
|
+
// Plugin entry
|
|
397
|
+
// ---------------------------------------------------------------------------
|
|
398
|
+
|
|
399
|
+
export default definePluginEntry({
|
|
400
|
+
id: 'dashclaw-governance',
|
|
401
|
+
name: 'DashClaw Governance',
|
|
402
|
+
description:
|
|
403
|
+
'Policy enforcement, human-in-the-loop approval, and decision recording for every OpenClaw tool call. Powered by DashClaw.',
|
|
404
|
+
|
|
405
|
+
register(api: OpenClawPluginApi): void {
|
|
406
|
+
const config = resolveConfig(api.pluginConfig);
|
|
407
|
+
|
|
408
|
+
// -----------------------------------------------------------------------
|
|
409
|
+
// Governance gate
|
|
410
|
+
// -----------------------------------------------------------------------
|
|
411
|
+
api.on('before_tool_call', async (event, _ctx) => {
|
|
412
|
+
const { toolName, params, toolCallId, runId } = event;
|
|
413
|
+
const key = callKey(toolName, toolCallId, runId);
|
|
414
|
+
|
|
415
|
+
// Classify the tool call using the same vocabulary as DashClaw hooks
|
|
416
|
+
// so policies written for Claude Code also fire for OpenClaw calls.
|
|
417
|
+
const classification = classifyToolCall(toolName, params, config);
|
|
418
|
+
const { actionType, riskScore, reversible, systemsTouched, declaredGoal } = classification;
|
|
419
|
+
|
|
420
|
+
let client: DashClaw;
|
|
421
|
+
try {
|
|
422
|
+
client = getClient(config);
|
|
423
|
+
} catch (err) {
|
|
424
|
+
const msg = errorMessage(err) || 'unknown error';
|
|
425
|
+
if (config.failClosed) {
|
|
426
|
+
return { block: true, blockReason: `DashClaw config error: ${msg}` };
|
|
427
|
+
}
|
|
428
|
+
console.warn(`[dashclaw-governance] config error (fail-open): ${msg}`);
|
|
429
|
+
return;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
let decision: GuardDecision;
|
|
433
|
+
try {
|
|
434
|
+
decision = await client.guard({
|
|
435
|
+
action_type: actionType,
|
|
436
|
+
risk_score: riskScore,
|
|
437
|
+
declared_goal: declaredGoal,
|
|
438
|
+
reversible,
|
|
439
|
+
systems_touched: systemsTouched,
|
|
440
|
+
});
|
|
441
|
+
} catch (err) {
|
|
442
|
+
const msg = errorMessage(err) || 'unknown error';
|
|
443
|
+
if (config.failClosed) {
|
|
444
|
+
return {
|
|
445
|
+
block: true,
|
|
446
|
+
blockReason: `DashClaw unreachable — fail-closed policy (${msg})`,
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
console.warn(`[dashclaw-governance] guard call failed (fail-open): ${msg}`);
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// Hard stop on block — never open an action record for a forbidden call.
|
|
454
|
+
if (decision.decision === 'block') {
|
|
455
|
+
return {
|
|
456
|
+
block: true,
|
|
457
|
+
blockReason: decision.reason || 'Blocked by DashClaw policy',
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
if (decision.decision === 'warn') {
|
|
462
|
+
console.warn(
|
|
463
|
+
`[dashclaw-governance] WARN ${toolName}: ${decision.reason || 'flagged by policy'}`
|
|
464
|
+
);
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// Open a governance record. The server re-evaluates policy at this
|
|
468
|
+
// point and is the authoritative source for HITL gating — even when
|
|
469
|
+
// guard returned `allow`, the server may still set `pending_approval`
|
|
470
|
+
// (for example, if the capability has `requires_approval=true`).
|
|
471
|
+
//
|
|
472
|
+
// NOTE: we MUST call `createAction` before `waitForApproval`, because
|
|
473
|
+
// `waitForApproval` polls `GET /api/actions/:id` — which is backed by
|
|
474
|
+
// the `action_records` table. `decision.action_id` from `guard()` is a
|
|
475
|
+
// row in the separate `guard_decisions` table (prefix `act_gd_`) and
|
|
476
|
+
// cannot be resolved by that endpoint.
|
|
477
|
+
let createdActionId: string | undefined;
|
|
478
|
+
let createdStatus: string | undefined;
|
|
479
|
+
try {
|
|
480
|
+
const created = await client.createAction({
|
|
481
|
+
action_type: actionType,
|
|
482
|
+
declared_goal: declaredGoal,
|
|
483
|
+
risk_score: riskScore,
|
|
484
|
+
reversible,
|
|
485
|
+
systems_touched: systemsTouched,
|
|
486
|
+
metadata: { openclaw_tool_name: toolName },
|
|
487
|
+
});
|
|
488
|
+
createdActionId =
|
|
489
|
+
created.action_id ?? created.action?.action_id ?? created.action?.id;
|
|
490
|
+
createdStatus = created.action?.status;
|
|
491
|
+
} catch (err) {
|
|
492
|
+
const msg = errorMessage(err) || 'unknown';
|
|
493
|
+
console.warn(`[dashclaw-governance] createAction failed: ${msg}`);
|
|
494
|
+
if (config.failClosed) {
|
|
495
|
+
return {
|
|
496
|
+
block: true,
|
|
497
|
+
blockReason: `DashClaw action record could not be opened — fail-closed policy (${msg})`,
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
// Fail-open: proceed without an action record. We cannot wait for
|
|
501
|
+
// approval (no ID to wait on) and outcome recording will be skipped.
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
// If the server flagged this for human review, wait on the action
|
|
506
|
+
// record we just created. Either guard said `require_approval` OR the
|
|
507
|
+
// server upgraded the action to `pending_approval` independently — we
|
|
508
|
+
// trust the server's `action.status` over the guard advice.
|
|
509
|
+
const needsApproval =
|
|
510
|
+
decision.decision === 'require_approval' ||
|
|
511
|
+
createdStatus === 'pending_approval';
|
|
512
|
+
|
|
513
|
+
if (needsApproval && createdActionId) {
|
|
514
|
+
try {
|
|
515
|
+
const { action } = await client.waitForApproval(createdActionId);
|
|
516
|
+
if (!isApproved(action)) {
|
|
517
|
+
return {
|
|
518
|
+
block: true,
|
|
519
|
+
blockReason: action?.error_message || 'Action denied by operator',
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
} catch (err) {
|
|
523
|
+
return {
|
|
524
|
+
block: true,
|
|
525
|
+
blockReason: `Approval denied or wait failed: ${errorMessage(err) || 'denied'}`,
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
if (createdActionId) {
|
|
531
|
+
pendingActions.set(key, createdActionId);
|
|
532
|
+
// Track this action_id against the current run so the next
|
|
533
|
+
// `llm_output` can attribute token usage back to it.
|
|
534
|
+
if (runId) getTokenTurn(runId).turnActionIds.push(createdActionId);
|
|
535
|
+
}
|
|
536
|
+
return;
|
|
537
|
+
});
|
|
538
|
+
|
|
539
|
+
// -----------------------------------------------------------------------
|
|
540
|
+
// LLM token attribution — distribute the previous turn's usage across
|
|
541
|
+
// the tool calls it induced, then stash this turn's usage for the next
|
|
542
|
+
// boundary. Runs best-effort; failures never surface to the agent.
|
|
543
|
+
// -----------------------------------------------------------------------
|
|
544
|
+
api.on('llm_output', async (event, _ctx) => {
|
|
545
|
+
const { runId, model, usage } = event;
|
|
546
|
+
if (!runId) return;
|
|
547
|
+
|
|
548
|
+
let client: DashClaw;
|
|
549
|
+
try {
|
|
550
|
+
client = getClient(config);
|
|
551
|
+
} catch (err) {
|
|
552
|
+
// No client → skip attribution, don't disrupt the run. Log once per
|
|
553
|
+
// failure class so ops notice when token tracking is off (key
|
|
554
|
+
// rotation, base-URL typo) instead of silently losing every turn.
|
|
555
|
+
console.warn(
|
|
556
|
+
`[dashclaw-governance] llm_output dropped — client unavailable: ${errorMessage(err) || 'unknown'}`
|
|
557
|
+
);
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
const state = getTokenTurn(runId);
|
|
562
|
+
|
|
563
|
+
// Distribute the PREVIOUS turn's usage before stashing the new one.
|
|
564
|
+
if (state.pendingUsage) {
|
|
565
|
+
await distributePendingTokens(client, state);
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
// Stash this turn's usage for attribution on the next llm_output
|
|
569
|
+
// (or agent_end). Cache reads are billed at ~10% of base input price, so
|
|
570
|
+
// we weight them at 0.1 before summing — the server's pricing table
|
|
571
|
+
// doesn't model the cache discount, so applying it here keeps the
|
|
572
|
+
// derived cost aligned with real billing. Cache writes stay at full
|
|
573
|
+
// price (close enough for 5m caching; slightly under-counts 1h).
|
|
574
|
+
if (usage) {
|
|
575
|
+
const cacheReadEffective = Math.round((usage.cacheRead ?? 0) * 0.1);
|
|
576
|
+
const tokens_in =
|
|
577
|
+
(usage.input ?? 0) + (usage.cacheWrite ?? 0) + cacheReadEffective;
|
|
578
|
+
const tokens_out = usage.output ?? 0;
|
|
579
|
+
if (tokens_in > 0 || tokens_out > 0) {
|
|
580
|
+
state.pendingUsage = { tokens_in, tokens_out, model: model ?? '' };
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
});
|
|
584
|
+
|
|
585
|
+
// -----------------------------------------------------------------------
|
|
586
|
+
// Run end — flush any remaining usage, then drop per-run state.
|
|
587
|
+
// -----------------------------------------------------------------------
|
|
588
|
+
api.on('agent_end', async (_event, ctx) => {
|
|
589
|
+
const runId = ctx?.runId;
|
|
590
|
+
if (!runId) return;
|
|
591
|
+
const state = tokenTurnByRun.get(runId);
|
|
592
|
+
if (!state) return;
|
|
593
|
+
|
|
594
|
+
if (state.pendingUsage && state.turnActionIds.length > 0) {
|
|
595
|
+
try {
|
|
596
|
+
const client = getClient(config);
|
|
597
|
+
await distributePendingTokens(client, state);
|
|
598
|
+
} catch (err) {
|
|
599
|
+
// No client → drop state but log the lost attribution so ops can
|
|
600
|
+
// see how many actions went unattributed.
|
|
601
|
+
console.warn(
|
|
602
|
+
`[dashclaw-governance] agent_end token flush dropped ${state.turnActionIds.length} action(s): ${errorMessage(err) || 'unknown'}`
|
|
603
|
+
);
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
tokenTurnByRun.delete(runId);
|
|
607
|
+
});
|
|
608
|
+
|
|
609
|
+
// -----------------------------------------------------------------------
|
|
610
|
+
// Outcome recorder
|
|
611
|
+
// -----------------------------------------------------------------------
|
|
612
|
+
api.on('after_tool_call', async (event, _ctx) => {
|
|
613
|
+
const { toolName, toolCallId, runId, error } = event;
|
|
614
|
+
const key = callKey(toolName, toolCallId, runId);
|
|
615
|
+
const actionId = pendingActions.get(key);
|
|
616
|
+
if (!actionId) return;
|
|
617
|
+
pendingActions.delete(key);
|
|
618
|
+
|
|
619
|
+
const status = error ? 'failed' : 'completed';
|
|
620
|
+
|
|
621
|
+
let client: DashClaw;
|
|
622
|
+
try {
|
|
623
|
+
client = getClient(config);
|
|
624
|
+
} catch {
|
|
625
|
+
return; // No client → cannot record; never break tool execution.
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
try {
|
|
629
|
+
await client.updateOutcome(actionId, {
|
|
630
|
+
status,
|
|
631
|
+
...(error ? { error_message: error } : {}),
|
|
632
|
+
});
|
|
633
|
+
} catch (err) {
|
|
634
|
+
console.warn(
|
|
635
|
+
`[dashclaw-governance] updateOutcome failed: ${errorMessage(err) || 'unknown'}`
|
|
636
|
+
);
|
|
637
|
+
}
|
|
638
|
+
});
|
|
639
|
+
},
|
|
640
|
+
});
|