@dashclaw/openclaw-plugin 1.2.5 → 1.6.0

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
@@ -81,6 +81,8 @@ Every tool call your agent makes flows through DashClaw before it executes:
81
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
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
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
+
84
86
  The plugin is read-mostly: it never modifies the tool's parameters or the tool's result. It only blocks, allows, or records.
85
87
 
86
88
  ### Unified policy surface
@@ -117,11 +119,31 @@ empty because the wait target didn't exist. Fixed in `1.0.1`.
117
119
  | `dashclawUrl` | string | **required** | Base URL of your DashClaw instance, e.g. `https://my-dashclaw.vercel.app`. |
118
120
  | `dashclawApiKey` | string | **required** | DashClaw API key (starts with `oc_live_`). |
119
121
  | `agentId` | string | `"openclaw"` | Identifier this OpenClaw instance reports to DashClaw. |
120
- | `defaultModel` | string | `""` | Fallback model id (e.g. `claude-sonnet-4-6`, `gpt-4o`) 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`. |
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`. |
121
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`). |
122
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. |
123
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. |
124
127
 
128
+ ## Automatic identity pairing
129
+
130
+ When an admin clicks **Request pairing** for this agent on the DashClaw
131
+ `/identities` page, the plugin answers on the agent's next tool call — no LLM
132
+ involvement:
133
+
134
+ 1. It reads the agent's unread DashClaw inbox and finds the
135
+ `dashclaw.pairing_request` directive.
136
+ 2. It generates an RSA-2048 keypair locally. The private key is written to
137
+ `~/.dashclaw/identity/<agentId>.pem` (mode 600) and never leaves the
138
+ machine.
139
+ 3. It POSTs the public key to `/api/pairings` and marks the message read.
140
+
141
+ The pairing then appears under **Pending Pairings** on `/identities` for the
142
+ admin's one-click approval — approval is what creates the identity. Disable
143
+ with `autoPairing: false`. To rotate keys, delete the `.pem` file and click
144
+ **Request pairing** again. Auto-pairing is fire-and-forget: it runs once per
145
+ gateway process and can never block or fail a tool call.
146
+
125
147
  ## Fail-closed vs fail-open
126
148
 
127
149
  - **`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.
@@ -185,8 +207,6 @@ Interpretation:
185
207
  | `> 0` | `> 0` | `0` | Model string isn't matched by DashClaw's pricing table. Add it via Settings → Model Pricing. |
186
208
  | `> 0` | `> 0` | `> 0` | Working. If the UI disagrees, check the analytics aggregation. |
187
209
 
188
- Repo operators can run `node scripts/diagnose-cost-attribution.mjs` from a DashClaw checkout — it auto-discovers `org_id` from `.env.local` and prints the same table.
189
-
190
210
  ## Links
191
211
 
192
212
  - DashClaw: <https://github.com/ucsandman/DashClaw>
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Auto-pairing consumer — answers the operator's /identities "Request
3
+ * pairing" click without an LLM in the loop.
4
+ *
5
+ * On the first tool call per gateway process the plugin checks this agent's
6
+ * DashClaw inbox for a `dashclaw.pairing_request` directive (the fenced-JSON
7
+ * contract in app/lib/pairing-request.ts). When one targets this agent it
8
+ * generates an RSA-2048 keypair locally, POSTs the public PEM via the SDK's
9
+ * createPairing, stores the private key at
10
+ * ~/.dashclaw/identity/<agent_id>.pem (mode 600 — same path as the MCP
11
+ * dashclaw_pair tool), and marks the message read. Identity creation still
12
+ * happens only when an admin approves the pairing on /identities.
13
+ *
14
+ * Custody rule: the private key never leaves this machine and is never
15
+ * logged. Failure rule: every error is a console.warn — this path must
16
+ * never throw into or block a tool call.
17
+ */
18
+ import type { DashClaw } from 'dashclaw';
19
+ export declare const PAIRING_REQUEST_KIND = "dashclaw.pairing_request";
20
+ export interface AutoPairConfig {
21
+ dashclawUrl: string;
22
+ dashclawApiKey: string;
23
+ agentId: string;
24
+ autoPairing: boolean;
25
+ }
26
+ /** Test-only: reset the per-process attempt guard. */
27
+ export declare function __resetAutoPairing(): void;
28
+ export declare function identityKeyPath(agentId: string): string;
29
+ export declare function maybeAutoPair(client: DashClaw, config: AutoPairConfig): Promise<void>;
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Auto-pairing consumer — answers the operator's /identities "Request
3
+ * pairing" click without an LLM in the loop.
4
+ *
5
+ * On the first tool call per gateway process the plugin checks this agent's
6
+ * DashClaw inbox for a `dashclaw.pairing_request` directive (the fenced-JSON
7
+ * contract in app/lib/pairing-request.ts). When one targets this agent it
8
+ * generates an RSA-2048 keypair locally, POSTs the public PEM via the SDK's
9
+ * createPairing, stores the private key at
10
+ * ~/.dashclaw/identity/<agent_id>.pem (mode 600 — same path as the MCP
11
+ * dashclaw_pair tool), and marks the message read. Identity creation still
12
+ * happens only when an admin approves the pairing on /identities.
13
+ *
14
+ * Custody rule: the private key never leaves this machine and is never
15
+ * logged. Failure rule: every error is a console.warn — this path must
16
+ * never throw into or block a tool call.
17
+ */
18
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
19
+ import { homedir } from 'node:os';
20
+ import { dirname, join } from 'node:path';
21
+ import { generateKeyPairSync } from 'node:crypto';
22
+ export const PAIRING_REQUEST_KIND = 'dashclaw.pairing_request';
23
+ // One attempt per gateway process per (url, agent). Added BEFORE the first
24
+ // await so concurrent tool calls cannot double-run the flow. Per-process on
25
+ // purpose: a transient failure retries at the next gateway start.
26
+ let attempted = new Set();
27
+ /** Test-only: reset the per-process attempt guard. */
28
+ export function __resetAutoPairing() {
29
+ attempted = new Set();
30
+ }
31
+ export function identityKeyPath(agentId) {
32
+ const safe = agentId.replace(/[^A-Za-z0-9._-]/g, '_');
33
+ return join(homedir(), '.dashclaw', 'identity', `${safe}.pem`);
34
+ }
35
+ /** Same fence contract as app/lib/pairing-request.ts. */
36
+ function directiveTargets(body, agentId) {
37
+ if (typeof body !== 'string')
38
+ return false;
39
+ const match = body.match(/```json\s*([\s\S]*?)```/);
40
+ if (!match || !match[1])
41
+ return false;
42
+ try {
43
+ const parsed = JSON.parse(match[1]);
44
+ return parsed?.kind === PAIRING_REQUEST_KIND && parsed.agent_id === agentId;
45
+ }
46
+ catch {
47
+ return false;
48
+ }
49
+ }
50
+ function apiUrl(config, pathAndQuery) {
51
+ return `${config.dashclawUrl.replace(/\/+$/, '')}${pathAndQuery}`;
52
+ }
53
+ async function fetchUnreadInbox(config) {
54
+ const res = await fetch(apiUrl(config, `/api/messages?agent_id=${encodeURIComponent(config.agentId)}&direction=inbox&unread=true&limit=50`), { headers: { 'x-api-key': config.dashclawApiKey } });
55
+ if (!res.ok)
56
+ throw new Error(`messages GET failed (${res.status})`);
57
+ const data = (await res.json());
58
+ return Array.isArray(data.messages) ? data.messages : [];
59
+ }
60
+ async function markRead(config, messageIds) {
61
+ const res = await fetch(apiUrl(config, '/api/messages'), {
62
+ method: 'PATCH',
63
+ headers: { 'x-api-key': config.dashclawApiKey, 'Content-Type': 'application/json' },
64
+ body: JSON.stringify({ message_ids: messageIds, action: 'read', agent_id: config.agentId }),
65
+ });
66
+ if (!res.ok)
67
+ throw new Error(`messages PATCH failed (${res.status})`);
68
+ }
69
+ export async function maybeAutoPair(client, config) {
70
+ if (!config.autoPairing)
71
+ return;
72
+ const key = `${config.dashclawUrl}|${config.agentId}`;
73
+ if (attempted.has(key))
74
+ return;
75
+ attempted.add(key);
76
+ try {
77
+ const pemPath = identityKeyPath(config.agentId);
78
+ if (existsSync(pemPath)) {
79
+ // Already enrolled or pending. Deleting the pem + clicking Request
80
+ // pairing again is the rotation path.
81
+ return;
82
+ }
83
+ const inbox = await fetchUnreadInbox(config);
84
+ const requests = inbox.filter((m) => directiveTargets(m.body, config.agentId));
85
+ if (requests.length === 0)
86
+ return;
87
+ const { publicKey, privateKey } = generateKeyPairSync('rsa', {
88
+ modulusLength: 2048,
89
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
90
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
91
+ });
92
+ const created = await client.createPairing(publicKey);
93
+ const pairingId = created.pairing?.id ??
94
+ created.id ??
95
+ '(pending)';
96
+ // POST-then-write: a failed POST leaves no pem, so the next gateway
97
+ // start retries cleanly. A failed write AFTER a successful POST is the
98
+ // one loud case — that pending pairing has no usable private key.
99
+ try {
100
+ mkdirSync(dirname(pemPath), { recursive: true });
101
+ writeFileSync(pemPath, privateKey, { mode: 0o600 });
102
+ }
103
+ catch (err) {
104
+ console.warn(`[dashclaw-governance] auto-pairing: submitted pairing ${pairingId} but FAILED to store ` +
105
+ `the private key at ${pemPath}: ${errText(err)}. Reject that pairing on /identities, ` +
106
+ `fix the disk issue, and click Request pairing again.`);
107
+ return; // leave the message unread so a later gateway start retries
108
+ }
109
+ await markRead(config, requests.map((m) => m.id));
110
+ console.log(`[dashclaw-governance] auto-pairing submitted (${pairingId}) — approve it on /identities. ` +
111
+ `Private key stored at ${pemPath} (never sent).`);
112
+ }
113
+ catch (err) {
114
+ console.warn(`[dashclaw-governance] auto-pairing skipped: ${errText(err)}`);
115
+ }
116
+ }
117
+ function errText(err) {
118
+ return err instanceof Error ? err.message : String(err);
119
+ }
@@ -0,0 +1,24 @@
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
+ import { definePluginEntry } from 'openclaw/plugin-sdk/plugin-entry';
23
+ declare const pluginEntry: ReturnType<typeof definePluginEntry>;
24
+ export default pluginEntry;