@dashclaw/openclaw-plugin 1.2.5 → 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/dist/index.js ADDED
@@ -0,0 +1,665 @@
1
+ /**
2
+ * @dashclaw/openclaw-plugin
3
+ *
4
+ * OpenClaw plugin that routes every tool call through DashClaw governance:
5
+ * 1. `before_tool_call` → `guard()` + optional `waitForApproval()` +
6
+ * `createAction()` to open a governance record.
7
+ * 2. `after_tool_call` → `updateOutcome()` to close that record.
8
+ *
9
+ * Type accuracy notes (verified against `openclaw` plugin SDK types):
10
+ * - `PluginHookBeforeToolCallResult` uses `blockReason`, not `reason`.
11
+ * - `PluginKind` is `"memory" | "context-engine"` — neither applies to this
12
+ * generic hook plugin, so the manifest and `definePluginEntry` call both
13
+ * omit `kind`.
14
+ * - Event/context field shapes come from `PluginHookBeforeToolCallEvent`,
15
+ * `PluginHookAfterToolCallEvent`, and `PluginHookToolContext`. No
16
+ * defensive fallbacks for alternative field names are needed.
17
+ *
18
+ * The DashClaw client is cached at module scope and rebuilt only when the
19
+ * resolved config key changes, mirroring the pattern used by OpenClaw's
20
+ * bundled MemOS plugin.
21
+ */
22
+ import { definePluginEntry, } from 'openclaw/plugin-sdk/plugin-entry';
23
+ import { DashClaw, } from 'dashclaw';
24
+ /**
25
+ * Resolve the DashClaw URL from (in order of precedence):
26
+ * 1. `config.dashclawUrl` (canonical plugin-config key)
27
+ * 2. `config.baseUrl` (SDK-style alias)
28
+ * 3. `process.env.DASHCLAW_BASE_URL` (canonical env var — matches CLI, local scripts)
29
+ * 4. `process.env.DASHCLAW_URL` (legacy env var — matches MCP server docs)
30
+ *
31
+ * The same precedence applies to the API key (with DASHCLAW_API_KEY as the only env var).
32
+ */
33
+ function firstString(...candidates) {
34
+ for (const c of candidates) {
35
+ if (typeof c === 'string' && c.length > 0)
36
+ return c;
37
+ }
38
+ return '';
39
+ }
40
+ function stringSetFromConfig(value) {
41
+ return new Set(Array.isArray(value)
42
+ ? value.filter((v) => typeof v === 'string')
43
+ : []);
44
+ }
45
+ function numberFromConfig(value, fallback, allowNegative = true) {
46
+ if (typeof value !== 'number')
47
+ return fallback;
48
+ if (!Number.isFinite(value))
49
+ return fallback;
50
+ if (!allowNegative && value < 0)
51
+ return fallback;
52
+ return value;
53
+ }
54
+ function resolveConfig(raw) {
55
+ const cfg = raw ?? {};
56
+ const env = typeof process !== 'undefined' && process?.env ? process.env : {};
57
+ const failClosed = cfg.failClosed !== false; // default true
58
+ const riskScoreDefault = numberFromConfig(cfg.riskScoreDefault, 50);
59
+ const highRiskTools = stringSetFromConfig(cfg.highRiskTools);
60
+ const dashclawUrl = firstString(cfg.dashclawUrl, cfg.baseUrl, env.DASHCLAW_BASE_URL, env.DASHCLAW_URL);
61
+ const dashclawApiKey = firstString(cfg.dashclawApiKey, cfg.apiKey, env.DASHCLAW_API_KEY);
62
+ const agentId = firstString(cfg.agentId, env.DASHCLAW_AGENT_ID) || 'openclaw';
63
+ const defaultModel = firstString(cfg.defaultModel, env.DASHCLAW_DEFAULT_MODEL);
64
+ return {
65
+ dashclawUrl,
66
+ dashclawApiKey,
67
+ agentId,
68
+ defaultModel,
69
+ failClosed,
70
+ riskScoreDefault,
71
+ highRiskTools,
72
+ };
73
+ }
74
+ // ---------------------------------------------------------------------------
75
+ // Module state
76
+ // ---------------------------------------------------------------------------
77
+ let cachedClient = null;
78
+ let cachedClientKey = '';
79
+ /** Maps synthetic call key → DashClaw action_id so `after_tool_call` can close it. */
80
+ const pendingActions = new Map();
81
+ const tokenTurnByRun = new Map();
82
+ // Cap for in-memory per-run state. `agent_end` deletes entries, but a crash
83
+ // or an agent framework that never fires `agent_end` in a long-lived gateway
84
+ // process would leak. At ~100 bytes/entry this cap bounds worst-case memory
85
+ // to ~100KB while still comfortably above typical concurrency.
86
+ const MAX_TURN_RUNS = 1000;
87
+ function getTokenTurn(runId) {
88
+ let state = tokenTurnByRun.get(runId);
89
+ if (!state) {
90
+ if (tokenTurnByRun.size >= MAX_TURN_RUNS) {
91
+ // Evict oldest (Map preserves insertion order). One at a time is enough
92
+ // to stay at the cap under steady state — we only grow by one here.
93
+ const oldest = tokenTurnByRun.keys().next().value;
94
+ if (oldest !== undefined)
95
+ tokenTurnByRun.delete(oldest);
96
+ }
97
+ state = { turnActionIds: [] };
98
+ tokenTurnByRun.set(runId, state);
99
+ }
100
+ return state;
101
+ }
102
+ /** Split a non-negative integer `total` into `n` buckets, putting remainders
103
+ * in the earliest buckets so the sum is preserved exactly. */
104
+ function distributeEvenly(total, n) {
105
+ if (n <= 0 || total <= 0)
106
+ return new Array(Math.max(n, 0)).fill(0);
107
+ const base = Math.floor(total / n);
108
+ const remainder = total - base * n;
109
+ return Array.from({ length: n }, (_, i) => base + (i < remainder ? 1 : 0));
110
+ }
111
+ async function distributePendingTokens(client, state) {
112
+ const usage = state.pendingUsage;
113
+ const ids = state.turnActionIds;
114
+ state.pendingUsage = undefined;
115
+ state.turnActionIds = [];
116
+ if (!usage || ids.length === 0)
117
+ return;
118
+ if (usage.tokens_in === 0 && usage.tokens_out === 0)
119
+ return;
120
+ const inParts = distributeEvenly(usage.tokens_in, ids.length);
121
+ const outParts = distributeEvenly(usage.tokens_out, ids.length);
122
+ await Promise.all(ids.map((actionId, idx) => client
123
+ .updateOutcome(actionId, {
124
+ tokens_in: inParts[idx],
125
+ tokens_out: outParts[idx],
126
+ ...(usage.model ? { model: usage.model } : {}),
127
+ })
128
+ .catch((err) => {
129
+ console.warn(`[dashclaw-governance] token PATCH failed for ${actionId}: ${errorMessage(err) || 'unknown'}`);
130
+ })));
131
+ }
132
+ function getClient(config) {
133
+ const key = `${config.dashclawUrl}|${config.dashclawApiKey}|${config.agentId}`;
134
+ if (cachedClient && cachedClientKey === key)
135
+ return cachedClient;
136
+ if (!config.dashclawUrl || !config.dashclawApiKey) {
137
+ const missing = [];
138
+ if (!config.dashclawUrl)
139
+ missing.push('dashclawUrl');
140
+ if (!config.dashclawApiKey)
141
+ missing.push('dashclawApiKey');
142
+ throw new Error(`dashclaw-governance plugin: missing ${missing.join(' and ')}. ` +
143
+ 'Provide via openclaw.plugin.json config (dashclawUrl/dashclawApiKey or baseUrl/apiKey), ' +
144
+ 'or set env vars DASHCLAW_BASE_URL and DASHCLAW_API_KEY before starting the gateway.');
145
+ }
146
+ cachedClient = new DashClaw({
147
+ baseUrl: config.dashclawUrl,
148
+ apiKey: config.dashclawApiKey,
149
+ agentId: config.agentId,
150
+ });
151
+ cachedClientKey = key;
152
+ return cachedClient;
153
+ }
154
+ // ---------------------------------------------------------------------------
155
+ // Helpers
156
+ // ---------------------------------------------------------------------------
157
+ function summarizeParams(params) {
158
+ if (!params)
159
+ return '';
160
+ let serialized;
161
+ try {
162
+ serialized = JSON.stringify(params);
163
+ }
164
+ catch {
165
+ return '[unserializable params]';
166
+ }
167
+ if (serialized.length <= 500)
168
+ return serialized;
169
+ return serialized.slice(0, 500) + '…[truncated]';
170
+ }
171
+ function callKey(toolName, toolCallId, runId) {
172
+ // Prefer the provider-supplied tool call ID; fall back to runId-scoped tool
173
+ // name so a later `after_tool_call` without a toolCallId can still find the
174
+ // pending record.
175
+ if (toolCallId)
176
+ return `id:${toolCallId}`;
177
+ if (runId)
178
+ return `run:${runId}:${toolName}`;
179
+ return `tool:${toolName}`;
180
+ }
181
+ function errorMessage(err) {
182
+ if (!err)
183
+ return '';
184
+ if (typeof err === 'string')
185
+ return err;
186
+ if (err instanceof Error)
187
+ return err.message;
188
+ if (typeof err === 'object' && err !== null && 'message' in err) {
189
+ const m = err.message;
190
+ return typeof m === 'string' ? m : '';
191
+ }
192
+ return '';
193
+ }
194
+ const READONLY_COMMANDS = new Set([
195
+ 'cat', 'head', 'tail', 'less', 'more', 'wc', 'file', 'stat', 'du', 'df',
196
+ 'ls', 'tree', 'find', 'locate', 'which', 'whereis', 'type',
197
+ 'grep', 'rg', 'awk', 'cut', 'sort', 'uniq', 'diff', 'comm',
198
+ 'echo', 'printf', 'date', 'uname', 'whoami', 'pwd', 'hostname',
199
+ 'ps', 'top', 'htop', 'free', 'uptime', 'env', 'printenv',
200
+ ]);
201
+ const GIT_READONLY = new Set([
202
+ 'status', 'log', 'diff', 'show', 'branch', 'tag', 'remote',
203
+ 'stash', 'describe', 'rev-parse', 'blame', 'ls-files',
204
+ ]);
205
+ const DESTRUCTIVE_COMMANDS = new Set([
206
+ 'rm', 'rmdir', 'shred', 'mkfs', 'dd', 'truncate',
207
+ ]);
208
+ const NETWORK_COMMANDS = new Set([
209
+ 'curl', 'wget', 'ssh', 'scp', 'rsync', 'ping',
210
+ ]);
211
+ const PACKAGE_COMMANDS = new Set([
212
+ 'npm', 'yarn', 'pnpm', 'pip', 'pip3', 'cargo', 'go', 'gem',
213
+ 'brew', 'apt', 'apt-get', 'dnf',
214
+ ]);
215
+ const DEPLOY_PATTERN = /(?:git\s+push|deploy|vercel|kubectl|terraform|docker\s+push|helm)/i;
216
+ const DESTRUCTIVE_PATTERN = /(?:rm\s+-rf|DROP\s+TABLE|DELETE\s+FROM|TRUNCATE)/i;
217
+ const SENSITIVE_PATH_PATTERN = /(?:\.env|secret|credential|private_key|\.pem|id_rsa|\.key)/i;
218
+ function classifyBash(command, defaultRisk) {
219
+ if (!command) {
220
+ return { actionType: 'other', riskScore: defaultRisk, reversible: true, systemsTouched: [], declaredGoal: 'Bash: (empty)' };
221
+ }
222
+ const goal = `Bash: ${command.slice(0, 120)}`;
223
+ const patternClassification = classifyBashPattern(command, goal);
224
+ if (patternClassification)
225
+ return patternClassification;
226
+ const firstToken = command.trim().split(/[\s|;&]/)[0].replace(/^.*[/\\]/, '');
227
+ return classifyCommandToken(firstToken, command, goal, defaultRisk);
228
+ }
229
+ function classifyBashPattern(command, goal) {
230
+ if (DESTRUCTIVE_PATTERN.test(command)) {
231
+ return { actionType: 'security', riskScore: 90, reversible: false, systemsTouched: ['filesystem'], declaredGoal: goal };
232
+ }
233
+ if (DEPLOY_PATTERN.test(command)) {
234
+ return { actionType: 'deploy', riskScore: 80, reversible: false, systemsTouched: ['production'], declaredGoal: goal };
235
+ }
236
+ return null;
237
+ }
238
+ function classifyGitCommand(command, goal) {
239
+ const sub = command.match(/git\s+(\S+)/)?.[1] ?? '';
240
+ if (GIT_READONLY.has(sub)) {
241
+ return { actionType: 'review', riskScore: 10, reversible: true, systemsTouched: [], declaredGoal: goal };
242
+ }
243
+ if (sub === 'push') {
244
+ return { actionType: 'deploy', riskScore: 75, reversible: false, systemsTouched: [], declaredGoal: goal };
245
+ }
246
+ return { actionType: 'apply', riskScore: 30, reversible: true, systemsTouched: [], declaredGoal: goal };
247
+ }
248
+ function classifyCommandToken(firstToken, command, goal, defaultRisk) {
249
+ if (firstToken === 'git') {
250
+ return classifyGitCommand(command, goal);
251
+ }
252
+ if (READONLY_COMMANDS.has(firstToken)) {
253
+ return { actionType: 'review', riskScore: 10, reversible: true, systemsTouched: [], declaredGoal: goal };
254
+ }
255
+ if (DESTRUCTIVE_COMMANDS.has(firstToken)) {
256
+ return { actionType: 'security', riskScore: 85, reversible: false, systemsTouched: ['filesystem'], declaredGoal: goal };
257
+ }
258
+ if (NETWORK_COMMANDS.has(firstToken)) {
259
+ return { actionType: 'api', riskScore: 40, reversible: true, systemsTouched: [], declaredGoal: goal };
260
+ }
261
+ if (PACKAGE_COMMANDS.has(firstToken)) {
262
+ return { actionType: 'build', riskScore: 30, reversible: true, systemsTouched: [], declaredGoal: goal };
263
+ }
264
+ return { actionType: 'other', riskScore: defaultRisk, reversible: true, systemsTouched: ['shell'], declaredGoal: goal };
265
+ }
266
+ function classifyFile(toolName, params, defaultRisk) {
267
+ const filePath = String(params?.file_path ?? params?.path ?? '');
268
+ const goal = `${toolName}: ${filePath || '(unknown)'}`;
269
+ if (SENSITIVE_PATH_PATTERN.test(filePath)) {
270
+ return { actionType: 'security', riskScore: 85, reversible: true, systemsTouched: ['filesystem'], declaredGoal: goal };
271
+ }
272
+ return { actionType: 'apply', riskScore: defaultRisk, reversible: true, systemsTouched: ['filesystem'], declaredGoal: goal };
273
+ }
274
+ function classifyToolCall(toolName, params, config) {
275
+ const defaultRisk = config.highRiskTools.has(toolName) ? 85 : config.riskScoreDefault;
276
+ const classified = TOOL_CLASSIFIERS
277
+ .map((classify) => classify(toolName, params, defaultRisk))
278
+ .find((result) => result !== null);
279
+ return classified ?? classifyDefaultTool(toolName, params, defaultRisk);
280
+ }
281
+ const WRITE_TOOLS = new Set(['write', 'edit', 'apply_patch']);
282
+ const REVIEW_TOOLS = new Set([
283
+ 'read',
284
+ 'web_search',
285
+ 'web_fetch',
286
+ 'memory_search',
287
+ 'memory_get',
288
+ 'image',
289
+ ]);
290
+ const TOOL_CLASSIFIERS = [
291
+ classifyShellTool,
292
+ classifyWriteTool,
293
+ classifyReviewTool,
294
+ classifyMessageTool,
295
+ ];
296
+ function classifyShellTool(toolName, params, defaultRisk) {
297
+ return toolName === 'bash' || toolName === 'exec'
298
+ ? classifyBash(params?.command, defaultRisk)
299
+ : null;
300
+ }
301
+ function classifyWriteTool(toolName, params, defaultRisk) {
302
+ return WRITE_TOOLS.has(toolName) ? classifyFile(toolName, params, defaultRisk) : null;
303
+ }
304
+ function classifyReviewTool(toolName, params, defaultRisk) {
305
+ if (!REVIEW_TOOLS.has(toolName))
306
+ return null;
307
+ const target = String(params?.file_path ?? params?.path ?? params?.query ?? '');
308
+ return {
309
+ actionType: 'review',
310
+ riskScore: Math.min(defaultRisk, 15),
311
+ reversible: true,
312
+ systemsTouched: [],
313
+ declaredGoal: `${toolName}: ${target.slice(0, 120) || '(unknown)'}`,
314
+ };
315
+ }
316
+ function classifyMessageTool(toolName, params, defaultRisk) {
317
+ if (toolName !== 'sessions_send')
318
+ return null;
319
+ return {
320
+ actionType: 'message',
321
+ riskScore: defaultRisk,
322
+ reversible: false,
323
+ systemsTouched: [],
324
+ declaredGoal: `message: ${summarizeParams(params).slice(0, 120)}`,
325
+ };
326
+ }
327
+ function classifyDefaultTool(toolName, params, defaultRisk) {
328
+ return {
329
+ actionType: 'other',
330
+ riskScore: defaultRisk,
331
+ reversible: true,
332
+ systemsTouched: [],
333
+ declaredGoal: `${toolName}: ${summarizeParams(params).slice(0, 120)}`,
334
+ };
335
+ }
336
+ function isApproved(action) {
337
+ if (!action)
338
+ return false;
339
+ if (action.approved_by)
340
+ return true;
341
+ return action.status === 'running' || action.status === 'completed';
342
+ }
343
+ function registerGovernanceGate(api, config) {
344
+ api.on('before_tool_call', async (event, _ctx) => handleBeforeToolCall(event, config));
345
+ }
346
+ function registerTokenAttribution(api, config) {
347
+ api.on('llm_output', async (event, _ctx) => handleLlmOutput(event, config));
348
+ }
349
+ function registerRunCleanup(api, config) {
350
+ api.on('agent_end', async (_event, ctx) => handleAgentEnd(ctx, config));
351
+ }
352
+ function registerOutcomeRecorder(api, config) {
353
+ api.on('after_tool_call', async (event, _ctx) => handleAfterToolCall(event, config));
354
+ }
355
+ async function handleBeforeToolCall(event, config) {
356
+ const { toolName, params, toolCallId, runId } = event;
357
+ const key = callKey(toolName, toolCallId, runId);
358
+ const classification = classifyToolCall(toolName, params, config);
359
+ const client = getBeforeClient(config);
360
+ if ('result' in client)
361
+ return client.result;
362
+ await maybeStartSession(event, client.value, config);
363
+ const decision = await guardClassifiedAction(client.value, classification, config);
364
+ if ('result' in decision)
365
+ return decision.result;
366
+ const block = blockResultForDecision(decision.value, toolName);
367
+ if (block)
368
+ return block;
369
+ return openActionRecord({
370
+ client: client.value,
371
+ classification,
372
+ decision: decision.value,
373
+ toolName,
374
+ key,
375
+ runId,
376
+ config,
377
+ });
378
+ }
379
+ function getBeforeClient(config) {
380
+ try {
381
+ return { value: getClient(config) };
382
+ }
383
+ catch (err) {
384
+ const msg = errorMessage(err) || 'unknown error';
385
+ if (config.failClosed) {
386
+ return { result: { block: true, blockReason: `DashClaw config error: ${msg}` } };
387
+ }
388
+ console.warn(`[dashclaw-governance] config error (fail-open): ${msg}`);
389
+ return { result: undefined };
390
+ }
391
+ }
392
+ async function maybeStartSession(event, client, config) {
393
+ if (!event.runId)
394
+ return;
395
+ const runState = getTokenTurn(event.runId);
396
+ if (runState.sessionStarted)
397
+ return;
398
+ runState.sessionStarted = true; // guard before await — once per run
399
+ const workspace = typeof event.workspace === 'string' ? event.workspace : undefined;
400
+ const branch = typeof event.branch === 'string' ? event.branch : null;
401
+ try {
402
+ const res = await client.createSession(config.agentId, workspace, branch);
403
+ const sessionId = res.session?.id ??
404
+ res.id;
405
+ if (sessionId)
406
+ runState.sessionId = sessionId;
407
+ }
408
+ catch (err) {
409
+ console.warn(`[dashclaw-governance] createSession failed: ${errorMessage(err) || 'unknown'}`);
410
+ }
411
+ }
412
+ async function guardClassifiedAction(client, classification, config) {
413
+ try {
414
+ return {
415
+ value: await client.guard({
416
+ action_type: classification.actionType,
417
+ risk_score: classification.riskScore,
418
+ declared_goal: classification.declaredGoal,
419
+ reversible: classification.reversible,
420
+ systems_touched: classification.systemsTouched,
421
+ }),
422
+ };
423
+ }
424
+ catch (err) {
425
+ const msg = errorMessage(err) || 'unknown error';
426
+ if (config.failClosed) {
427
+ return {
428
+ result: {
429
+ block: true,
430
+ blockReason: `DashClaw unreachable — fail-closed policy (${msg})`,
431
+ },
432
+ };
433
+ }
434
+ console.warn(`[dashclaw-governance] guard call failed (fail-open): ${msg}`);
435
+ return { result: undefined };
436
+ }
437
+ }
438
+ function blockResultForDecision(decision, toolName) {
439
+ if (decision.decision === 'block') {
440
+ return {
441
+ block: true,
442
+ blockReason: decision.reason || 'Blocked by DashClaw policy',
443
+ };
444
+ }
445
+ if (decision.decision === 'warn') {
446
+ console.warn(`[dashclaw-governance] WARN ${toolName}: ${decision.reason || 'flagged by policy'}`);
447
+ }
448
+ return undefined;
449
+ }
450
+ async function openActionRecord(ctx) {
451
+ const created = await createGovernanceAction(ctx);
452
+ if ('result' in created)
453
+ return created.result;
454
+ const approval = await waitForRequiredApproval(ctx.client, ctx.decision, created.value);
455
+ if (approval)
456
+ return approval;
457
+ rememberPendingAction(ctx.key, created.value.actionId, ctx.runId);
458
+ return;
459
+ }
460
+ async function createGovernanceAction(ctx) {
461
+ const { actionType, declaredGoal, riskScore, reversible, systemsTouched } = ctx.classification;
462
+ try {
463
+ const created = await ctx.client.createAction({
464
+ action_type: actionType,
465
+ declared_goal: declaredGoal,
466
+ risk_score: riskScore,
467
+ reversible,
468
+ systems_touched: systemsTouched,
469
+ metadata: { openclaw_tool_name: ctx.toolName },
470
+ });
471
+ return {
472
+ value: {
473
+ actionId: created.action_id ?? created.action?.action_id ?? created.action?.id,
474
+ status: created.action?.status,
475
+ },
476
+ };
477
+ }
478
+ catch (err) {
479
+ const msg = errorMessage(err) || 'unknown';
480
+ console.warn(`[dashclaw-governance] createAction failed: ${msg}`);
481
+ if (ctx.config.failClosed) {
482
+ return {
483
+ result: {
484
+ block: true,
485
+ blockReason: `DashClaw action record could not be opened — fail-closed policy (${msg})`,
486
+ },
487
+ };
488
+ }
489
+ return { result: undefined };
490
+ }
491
+ }
492
+ async function waitForRequiredApproval(client, decision, created) {
493
+ const needsApproval = decision.decision === 'require_approval' ||
494
+ created.status === 'pending_approval';
495
+ if (!needsApproval || !created.actionId)
496
+ return undefined;
497
+ try {
498
+ const { action } = await client.waitForApproval(created.actionId);
499
+ if (isApproved(action))
500
+ return undefined;
501
+ return {
502
+ block: true,
503
+ blockReason: action?.error_message || 'Action denied by operator',
504
+ };
505
+ }
506
+ catch (err) {
507
+ return {
508
+ block: true,
509
+ blockReason: `Approval denied or wait failed: ${errorMessage(err) || 'denied'}`,
510
+ };
511
+ }
512
+ }
513
+ function rememberPendingAction(key, actionId, runId) {
514
+ if (!actionId)
515
+ return;
516
+ pendingActions.set(key, actionId);
517
+ if (runId)
518
+ getTokenTurn(runId).turnActionIds.push(actionId);
519
+ }
520
+ async function handleLlmOutput(event, config) {
521
+ const { runId, model, usage } = event;
522
+ if (!runId)
523
+ return;
524
+ const client = getClientForLlmOutput(config);
525
+ if (!client)
526
+ return;
527
+ const state = getTokenTurn(runId);
528
+ if (state.pendingUsage) {
529
+ await distributePendingTokens(client, state);
530
+ }
531
+ const pendingUsage = tokenUsageFromEvent({
532
+ usage,
533
+ model,
534
+ config,
535
+ state,
536
+ runId,
537
+ });
538
+ if (pendingUsage)
539
+ state.pendingUsage = pendingUsage;
540
+ }
541
+ function getClientForLlmOutput(config) {
542
+ try {
543
+ return getClient(config);
544
+ }
545
+ catch (err) {
546
+ console.warn(`[dashclaw-governance] llm_output dropped — client unavailable: ${errorMessage(err) || 'unknown'}`);
547
+ return undefined;
548
+ }
549
+ }
550
+ function tokenUsageFromEvent(ctx) {
551
+ const { usage, model, config, state, runId } = ctx;
552
+ if (!usage)
553
+ return undefined;
554
+ const cacheReadEffective = Math.round((usage.cacheRead ?? 0) * 0.1);
555
+ const tokens_in = (usage.input ?? 0) + (usage.cacheWrite ?? 0) + cacheReadEffective;
556
+ const tokens_out = usage.output ?? 0;
557
+ if (tokens_in <= 0 && tokens_out <= 0)
558
+ return undefined;
559
+ const resolvedModel = model && model.length > 0 ? model : config.defaultModel;
560
+ warnOnceForMissingModel(resolvedModel, state, runId);
561
+ return { tokens_in, tokens_out, model: resolvedModel };
562
+ }
563
+ function warnOnceForMissingModel(model, state, runId) {
564
+ if (model || state.warnedMissingModel)
565
+ return;
566
+ console.warn(`[dashclaw-governance] llm_output has no model for run ${runId} — ` +
567
+ `tokens will land on action records but cost_estimate will stay $0. ` +
568
+ `Set config.defaultModel or DASHCLAW_DEFAULT_MODEL to price these turns.`);
569
+ state.warnedMissingModel = true;
570
+ }
571
+ async function handleAgentEnd(ctx, config) {
572
+ const runId = ctx?.runId;
573
+ if (!runId)
574
+ return;
575
+ const state = tokenTurnByRun.get(runId);
576
+ if (!state)
577
+ return;
578
+ const client = getClientForAgentEnd(config, state);
579
+ if (client && state.pendingUsage && state.turnActionIds.length > 0) {
580
+ await distributePendingTokens(client, state);
581
+ }
582
+ // Codex turns whose `llm_output` fired without usage stash their action_ids
583
+ // to fold into the NEXT usage-bearing turn (the only in-process recovery
584
+ // signal — the Codex app-server emits no late/secondary usage event). When a
585
+ // run ends on such a turn, no later signal ever arrives and those actions
586
+ // stay unattributed (their tokens are genuinely unrecoverable). That's the
587
+ // existing behavior; we just refuse to drop them silently. (background path
588
+ // → console.warn with context, never a bare drop.)
589
+ if (state.turnActionIds.length > 0) {
590
+ console.warn(`[dashclaw-governance] agent_end for run ${runId}: ${state.turnActionIds.length} ` +
591
+ `action(s) end the run unattributed — their codex turn(s) reported no token ` +
592
+ `usage and no later usage-bearing turn followed. tokens_in/out stay unrecorded.`);
593
+ }
594
+ if (client && state.sessionId) {
595
+ await closeSession(client, state.sessionId);
596
+ }
597
+ tokenTurnByRun.delete(runId);
598
+ }
599
+ function getClientForAgentEnd(config, state) {
600
+ try {
601
+ return getClient(config);
602
+ }
603
+ catch (err) {
604
+ const lost = state.turnActionIds.length;
605
+ if ((state.pendingUsage && lost > 0) || state.sessionId) {
606
+ console.warn(`[dashclaw-governance] agent_end cleanup dropped (client unavailable): ${lost} token action(s), session ${state.sessionId ?? 'none'}: ${errorMessage(err) || 'unknown'}`);
607
+ }
608
+ return null;
609
+ }
610
+ }
611
+ async function closeSession(client, sessionId) {
612
+ try {
613
+ await client.updateSession(sessionId, { status: 'completed' });
614
+ }
615
+ catch (err) {
616
+ console.warn(`[dashclaw-governance] updateSession(end) failed for ${sessionId}: ${errorMessage(err) || 'unknown'}`);
617
+ }
618
+ }
619
+ async function handleAfterToolCall(event, config) {
620
+ const { toolName, toolCallId, runId } = event;
621
+ const key = callKey(toolName, toolCallId, runId);
622
+ await handleGenericAfterToolCall(key, event.error, config);
623
+ }
624
+ function getClientForOutcome(config) {
625
+ try {
626
+ return getClient(config);
627
+ }
628
+ catch {
629
+ return undefined;
630
+ }
631
+ }
632
+ async function handleGenericAfterToolCall(key, error, config) {
633
+ const actionId = pendingActions.get(key);
634
+ if (!actionId)
635
+ return;
636
+ pendingActions.delete(key);
637
+ const client = getClientForOutcome(config);
638
+ if (!client)
639
+ return;
640
+ try {
641
+ await client.updateOutcome(actionId, {
642
+ status: error ? 'failed' : 'completed',
643
+ ...(error ? { error_message: error } : {}),
644
+ });
645
+ }
646
+ catch (err) {
647
+ console.warn(`[dashclaw-governance] updateOutcome failed: ${errorMessage(err) || 'unknown'}`);
648
+ }
649
+ }
650
+ // ---------------------------------------------------------------------------
651
+ // Plugin entry
652
+ // ---------------------------------------------------------------------------
653
+ const pluginEntry = definePluginEntry({
654
+ id: 'dashclaw-governance',
655
+ name: 'DashClaw Governance',
656
+ description: 'Policy enforcement, human-in-the-loop approval, and decision recording for every OpenClaw tool call. Powered by DashClaw.',
657
+ register(api) {
658
+ const config = resolveConfig(api.pluginConfig);
659
+ registerGovernanceGate(api, config);
660
+ registerTokenAttribution(api, config);
661
+ registerRunCleanup(api, config);
662
+ registerOutcomeRecorder(api, config);
663
+ },
664
+ });
665
+ export default pluginEntry;