@dashclaw/openclaw-plugin 1.6.2 → 1.6.4

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 CHANGED
@@ -1,219 +1,248 @@
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
- On the first tool call of each run the plugin opens a DashClaw **Agent Session** and closes it (`status: completed`) on `agent_end`, so every OpenClaw run shows up under the Agent Sessions feature (not just Code Sessions). Session lifecycle calls are fully fail-safe — a session error never blocks a tool call or the run.
85
-
86
- The plugin is read-mostly: it never modifies the tool's parameters or the tool's result. It only blocks, allows, or records.
87
-
88
- ### Unified policy surface
89
-
90
- 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.
91
-
92
- | Tool call | Action type | Risk | Reversible |
93
- |---|---|---|---|
94
- | `bash: git push origin main` | `deploy` | 80 | no |
95
- | `bash: rm -rf /tmp/data` | `security` | 90 | no |
96
- | `bash: git diff` | `review` | 10 | yes |
97
- | `bash: curl https://api.example.com` | `api` | 40 | yes |
98
- | `bash: npm install express` | `build` | 30 | yes |
99
- | `write: .env.production` | `security` | 85 | yes |
100
- | `edit: src/app.ts` | `apply` | 50 | yes |
101
- | `read: config.json` | `review` | 15 | yes |
102
-
103
- 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.
104
-
105
- ### `action_id` distinction
106
-
107
- `guard()` returns an `action_id` that points at the `guard_decisions` table
108
- (prefix `act_gd_…`). `createAction()` returns an `action_id` that points at
109
- the `action_records` table. `waitForApproval()` polls
110
- `GET /api/actions/:id`, which resolves against `action_records` — so the
111
- plugin always waits using the `createAction()` ID, never the `guard()` ID.
112
- Plugin builds at `1.0.0` had this wrong and the PWA approval queue stayed
113
- empty because the wait target didn't exist. Fixed in `1.0.1`.
114
-
115
- ## Configuration reference
116
-
117
- | Field | Type | Default | Description |
118
- |---|---|---|---|
119
- | `dashclawUrl` | string | **required** | Base URL of your DashClaw instance, e.g. `https://my-dashclaw.vercel.app`. |
120
- | `dashclawApiKey` | string | **required** | DashClaw API key (starts with `oc_live_`). |
121
- | `agentId` | string | `"openclaw"` | Identifier this OpenClaw instance reports to DashClaw. |
122
- | `defaultModel` | string | `""` | Fallback model id (e.g. `claude-sonnet-5`, `openai-codex/gpt-5.4`) used when `llm_output` events don't include a `model` field. Without this, unpriced turns land `tokens_in`/`tokens_out` but `cost_estimate` stays `$0`. Env var: `DASHCLAW_DEFAULT_MODEL`. |
123
- | `failClosed` | boolean | `true` | If DashClaw is unreachable, block the tool call. Set `false` to fail open. |
124
- | `autoPairing` | boolean | `true` | Automatically answer operator pairing requests from the DashClaw `/identities` page. The private key is stored at `~/.dashclaw/identity/<agentId>.pem` and never leaves this machine. Set `false` to require manual pairing (MCP `dashclaw_pair` or SDK `createPairing`). |
125
- | `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. |
126
- | `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. |
1
+ # @dashclaw/openclaw-plugin
2
+
3
+ Add DashClaw governance to tool calls that OpenClaw delivers through the installed `before_tool_call` hook, with policy enforcement, human approval gates, and a verifiable decision trail.
4
+
5
+ ## Install
6
+
7
+ The recommended path is the DashClaw CLI installer — it runs the plugin install for you and finishes everything the plugin needs to actually enforce (API key written to the profile's `.env`, gateway config patched, plugin enabled, governance protocol written to `AGENTS.md`, install verified). Run it bare in a terminal and it walks you through the rest, including creating a DashClaw instance (hosted trial or local `dashclaw up`) and collecting a key if you don't have them yet:
8
+
9
+ ```bash
10
+ dashclaw install openclaw
11
+ ```
12
+
13
+ Installing the plugin directly also works:
14
+
15
+ ```bash
16
+ openclaw plugins install @dashclaw/openclaw-plugin
17
+ ```
18
+
19
+ but the raw install only puts the plugin on disk — it is not enabled and has no configuration until you complete the steps below. Already ran it? `dashclaw install openclaw` detects the installed plugin, keeps it (it never downgrades an equal-or-newer version), and finishes the rest. Full walkthrough: [dashclaw.io/guides/openclaw](https://www.dashclaw.io/guides/openclaw).
20
+
21
+ ## Configure
22
+
23
+ The plugin accepts **three interchangeable configuration shapes** — pick whichever fits your deployment. Precedence is plugin config > env vars.
24
+
25
+ ### Option A — canonical plugin-config keys
26
+
27
+ ```json
28
+ {
29
+ "plugins": {
30
+ "entries": {
31
+ "dashclaw-governance": {
32
+ "enabled": true,
33
+ "config": {
34
+ "dashclawUrl": "https://my-dashclaw.vercel.app",
35
+ "dashclawApiKey": "oc_live_...",
36
+ "agentId": "my-openclaw-agent",
37
+ "failClosed": true,
38
+ "highRiskTools": ["bash", "exec", "write_file"]
39
+ }
40
+ }
41
+ }
42
+ }
43
+ }
44
+ ```
45
+
46
+ ### Option B — SDK-style aliases
47
+
48
+ If you prefer the same naming as the DashClaw Node SDK:
49
+
50
+ ```json
51
+ {
52
+ "config": {
53
+ "baseUrl": "https://my-dashclaw.vercel.app",
54
+ "apiKey": "oc_live_...",
55
+ "agentId": "my-openclaw-agent"
56
+ }
57
+ }
58
+ ```
59
+
60
+ ### Option C — environment variables (recommended for secrets)
61
+
62
+ Set these before the gateway starts and omit URL/key from plugin config entirely:
63
+
64
+ ```bash
65
+ export DASHCLAW_BASE_URL="https://my-dashclaw.vercel.app" # DASHCLAW_URL also accepted
66
+ export DASHCLAW_API_KEY="oc_live_..."
67
+ export DASHCLAW_AGENT_ID="my-openclaw-agent" # optional
68
+ ```
69
+
70
+ ```json
71
+ {
72
+ "config": {
73
+ "failClosed": true,
74
+ "highRiskTools": ["bash", "exec", "write_file"]
75
+ }
76
+ }
77
+ ```
78
+
79
+ 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).
80
+
81
+ Config changes require a gateway restart, the same as any other OpenClaw plugin.
82
+
83
+ ## What happens
84
+
85
+ Every tool call delivered to the installed OpenClaw `before_tool_call` hook flows through DashClaw before it executes:
86
+
87
+ 1. Agent decides to call a tool (e.g. `bash`, `write`, a custom HTTP tool).
88
+ 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.
89
+ 3. The plugin calls DashClaw `/api/guard` with the full classification (`action_type`, `risk_score`, `declared_goal`, `reversible`, `systems_touched`) and canonical act evidence: the full shell command for `bash`/`exec`, or the file target for `write`/`edit`/`apply_patch`. DashClaw can therefore derive risk from what will run and match protected paths. File content is never copied into evidence. If the verdict is `block`, the tool call is rejected immediately.
90
+ 4. On `allow`, `warn`, or `require_approval`, the plugin opens a governance record via `/api/actions` with the same act evidence. The server re-runs current policy and is authoritative for HITL gating. It may return `action.status === 'pending_approval'` even when the earlier guard said `allow`.
91
+ 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 wait uses SSE plus concurrent authoritative action polling, so a connected stream cannot hide a missed event.
92
+ 6. When the server advertises execution-claim protocol 1, the plugin atomically claims the exact action, agent, act, and fresh attempt immediately before returning control to OpenClaw. Approval is consumed at this claim, not at guard time. A rejected, malformed, or lost claim acknowledgement blocks and is never retried automatically.
93
+ 7. OpenClaw executes the tool once the plugin releases it. The `after_tool_call` hook records `completed` or `failed` with the error message.
94
+
95
+ This boundary covers calls OpenClaw delivers to those lifecycle hooks. Embedded
96
+ Codex native tools run behind their own runtime and require the separately
97
+ installed DashClaw Codex hooks. Older OpenClaw 0.13x Codex integrations remain
98
+ cooperative and do not inherit this plugin's mechanical interception boundary.
99
+
100
+ Claim negotiation supports server-first upgrades. A server that omits both claim
101
+ fields keeps the legacy guard and approval flow until you set
102
+ `DASHCLAW_REQUIRE_EXECUTION_CLAIMS=1`. Any server that advertises an incomplete,
103
+ unknown, or malformed claim protocol is blocked even when strict mode is unset.
104
+
105
+ On the first intercepted tool call of each run the plugin opens a DashClaw **Agent Session** and closes it (`status: completed`) on `agent_end`, so every OpenClaw run with at least one intercepted call shows up under the Agent Sessions feature (not just Code Sessions). Session lifecycle calls are fully fail-safe — a session error never blocks a tool call or the run.
106
+
107
+ The plugin is read-mostly: it never modifies the tool's parameters or the tool's result. It only blocks, allows, or records.
108
+
109
+ ### Unified policy surface
110
+
111
+ The plugin uses the **same action type vocabulary** as the DashClaw Claude Code hooks. Policies you write for Claude Code apply to OpenClaw calls delivered through the plugin hook without duplicating the policy.
112
+
113
+ | Tool call | Action type | Risk | Reversible |
114
+ |---|---|---|---|
115
+ | `bash: git push origin main` | `deploy` | 80 | no |
116
+ | `bash: rm -rf /tmp/data` | `security` | 90 | no |
117
+ | `bash: git diff` | `review` | 10 | yes |
118
+ | `bash: curl https://api.example.com` | `api` | 40 | yes |
119
+ | `bash: npm install express` | `build` | 30 | yes |
120
+ | `write: .env.production` | `security` | 85 | yes |
121
+ | `edit: src/app.ts` | `apply` | 50 | yes |
122
+ | `read: config.json` | `review` | 15 | yes |
123
+
124
+ 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.
125
+
126
+ ### `action_id` distinction
127
+
128
+ `guard()` returns an `action_id` that points at the `guard_decisions` table
129
+ (prefix `act_gd_…`). `createAction()` returns an `action_id` that points at
130
+ the `action_records` table. `waitForApproval()` polls
131
+ `GET /api/actions/:id`, which resolves against `action_records` — so the
132
+ plugin always waits using the `createAction()` ID, never the `guard()` ID.
133
+ Plugin builds at `1.0.0` had this wrong and the PWA approval queue stayed
134
+ empty because the wait target didn't exist. Fixed in `1.0.1`.
135
+
136
+ ## Configuration reference
137
+
138
+ | Field | Type | Default | Description |
139
+ |---|---|---|---|
140
+ | `dashclawUrl` | string | **required** | Base URL of your DashClaw instance, e.g. `https://my-dashclaw.vercel.app`. |
141
+ | `dashclawApiKey` | string | **required** | DashClaw API key (starts with `oc_live_`). |
142
+ | `agentId` | string | `"openclaw"` | Identifier this OpenClaw instance reports to DashClaw. |
143
+ | `defaultModel` | string | `""` | Fallback model id (e.g. `claude-sonnet-5`, `openai-codex/gpt-5.4`) used when `llm_output` events don't include a `model` field. Without this, unpriced turns land `tokens_in`/`tokens_out` but `cost_estimate` stays `$0`. Env var: `DASHCLAW_DEFAULT_MODEL`. |
144
+ | `failClosed` | boolean | `true` | If DashClaw is unreachable, block the tool call. Set `false` to fail open. |
145
+ | `autoPairing` | boolean | `true` | Automatically answer operator pairing requests from the DashClaw `/identities` page. The private key is stored at `~/.dashclaw/identity/<agentId>.pem` and never leaves this machine. Set `false` to require manual pairing (MCP `dashclaw_pair` or SDK `createPairing`). |
146
+ | `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. |
147
+ | `highRiskTools` | string[] | `[]` | Tool names that start at risk score 85 instead of the default, before classification. A pattern match then takes precedence over that starting score in both directions: a destructive command still scores 90, a deploy scores 80, and read-only tools are capped at 15 no matter what they started at. |
127
148
  | `approvalWaitMs` | number | `60000` | How long a `require_approval` decision waits for the operator before blocking with a retry hint. Keep it below your runtime's per-tool-call watchdog — Codex's embedded dynamic-tool RPC kills calls at ~90s, which would silently drop the tool result instead of blocking cleanly. The approval stays open ~300s server-side, so the operator can approve after the wait and the agent's retry of the same call passes (guard approval grant + idempotent `createAction`). |
128
149
 
129
- ## Automatic identity pairing
130
-
131
- When an admin clicks **Request pairing** for this agent on the DashClaw
132
- `/identities` page, the plugin answers on the agent's next tool call — no LLM
133
- involvement:
134
-
135
- 1. It reads the agent's unread DashClaw inbox and finds the
136
- `dashclaw.pairing_request` directive.
137
- 2. It generates an RSA-2048 keypair locally. The private key is written to
138
- `~/.dashclaw/identity/<agentId>.pem` (mode 600) and never leaves the
139
- machine.
140
- 3. It POSTs the public key to `/api/pairings` and marks the message read.
141
-
142
- The pairing then appears under **Pending Pairings** on `/identities` for the
143
- admin's one-click approval — approval is what creates the identity. Disable
144
- with `autoPairing: false`. To rotate keys, delete the `.pem` file and click
145
- **Request pairing** again. Auto-pairing is fire-and-forget: it runs once per
146
- gateway process and can never block or fail a tool call.
147
-
148
- ## Fail-closed vs fail-open
149
-
150
- - **`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.
151
- - **`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).
152
-
153
- 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`.
154
-
155
- ## How tool calls are classified
156
-
157
- The plugin goes beyond tool names — it inspects the **content** of each call:
158
-
159
- - **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).
160
- - **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`.
161
- - **read/web_search/web_fetch**: Always `review` with low risk (capped at 15).
162
- - **sessions_send**: `message`, irreversible.
163
- - **Everything else**: `other` with the configured default risk.
164
-
165
- This classification mirrors what the DashClaw Claude Code hooks do via `dashclaw_agent_intel`, so the same guard policies fire consistently across both platforms.
166
-
167
- ## Outcome recording
168
-
169
- 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.
170
-
171
- 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.
172
-
173
- ## Token usage and cost (v1.2.1+)
174
-
175
- 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.
176
-
177
- Accounting notes:
178
-
179
- - 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.
180
- - 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.
181
- - Failures are silent: a warning is logged but token attribution never blocks or throws. If your provider doesn't populate `usage`, nothing is patched.
182
- - **Missing `model`:** if `llm_output` fires with `usage` but no `model`, the plugin stashes tokens using `config.defaultModel` / `DASHCLAW_DEFAULT_MODEL` as a fallback. When both are unset, tokens are still attributed but `cost_estimate` stays `$0` — because the server refuses to guess the model (retroactively backfilling `model = NULL` would have priced every historical row as Opus). The plugin logs a one-time breadcrumb per run in this case so ops can spot it quickly.
183
-
184
- ## Troubleshooting cost attribution
185
-
186
- If actions are flowing but `cost_estimate` stays `$0` for an OpenClaw agent, run this query against your DashClaw DB — it decomposes the three failure modes in one shot:
187
-
188
- ```sql
189
- SELECT
190
- agent_id,
191
- COUNT(*) AS actions,
192
- COUNT(*) FILTER (WHERE tokens_in > 0 OR tokens_out > 0) AS with_tokens,
193
- COUNT(*) FILTER (WHERE model IS NOT NULL AND model <> '') AS with_model,
194
- COUNT(*) FILTER (WHERE cost_estimate > 0) AS with_cost
195
- FROM action_records
196
- WHERE org_id = '<your_org_id>'
197
- AND timestamp_start::timestamptz >= NOW() - INTERVAL '30 days'
198
- GROUP BY agent_id
199
- ORDER BY actions DESC;
200
- ```
201
-
202
- Interpretation:
203
-
204
- | `with_tokens` | `with_model` | `with_cost` | Likely cause |
205
- |---|---|---|---|
206
- | `0` | `0` | `0` | Plugin older than v1.2.0, or OpenClaw runtime doesn't emit `llm_output`. Upgrade both. |
207
- | `> 0` | `0` | `0` | `llm_output` fires without `model`. Set `config.defaultModel` or `DASHCLAW_DEFAULT_MODEL`. |
208
- | `> 0` | `> 0` | `0` | Model string isn't matched by DashClaw's pricing table. Add it via Settings → Model Pricing. |
209
- | `> 0` | `> 0` | `> 0` | Working. If the UI disagrees, check the analytics aggregation. |
210
-
211
- ## Links
212
-
213
- - DashClaw: <https://github.com/ucsandman/DashClaw>
214
- - DashClaw Node SDK: <https://www.npmjs.com/package/dashclaw>
215
- - OpenClaw: <https://docs.openclaw.ai>
216
-
217
- ## License
218
-
219
- MIT — see [LICENSE](./LICENSE).
150
+ `DASHCLAW_REQUIRE_EXECUTION_CLAIMS=1` is an environment-only rollout pin. Enable
151
+ it after the DashClaw server supports protocol 1 to reject legacy responses that
152
+ do not advertise claims.
153
+
154
+ ## Automatic identity pairing
155
+
156
+ When an admin clicks **Request pairing** for this agent on the DashClaw
157
+ `/identities` page, the plugin answers on the agent's next tool call — no LLM
158
+ involvement:
159
+
160
+ 1. It reads the agent's unread DashClaw inbox and finds the
161
+ `dashclaw.pairing_request` directive.
162
+ 2. It generates an RSA-2048 keypair locally. The private key is written to
163
+ `~/.dashclaw/identity/<agentId>.pem` (mode 600) and never leaves the
164
+ machine.
165
+ 3. It POSTs the public key to `/api/pairings` and marks the message read.
166
+
167
+ The pairing then appears under **Pending Pairings** on `/identities` for the
168
+ admin's one-click approval — approval is what creates the identity. Disable
169
+ with `autoPairing: false`. To rotate keys, delete the `.pem` file and click
170
+ **Request pairing** again. Auto-pairing is fire-and-forget: it runs once per
171
+ gateway process and can never block or fail a tool call.
172
+
173
+ ## Fail-closed vs fail-open
174
+
175
+ - **`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.
176
+ - **`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).
177
+
178
+ 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`.
179
+
180
+ ## How tool calls are classified
181
+
182
+ The plugin goes beyond tool names — it inspects the **content** of each call:
183
+
184
+ - **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).
185
+ - **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`.
186
+ - **read/web_search/web_fetch**: Always `review` with low risk (capped at 15).
187
+ - **sessions_send**: `message`, irreversible.
188
+ - **Everything else**: `other` with the configured default risk.
189
+
190
+ This classification mirrors what the DashClaw Claude Code hooks do via `dashclaw_agent_intel`, so the same guard policies fire consistently across both platforms.
191
+
192
+ ### Evidence attachment
193
+
194
+ Every `guard()` and `createAction()` call now carries an `act` payload alongside the self-declared `action_type`/`risk_score`, so the server's evidence classifier grades what actually ran instead of only the plugin's own summary. Shell calls (`bash`, `exec`) attach `act.kind: 'shell'` with the full command; write calls (`write`, `edit`, `apply_patch`) attach `act.kind: 'file'` with the file path. When a shell command invokes a local script (for example `node tmp/domain-buy.mjs <name>`), the plugin also resolves that script against the tool call's workspace and attaches its first 6144 characters as `act.script.content_excerpt`, so a wrapper script can't hide its risk behind an innocuous-looking command line. For sensitive paths (`.env`, `credential`, `.pem`, `id_rsa`, `.key`) only `act.script.path` is attached, never content. If the script can't be resolved or read, or exceeds 64KB, `script` is omitted entirely — evidence attachment fails soft and never blocks the call.
195
+
196
+ ## Outcome recording
197
+
198
+ 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.
199
+
200
+ If the outcome update itself fails, the plugin logs a warning but never throws because the tool has already run. Treat that action's completion as unconfirmed. Do not infer that the external effect failed or retry it without reconciling the affected system.
201
+
202
+ ## Token usage and cost (v1.2.1+)
203
+
204
+ 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.
205
+
206
+ Accounting notes:
207
+
208
+ - 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.
209
+ - 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.
210
+ - Failures are silent: a warning is logged but token attribution never blocks or throws. If your provider doesn't populate `usage`, nothing is patched.
211
+ - **Missing `model`:** if `llm_output` fires with `usage` but no `model`, the plugin stashes tokens using `config.defaultModel` / `DASHCLAW_DEFAULT_MODEL` as a fallback. When both are unset, tokens are still attributed but `cost_estimate` stays `$0` — because the server refuses to guess the model (retroactively backfilling `model = NULL` would have priced every historical row as Opus). The plugin logs a one-time breadcrumb per run in this case so ops can spot it quickly.
212
+
213
+ ## Troubleshooting cost attribution
214
+
215
+ If actions are flowing but `cost_estimate` stays `$0` for an OpenClaw agent, run this query against your DashClaw DB — it decomposes the three failure modes in one shot:
216
+
217
+ ```sql
218
+ SELECT
219
+ agent_id,
220
+ COUNT(*) AS actions,
221
+ COUNT(*) FILTER (WHERE tokens_in > 0 OR tokens_out > 0) AS with_tokens,
222
+ COUNT(*) FILTER (WHERE model IS NOT NULL AND model <> '') AS with_model,
223
+ COUNT(*) FILTER (WHERE cost_estimate > 0) AS with_cost
224
+ FROM action_records
225
+ WHERE org_id = '<your_org_id>'
226
+ AND timestamp_start::timestamptz >= NOW() - INTERVAL '30 days'
227
+ GROUP BY agent_id
228
+ ORDER BY actions DESC;
229
+ ```
230
+
231
+ Interpretation:
232
+
233
+ | `with_tokens` | `with_model` | `with_cost` | Likely cause |
234
+ |---|---|---|---|
235
+ | `0` | `0` | `0` | Plugin older than v1.2.0, or OpenClaw runtime doesn't emit `llm_output`. Upgrade both. |
236
+ | `> 0` | `0` | `0` | `llm_output` fires without `model`. Set `config.defaultModel` or `DASHCLAW_DEFAULT_MODEL`. |
237
+ | `> 0` | `> 0` | `0` | Model string isn't matched by DashClaw's pricing table. Add it via Settings → Model Pricing. |
238
+ | `> 0` | `> 0` | `> 0` | Working. If the UI disagrees, check the analytics aggregation. |
239
+
240
+ ## Links
241
+
242
+ - DashClaw: <https://github.com/ucsandman/DashClaw>
243
+ - DashClaw Node SDK: <https://www.npmjs.com/package/dashclaw>
244
+ - OpenClaw: <https://docs.openclaw.ai>
245
+
246
+ ## License
247
+
248
+ MIT — see [LICENSE](./LICENSE).