@dashclaw/openclaw-plugin 1.2.4 → 1.5.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/src/index.ts CHANGED
@@ -1,669 +1,971 @@
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
- // Fallback model id used when `llm_output` events fire without a `model`
42
- // field. Without this, the server's `estimateCost` treats the usage as
43
- // unpriceable and stores `cost_estimate = 0` — producing the "tokens
44
- // but no cost" failure mode. Empty string disables the fallback.
45
- defaultModel: string;
46
- failClosed: boolean;
47
- riskScoreDefault: number;
48
- highRiskTools: ReadonlySet<string>;
49
- }
50
-
51
- /**
52
- * Resolve the DashClaw URL from (in order of precedence):
53
- * 1. `config.dashclawUrl` (canonical plugin-config key)
54
- * 2. `config.baseUrl` (SDK-style alias)
55
- * 3. `process.env.DASHCLAW_BASE_URL` (canonical env var — matches CLI, local scripts)
56
- * 4. `process.env.DASHCLAW_URL` (legacy env var — matches MCP server docs)
57
- *
58
- * The same precedence applies to the API key (with DASHCLAW_API_KEY as the only env var).
59
- */
60
- function firstString(...candidates: unknown[]): string {
61
- for (const c of candidates) {
62
- if (typeof c === 'string' && c.length > 0) return c;
63
- }
64
- return '';
65
- }
66
-
67
- function resolveConfig(raw: Record<string, unknown> | undefined): PluginConfig {
68
- const cfg = raw ?? {};
69
- const env = typeof process !== 'undefined' && process?.env ? process.env : {};
70
-
71
- const failClosed = cfg.failClosed !== false; // default true
72
- const riskScoreDefault =
73
- typeof cfg.riskScoreDefault === 'number' ? cfg.riskScoreDefault : 50;
74
- const highRiskTools = new Set<string>(
75
- Array.isArray(cfg.highRiskTools)
76
- ? cfg.highRiskTools.filter((v): v is string => typeof v === 'string')
77
- : []
78
- );
79
-
80
- const dashclawUrl = firstString(
81
- cfg.dashclawUrl,
82
- cfg.baseUrl,
83
- env.DASHCLAW_BASE_URL,
84
- env.DASHCLAW_URL
85
- );
86
- const dashclawApiKey = firstString(
87
- cfg.dashclawApiKey,
88
- cfg.apiKey,
89
- env.DASHCLAW_API_KEY
90
- );
91
- const agentId = firstString(cfg.agentId, env.DASHCLAW_AGENT_ID) || 'openclaw';
92
- const defaultModel = firstString(
93
- cfg.defaultModel,
94
- env.DASHCLAW_DEFAULT_MODEL
95
- );
96
-
97
- return {
98
- dashclawUrl,
99
- dashclawApiKey,
100
- agentId,
101
- defaultModel,
102
- failClosed,
103
- riskScoreDefault,
104
- highRiskTools,
105
- };
106
- }
107
-
108
- // ---------------------------------------------------------------------------
109
- // Module state
110
- // ---------------------------------------------------------------------------
111
-
112
- let cachedClient: DashClaw | null = null;
113
- let cachedClientKey = '';
114
-
115
- /** Maps synthetic call key → DashClaw action_id so `after_tool_call` can close it. */
116
- const pendingActions = new Map<string, string>();
117
-
118
- /**
119
- * Per-run state for LLM token attribution. OpenClaw's `llm_output` event
120
- * fires once per assistant response with `usage.{input,output,cacheRead,
121
- * cacheWrite}` and `model`. The tool calls induced by that response arrive
122
- * via `before_tool_call` after the `llm_output`. We stash the most recent
123
- * usage and the action_ids opened since we stashed it; on the NEXT
124
- * `llm_output` (or on `agent_end`) we distribute that usage evenly across
125
- * those action_ids via `updateOutcome` PATCHes. Cost is derived server-side.
126
- */
127
- interface TokenTurnState {
128
- pendingUsage?: { tokens_in: number; tokens_out: number; model: string };
129
- turnActionIds: string[];
130
- // Set after the first llm_output on this run that fires without a model
131
- // field. Used to suppress repeat warnings within the same run — ops see
132
- // one log line per run, not one per turn.
133
- warnedMissingModel?: boolean;
134
- }
135
- const tokenTurnByRun = new Map<string, TokenTurnState>();
136
-
137
- // Cap for in-memory per-run state. `agent_end` deletes entries, but a crash
138
- // or an agent framework that never fires `agent_end` in a long-lived gateway
139
- // process would leak. At ~100 bytes/entry this cap bounds worst-case memory
140
- // to ~100KB while still comfortably above typical concurrency.
141
- const MAX_TURN_RUNS = 1000;
142
-
143
- function getTokenTurn(runId: string): TokenTurnState {
144
- let state = tokenTurnByRun.get(runId);
145
- if (!state) {
146
- if (tokenTurnByRun.size >= MAX_TURN_RUNS) {
147
- // Evict oldest (Map preserves insertion order). One at a time is enough
148
- // to stay at the cap under steady state — we only grow by one here.
149
- const oldest = tokenTurnByRun.keys().next().value;
150
- if (oldest !== undefined) tokenTurnByRun.delete(oldest);
151
- }
152
- state = { turnActionIds: [] };
153
- tokenTurnByRun.set(runId, state);
154
- }
155
- return state;
156
- }
157
-
158
- /** Split a non-negative integer `total` into `n` buckets, putting remainders
159
- * in the earliest buckets so the sum is preserved exactly. */
160
- function distributeEvenly(total: number, n: number): number[] {
161
- if (n <= 0 || total <= 0) return new Array<number>(Math.max(n, 0)).fill(0);
162
- const base = Math.floor(total / n);
163
- const remainder = total - base * n;
164
- return Array.from({ length: n }, (_, i) => base + (i < remainder ? 1 : 0));
165
- }
166
-
167
- async function distributePendingTokens(
168
- client: DashClaw,
169
- state: TokenTurnState,
170
- ): Promise<void> {
171
- const usage = state.pendingUsage;
172
- const ids = state.turnActionIds;
173
- state.pendingUsage = undefined;
174
- state.turnActionIds = [];
175
-
176
- if (!usage || ids.length === 0) return;
177
- if (usage.tokens_in === 0 && usage.tokens_out === 0) return;
178
-
179
- const inParts = distributeEvenly(usage.tokens_in, ids.length);
180
- const outParts = distributeEvenly(usage.tokens_out, ids.length);
181
-
182
- await Promise.all(
183
- ids.map((actionId, idx) =>
184
- client
185
- .updateOutcome(actionId, {
186
- tokens_in: inParts[idx],
187
- tokens_out: outParts[idx],
188
- ...(usage.model ? { model: usage.model } : {}),
189
- })
190
- .catch((err: unknown) => {
191
- console.warn(
192
- `[dashclaw-governance] token PATCH failed for ${actionId}: ${errorMessage(err) || 'unknown'}`
193
- );
194
- })
195
- )
196
- );
197
- }
198
-
199
- function getClient(config: PluginConfig): DashClaw {
200
- const key = `${config.dashclawUrl}|${config.dashclawApiKey}|${config.agentId}`;
201
- if (cachedClient && cachedClientKey === key) return cachedClient;
202
-
203
- if (!config.dashclawUrl || !config.dashclawApiKey) {
204
- const missing: string[] = [];
205
- if (!config.dashclawUrl) missing.push('dashclawUrl');
206
- if (!config.dashclawApiKey) missing.push('dashclawApiKey');
207
- throw new Error(
208
- `dashclaw-governance plugin: missing ${missing.join(' and ')}. ` +
209
- 'Provide via openclaw.plugin.json config (dashclawUrl/dashclawApiKey or baseUrl/apiKey), ' +
210
- 'or set env vars DASHCLAW_BASE_URL and DASHCLAW_API_KEY before starting the gateway.'
211
- );
212
- }
213
-
214
- cachedClient = new DashClaw({
215
- baseUrl: config.dashclawUrl,
216
- apiKey: config.dashclawApiKey,
217
- agentId: config.agentId,
218
- });
219
- cachedClientKey = key;
220
- return cachedClient;
221
- }
222
-
223
- // ---------------------------------------------------------------------------
224
- // Helpers
225
- // ---------------------------------------------------------------------------
226
-
227
- function summarizeParams(params: Record<string, unknown> | undefined): string {
228
- if (!params) return '';
229
- let serialized: string;
230
- try {
231
- serialized = JSON.stringify(params);
232
- } catch {
233
- return '[unserializable params]';
234
- }
235
- if (serialized.length <= 500) return serialized;
236
- return serialized.slice(0, 500) + '…[truncated]';
237
- }
238
-
239
- function callKey(
240
- toolName: string,
241
- toolCallId: string | undefined,
242
- runId: string | undefined
243
- ): string {
244
- // Prefer the provider-supplied tool call ID; fall back to runId-scoped tool
245
- // name so a later `after_tool_call` without a toolCallId can still find the
246
- // pending record.
247
- if (toolCallId) return `id:${toolCallId}`;
248
- if (runId) return `run:${runId}:${toolName}`;
249
- return `tool:${toolName}`;
250
- }
251
-
252
- function errorMessage(err: unknown): string {
253
- if (!err) return '';
254
- if (typeof err === 'string') return err;
255
- if (err instanceof Error) return err.message;
256
- if (typeof err === 'object' && err !== null && 'message' in err) {
257
- const m = (err as { message?: unknown }).message;
258
- return typeof m === 'string' ? m : '';
259
- }
260
- return '';
261
- }
262
-
263
- // ---------------------------------------------------------------------------
264
- // Tool classification (aligned with DashClaw hooks vocabulary so policies
265
- // written for the Claude Code hooks also fire for OpenClaw tool calls)
266
- // ---------------------------------------------------------------------------
267
-
268
- interface ActionClassification {
269
- actionType: string;
270
- riskScore: number;
271
- reversible: boolean;
272
- systemsTouched: string[];
273
- declaredGoal: string;
274
- }
275
-
276
- const READONLY_COMMANDS = new Set([
277
- 'cat', 'head', 'tail', 'less', 'more', 'wc', 'file', 'stat', 'du', 'df',
278
- 'ls', 'tree', 'find', 'locate', 'which', 'whereis', 'type',
279
- 'grep', 'rg', 'awk', 'cut', 'sort', 'uniq', 'diff', 'comm',
280
- 'echo', 'printf', 'date', 'uname', 'whoami', 'pwd', 'hostname',
281
- 'ps', 'top', 'htop', 'free', 'uptime', 'env', 'printenv',
282
- ]);
283
-
284
- const GIT_READONLY = new Set([
285
- 'status', 'log', 'diff', 'show', 'branch', 'tag', 'remote',
286
- 'stash', 'describe', 'rev-parse', 'blame', 'ls-files',
287
- ]);
288
-
289
- const DESTRUCTIVE_COMMANDS = new Set([
290
- 'rm', 'rmdir', 'shred', 'mkfs', 'dd', 'truncate',
291
- ]);
292
-
293
- const NETWORK_COMMANDS = new Set([
294
- 'curl', 'wget', 'ssh', 'scp', 'rsync', 'ping',
295
- ]);
296
-
297
- const PACKAGE_COMMANDS = new Set([
298
- 'npm', 'yarn', 'pnpm', 'pip', 'pip3', 'cargo', 'go', 'gem',
299
- 'brew', 'apt', 'apt-get', 'dnf',
300
- ]);
301
-
302
- const DEPLOY_PATTERN = /(?:git\s+push|deploy|vercel|kubectl|terraform|docker\s+push|helm)/i;
303
- const DESTRUCTIVE_PATTERN = /(?:rm\s+-rf|DROP\s+TABLE|DELETE\s+FROM|TRUNCATE)/i;
304
- const SENSITIVE_PATH_PATTERN = /(?:\.env|secret|credential|private_key|\.pem|id_rsa|\.key)/i;
305
-
306
- function classifyBash(
307
- command: string | undefined,
308
- defaultRisk: number,
309
- ): ActionClassification {
310
- if (!command) {
311
- return { actionType: 'other', riskScore: defaultRisk, reversible: true, systemsTouched: [], declaredGoal: 'Bash: (empty)' };
312
- }
313
- const goal = `Bash: ${command.slice(0, 120)}`;
314
-
315
- if (DESTRUCTIVE_PATTERN.test(command)) {
316
- return { actionType: 'security', riskScore: 90, reversible: false, systemsTouched: ['filesystem'], declaredGoal: goal };
317
- }
318
- if (DEPLOY_PATTERN.test(command)) {
319
- return { actionType: 'deploy', riskScore: 80, reversible: false, systemsTouched: ['production'], declaredGoal: goal };
320
- }
321
-
322
- const firstToken = command.trim().split(/[\s|;&]/)[0].replace(/^.*[/\\]/, '');
323
-
324
- if (firstToken === 'git') {
325
- const sub = command.match(/git\s+(\S+)/)?.[1] ?? '';
326
- if (GIT_READONLY.has(sub)) {
327
- return { actionType: 'review', riskScore: 10, reversible: true, systemsTouched: [], declaredGoal: goal };
328
- }
329
- if (sub === 'push') {
330
- return { actionType: 'deploy', riskScore: 75, reversible: false, systemsTouched: [], declaredGoal: goal };
331
- }
332
- return { actionType: 'apply', riskScore: 30, reversible: true, systemsTouched: [], declaredGoal: goal };
333
- }
334
- if (READONLY_COMMANDS.has(firstToken)) {
335
- return { actionType: 'review', riskScore: 10, reversible: true, systemsTouched: [], declaredGoal: goal };
336
- }
337
- if (DESTRUCTIVE_COMMANDS.has(firstToken)) {
338
- return { actionType: 'security', riskScore: 85, reversible: false, systemsTouched: ['filesystem'], declaredGoal: goal };
339
- }
340
- if (NETWORK_COMMANDS.has(firstToken)) {
341
- return { actionType: 'api', riskScore: 40, reversible: true, systemsTouched: [], declaredGoal: goal };
342
- }
343
- if (PACKAGE_COMMANDS.has(firstToken)) {
344
- return { actionType: 'build', riskScore: 30, reversible: true, systemsTouched: [], declaredGoal: goal };
345
- }
346
- return { actionType: 'other', riskScore: defaultRisk, reversible: true, systemsTouched: ['shell'], declaredGoal: goal };
347
- }
348
-
349
- function classifyFile(
350
- toolName: string,
351
- params: Record<string, unknown> | undefined,
352
- defaultRisk: number,
353
- ): ActionClassification {
354
- const filePath = String(params?.file_path ?? params?.path ?? '');
355
- const goal = `${toolName}: ${filePath || '(unknown)'}`;
356
- if (SENSITIVE_PATH_PATTERN.test(filePath)) {
357
- return { actionType: 'security', riskScore: 85, reversible: true, systemsTouched: ['filesystem'], declaredGoal: goal };
358
- }
359
- return { actionType: 'apply', riskScore: defaultRisk, reversible: true, systemsTouched: ['filesystem'], declaredGoal: goal };
360
- }
361
-
362
- function classifyToolCall(
363
- toolName: string,
364
- params: Record<string, unknown> | undefined,
365
- config: PluginConfig,
366
- ): ActionClassification {
367
- const defaultRisk = config.highRiskTools.has(toolName) ? 85 : config.riskScoreDefault;
368
-
369
- if (toolName === 'bash' || toolName === 'exec') {
370
- return classifyBash(params?.command as string | undefined, defaultRisk);
371
- }
372
- if (toolName === 'write' || toolName === 'edit' || toolName === 'apply_patch') {
373
- return classifyFile(toolName, params, defaultRisk);
374
- }
375
- if (['read', 'web_search', 'web_fetch', 'memory_search', 'memory_get', 'image'].includes(toolName)) {
376
- const target = String(params?.file_path ?? params?.path ?? params?.query ?? '');
377
- return {
378
- actionType: 'review',
379
- riskScore: Math.min(defaultRisk, 15),
380
- reversible: true,
381
- systemsTouched: [],
382
- declaredGoal: `${toolName}: ${target.slice(0, 120) || '(unknown)'}`,
383
- };
384
- }
385
- if (toolName === 'sessions_send') {
386
- return {
387
- actionType: 'message',
388
- riskScore: defaultRisk,
389
- reversible: false,
390
- systemsTouched: [],
391
- declaredGoal: `message: ${summarizeParams(params).slice(0, 120)}`,
392
- };
393
- }
394
- return {
395
- actionType: 'other',
396
- riskScore: defaultRisk,
397
- reversible: true,
398
- systemsTouched: [],
399
- declaredGoal: `${toolName}: ${summarizeParams(params).slice(0, 120)}`,
400
- };
401
- }
402
-
403
- function isApproved(action: ActionRecord | undefined): boolean {
404
- if (!action) return false;
405
- if (action.approved_by) return true;
406
- return action.status === 'running' || action.status === 'completed';
407
- }
408
-
409
- // ---------------------------------------------------------------------------
410
- // Plugin entry
411
- // ---------------------------------------------------------------------------
412
-
413
- export default definePluginEntry({
414
- id: 'dashclaw-governance',
415
- name: 'DashClaw Governance',
416
- description:
417
- 'Policy enforcement, human-in-the-loop approval, and decision recording for every OpenClaw tool call. Powered by DashClaw.',
418
-
419
- register(api: OpenClawPluginApi): void {
420
- const config = resolveConfig(api.pluginConfig);
421
-
422
- // -----------------------------------------------------------------------
423
- // Governance gate
424
- // -----------------------------------------------------------------------
425
- api.on('before_tool_call', async (event, _ctx) => {
426
- const { toolName, params, toolCallId, runId } = event;
427
- const key = callKey(toolName, toolCallId, runId);
428
-
429
- // Classify the tool call using the same vocabulary as DashClaw hooks
430
- // so policies written for Claude Code also fire for OpenClaw calls.
431
- const classification = classifyToolCall(toolName, params, config);
432
- const { actionType, riskScore, reversible, systemsTouched, declaredGoal } = classification;
433
-
434
- let client: DashClaw;
435
- try {
436
- client = getClient(config);
437
- } catch (err) {
438
- const msg = errorMessage(err) || 'unknown error';
439
- if (config.failClosed) {
440
- return { block: true, blockReason: `DashClaw config error: ${msg}` };
441
- }
442
- console.warn(`[dashclaw-governance] config error (fail-open): ${msg}`);
443
- return;
444
- }
445
-
446
- let decision: GuardDecision;
447
- try {
448
- decision = await client.guard({
449
- action_type: actionType,
450
- risk_score: riskScore,
451
- declared_goal: declaredGoal,
452
- reversible,
453
- systems_touched: systemsTouched,
454
- });
455
- } catch (err) {
456
- const msg = errorMessage(err) || 'unknown error';
457
- if (config.failClosed) {
458
- return {
459
- block: true,
460
- blockReason: `DashClaw unreachable — fail-closed policy (${msg})`,
461
- };
462
- }
463
- console.warn(`[dashclaw-governance] guard call failed (fail-open): ${msg}`);
464
- return;
465
- }
466
-
467
- // Hard stop on block — never open an action record for a forbidden call.
468
- if (decision.decision === 'block') {
469
- return {
470
- block: true,
471
- blockReason: decision.reason || 'Blocked by DashClaw policy',
472
- };
473
- }
474
-
475
- if (decision.decision === 'warn') {
476
- console.warn(
477
- `[dashclaw-governance] WARN ${toolName}: ${decision.reason || 'flagged by policy'}`
478
- );
479
- }
480
-
481
- // Open a governance record. The server re-evaluates policy at this
482
- // point and is the authoritative source for HITL gating — even when
483
- // guard returned `allow`, the server may still set `pending_approval`
484
- // (for example, if the capability has `requires_approval=true`).
485
- //
486
- // NOTE: we MUST call `createAction` before `waitForApproval`, because
487
- // `waitForApproval` polls `GET /api/actions/:id` — which is backed by
488
- // the `action_records` table. `decision.action_id` from `guard()` is a
489
- // row in the separate `guard_decisions` table (prefix `act_gd_`) and
490
- // cannot be resolved by that endpoint.
491
- let createdActionId: string | undefined;
492
- let createdStatus: string | undefined;
493
- try {
494
- const created = await client.createAction({
495
- action_type: actionType,
496
- declared_goal: declaredGoal,
497
- risk_score: riskScore,
498
- reversible,
499
- systems_touched: systemsTouched,
500
- metadata: { openclaw_tool_name: toolName },
501
- });
502
- createdActionId =
503
- created.action_id ?? created.action?.action_id ?? created.action?.id;
504
- createdStatus = created.action?.status;
505
- } catch (err) {
506
- const msg = errorMessage(err) || 'unknown';
507
- console.warn(`[dashclaw-governance] createAction failed: ${msg}`);
508
- if (config.failClosed) {
509
- return {
510
- block: true,
511
- blockReason: `DashClaw action record could not be opened — fail-closed policy (${msg})`,
512
- };
513
- }
514
- // Fail-open: proceed without an action record. We cannot wait for
515
- // approval (no ID to wait on) and outcome recording will be skipped.
516
- return;
517
- }
518
-
519
- // If the server flagged this for human review, wait on the action
520
- // record we just created. Either guard said `require_approval` OR the
521
- // server upgraded the action to `pending_approval` independently — we
522
- // trust the server's `action.status` over the guard advice.
523
- const needsApproval =
524
- decision.decision === 'require_approval' ||
525
- createdStatus === 'pending_approval';
526
-
527
- if (needsApproval && createdActionId) {
528
- try {
529
- const { action } = await client.waitForApproval(createdActionId);
530
- if (!isApproved(action)) {
531
- return {
532
- block: true,
533
- blockReason: action?.error_message || 'Action denied by operator',
534
- };
535
- }
536
- } catch (err) {
537
- return {
538
- block: true,
539
- blockReason: `Approval denied or wait failed: ${errorMessage(err) || 'denied'}`,
540
- };
541
- }
542
- }
543
-
544
- if (createdActionId) {
545
- pendingActions.set(key, createdActionId);
546
- // Track this action_id against the current run so the next
547
- // `llm_output` can attribute token usage back to it.
548
- if (runId) getTokenTurn(runId).turnActionIds.push(createdActionId);
549
- }
550
- return;
551
- });
552
-
553
- // -----------------------------------------------------------------------
554
- // LLM token attribution — distribute the previous turn's usage across
555
- // the tool calls it induced, then stash this turn's usage for the next
556
- // boundary. Runs best-effort; failures never surface to the agent.
557
- // -----------------------------------------------------------------------
558
- api.on('llm_output', async (event, _ctx) => {
559
- const { runId, model, usage } = event;
560
- if (!runId) return;
561
-
562
- let client: DashClaw;
563
- try {
564
- client = getClient(config);
565
- } catch (err) {
566
- // No client → skip attribution, don't disrupt the run. Log once per
567
- // failure class so ops notice when token tracking is off (key
568
- // rotation, base-URL typo) instead of silently losing every turn.
569
- console.warn(
570
- `[dashclaw-governance] llm_output dropped — client unavailable: ${errorMessage(err) || 'unknown'}`
571
- );
572
- return;
573
- }
574
-
575
- const state = getTokenTurn(runId);
576
-
577
- // Distribute the PREVIOUS turn's usage before stashing the new one.
578
- if (state.pendingUsage) {
579
- await distributePendingTokens(client, state);
580
- }
581
-
582
- // Stash this turn's usage for attribution on the next llm_output
583
- // (or agent_end). Cache reads are billed at ~10% of base input price, so
584
- // we weight them at 0.1 before summing — the server's pricing table
585
- // doesn't model the cache discount, so applying it here keeps the
586
- // derived cost aligned with real billing. Cache writes stay at full
587
- // price (close enough for 5m caching; slightly under-counts 1h).
588
- if (usage) {
589
- const cacheReadEffective = Math.round((usage.cacheRead ?? 0) * 0.1);
590
- const tokens_in =
591
- (usage.input ?? 0) + (usage.cacheWrite ?? 0) + cacheReadEffective;
592
- const tokens_out = usage.output ?? 0;
593
- if (tokens_in > 0 || tokens_out > 0) {
594
- // Model resolution: real event value > configured default > empty.
595
- // When both are empty, still stash the tokens so ops see activity,
596
- // but log a one-time breadcrumb per run — otherwise the "tokens
597
- // arrive but cost stays $0" failure mode is invisible.
598
- const resolvedModel = (model && model.length > 0)
599
- ? model
600
- : config.defaultModel;
601
- if (!resolvedModel && !state.warnedMissingModel) {
602
- console.warn(
603
- `[dashclaw-governance] llm_output has no model for run ${runId} — ` +
604
- `tokens will land on action records but cost_estimate will stay $0. ` +
605
- `Set config.defaultModel or DASHCLAW_DEFAULT_MODEL to price these turns.`
606
- );
607
- state.warnedMissingModel = true;
608
- }
609
- state.pendingUsage = { tokens_in, tokens_out, model: resolvedModel };
610
- }
611
- }
612
- });
613
-
614
- // -----------------------------------------------------------------------
615
- // Run end — flush any remaining usage, then drop per-run state.
616
- // -----------------------------------------------------------------------
617
- api.on('agent_end', async (_event, ctx) => {
618
- const runId = ctx?.runId;
619
- if (!runId) return;
620
- const state = tokenTurnByRun.get(runId);
621
- if (!state) return;
622
-
623
- if (state.pendingUsage && state.turnActionIds.length > 0) {
624
- try {
625
- const client = getClient(config);
626
- await distributePendingTokens(client, state);
627
- } catch (err) {
628
- // No client → drop state but log the lost attribution so ops can
629
- // see how many actions went unattributed.
630
- console.warn(
631
- `[dashclaw-governance] agent_end token flush dropped ${state.turnActionIds.length} action(s): ${errorMessage(err) || 'unknown'}`
632
- );
633
- }
634
- }
635
- tokenTurnByRun.delete(runId);
636
- });
637
-
638
- // -----------------------------------------------------------------------
639
- // Outcome recorder
640
- // -----------------------------------------------------------------------
641
- api.on('after_tool_call', async (event, _ctx) => {
642
- const { toolName, toolCallId, runId, error } = event;
643
- const key = callKey(toolName, toolCallId, runId);
644
- const actionId = pendingActions.get(key);
645
- if (!actionId) return;
646
- pendingActions.delete(key);
647
-
648
- const status = error ? 'failed' : 'completed';
649
-
650
- let client: DashClaw;
651
- try {
652
- client = getClient(config);
653
- } catch {
654
- return; // No client → cannot record; never break tool execution.
655
- }
656
-
657
- try {
658
- await client.updateOutcome(actionId, {
659
- status,
660
- ...(error ? { error_message: error } : {}),
661
- });
662
- } catch (err) {
663
- console.warn(
664
- `[dashclaw-governance] updateOutcome failed: ${errorMessage(err) || 'unknown'}`
665
- );
666
- }
667
- });
668
- },
669
- });
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
+ // Fallback model id used when `llm_output` events fire without a `model`
42
+ // field. Without this, the server's `estimateCost` treats the usage as
43
+ // unpriceable and stores `cost_estimate = 0` — producing the "tokens
44
+ // but no cost" failure mode. Empty string disables the fallback.
45
+ defaultModel: string;
46
+ failClosed: boolean;
47
+ riskScoreDefault: number;
48
+ highRiskTools: ReadonlySet<string>;
49
+ }
50
+
51
+ /**
52
+ * Resolve the DashClaw URL from (in order of precedence):
53
+ * 1. `config.dashclawUrl` (canonical plugin-config key)
54
+ * 2. `config.baseUrl` (SDK-style alias)
55
+ * 3. `process.env.DASHCLAW_BASE_URL` (canonical env var — matches CLI, local scripts)
56
+ * 4. `process.env.DASHCLAW_URL` (legacy env var — matches MCP server docs)
57
+ *
58
+ * The same precedence applies to the API key (with DASHCLAW_API_KEY as the only env var).
59
+ */
60
+ function firstString(...candidates: unknown[]): string {
61
+ for (const c of candidates) {
62
+ if (typeof c === 'string' && c.length > 0) return c;
63
+ }
64
+ return '';
65
+ }
66
+
67
+ function stringSetFromConfig(value: unknown): ReadonlySet<string> {
68
+ return new Set<string>(
69
+ Array.isArray(value)
70
+ ? value.filter((v): v is string => typeof v === 'string')
71
+ : []
72
+ );
73
+ }
74
+
75
+ function numberFromConfig(
76
+ value: unknown,
77
+ fallback: number,
78
+ allowNegative = true,
79
+ ): number {
80
+ if (typeof value !== 'number') return fallback;
81
+ if (!Number.isFinite(value)) return fallback;
82
+ if (!allowNegative && value < 0) return fallback;
83
+ return value;
84
+ }
85
+
86
+ function resolveConfig(raw: Record<string, unknown> | undefined): PluginConfig {
87
+ const cfg = raw ?? {};
88
+ const env = typeof process !== 'undefined' && process?.env ? process.env : {};
89
+
90
+ const failClosed = cfg.failClosed !== false; // default true
91
+ const riskScoreDefault = numberFromConfig(cfg.riskScoreDefault, 50);
92
+ const highRiskTools = stringSetFromConfig(cfg.highRiskTools);
93
+
94
+ const dashclawUrl = firstString(
95
+ cfg.dashclawUrl,
96
+ cfg.baseUrl,
97
+ env.DASHCLAW_BASE_URL,
98
+ env.DASHCLAW_URL
99
+ );
100
+ const dashclawApiKey = firstString(
101
+ cfg.dashclawApiKey,
102
+ cfg.apiKey,
103
+ env.DASHCLAW_API_KEY
104
+ );
105
+ const agentId = firstString(cfg.agentId, env.DASHCLAW_AGENT_ID) || 'openclaw';
106
+ const defaultModel = firstString(
107
+ cfg.defaultModel,
108
+ env.DASHCLAW_DEFAULT_MODEL
109
+ );
110
+
111
+ return {
112
+ dashclawUrl,
113
+ dashclawApiKey,
114
+ agentId,
115
+ defaultModel,
116
+ failClosed,
117
+ riskScoreDefault,
118
+ highRiskTools,
119
+ };
120
+ }
121
+
122
+ // ---------------------------------------------------------------------------
123
+ // Module state
124
+ // ---------------------------------------------------------------------------
125
+
126
+ let cachedClient: DashClaw | null = null;
127
+ let cachedClientKey = '';
128
+
129
+ /** Maps synthetic call key → DashClaw action_id so `after_tool_call` can close it. */
130
+ const pendingActions = new Map<string, string>();
131
+
132
+ /**
133
+ * Per-run state for LLM token attribution. OpenClaw's `llm_output` event
134
+ * fires once per assistant response with `usage.{input,output,cacheRead,
135
+ * cacheWrite}` and `model`. The tool calls induced by that response arrive
136
+ * via `before_tool_call` after the `llm_output`. We stash the most recent
137
+ * usage and the action_ids opened since we stashed it; on the NEXT
138
+ * `llm_output` (or on `agent_end`) we distribute that usage evenly across
139
+ * those action_ids via `updateOutcome` PATCHes. Cost is derived server-side.
140
+ */
141
+ interface TokenTurnState {
142
+ pendingUsage?: { tokens_in: number; tokens_out: number; model: string };
143
+ turnActionIds: string[];
144
+ // Set after the first llm_output on this run that fires without a model
145
+ // field. Used to suppress repeat warnings within the same run — ops see
146
+ // one log line per run, not one per turn.
147
+ warnedMissingModel?: boolean;
148
+ // DashClaw Agent Session opened on the first tool call of this run, so the
149
+ // run shows up under the Agent Sessions feature (not just Code Sessions).
150
+ // Closed (status='completed') and cleared on agent_end. `sessionStarted`
151
+ // guards the lazy create so we POST /api/sessions exactly once per run.
152
+ sessionId?: string;
153
+ sessionStarted?: boolean;
154
+ }
155
+ const tokenTurnByRun = new Map<string, TokenTurnState>();
156
+
157
+ // Cap for in-memory per-run state. `agent_end` deletes entries, but a crash
158
+ // or an agent framework that never fires `agent_end` in a long-lived gateway
159
+ // process would leak. At ~100 bytes/entry this cap bounds worst-case memory
160
+ // to ~100KB while still comfortably above typical concurrency.
161
+ const MAX_TURN_RUNS = 1000;
162
+
163
+ function getTokenTurn(runId: string): TokenTurnState {
164
+ let state = tokenTurnByRun.get(runId);
165
+ if (!state) {
166
+ if (tokenTurnByRun.size >= MAX_TURN_RUNS) {
167
+ // Evict oldest (Map preserves insertion order). One at a time is enough
168
+ // to stay at the cap under steady state — we only grow by one here.
169
+ const oldest = tokenTurnByRun.keys().next().value;
170
+ if (oldest !== undefined) tokenTurnByRun.delete(oldest);
171
+ }
172
+ state = { turnActionIds: [] };
173
+ tokenTurnByRun.set(runId, state);
174
+ }
175
+ return state;
176
+ }
177
+
178
+ /** Split a non-negative integer `total` into `n` buckets, putting remainders
179
+ * in the earliest buckets so the sum is preserved exactly. */
180
+ function distributeEvenly(total: number, n: number): number[] {
181
+ if (n <= 0 || total <= 0) return new Array<number>(Math.max(n, 0)).fill(0);
182
+ const base = Math.floor(total / n);
183
+ const remainder = total - base * n;
184
+ return Array.from({ length: n }, (_, i) => base + (i < remainder ? 1 : 0));
185
+ }
186
+
187
+ async function distributePendingTokens(
188
+ client: DashClaw,
189
+ state: TokenTurnState,
190
+ ): Promise<void> {
191
+ const usage = state.pendingUsage;
192
+ const ids = state.turnActionIds;
193
+ state.pendingUsage = undefined;
194
+ state.turnActionIds = [];
195
+
196
+ if (!usage || ids.length === 0) return;
197
+ if (usage.tokens_in === 0 && usage.tokens_out === 0) return;
198
+
199
+ const inParts = distributeEvenly(usage.tokens_in, ids.length);
200
+ const outParts = distributeEvenly(usage.tokens_out, ids.length);
201
+
202
+ await Promise.all(
203
+ ids.map((actionId, idx) =>
204
+ client
205
+ .updateOutcome(actionId, {
206
+ tokens_in: inParts[idx],
207
+ tokens_out: outParts[idx],
208
+ ...(usage.model ? { model: usage.model } : {}),
209
+ })
210
+ .catch((err: unknown) => {
211
+ console.warn(
212
+ `[dashclaw-governance] token PATCH failed for ${actionId}: ${errorMessage(err) || 'unknown'}`
213
+ );
214
+ })
215
+ )
216
+ );
217
+ }
218
+
219
+ function getClient(config: PluginConfig): DashClaw {
220
+ const key = `${config.dashclawUrl}|${config.dashclawApiKey}|${config.agentId}`;
221
+ if (cachedClient && cachedClientKey === key) return cachedClient;
222
+
223
+ if (!config.dashclawUrl || !config.dashclawApiKey) {
224
+ const missing: string[] = [];
225
+ if (!config.dashclawUrl) missing.push('dashclawUrl');
226
+ if (!config.dashclawApiKey) missing.push('dashclawApiKey');
227
+ throw new Error(
228
+ `dashclaw-governance plugin: missing ${missing.join(' and ')}. ` +
229
+ 'Provide via openclaw.plugin.json config (dashclawUrl/dashclawApiKey or baseUrl/apiKey), ' +
230
+ 'or set env vars DASHCLAW_BASE_URL and DASHCLAW_API_KEY before starting the gateway.'
231
+ );
232
+ }
233
+
234
+ cachedClient = new DashClaw({
235
+ baseUrl: config.dashclawUrl,
236
+ apiKey: config.dashclawApiKey,
237
+ agentId: config.agentId,
238
+ });
239
+ cachedClientKey = key;
240
+ return cachedClient;
241
+ }
242
+
243
+ // ---------------------------------------------------------------------------
244
+ // Helpers
245
+ // ---------------------------------------------------------------------------
246
+
247
+ function summarizeParams(params: Record<string, unknown> | undefined): string {
248
+ if (!params) return '';
249
+ let serialized: string;
250
+ try {
251
+ serialized = JSON.stringify(params);
252
+ } catch {
253
+ return '[unserializable params]';
254
+ }
255
+ if (serialized.length <= 500) return serialized;
256
+ return serialized.slice(0, 500) + '…[truncated]';
257
+ }
258
+
259
+ function callKey(
260
+ toolName: string,
261
+ toolCallId: string | undefined,
262
+ runId: string | undefined
263
+ ): string {
264
+ // Prefer the provider-supplied tool call ID; fall back to runId-scoped tool
265
+ // name so a later `after_tool_call` without a toolCallId can still find the
266
+ // pending record.
267
+ if (toolCallId) return `id:${toolCallId}`;
268
+ if (runId) return `run:${runId}:${toolName}`;
269
+ return `tool:${toolName}`;
270
+ }
271
+
272
+ function errorMessage(err: unknown): string {
273
+ if (!err) return '';
274
+ if (typeof err === 'string') return err;
275
+ if (err instanceof Error) return err.message;
276
+ if (typeof err === 'object' && err !== null && 'message' in err) {
277
+ const m = (err as { message?: unknown }).message;
278
+ return typeof m === 'string' ? m : '';
279
+ }
280
+ return '';
281
+ }
282
+
283
+ // ---------------------------------------------------------------------------
284
+ // Tool classification (aligned with DashClaw hooks vocabulary so policies
285
+ // written for the Claude Code hooks also fire for OpenClaw tool calls)
286
+ // ---------------------------------------------------------------------------
287
+
288
+ interface ActionClassification {
289
+ actionType: string;
290
+ riskScore: number;
291
+ reversible: boolean;
292
+ systemsTouched: string[];
293
+ declaredGoal: string;
294
+ }
295
+
296
+ const READONLY_COMMANDS = new Set([
297
+ 'cat', 'head', 'tail', 'less', 'more', 'wc', 'file', 'stat', 'du', 'df',
298
+ 'ls', 'tree', 'find', 'locate', 'which', 'whereis', 'type',
299
+ 'grep', 'rg', 'awk', 'cut', 'sort', 'uniq', 'diff', 'comm',
300
+ 'echo', 'printf', 'date', 'uname', 'whoami', 'pwd', 'hostname',
301
+ 'ps', 'top', 'htop', 'free', 'uptime', 'env', 'printenv',
302
+ ]);
303
+
304
+ const GIT_READONLY = new Set([
305
+ 'status', 'log', 'diff', 'show', 'branch', 'tag', 'remote',
306
+ 'stash', 'describe', 'rev-parse', 'blame', 'ls-files',
307
+ ]);
308
+
309
+ const DESTRUCTIVE_COMMANDS = new Set([
310
+ 'rm', 'rmdir', 'shred', 'mkfs', 'dd', 'truncate',
311
+ ]);
312
+
313
+ const NETWORK_COMMANDS = new Set([
314
+ 'curl', 'wget', 'ssh', 'scp', 'rsync', 'ping',
315
+ ]);
316
+
317
+ const PACKAGE_COMMANDS = new Set([
318
+ 'npm', 'yarn', 'pnpm', 'pip', 'pip3', 'cargo', 'go', 'gem',
319
+ 'brew', 'apt', 'apt-get', 'dnf',
320
+ ]);
321
+
322
+ const DEPLOY_PATTERN = /(?:git\s+push|deploy|vercel|kubectl|terraform|docker\s+push|helm)/i;
323
+ const DESTRUCTIVE_PATTERN = /(?:rm\s+-rf|DROP\s+TABLE|DELETE\s+FROM|TRUNCATE)/i;
324
+ const SENSITIVE_PATH_PATTERN = /(?:\.env|secret|credential|private_key|\.pem|id_rsa|\.key)/i;
325
+
326
+ function classifyBash(
327
+ command: string | undefined,
328
+ defaultRisk: number,
329
+ ): ActionClassification {
330
+ if (!command) {
331
+ return { actionType: 'other', riskScore: defaultRisk, reversible: true, systemsTouched: [], declaredGoal: 'Bash: (empty)' };
332
+ }
333
+ const goal = `Bash: ${command.slice(0, 120)}`;
334
+
335
+ const patternClassification = classifyBashPattern(command, goal);
336
+ if (patternClassification) return patternClassification;
337
+
338
+ const firstToken = command.trim().split(/[\s|;&]/)[0].replace(/^.*[/\\]/, '');
339
+ return classifyCommandToken(firstToken, command, goal, defaultRisk);
340
+ }
341
+
342
+ function classifyBashPattern(
343
+ command: string,
344
+ goal: string,
345
+ ): ActionClassification | null {
346
+ if (DESTRUCTIVE_PATTERN.test(command)) {
347
+ return { actionType: 'security', riskScore: 90, reversible: false, systemsTouched: ['filesystem'], declaredGoal: goal };
348
+ }
349
+ if (DEPLOY_PATTERN.test(command)) {
350
+ return { actionType: 'deploy', riskScore: 80, reversible: false, systemsTouched: ['production'], declaredGoal: goal };
351
+ }
352
+ return null;
353
+ }
354
+
355
+ function classifyGitCommand(
356
+ command: string,
357
+ goal: string,
358
+ ): ActionClassification {
359
+ const sub = command.match(/git\s+(\S+)/)?.[1] ?? '';
360
+ if (GIT_READONLY.has(sub)) {
361
+ return { actionType: 'review', riskScore: 10, reversible: true, systemsTouched: [], declaredGoal: goal };
362
+ }
363
+ if (sub === 'push') {
364
+ return { actionType: 'deploy', riskScore: 75, reversible: false, systemsTouched: [], declaredGoal: goal };
365
+ }
366
+ return { actionType: 'apply', riskScore: 30, reversible: true, systemsTouched: [], declaredGoal: goal };
367
+ }
368
+
369
+ function classifyCommandToken(
370
+ firstToken: string,
371
+ command: string,
372
+ goal: string,
373
+ defaultRisk: number,
374
+ ): ActionClassification {
375
+ if (firstToken === 'git') {
376
+ return classifyGitCommand(command, goal);
377
+ }
378
+ if (READONLY_COMMANDS.has(firstToken)) {
379
+ return { actionType: 'review', riskScore: 10, reversible: true, systemsTouched: [], declaredGoal: goal };
380
+ }
381
+ if (DESTRUCTIVE_COMMANDS.has(firstToken)) {
382
+ return { actionType: 'security', riskScore: 85, reversible: false, systemsTouched: ['filesystem'], declaredGoal: goal };
383
+ }
384
+ if (NETWORK_COMMANDS.has(firstToken)) {
385
+ return { actionType: 'api', riskScore: 40, reversible: true, systemsTouched: [], declaredGoal: goal };
386
+ }
387
+ if (PACKAGE_COMMANDS.has(firstToken)) {
388
+ return { actionType: 'build', riskScore: 30, reversible: true, systemsTouched: [], declaredGoal: goal };
389
+ }
390
+ return { actionType: 'other', riskScore: defaultRisk, reversible: true, systemsTouched: ['shell'], declaredGoal: goal };
391
+ }
392
+
393
+ function classifyFile(
394
+ toolName: string,
395
+ params: Record<string, unknown> | undefined,
396
+ defaultRisk: number,
397
+ ): ActionClassification {
398
+ const filePath = String(params?.file_path ?? params?.path ?? '');
399
+ const goal = `${toolName}: ${filePath || '(unknown)'}`;
400
+ if (SENSITIVE_PATH_PATTERN.test(filePath)) {
401
+ return { actionType: 'security', riskScore: 85, reversible: true, systemsTouched: ['filesystem'], declaredGoal: goal };
402
+ }
403
+ return { actionType: 'apply', riskScore: defaultRisk, reversible: true, systemsTouched: ['filesystem'], declaredGoal: goal };
404
+ }
405
+
406
+ function classifyToolCall(
407
+ toolName: string,
408
+ params: Record<string, unknown> | undefined,
409
+ config: PluginConfig,
410
+ ): ActionClassification {
411
+ const defaultRisk = config.highRiskTools.has(toolName) ? 85 : config.riskScoreDefault;
412
+ const classified = TOOL_CLASSIFIERS
413
+ .map((classify) => classify(toolName, params, defaultRisk))
414
+ .find((result): result is ActionClassification => result !== null);
415
+ return classified ?? classifyDefaultTool(toolName, params, defaultRisk);
416
+ }
417
+
418
+ type ToolClassifier = (
419
+ toolName: string,
420
+ params: Record<string, unknown> | undefined,
421
+ defaultRisk: number,
422
+ ) => ActionClassification | null;
423
+
424
+ const WRITE_TOOLS = new Set(['write', 'edit', 'apply_patch']);
425
+ const REVIEW_TOOLS = new Set([
426
+ 'read',
427
+ 'web_search',
428
+ 'web_fetch',
429
+ 'memory_search',
430
+ 'memory_get',
431
+ 'image',
432
+ ]);
433
+
434
+ const TOOL_CLASSIFIERS: ToolClassifier[] = [
435
+ classifyShellTool,
436
+ classifyWriteTool,
437
+ classifyReviewTool,
438
+ classifyMessageTool,
439
+ ];
440
+
441
+ function classifyShellTool(
442
+ toolName: string,
443
+ params: Record<string, unknown> | undefined,
444
+ defaultRisk: number,
445
+ ): ActionClassification | null {
446
+ return toolName === 'bash' || toolName === 'exec'
447
+ ? classifyBash(params?.command as string | undefined, defaultRisk)
448
+ : null;
449
+ }
450
+
451
+ function classifyWriteTool(
452
+ toolName: string,
453
+ params: Record<string, unknown> | undefined,
454
+ defaultRisk: number,
455
+ ): ActionClassification | null {
456
+ return WRITE_TOOLS.has(toolName) ? classifyFile(toolName, params, defaultRisk) : null;
457
+ }
458
+
459
+ function classifyReviewTool(
460
+ toolName: string,
461
+ params: Record<string, unknown> | undefined,
462
+ defaultRisk: number,
463
+ ): ActionClassification | null {
464
+ if (!REVIEW_TOOLS.has(toolName)) return null;
465
+ const target = String(params?.file_path ?? params?.path ?? params?.query ?? '');
466
+ return {
467
+ actionType: 'review',
468
+ riskScore: Math.min(defaultRisk, 15),
469
+ reversible: true,
470
+ systemsTouched: [],
471
+ declaredGoal: `${toolName}: ${target.slice(0, 120) || '(unknown)'}`,
472
+ };
473
+ }
474
+
475
+ function classifyMessageTool(
476
+ toolName: string,
477
+ params: Record<string, unknown> | undefined,
478
+ defaultRisk: number,
479
+ ): ActionClassification | null {
480
+ if (toolName !== 'sessions_send') return null;
481
+ return {
482
+ actionType: 'message',
483
+ riskScore: defaultRisk,
484
+ reversible: false,
485
+ systemsTouched: [],
486
+ declaredGoal: `message: ${summarizeParams(params).slice(0, 120)}`,
487
+ };
488
+ }
489
+
490
+ function classifyDefaultTool(
491
+ toolName: string,
492
+ params: Record<string, unknown> | undefined,
493
+ defaultRisk: number,
494
+ ): ActionClassification {
495
+ return {
496
+ actionType: 'other',
497
+ riskScore: defaultRisk,
498
+ reversible: true,
499
+ systemsTouched: [],
500
+ declaredGoal: `${toolName}: ${summarizeParams(params).slice(0, 120)}`,
501
+ };
502
+ }
503
+
504
+ function isApproved(action: ActionRecord | undefined): boolean {
505
+ if (!action) return false;
506
+ if (action.approved_by) return true;
507
+ return action.status === 'running' || action.status === 'completed';
508
+ }
509
+
510
+ type HookBlockResult = { block: true; blockReason: string };
511
+ type HookResult = HookBlockResult | void;
512
+
513
+ interface ToolCallEvent {
514
+ toolName: string;
515
+ params?: Record<string, unknown>;
516
+ toolCallId?: string;
517
+ runId?: string;
518
+ error?: string;
519
+ result?: unknown;
520
+ workspace?: unknown;
521
+ branch?: unknown;
522
+ }
523
+
524
+ interface LlmOutputEvent {
525
+ runId?: string;
526
+ model?: string;
527
+ usage?: {
528
+ input?: number;
529
+ output?: number;
530
+ cacheRead?: number;
531
+ cacheWrite?: number;
532
+ };
533
+ }
534
+
535
+ interface AgentEndContext {
536
+ runId?: string;
537
+ }
538
+
539
+ interface CreatedAction {
540
+ actionId?: string;
541
+ status?: string;
542
+ }
543
+
544
+ function registerGovernanceGate(api: OpenClawPluginApi, config: PluginConfig): void {
545
+ api.on('before_tool_call', async (event, _ctx) =>
546
+ handleBeforeToolCall(event as ToolCallEvent, config)
547
+ );
548
+ }
549
+
550
+ function registerTokenAttribution(api: OpenClawPluginApi, config: PluginConfig): void {
551
+ api.on('llm_output', async (event, _ctx) =>
552
+ handleLlmOutput(event as LlmOutputEvent, config)
553
+ );
554
+ }
555
+
556
+ function registerRunCleanup(api: OpenClawPluginApi, config: PluginConfig): void {
557
+ api.on('agent_end', async (_event, ctx) =>
558
+ handleAgentEnd(ctx as AgentEndContext | undefined, config)
559
+ );
560
+ }
561
+
562
+ function registerOutcomeRecorder(api: OpenClawPluginApi, config: PluginConfig): void {
563
+ api.on('after_tool_call', async (event, _ctx) =>
564
+ handleAfterToolCall(event as ToolCallEvent, config)
565
+ );
566
+ }
567
+
568
+ async function handleBeforeToolCall(
569
+ event: ToolCallEvent,
570
+ config: PluginConfig,
571
+ ): Promise<HookResult> {
572
+ const { toolName, params, toolCallId, runId } = event;
573
+ const key = callKey(toolName, toolCallId, runId);
574
+ const classification = classifyToolCall(toolName, params, config);
575
+
576
+ const client = getBeforeClient(config);
577
+ if ('result' in client) return client.result;
578
+
579
+ await maybeStartSession(event, client.value, config);
580
+
581
+ const decision = await guardClassifiedAction(client.value, classification, config);
582
+ if ('result' in decision) return decision.result;
583
+
584
+ const block = blockResultForDecision(decision.value, toolName);
585
+ if (block) return block;
586
+
587
+ return openActionRecord({
588
+ client: client.value,
589
+ classification,
590
+ decision: decision.value,
591
+ toolName,
592
+ key,
593
+ runId,
594
+ config,
595
+ });
596
+ }
597
+
598
+ function getBeforeClient(
599
+ config: PluginConfig,
600
+ ): { value: DashClaw } | { result: HookResult } {
601
+ try {
602
+ return { value: getClient(config) };
603
+ } catch (err) {
604
+ const msg = errorMessage(err) || 'unknown error';
605
+ if (config.failClosed) {
606
+ return { result: { block: true, blockReason: `DashClaw config error: ${msg}` } };
607
+ }
608
+ console.warn(`[dashclaw-governance] config error (fail-open): ${msg}`);
609
+ return { result: undefined };
610
+ }
611
+ }
612
+
613
+ async function maybeStartSession(
614
+ event: ToolCallEvent,
615
+ client: DashClaw,
616
+ config: PluginConfig,
617
+ ): Promise<void> {
618
+ if (!event.runId) return;
619
+ const runState = getTokenTurn(event.runId);
620
+ if (runState.sessionStarted) return;
621
+
622
+ runState.sessionStarted = true; // guard before await — once per run
623
+ const workspace = typeof event.workspace === 'string' ? event.workspace : undefined;
624
+ const branch = typeof event.branch === 'string' ? event.branch : null;
625
+ try {
626
+ const res = await client.createSession(config.agentId, workspace, branch);
627
+ const sessionId =
628
+ (res as { session?: { id?: string }; id?: string }).session?.id ??
629
+ (res as { id?: string }).id;
630
+ if (sessionId) runState.sessionId = sessionId;
631
+ } catch (err) {
632
+ console.warn(
633
+ `[dashclaw-governance] createSession failed: ${errorMessage(err) || 'unknown'}`
634
+ );
635
+ }
636
+ }
637
+
638
+ async function guardClassifiedAction(
639
+ client: DashClaw,
640
+ classification: ActionClassification,
641
+ config: PluginConfig,
642
+ ): Promise<{ value: GuardDecision } | { result: HookResult }> {
643
+ try {
644
+ return {
645
+ value: await client.guard({
646
+ action_type: classification.actionType,
647
+ risk_score: classification.riskScore,
648
+ declared_goal: classification.declaredGoal,
649
+ reversible: classification.reversible,
650
+ systems_touched: classification.systemsTouched,
651
+ }),
652
+ };
653
+ } catch (err) {
654
+ const msg = errorMessage(err) || 'unknown error';
655
+ if (config.failClosed) {
656
+ return {
657
+ result: {
658
+ block: true,
659
+ blockReason: `DashClaw unreachable — fail-closed policy (${msg})`,
660
+ },
661
+ };
662
+ }
663
+ console.warn(`[dashclaw-governance] guard call failed (fail-open): ${msg}`);
664
+ return { result: undefined };
665
+ }
666
+ }
667
+
668
+ function blockResultForDecision(
669
+ decision: GuardDecision,
670
+ toolName: string,
671
+ ): HookBlockResult | undefined {
672
+ if (decision.decision === 'block') {
673
+ return {
674
+ block: true,
675
+ blockReason: decision.reason || 'Blocked by DashClaw policy',
676
+ };
677
+ }
678
+ if (decision.decision === 'warn') {
679
+ console.warn(
680
+ `[dashclaw-governance] WARN ${toolName}: ${decision.reason || 'flagged by policy'}`
681
+ );
682
+ }
683
+ return undefined;
684
+ }
685
+
686
+ interface OpenActionContext {
687
+ client: DashClaw;
688
+ classification: ActionClassification;
689
+ decision: GuardDecision;
690
+ toolName: string;
691
+ key: string;
692
+ runId?: string;
693
+ config: PluginConfig;
694
+ }
695
+
696
+ async function openActionRecord(ctx: OpenActionContext): Promise<HookResult> {
697
+ const created = await createGovernanceAction(ctx);
698
+ if ('result' in created) return created.result;
699
+
700
+ const approval = await waitForRequiredApproval(ctx.client, ctx.decision, created.value);
701
+ if (approval) return approval;
702
+ rememberPendingAction(ctx.key, created.value.actionId, ctx.runId);
703
+ return;
704
+ }
705
+
706
+ async function createGovernanceAction(
707
+ ctx: OpenActionContext,
708
+ ): Promise<{ value: CreatedAction } | { result: HookResult }> {
709
+ const { actionType, declaredGoal, riskScore, reversible, systemsTouched } =
710
+ ctx.classification;
711
+ try {
712
+ const created = await ctx.client.createAction({
713
+ action_type: actionType,
714
+ declared_goal: declaredGoal,
715
+ risk_score: riskScore,
716
+ reversible,
717
+ systems_touched: systemsTouched,
718
+ metadata: { openclaw_tool_name: ctx.toolName },
719
+ });
720
+ return {
721
+ value: {
722
+ actionId: created.action_id ?? created.action?.action_id ?? created.action?.id,
723
+ status: created.action?.status,
724
+ },
725
+ };
726
+ } catch (err) {
727
+ const msg = errorMessage(err) || 'unknown';
728
+ console.warn(`[dashclaw-governance] createAction failed: ${msg}`);
729
+ if (ctx.config.failClosed) {
730
+ return {
731
+ result: {
732
+ block: true,
733
+ blockReason: `DashClaw action record could not be opened — fail-closed policy (${msg})`,
734
+ },
735
+ };
736
+ }
737
+ return { result: undefined };
738
+ }
739
+ }
740
+
741
+ async function waitForRequiredApproval(
742
+ client: DashClaw,
743
+ decision: GuardDecision,
744
+ created: CreatedAction,
745
+ ): Promise<HookBlockResult | undefined> {
746
+ const needsApproval =
747
+ decision.decision === 'require_approval' ||
748
+ created.status === 'pending_approval';
749
+ if (!needsApproval || !created.actionId) return undefined;
750
+
751
+ try {
752
+ const { action } = await client.waitForApproval(created.actionId);
753
+ if (isApproved(action)) return undefined;
754
+ return {
755
+ block: true,
756
+ blockReason: action?.error_message || 'Action denied by operator',
757
+ };
758
+ } catch (err) {
759
+ return {
760
+ block: true,
761
+ blockReason: `Approval denied or wait failed: ${errorMessage(err) || 'denied'}`,
762
+ };
763
+ }
764
+ }
765
+
766
+ function rememberPendingAction(
767
+ key: string,
768
+ actionId: string | undefined,
769
+ runId: string | undefined,
770
+ ): void {
771
+ if (!actionId) return;
772
+ pendingActions.set(key, actionId);
773
+ if (runId) getTokenTurn(runId).turnActionIds.push(actionId);
774
+ }
775
+
776
+ async function handleLlmOutput(
777
+ event: LlmOutputEvent,
778
+ config: PluginConfig,
779
+ ): Promise<void> {
780
+ const { runId, model, usage } = event;
781
+ if (!runId) return;
782
+
783
+ const client = getClientForLlmOutput(config);
784
+ if (!client) return;
785
+
786
+ const state = getTokenTurn(runId);
787
+ if (state.pendingUsage) {
788
+ await distributePendingTokens(client, state);
789
+ }
790
+
791
+ const pendingUsage = tokenUsageFromEvent({
792
+ usage,
793
+ model,
794
+ config,
795
+ state,
796
+ runId,
797
+ });
798
+ if (pendingUsage) state.pendingUsage = pendingUsage;
799
+ }
800
+
801
+ function getClientForLlmOutput(config: PluginConfig): DashClaw | undefined {
802
+ try {
803
+ return getClient(config);
804
+ } catch (err) {
805
+ console.warn(
806
+ `[dashclaw-governance] llm_output dropped — client unavailable: ${errorMessage(err) || 'unknown'}`
807
+ );
808
+ return undefined;
809
+ }
810
+ }
811
+
812
+ interface TokenUsageContext {
813
+ usage: LlmOutputEvent['usage'];
814
+ model?: string;
815
+ config: PluginConfig;
816
+ state: TokenTurnState;
817
+ runId: string;
818
+ }
819
+
820
+ function tokenUsageFromEvent(ctx: TokenUsageContext): TokenTurnState['pendingUsage'] {
821
+ const { usage, model, config, state, runId } = ctx;
822
+ if (!usage) return undefined;
823
+ const cacheReadEffective = Math.round((usage.cacheRead ?? 0) * 0.1);
824
+ const tokens_in = (usage.input ?? 0) + (usage.cacheWrite ?? 0) + cacheReadEffective;
825
+ const tokens_out = usage.output ?? 0;
826
+ if (tokens_in <= 0 && tokens_out <= 0) return undefined;
827
+
828
+ const resolvedModel = model && model.length > 0 ? model : config.defaultModel;
829
+ warnOnceForMissingModel(resolvedModel, state, runId);
830
+ return { tokens_in, tokens_out, model: resolvedModel };
831
+ }
832
+
833
+ function warnOnceForMissingModel(
834
+ model: string,
835
+ state: TokenTurnState,
836
+ runId: string,
837
+ ): void {
838
+ if (model || state.warnedMissingModel) return;
839
+ console.warn(
840
+ `[dashclaw-governance] llm_output has no model for run ${runId} — ` +
841
+ `tokens will land on action records but cost_estimate will stay $0. ` +
842
+ `Set config.defaultModel or DASHCLAW_DEFAULT_MODEL to price these turns.`
843
+ );
844
+ state.warnedMissingModel = true;
845
+ }
846
+
847
+ async function handleAgentEnd(
848
+ ctx: AgentEndContext | undefined,
849
+ config: PluginConfig,
850
+ ): Promise<void> {
851
+ const runId = ctx?.runId;
852
+ if (!runId) return;
853
+ const state = tokenTurnByRun.get(runId);
854
+ if (!state) return;
855
+
856
+ const client = getClientForAgentEnd(config, state);
857
+ if (client && state.pendingUsage && state.turnActionIds.length > 0) {
858
+ await distributePendingTokens(client, state);
859
+ }
860
+ // Codex turns whose `llm_output` fired without usage stash their action_ids
861
+ // to fold into the NEXT usage-bearing turn (the only in-process recovery
862
+ // signal — the Codex app-server emits no late/secondary usage event). When a
863
+ // run ends on such a turn, no later signal ever arrives and those actions
864
+ // stay unattributed (their tokens are genuinely unrecoverable). That's the
865
+ // existing behavior; we just refuse to drop them silently. (background path
866
+ // → console.warn with context, never a bare drop.)
867
+ if (state.turnActionIds.length > 0) {
868
+ console.warn(
869
+ `[dashclaw-governance] agent_end for run ${runId}: ${state.turnActionIds.length} ` +
870
+ `action(s) end the run unattributed — their codex turn(s) reported no token ` +
871
+ `usage and no later usage-bearing turn followed. tokens_in/out stay unrecorded.`
872
+ );
873
+ }
874
+ if (client && state.sessionId) {
875
+ await closeSession(client, state.sessionId);
876
+ }
877
+ tokenTurnByRun.delete(runId);
878
+ }
879
+
880
+ function getClientForAgentEnd(
881
+ config: PluginConfig,
882
+ state: TokenTurnState,
883
+ ): DashClaw | null {
884
+ try {
885
+ return getClient(config);
886
+ } catch (err) {
887
+ const lost = state.turnActionIds.length;
888
+ if ((state.pendingUsage && lost > 0) || state.sessionId) {
889
+ console.warn(
890
+ `[dashclaw-governance] agent_end cleanup dropped (client unavailable): ${lost} token action(s), session ${state.sessionId ?? 'none'}: ${errorMessage(err) || 'unknown'}`
891
+ );
892
+ }
893
+ return null;
894
+ }
895
+ }
896
+
897
+ async function closeSession(client: DashClaw, sessionId: string): Promise<void> {
898
+ try {
899
+ await client.updateSession(sessionId, { status: 'completed' });
900
+ } catch (err) {
901
+ console.warn(
902
+ `[dashclaw-governance] updateSession(end) failed for ${sessionId}: ${errorMessage(err) || 'unknown'}`
903
+ );
904
+ }
905
+ }
906
+
907
+ async function handleAfterToolCall(
908
+ event: ToolCallEvent,
909
+ config: PluginConfig,
910
+ ): Promise<void> {
911
+ const { toolName, toolCallId, runId } = event;
912
+ const key = callKey(toolName, toolCallId, runId);
913
+
914
+ await handleGenericAfterToolCall(key, event.error, config);
915
+ }
916
+
917
+ function getClientForOutcome(config: PluginConfig): DashClaw | undefined {
918
+ try {
919
+ return getClient(config);
920
+ } catch {
921
+ return undefined;
922
+ }
923
+ }
924
+
925
+ async function handleGenericAfterToolCall(
926
+ key: string,
927
+ error: string | undefined,
928
+ config: PluginConfig,
929
+ ): Promise<void> {
930
+ const actionId = pendingActions.get(key);
931
+ if (!actionId) return;
932
+ pendingActions.delete(key);
933
+
934
+ const client = getClientForOutcome(config);
935
+ if (!client) return;
936
+
937
+ try {
938
+ await client.updateOutcome(actionId, {
939
+ status: error ? 'failed' : 'completed',
940
+ ...(error ? { error_message: error } : {}),
941
+ });
942
+ } catch (err) {
943
+ console.warn(
944
+ `[dashclaw-governance] updateOutcome failed: ${errorMessage(err) || 'unknown'}`
945
+ );
946
+ }
947
+ }
948
+
949
+ // ---------------------------------------------------------------------------
950
+ // Plugin entry
951
+ // ---------------------------------------------------------------------------
952
+
953
+ const pluginEntry: ReturnType<typeof definePluginEntry> = definePluginEntry({
954
+ id: 'dashclaw-governance',
955
+ name: 'DashClaw Governance',
956
+ description:
957
+ 'Policy enforcement, human-in-the-loop approval, and decision recording for every OpenClaw tool call. Powered by DashClaw.',
958
+
959
+ register(api: OpenClawPluginApi): void {
960
+ const config = resolveConfig(api.pluginConfig);
961
+
962
+ registerGovernanceGate(api, config);
963
+
964
+ registerTokenAttribution(api, config);
965
+ registerRunCleanup(api, config);
966
+
967
+ registerOutcomeRecorder(api, config);
968
+ },
969
+ });
970
+
971
+ export default pluginEntry;