@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/README.md +3 -3
- package/dist/index.d.ts +24 -0
- package/dist/index.js +665 -0
- package/openclaw.plugin.json +67 -67
- package/package.json +80 -63
- package/src/HOOK.md +3 -1
- package/src/dashclaw.d.ts +79 -70
- package/src/index.ts +971 -669
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
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
const
|
|
92
|
-
const
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
)
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
);
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
const
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
if (
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
if (
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
//
|
|
265
|
-
//
|
|
266
|
-
//
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
'
|
|
299
|
-
'
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
const
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
if (
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
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;
|