@dashclaw/openclaw-plugin 1.6.3 → 1.6.5
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 +26 -11
- package/dist/index.js +204 -21
- package/openclaw.plugin.json +2 -2
- package/package.json +3 -3
- package/src/HOOK.md +9 -5
- package/src/dashclaw.d.ts +3 -0
- package/src/index.ts +230 -18
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @dashclaw/openclaw-plugin
|
|
2
2
|
|
|
3
|
-
Add DashClaw governance to OpenClaw
|
|
3
|
+
Add DashClaw governance to tool calls that OpenClaw delivers through the installed `before_tool_call` hook, with policy enforcement, human approval gates, and a verifiable decision trail.
|
|
4
4
|
|
|
5
5
|
## Install
|
|
6
6
|
|
|
@@ -82,22 +82,33 @@ Config changes require a gateway restart, the same as any other OpenClaw plugin.
|
|
|
82
82
|
|
|
83
83
|
## What happens
|
|
84
84
|
|
|
85
|
-
Every tool call
|
|
85
|
+
Every tool call delivered to the installed OpenClaw `before_tool_call` hook flows through DashClaw before it executes:
|
|
86
86
|
|
|
87
87
|
1. Agent decides to call a tool (e.g. `bash`, `write`, a custom HTTP tool).
|
|
88
88
|
2. The plugin **classifies the tool call** — parsing bash commands, inspecting file paths, and detecting deploy/destructive/network intents — to determine the DashClaw action type, risk score, reversibility, and systems touched.
|
|
89
89
|
3. The plugin calls DashClaw `/api/guard` with the full classification (`action_type`, `risk_score`, `declared_goal`, `reversible`, `systems_touched`) and canonical act evidence: the full shell command for `bash`/`exec`, or the file target for `write`/`edit`/`apply_patch`. DashClaw can therefore derive risk from what will run and match protected paths. File content is never copied into evidence. If the verdict is `block`, the tool call is rejected immediately.
|
|
90
|
-
4. On `allow`, `warn`, or `require_approval`, the plugin opens a governance record via `/api/actions
|
|
91
|
-
5. If the action is `pending_approval`, the plugin pauses on `waitForApproval(action.action_id)`. You approve from the DashClaw dashboard, the CLI (`dashclaw approve <id>`), or the mobile PWA
|
|
92
|
-
6.
|
|
93
|
-
|
|
94
|
-
|
|
90
|
+
4. On `allow`, `warn`, or `require_approval`, the plugin opens a governance record via `/api/actions` with the same act evidence. The server re-runs current policy and is authoritative for HITL gating. It may return `action.status === 'pending_approval'` even when the earlier guard said `allow`.
|
|
91
|
+
5. If the action is `pending_approval`, the plugin pauses on `waitForApproval(action.action_id)`. You approve from the DashClaw dashboard, the CLI (`dashclaw approve <id>`), or the mobile PWA. The wait uses SSE plus concurrent authoritative action polling, so a connected stream cannot hide a missed event.
|
|
92
|
+
6. When the server advertises execution-claim protocol 1, the plugin atomically claims the exact action, agent, act, and fresh attempt immediately before returning control to OpenClaw. Approval is consumed at this claim, not at guard time. A rejected, malformed, or lost claim acknowledgement blocks and is never retried automatically.
|
|
93
|
+
7. OpenClaw executes the tool once the plugin releases it. The `after_tool_call` hook records `completed` or `failed` with the error message.
|
|
94
|
+
|
|
95
|
+
This boundary covers calls OpenClaw delivers to those lifecycle hooks. Embedded
|
|
96
|
+
Codex native tools run behind their own runtime and require the separately
|
|
97
|
+
installed DashClaw Codex hooks. Older OpenClaw 0.13x Codex integrations remain
|
|
98
|
+
cooperative and do not inherit this plugin's mechanical interception boundary.
|
|
99
|
+
|
|
100
|
+
Claim negotiation supports server-first upgrades. A server that omits both claim
|
|
101
|
+
fields keeps the legacy guard and approval flow until you set
|
|
102
|
+
`DASHCLAW_REQUIRE_EXECUTION_CLAIMS=1`. Any server that advertises an incomplete,
|
|
103
|
+
unknown, or malformed claim protocol is blocked even when strict mode is unset.
|
|
104
|
+
|
|
105
|
+
On the first intercepted tool call of each run the plugin opens a DashClaw **Agent Session** and closes it (`status: completed`) on `agent_end`, so every OpenClaw run with at least one intercepted call shows up under the Agent Sessions feature (not just Code Sessions). Session lifecycle calls are fully fail-safe — a session error never blocks a tool call or the run.
|
|
95
106
|
|
|
96
107
|
The plugin is read-mostly: it never modifies the tool's parameters or the tool's result. It only blocks, allows, or records.
|
|
97
108
|
|
|
98
109
|
### Unified policy surface
|
|
99
110
|
|
|
100
|
-
The plugin uses the **same action type vocabulary** as the DashClaw Claude Code hooks. Policies you write for Claude Code
|
|
111
|
+
The plugin uses the **same action type vocabulary** as the DashClaw Claude Code hooks. Policies you write for Claude Code apply to OpenClaw calls delivered through the plugin hook without duplicating the policy.
|
|
101
112
|
|
|
102
113
|
| Tool call | Action type | Risk | Reversible |
|
|
103
114
|
|---|---|---|---|
|
|
@@ -134,7 +145,11 @@ empty because the wait target didn't exist. Fixed in `1.0.1`.
|
|
|
134
145
|
| `autoPairing` | boolean | `true` | Automatically answer operator pairing requests from the DashClaw `/identities` page. The private key is stored at `~/.dashclaw/identity/<agentId>.pem` and never leaves this machine. Set `false` to require manual pairing (MCP `dashclaw_pair` or SDK `createPairing`). |
|
|
135
146
|
| `riskScoreDefault` | number | `50` | Fallback risk score for tool calls the classifier doesn't recognize. Recognized commands (git, curl, rm, npm, etc.) compute their own risk score automatically. |
|
|
136
147
|
| `highRiskTools` | string[] | `[]` | Tool names that start at risk score 85 instead of the default, before classification. A pattern match then takes precedence over that starting score in both directions: a destructive command still scores 90, a deploy scores 80, and read-only tools are capped at 15 no matter what they started at. |
|
|
137
|
-
| `approvalWaitMs` | number | `60000` | How long a `require_approval` decision waits for the operator before blocking with a retry hint. Keep it below your runtime's per-tool-call watchdog — Codex's embedded dynamic-tool RPC kills calls at ~90s, which would silently drop the tool result instead of blocking cleanly. The approval stays open ~300s server-side, so the operator can approve after the wait and the agent's retry of the same call passes (guard approval grant + idempotent `createAction`). |
|
|
148
|
+
| `approvalWaitMs` | number | `60000` | How long a `require_approval` decision waits for the operator before blocking with a retry hint. Keep it below your runtime's per-tool-call watchdog — Codex's embedded dynamic-tool RPC kills calls at ~90s, which would silently drop the tool result instead of blocking cleanly. The approval stays open ~300s server-side, so the operator can approve after the wait and the agent's retry of the same call passes (guard approval grant + idempotent `createAction`). |
|
|
149
|
+
|
|
150
|
+
`DASHCLAW_REQUIRE_EXECUTION_CLAIMS=1` is an environment-only rollout pin. Enable
|
|
151
|
+
it after the DashClaw server supports protocol 1 to reject legacy responses that
|
|
152
|
+
do not advertise claims.
|
|
138
153
|
|
|
139
154
|
## Automatic identity pairing
|
|
140
155
|
|
|
@@ -174,7 +189,7 @@ The plugin goes beyond tool names — it inspects the **content** of each call:
|
|
|
174
189
|
|
|
175
190
|
This classification mirrors what the DashClaw Claude Code hooks do via `dashclaw_agent_intel`, so the same guard policies fire consistently across both platforms.
|
|
176
191
|
|
|
177
|
-
### Evidence attachment
|
|
192
|
+
### Evidence attachment
|
|
178
193
|
|
|
179
194
|
Every `guard()` and `createAction()` call now carries an `act` payload alongside the self-declared `action_type`/`risk_score`, so the server's evidence classifier grades what actually ran instead of only the plugin's own summary. Shell calls (`bash`, `exec`) attach `act.kind: 'shell'` with the full command; write calls (`write`, `edit`, `apply_patch`) attach `act.kind: 'file'` with the file path. When a shell command invokes a local script (for example `node tmp/domain-buy.mjs <name>`), the plugin also resolves that script against the tool call's workspace and attaches its first 6144 characters as `act.script.content_excerpt`, so a wrapper script can't hide its risk behind an innocuous-looking command line. For sensitive paths (`.env`, `credential`, `.pem`, `id_rsa`, `.key`) only `act.script.path` is attached, never content. If the script can't be resolved or read, or exceeds 64KB, `script` is omitted entirely — evidence attachment fails soft and never blocks the call.
|
|
180
195
|
|
|
@@ -182,7 +197,7 @@ Every `guard()` and `createAction()` call now carries an `act` payload alongside
|
|
|
182
197
|
|
|
183
198
|
The plugin caches the DashClaw `action_id` from `before_tool_call` in a module-level map keyed by the call id, then resolves it in `after_tool_call` to send `updateOutcome`. If `after_tool_call` doesn't fire (process crash, hook misordering), the action stays in `running` state in DashClaw — you'll see it in the open-loops view and can resolve it manually.
|
|
184
199
|
|
|
185
|
-
If the outcome update itself fails, the plugin logs a warning but never throws
|
|
200
|
+
If the outcome update itself fails, the plugin logs a warning but never throws because the tool has already run. Treat that action's completion as unconfirmed. Do not infer that the external effect failed or retry it without reconciling the affected system.
|
|
186
201
|
|
|
187
202
|
## Token usage and cost (v1.2.1+)
|
|
188
203
|
|
package/dist/index.js
CHANGED
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
import { definePluginEntry, } from 'openclaw/plugin-sdk/plugin-entry';
|
|
23
23
|
import { DashClaw, } from 'dashclaw';
|
|
24
24
|
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
25
|
+
import { randomUUID } from 'node:crypto';
|
|
25
26
|
import { resolve as resolvePath } from 'node:path';
|
|
26
27
|
import { maybeAutoPair } from './auto-pairing.js';
|
|
27
28
|
import { runLivenessProbe, shouldProbeNow, PROBE_AGENT_ID } from './liveness-probe.js';
|
|
@@ -55,10 +56,14 @@ function numberFromConfig(value, fallback, allowNegative = true) {
|
|
|
55
56
|
return fallback;
|
|
56
57
|
return value;
|
|
57
58
|
}
|
|
59
|
+
function enabledEnvFlag(value) {
|
|
60
|
+
return typeof value === 'string' && ['1', 'true'].includes(value.toLowerCase());
|
|
61
|
+
}
|
|
58
62
|
function resolveConfig(raw) {
|
|
59
63
|
const cfg = raw ?? {};
|
|
60
64
|
const env = typeof process !== 'undefined' && process?.env ? process.env : {};
|
|
61
65
|
const failClosed = cfg.failClosed !== false; // default true
|
|
66
|
+
const requireExecutionClaims = enabledEnvFlag(env.DASHCLAW_REQUIRE_EXECUTION_CLAIMS);
|
|
62
67
|
const autoPairing = cfg.autoPairing !== false; // default true
|
|
63
68
|
const riskScoreDefault = numberFromConfig(cfg.riskScoreDefault, 50);
|
|
64
69
|
const highRiskTools = stringSetFromConfig(cfg.highRiskTools);
|
|
@@ -73,6 +78,7 @@ function resolveConfig(raw) {
|
|
|
73
78
|
agentId,
|
|
74
79
|
defaultModel,
|
|
75
80
|
failClosed,
|
|
81
|
+
requireExecutionClaims,
|
|
76
82
|
autoPairing,
|
|
77
83
|
riskScoreDefault,
|
|
78
84
|
highRiskTools,
|
|
@@ -494,6 +500,13 @@ function registerLivenessProbe(api, config) {
|
|
|
494
500
|
async function handleBeforeToolCall(event, config) {
|
|
495
501
|
const { toolName, params, toolCallId, runId } = event;
|
|
496
502
|
const key = callKey(toolName, toolCallId, runId);
|
|
503
|
+
if (!toolCallId && pendingActions.has(key)) {
|
|
504
|
+
return {
|
|
505
|
+
block: true,
|
|
506
|
+
blockReason: 'OpenClaw did not provide a stable tool call ID and another matching call is still open. ' +
|
|
507
|
+
'Execution was interrupted because its outcome could not be correlated safely.',
|
|
508
|
+
};
|
|
509
|
+
}
|
|
497
510
|
const workspace = typeof event.workspace === 'string' ? event.workspace : undefined;
|
|
498
511
|
const classification = classifyToolCall(toolName, params, config, workspace);
|
|
499
512
|
const client = getBeforeClient(config);
|
|
@@ -554,16 +567,25 @@ async function maybeStartSession(event, client, config) {
|
|
|
554
567
|
}
|
|
555
568
|
async function guardClassifiedAction(client, classification, config) {
|
|
556
569
|
try {
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
570
|
+
const raw = await client.guard({
|
|
571
|
+
action_type: classification.actionType,
|
|
572
|
+
risk_score: classification.riskScore,
|
|
573
|
+
declared_goal: classification.declaredGoal,
|
|
574
|
+
reversible: classification.reversible,
|
|
575
|
+
systems_touched: classification.systemsTouched,
|
|
576
|
+
client_capabilities: ['execution_claims'],
|
|
577
|
+
...(classification.act ? { act: classification.act } : {}),
|
|
578
|
+
});
|
|
579
|
+
const validated = validateGuardDecision(raw, config.requireExecutionClaims);
|
|
580
|
+
if ('reason' in validated) {
|
|
581
|
+
return {
|
|
582
|
+
result: {
|
|
583
|
+
block: true,
|
|
584
|
+
blockReason: validated.reason,
|
|
585
|
+
},
|
|
586
|
+
};
|
|
587
|
+
}
|
|
588
|
+
return { value: validated.value };
|
|
567
589
|
}
|
|
568
590
|
catch (err) {
|
|
569
591
|
const msg = errorMessage(err) || 'unknown error';
|
|
@@ -579,6 +601,28 @@ async function guardClassifiedAction(client, classification, config) {
|
|
|
579
601
|
return { result: undefined };
|
|
580
602
|
}
|
|
581
603
|
}
|
|
604
|
+
const GUARD_DECISIONS = new Set(['allow', 'block', 'warn', 'require_approval']);
|
|
605
|
+
const EXECUTION_CLAIM_TIMEOUT_MS = 30_000;
|
|
606
|
+
function validateGuardDecision(value, requireExecutionClaims) {
|
|
607
|
+
if (!value || typeof value !== 'object') {
|
|
608
|
+
return { reason: 'DashClaw returned a malformed guard response; tool execution was interrupted.' };
|
|
609
|
+
}
|
|
610
|
+
const response = value;
|
|
611
|
+
if (typeof response.decision !== 'string' || !GUARD_DECISIONS.has(response.decision)) {
|
|
612
|
+
return { reason: 'DashClaw returned a malformed or unknown guard decision; tool execution was interrupted.' };
|
|
613
|
+
}
|
|
614
|
+
if (response.decision === 'block') {
|
|
615
|
+
return { value: value };
|
|
616
|
+
}
|
|
617
|
+
const advertised = 'execution_claim_required' in response || 'claim_protocol' in response;
|
|
618
|
+
const validClaims = response.execution_claim_required === true && response.claim_protocol === 1;
|
|
619
|
+
if ((requireExecutionClaims || advertised) && !validClaims) {
|
|
620
|
+
return {
|
|
621
|
+
reason: 'DashClaw server upgrade required: execution-claim protocol 1 was not advertised, so this tool call cannot run safely.',
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
return { value: value };
|
|
625
|
+
}
|
|
582
626
|
function blockResultForDecision(decision, toolName) {
|
|
583
627
|
if (decision.decision === 'block') {
|
|
584
628
|
return {
|
|
@@ -598,6 +642,11 @@ async function openActionRecord(ctx) {
|
|
|
598
642
|
const approval = await waitForRequiredApproval(ctx, created.value);
|
|
599
643
|
if (approval)
|
|
600
644
|
return approval;
|
|
645
|
+
if (ctx.decision.execution_claim_required === true && ctx.decision.claim_protocol === 1) {
|
|
646
|
+
const claim = await claimExecution(ctx, created.value.actionId);
|
|
647
|
+
if (claim)
|
|
648
|
+
return claim;
|
|
649
|
+
}
|
|
601
650
|
rememberPendingAction(ctx.key, created.value.actionId, ctx.runId);
|
|
602
651
|
return;
|
|
603
652
|
}
|
|
@@ -610,15 +659,21 @@ async function createGovernanceAction(ctx) {
|
|
|
610
659
|
risk_score: riskScore,
|
|
611
660
|
reversible,
|
|
612
661
|
systems_touched: systemsTouched,
|
|
662
|
+
client_capabilities: ['execution_claims'],
|
|
613
663
|
...(ctx.classification.act ? { act: ctx.classification.act } : {}),
|
|
614
664
|
metadata: { openclaw_tool_name: ctx.toolName },
|
|
615
665
|
});
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
666
|
+
const ids = [created.action_id, created.action?.action_id, created.action?.id]
|
|
667
|
+
.filter((id) => typeof id === 'string' && id.length > 0);
|
|
668
|
+
if (ids.length === 0 || new Set(ids).size !== 1) {
|
|
669
|
+
return {
|
|
670
|
+
result: {
|
|
671
|
+
block: true,
|
|
672
|
+
blockReason: 'DashClaw action response did not contain one exact action ID; tool execution was interrupted.',
|
|
673
|
+
},
|
|
674
|
+
};
|
|
675
|
+
}
|
|
676
|
+
return { value: { actionId: ids[0], status: created.action?.status } };
|
|
622
677
|
}
|
|
623
678
|
catch (err) {
|
|
624
679
|
const msg = errorMessage(err) || 'unknown';
|
|
@@ -634,10 +689,70 @@ async function createGovernanceAction(ctx) {
|
|
|
634
689
|
return { result: undefined };
|
|
635
690
|
}
|
|
636
691
|
}
|
|
692
|
+
async function claimExecution(ctx, actionId) {
|
|
693
|
+
const attemptId = randomUUID();
|
|
694
|
+
const body = {
|
|
695
|
+
claim_execution: true,
|
|
696
|
+
attempt_id: attemptId,
|
|
697
|
+
agent_id: ctx.config.agentId,
|
|
698
|
+
...(ctx.classification.act ? { act: ctx.classification.act } : {}),
|
|
699
|
+
};
|
|
700
|
+
let response;
|
|
701
|
+
let payload;
|
|
702
|
+
const controller = new AbortController();
|
|
703
|
+
const timeoutError = new Error(`execution claim timed out after ${EXECUTION_CLAIM_TIMEOUT_MS}ms`);
|
|
704
|
+
const timer = setTimeout(() => controller.abort(timeoutError), EXECUTION_CLAIM_TIMEOUT_MS);
|
|
705
|
+
const aborted = new Promise((_resolve, reject) => {
|
|
706
|
+
controller.signal.addEventListener('abort', () => reject(controller.signal.reason instanceof Error ? controller.signal.reason : timeoutError), { once: true });
|
|
707
|
+
});
|
|
708
|
+
try {
|
|
709
|
+
response = await Promise.race([
|
|
710
|
+
fetch(`${ctx.config.dashclawUrl}/api/actions/${encodeURIComponent(actionId)}`, {
|
|
711
|
+
method: 'PATCH',
|
|
712
|
+
headers: {
|
|
713
|
+
'Content-Type': 'application/json',
|
|
714
|
+
'x-api-key': ctx.config.dashclawApiKey,
|
|
715
|
+
},
|
|
716
|
+
body: JSON.stringify(body),
|
|
717
|
+
signal: controller.signal,
|
|
718
|
+
}),
|
|
719
|
+
aborted,
|
|
720
|
+
]);
|
|
721
|
+
if (!response.ok) {
|
|
722
|
+
return {
|
|
723
|
+
block: true,
|
|
724
|
+
blockReason: `DashClaw execution claim failed (HTTP ${response.status}); reconcile action ${actionId} before retrying.`,
|
|
725
|
+
};
|
|
726
|
+
}
|
|
727
|
+
payload = await Promise.race([response.json(), aborted]);
|
|
728
|
+
}
|
|
729
|
+
catch (err) {
|
|
730
|
+
return {
|
|
731
|
+
block: true,
|
|
732
|
+
blockReason: `DashClaw execution claim failed (${errorMessage(err) || 'response lost'}); ` +
|
|
733
|
+
`reconcile action ${actionId} before retrying.`,
|
|
734
|
+
};
|
|
735
|
+
}
|
|
736
|
+
finally {
|
|
737
|
+
clearTimeout(timer);
|
|
738
|
+
}
|
|
739
|
+
const claimed = payload;
|
|
740
|
+
if (!claimed
|
|
741
|
+
|| claimed.claimed !== true
|
|
742
|
+
|| claimed.action_id !== actionId
|
|
743
|
+
|| claimed.attempt_id !== attemptId) {
|
|
744
|
+
return {
|
|
745
|
+
block: true,
|
|
746
|
+
blockReason: `DashClaw execution claim returned a malformed acknowledgement; ` +
|
|
747
|
+
`reconcile action ${actionId} before retrying.`,
|
|
748
|
+
};
|
|
749
|
+
}
|
|
750
|
+
return undefined;
|
|
751
|
+
}
|
|
637
752
|
async function waitForRequiredApproval(ctx, created) {
|
|
638
753
|
const needsApproval = ctx.decision.decision === 'require_approval' ||
|
|
639
754
|
created.status === 'pending_approval';
|
|
640
|
-
if (!needsApproval
|
|
755
|
+
if (!needsApproval)
|
|
641
756
|
return undefined;
|
|
642
757
|
const timeout = ctx.config.approvalWaitMs;
|
|
643
758
|
try {
|
|
@@ -647,10 +762,7 @@ async function waitForRequiredApproval(ctx, created) {
|
|
|
647
762
|
});
|
|
648
763
|
if (isApproved(action))
|
|
649
764
|
return undefined;
|
|
650
|
-
return {
|
|
651
|
-
block: true,
|
|
652
|
-
blockReason: action?.error_message || 'Action denied by operator',
|
|
653
|
-
};
|
|
765
|
+
return { block: true, blockReason: denialBlockReason(action) };
|
|
654
766
|
}
|
|
655
767
|
catch (err) {
|
|
656
768
|
if (isApprovalTimeout(err)) {
|
|
@@ -665,12 +777,83 @@ async function waitForRequiredApproval(ctx, created) {
|
|
|
665
777
|
`Approve it at ${ctx.config.dashclawUrl}/approvals, then retry this tool call.`,
|
|
666
778
|
};
|
|
667
779
|
}
|
|
780
|
+
if (isApprovalDenial(err)) {
|
|
781
|
+
// The SDK's error text is not used: SDK versions before 5.40.4 build it
|
|
782
|
+
// from `error_message`. Re-read the record and take the note from there.
|
|
783
|
+
if (err.decision === 'expired') {
|
|
784
|
+
return { block: true, blockReason: 'Approval expired before a decision was made' };
|
|
785
|
+
}
|
|
786
|
+
const action = await fetchResolvedAction(ctx, created.actionId);
|
|
787
|
+
return { block: true, blockReason: denialBlockReason(action) };
|
|
788
|
+
}
|
|
668
789
|
return {
|
|
669
790
|
block: true,
|
|
670
791
|
blockReason: `Approval denied or wait failed: ${errorMessage(err) || 'denied'}`,
|
|
671
792
|
};
|
|
672
793
|
}
|
|
673
794
|
}
|
|
795
|
+
const HITL_DENY_MARKER = '[HITL Decision: DENY by ';
|
|
796
|
+
const HITL_DENY_NOTE_PREFIX = '\nReason: ';
|
|
797
|
+
const DENY_NOTE_FETCH_MS = 5000;
|
|
798
|
+
/**
|
|
799
|
+
* The note an approver typed when denying, or ''.
|
|
800
|
+
*
|
|
801
|
+
* Read ONLY from the marker the approvals route appends to `reasoning`: that
|
|
802
|
+
* column is not writable through PATCH /api/actions/:id, while `error_message`
|
|
803
|
+
* is writable by any org key, so relaying it as the block reason would let
|
|
804
|
+
* another agent speak to this one with the operator's voice. The LAST marker
|
|
805
|
+
* is the server's; one the action's creator wrote earlier loses to it.
|
|
806
|
+
*/
|
|
807
|
+
function operatorDenyNote(action) {
|
|
808
|
+
const reasoning = action?.reasoning;
|
|
809
|
+
if (typeof reasoning !== 'string')
|
|
810
|
+
return '';
|
|
811
|
+
// approval_expires_at is stamped by the server only on a row created
|
|
812
|
+
// pending_approval. A row created already failed never met an approver, so a
|
|
813
|
+
// marker in it was written by whoever created it.
|
|
814
|
+
if (action?.approval_expires_at == null)
|
|
815
|
+
return '';
|
|
816
|
+
const at = reasoning.lastIndexOf(HITL_DENY_MARKER);
|
|
817
|
+
if (at < 0)
|
|
818
|
+
return '';
|
|
819
|
+
const close = reasoning.indexOf(']', at);
|
|
820
|
+
if (close < 0 || !reasoning.startsWith(HITL_DENY_NOTE_PREFIX, close + 1))
|
|
821
|
+
return '';
|
|
822
|
+
const note = reasoning
|
|
823
|
+
.slice(close + 1 + HITL_DENY_NOTE_PREFIX.length)
|
|
824
|
+
// eslint-disable-next-line no-control-regex
|
|
825
|
+
.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, '')
|
|
826
|
+
.trim();
|
|
827
|
+
// Cut by code point: a UTF-16 slice can end on half of a surrogate pair.
|
|
828
|
+
return Array.from(note).slice(0, 500).join('');
|
|
829
|
+
}
|
|
830
|
+
function denialBlockReason(action) {
|
|
831
|
+
if (action?.status === 'expired')
|
|
832
|
+
return 'Approval expired before a decision was made';
|
|
833
|
+
const note = operatorDenyNote(action);
|
|
834
|
+
return note ? `Denied by operator: ${note}` : 'Action denied by operator';
|
|
835
|
+
}
|
|
836
|
+
function isApprovalDenial(err) {
|
|
837
|
+
return typeof err === 'object' && err !== null
|
|
838
|
+
&& err.name === 'ApprovalDeniedError';
|
|
839
|
+
}
|
|
840
|
+
/** Re-read a resolved action, bounded so a slow server cannot outlast the tool-call watchdog. */
|
|
841
|
+
async function fetchResolvedAction(ctx, actionId) {
|
|
842
|
+
let timer;
|
|
843
|
+
try {
|
|
844
|
+
const fetched = ctx.client.getAction(actionId).catch(() => undefined);
|
|
845
|
+
const bound = new Promise((resolve) => {
|
|
846
|
+
timer = setTimeout(() => resolve(undefined), DENY_NOTE_FETCH_MS);
|
|
847
|
+
});
|
|
848
|
+
return (await Promise.race([fetched, bound]))?.action;
|
|
849
|
+
}
|
|
850
|
+
catch {
|
|
851
|
+
return undefined;
|
|
852
|
+
}
|
|
853
|
+
finally {
|
|
854
|
+
clearTimeout(timer);
|
|
855
|
+
}
|
|
856
|
+
}
|
|
674
857
|
/** Sample the approval at least ~4 times inside the window; keep the SDK's 5s ceiling. */
|
|
675
858
|
function approvalPollInterval(timeoutMs) {
|
|
676
859
|
return Math.min(5000, Math.max(50, Math.floor(timeoutMs / 4)));
|
package/openclaw.plugin.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"id": "dashclaw-governance",
|
|
3
3
|
"name": "DashClaw Governance",
|
|
4
|
-
"description": "Policy
|
|
5
|
-
"version": "1.6.
|
|
4
|
+
"description": "Policy checks, remote approvals, and execution claims at OpenClaw's supported tool hook boundary.",
|
|
5
|
+
"version": "1.6.5",
|
|
6
6
|
"entry": "dist/index.js",
|
|
7
7
|
"main": "./dist/index.js",
|
|
8
8
|
"configSchema": {
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dashclaw/openclaw-plugin",
|
|
3
|
-
"version": "1.6.
|
|
4
|
-
"description": "DashClaw
|
|
3
|
+
"version": "1.6.5",
|
|
4
|
+
"description": "DashClaw policy checks, remote approvals, and execution claims at OpenClaw's supported tool hook boundary.",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
7
7
|
"type": "module",
|
|
@@ -73,7 +73,7 @@
|
|
|
73
73
|
"uuid": "^11.1.1"
|
|
74
74
|
},
|
|
75
75
|
"brace-expansion": "^5.0.8",
|
|
76
|
-
"@hono/node-server": "^1.
|
|
76
|
+
"@hono/node-server": "^2.1.3",
|
|
77
77
|
"fast-uri": "^3.1.4",
|
|
78
78
|
"hono": "^4.12.34"
|
|
79
79
|
}
|
package/src/HOOK.md
CHANGED
|
@@ -1,17 +1,18 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: dashclaw-governance
|
|
3
|
-
description: Policy
|
|
4
|
-
version: 1.5
|
|
3
|
+
description: Policy checks, remote approvals, and execution claims at OpenClaw's supported tool hook boundary.
|
|
4
|
+
version: 1.6.5
|
|
5
5
|
---
|
|
6
6
|
|
|
7
7
|
# DashClaw Governance Hook
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
Governs tool calls delivered to OpenClaw's installed `before_tool_call` hook through a five-step loop. Calls outside that host hook are outside this enforcement boundary:
|
|
10
10
|
|
|
11
11
|
1. **Guard** — `before_tool_call` sends the tool name, risk score, and a 500-character parameter summary to DashClaw `/api/guard`. Policies decide `allow`, `warn`, `block`, or `require_approval`.
|
|
12
12
|
2. **Record** — On `allow`/`warn`/`require_approval`, the hook opens a governance record via `/api/actions`. The server is authoritative — it may upgrade an `allow` decision to `pending_approval` for capabilities that require human review.
|
|
13
13
|
3. **Wait** — For `pending_approval` actions, the hook calls `waitForApproval(action_id)` using the **action_records ID from step 2**, not the `guard_decisions` ID from step 1. Operators approve from the DashClaw dashboard, CLI, or mobile PWA. The wait is bounded by `approvalWaitMs` (default 60s — under Codex's ~90s per-tool-call RPC watchdog); on timeout the call blocks with a retry hint while the approval stays open ~300s server-side, so approving late and retrying the same call still works.
|
|
14
|
-
4. **
|
|
14
|
+
4. **Claim** — When the guard advertises execution-claim protocol 1, the hook claims the exact action once immediately before returning control to the host. A lost, rejected, or malformed claim blocks the call and is never retried automatically. Servers that do not advertise claims retain the existing policy and approval flow during the staged rollout. Set `DASHCLAW_REQUIRE_EXECUTION_CLAIMS=1` after the server upgrade to reject legacy responses.
|
|
15
|
+
5. **Outcome** — `after_tool_call` records `completed` or `failed` with the error message, giving DashClaw a full intent → policy → outcome trail.
|
|
15
16
|
|
|
16
17
|
On the first tool call of a run the plugin also opens a DashClaw **Agent Session** (`POST /api/sessions`), and closes it (`PATCH /api/sessions/:id` → `status: completed`) on `agent_end`, so each OpenClaw run appears under the Agent Sessions feature. Session calls are fully fail-safe — a session error never blocks a tool call or the run.
|
|
17
18
|
|
|
@@ -27,13 +28,16 @@ The plugin accepts three interchangeable configuration shapes — pick whichever
|
|
|
27
28
|
|
|
28
29
|
Precedence is `plugin config > env vars`. If env vars are set before the gateway starts, the plugin config can omit URL and API key entirely.
|
|
29
30
|
|
|
30
|
-
See the `configSchema` section in `openclaw.plugin.json` for the full list of optional fields (`agentId`, `failClosed`, `riskScoreDefault`, `highRiskTools`, `approvalWaitMs`).
|
|
31
|
+
See the `configSchema` section in `openclaw.plugin.json` for the full list of optional fields (`agentId`, `failClosed`, `riskScoreDefault`, `highRiskTools`, `approvalWaitMs`). `DASHCLAW_REQUIRE_EXECUTION_CLAIMS=1` is an environment-only rollout pin: enable it after the server supports protocol 1 to reject legacy responses that omit claim negotiation.
|
|
31
32
|
|
|
32
33
|
## Failure modes
|
|
33
34
|
|
|
34
35
|
- If `createAction` fails and `failClosed=true` (default), the tool call is blocked with a clear reason.
|
|
35
36
|
- If `failClosed=false`, the tool call proceeds ungoverned with a warning in the console.
|
|
36
37
|
- If the guard verdict is `block`, no action record is opened — the tool call is hard-stopped and no governance row is created.
|
|
38
|
+
- A server that omits both claim fields retains the legacy guard and approval flow unless strict mode is set. Partial, malformed, or unknown claim advertisements always block.
|
|
39
|
+
- A lost, rejected, or malformed protocol-1 claim acknowledgement blocks the call and is never retried automatically.
|
|
40
|
+
- If the tool runs but outcome recording fails, completion is unknown. Reconcile the external system before retrying the effect.
|
|
37
41
|
|
|
38
42
|
## See also
|
|
39
43
|
|
package/src/dashclaw.d.ts
CHANGED
|
@@ -17,6 +17,8 @@ declare module 'dashclaw' {
|
|
|
17
17
|
action_id: string;
|
|
18
18
|
reason?: string;
|
|
19
19
|
signals?: string[];
|
|
20
|
+
execution_claim_required?: boolean;
|
|
21
|
+
claim_protocol?: number;
|
|
20
22
|
}
|
|
21
23
|
|
|
22
24
|
export interface ActionRecord {
|
|
@@ -57,6 +59,7 @@ declare module 'dashclaw' {
|
|
|
57
59
|
actionId: string,
|
|
58
60
|
opts?: { timeout?: number; interval?: number }
|
|
59
61
|
): Promise<WaitForApprovalResult>;
|
|
62
|
+
getAction(actionId: string): Promise<{ action?: ActionRecord; [key: string]: unknown }>;
|
|
60
63
|
recordAssumption(assumption: Record<string, unknown>): Promise<unknown>;
|
|
61
64
|
createSession(
|
|
62
65
|
agentId?: string,
|
package/src/index.ts
CHANGED
|
@@ -30,6 +30,7 @@ import {
|
|
|
30
30
|
type GuardDecision,
|
|
31
31
|
} from 'dashclaw';
|
|
32
32
|
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
33
|
+
import { randomUUID } from 'node:crypto';
|
|
33
34
|
import { resolve as resolvePath } from 'node:path';
|
|
34
35
|
import { maybeAutoPair } from './auto-pairing.js';
|
|
35
36
|
import { runLivenessProbe, shouldProbeNow, PROBE_AGENT_ID } from './liveness-probe.js';
|
|
@@ -48,6 +49,7 @@ interface PluginConfig {
|
|
|
48
49
|
// but no cost" failure mode. Empty string disables the fallback.
|
|
49
50
|
defaultModel: string;
|
|
50
51
|
failClosed: boolean;
|
|
52
|
+
requireExecutionClaims: boolean;
|
|
51
53
|
autoPairing: boolean;
|
|
52
54
|
riskScoreDefault: number;
|
|
53
55
|
highRiskTools: ReadonlySet<string>;
|
|
@@ -95,11 +97,16 @@ function numberFromConfig(
|
|
|
95
97
|
return value;
|
|
96
98
|
}
|
|
97
99
|
|
|
100
|
+
function enabledEnvFlag(value: unknown): boolean {
|
|
101
|
+
return typeof value === 'string' && ['1', 'true'].includes(value.toLowerCase());
|
|
102
|
+
}
|
|
103
|
+
|
|
98
104
|
function resolveConfig(raw: Record<string, unknown> | undefined): PluginConfig {
|
|
99
105
|
const cfg = raw ?? {};
|
|
100
106
|
const env = typeof process !== 'undefined' && process?.env ? process.env : {};
|
|
101
107
|
|
|
102
108
|
const failClosed = cfg.failClosed !== false; // default true
|
|
109
|
+
const requireExecutionClaims = enabledEnvFlag(env.DASHCLAW_REQUIRE_EXECUTION_CLAIMS);
|
|
103
110
|
const autoPairing = cfg.autoPairing !== false; // default true
|
|
104
111
|
const riskScoreDefault = numberFromConfig(cfg.riskScoreDefault, 50);
|
|
105
112
|
const highRiskTools = stringSetFromConfig(cfg.highRiskTools);
|
|
@@ -128,6 +135,7 @@ function resolveConfig(raw: Record<string, unknown> | undefined): PluginConfig {
|
|
|
128
135
|
agentId,
|
|
129
136
|
defaultModel,
|
|
130
137
|
failClosed,
|
|
138
|
+
requireExecutionClaims,
|
|
131
139
|
autoPairing,
|
|
132
140
|
riskScoreDefault,
|
|
133
141
|
highRiskTools,
|
|
@@ -666,7 +674,7 @@ interface AgentEndContext {
|
|
|
666
674
|
}
|
|
667
675
|
|
|
668
676
|
interface CreatedAction {
|
|
669
|
-
actionId
|
|
677
|
+
actionId: string;
|
|
670
678
|
status?: string;
|
|
671
679
|
}
|
|
672
680
|
|
|
@@ -732,6 +740,14 @@ async function handleBeforeToolCall(
|
|
|
732
740
|
): Promise<HookResult> {
|
|
733
741
|
const { toolName, params, toolCallId, runId } = event;
|
|
734
742
|
const key = callKey(toolName, toolCallId, runId);
|
|
743
|
+
if (!toolCallId && pendingActions.has(key)) {
|
|
744
|
+
return {
|
|
745
|
+
block: true,
|
|
746
|
+
blockReason:
|
|
747
|
+
'OpenClaw did not provide a stable tool call ID and another matching call is still open. ' +
|
|
748
|
+
'Execution was interrupted because its outcome could not be correlated safely.',
|
|
749
|
+
};
|
|
750
|
+
}
|
|
735
751
|
const workspace = typeof event.workspace === 'string' ? event.workspace : undefined;
|
|
736
752
|
const classification = classifyToolCall(toolName, params, config, workspace);
|
|
737
753
|
|
|
@@ -805,18 +821,27 @@ async function guardClassifiedAction(
|
|
|
805
821
|
client: DashClaw,
|
|
806
822
|
classification: ActionClassification,
|
|
807
823
|
config: PluginConfig,
|
|
808
|
-
): Promise<{ value:
|
|
824
|
+
): Promise<{ value: ClaimAwareGuardDecision } | { result: HookResult }> {
|
|
809
825
|
try {
|
|
810
|
-
|
|
811
|
-
value: await client.guard({
|
|
826
|
+
const raw = await client.guard({
|
|
812
827
|
action_type: classification.actionType,
|
|
813
828
|
risk_score: classification.riskScore,
|
|
814
829
|
declared_goal: classification.declaredGoal,
|
|
815
830
|
reversible: classification.reversible,
|
|
816
831
|
systems_touched: classification.systemsTouched,
|
|
832
|
+
client_capabilities: ['execution_claims'],
|
|
817
833
|
...(classification.act ? { act: classification.act } : {}),
|
|
818
|
-
})
|
|
819
|
-
|
|
834
|
+
});
|
|
835
|
+
const validated = validateGuardDecision(raw, config.requireExecutionClaims);
|
|
836
|
+
if ('reason' in validated) {
|
|
837
|
+
return {
|
|
838
|
+
result: {
|
|
839
|
+
block: true,
|
|
840
|
+
blockReason: validated.reason,
|
|
841
|
+
},
|
|
842
|
+
};
|
|
843
|
+
}
|
|
844
|
+
return { value: validated.value };
|
|
820
845
|
} catch (err) {
|
|
821
846
|
const msg = errorMessage(err) || 'unknown error';
|
|
822
847
|
if (config.failClosed) {
|
|
@@ -832,6 +857,38 @@ async function guardClassifiedAction(
|
|
|
832
857
|
}
|
|
833
858
|
}
|
|
834
859
|
|
|
860
|
+
type ClaimAwareGuardDecision = GuardDecision & {
|
|
861
|
+
execution_claim_required?: boolean;
|
|
862
|
+
claim_protocol?: number;
|
|
863
|
+
};
|
|
864
|
+
|
|
865
|
+
const GUARD_DECISIONS = new Set(['allow', 'block', 'warn', 'require_approval']);
|
|
866
|
+
const EXECUTION_CLAIM_TIMEOUT_MS = 30_000;
|
|
867
|
+
|
|
868
|
+
function validateGuardDecision(value: unknown, requireExecutionClaims: boolean):
|
|
869
|
+
| { value: ClaimAwareGuardDecision }
|
|
870
|
+
| { reason: string } {
|
|
871
|
+
if (!value || typeof value !== 'object') {
|
|
872
|
+
return { reason: 'DashClaw returned a malformed guard response; tool execution was interrupted.' };
|
|
873
|
+
}
|
|
874
|
+
const response = value as Record<string, unknown>;
|
|
875
|
+
if (typeof response.decision !== 'string' || !GUARD_DECISIONS.has(response.decision)) {
|
|
876
|
+
return { reason: 'DashClaw returned a malformed or unknown guard decision; tool execution was interrupted.' };
|
|
877
|
+
}
|
|
878
|
+
if (response.decision === 'block') {
|
|
879
|
+
return { value: value as ClaimAwareGuardDecision };
|
|
880
|
+
}
|
|
881
|
+
const advertised = 'execution_claim_required' in response || 'claim_protocol' in response;
|
|
882
|
+
const validClaims = response.execution_claim_required === true && response.claim_protocol === 1;
|
|
883
|
+
if ((requireExecutionClaims || advertised) && !validClaims) {
|
|
884
|
+
return {
|
|
885
|
+
reason:
|
|
886
|
+
'DashClaw server upgrade required: execution-claim protocol 1 was not advertised, so this tool call cannot run safely.',
|
|
887
|
+
};
|
|
888
|
+
}
|
|
889
|
+
return { value: value as ClaimAwareGuardDecision };
|
|
890
|
+
}
|
|
891
|
+
|
|
835
892
|
function blockResultForDecision(
|
|
836
893
|
decision: GuardDecision,
|
|
837
894
|
toolName: string,
|
|
@@ -853,7 +910,7 @@ function blockResultForDecision(
|
|
|
853
910
|
interface OpenActionContext {
|
|
854
911
|
client: DashClaw;
|
|
855
912
|
classification: ActionClassification;
|
|
856
|
-
decision:
|
|
913
|
+
decision: ClaimAwareGuardDecision;
|
|
857
914
|
toolName: string;
|
|
858
915
|
key: string;
|
|
859
916
|
runId?: string;
|
|
@@ -866,6 +923,10 @@ async function openActionRecord(ctx: OpenActionContext): Promise<HookResult> {
|
|
|
866
923
|
|
|
867
924
|
const approval = await waitForRequiredApproval(ctx, created.value);
|
|
868
925
|
if (approval) return approval;
|
|
926
|
+
if (ctx.decision.execution_claim_required === true && ctx.decision.claim_protocol === 1) {
|
|
927
|
+
const claim = await claimExecution(ctx, created.value.actionId);
|
|
928
|
+
if (claim) return claim;
|
|
929
|
+
}
|
|
869
930
|
rememberPendingAction(ctx.key, created.value.actionId, ctx.runId);
|
|
870
931
|
return;
|
|
871
932
|
}
|
|
@@ -882,15 +943,21 @@ async function createGovernanceAction(
|
|
|
882
943
|
risk_score: riskScore,
|
|
883
944
|
reversible,
|
|
884
945
|
systems_touched: systemsTouched,
|
|
946
|
+
client_capabilities: ['execution_claims'],
|
|
885
947
|
...(ctx.classification.act ? { act: ctx.classification.act } : {}),
|
|
886
948
|
metadata: { openclaw_tool_name: ctx.toolName },
|
|
887
949
|
});
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
950
|
+
const ids = [created.action_id, created.action?.action_id, created.action?.id]
|
|
951
|
+
.filter((id): id is string => typeof id === 'string' && id.length > 0);
|
|
952
|
+
if (ids.length === 0 || new Set(ids).size !== 1) {
|
|
953
|
+
return {
|
|
954
|
+
result: {
|
|
955
|
+
block: true,
|
|
956
|
+
blockReason: 'DashClaw action response did not contain one exact action ID; tool execution was interrupted.',
|
|
957
|
+
},
|
|
958
|
+
};
|
|
959
|
+
}
|
|
960
|
+
return { value: { actionId: ids[0], status: created.action?.status } };
|
|
894
961
|
} catch (err) {
|
|
895
962
|
const msg = errorMessage(err) || 'unknown';
|
|
896
963
|
console.warn(`[dashclaw-governance] createAction failed: ${msg}`);
|
|
@@ -906,6 +973,82 @@ async function createGovernanceAction(
|
|
|
906
973
|
}
|
|
907
974
|
}
|
|
908
975
|
|
|
976
|
+
async function claimExecution(
|
|
977
|
+
ctx: OpenActionContext,
|
|
978
|
+
actionId: string,
|
|
979
|
+
): Promise<HookBlockResult | undefined> {
|
|
980
|
+
const attemptId = randomUUID();
|
|
981
|
+
const body = {
|
|
982
|
+
claim_execution: true,
|
|
983
|
+
attempt_id: attemptId,
|
|
984
|
+
agent_id: ctx.config.agentId,
|
|
985
|
+
...(ctx.classification.act ? { act: ctx.classification.act } : {}),
|
|
986
|
+
};
|
|
987
|
+
let response: Response;
|
|
988
|
+
let payload: unknown;
|
|
989
|
+
const controller = new AbortController();
|
|
990
|
+
const timeoutError = new Error(
|
|
991
|
+
`execution claim timed out after ${EXECUTION_CLAIM_TIMEOUT_MS}ms`
|
|
992
|
+
);
|
|
993
|
+
const timer = setTimeout(
|
|
994
|
+
() => controller.abort(timeoutError),
|
|
995
|
+
EXECUTION_CLAIM_TIMEOUT_MS
|
|
996
|
+
);
|
|
997
|
+
const aborted = new Promise<never>((_resolve, reject) => {
|
|
998
|
+
controller.signal.addEventListener(
|
|
999
|
+
'abort',
|
|
1000
|
+
() => reject(controller.signal.reason instanceof Error ? controller.signal.reason : timeoutError),
|
|
1001
|
+
{ once: true }
|
|
1002
|
+
);
|
|
1003
|
+
});
|
|
1004
|
+
try {
|
|
1005
|
+
response = await Promise.race([
|
|
1006
|
+
fetch(
|
|
1007
|
+
`${ctx.config.dashclawUrl}/api/actions/${encodeURIComponent(actionId)}`,
|
|
1008
|
+
{
|
|
1009
|
+
method: 'PATCH',
|
|
1010
|
+
headers: {
|
|
1011
|
+
'Content-Type': 'application/json',
|
|
1012
|
+
'x-api-key': ctx.config.dashclawApiKey,
|
|
1013
|
+
},
|
|
1014
|
+
body: JSON.stringify(body),
|
|
1015
|
+
signal: controller.signal,
|
|
1016
|
+
},
|
|
1017
|
+
),
|
|
1018
|
+
aborted,
|
|
1019
|
+
]);
|
|
1020
|
+
if (!response.ok) {
|
|
1021
|
+
return {
|
|
1022
|
+
block: true,
|
|
1023
|
+
blockReason: `DashClaw execution claim failed (HTTP ${response.status}); reconcile action ${actionId} before retrying.`,
|
|
1024
|
+
};
|
|
1025
|
+
}
|
|
1026
|
+
payload = await Promise.race([response.json(), aborted]);
|
|
1027
|
+
} catch (err) {
|
|
1028
|
+
return {
|
|
1029
|
+
block: true,
|
|
1030
|
+
blockReason:
|
|
1031
|
+
`DashClaw execution claim failed (${errorMessage(err) || 'response lost'}); ` +
|
|
1032
|
+
`reconcile action ${actionId} before retrying.`,
|
|
1033
|
+
};
|
|
1034
|
+
} finally {
|
|
1035
|
+
clearTimeout(timer);
|
|
1036
|
+
}
|
|
1037
|
+
const claimed = payload as Record<string, unknown> | null;
|
|
1038
|
+
if (!claimed
|
|
1039
|
+
|| claimed.claimed !== true
|
|
1040
|
+
|| claimed.action_id !== actionId
|
|
1041
|
+
|| claimed.attempt_id !== attemptId) {
|
|
1042
|
+
return {
|
|
1043
|
+
block: true,
|
|
1044
|
+
blockReason:
|
|
1045
|
+
`DashClaw execution claim returned a malformed acknowledgement; ` +
|
|
1046
|
+
`reconcile action ${actionId} before retrying.`,
|
|
1047
|
+
};
|
|
1048
|
+
}
|
|
1049
|
+
return undefined;
|
|
1050
|
+
}
|
|
1051
|
+
|
|
909
1052
|
async function waitForRequiredApproval(
|
|
910
1053
|
ctx: OpenActionContext,
|
|
911
1054
|
created: CreatedAction,
|
|
@@ -913,7 +1056,7 @@ async function waitForRequiredApproval(
|
|
|
913
1056
|
const needsApproval =
|
|
914
1057
|
ctx.decision.decision === 'require_approval' ||
|
|
915
1058
|
created.status === 'pending_approval';
|
|
916
|
-
if (!needsApproval
|
|
1059
|
+
if (!needsApproval) return undefined;
|
|
917
1060
|
|
|
918
1061
|
const timeout = ctx.config.approvalWaitMs;
|
|
919
1062
|
try {
|
|
@@ -922,10 +1065,7 @@ async function waitForRequiredApproval(
|
|
|
922
1065
|
interval: approvalPollInterval(timeout),
|
|
923
1066
|
});
|
|
924
1067
|
if (isApproved(action)) return undefined;
|
|
925
|
-
return {
|
|
926
|
-
block: true,
|
|
927
|
-
blockReason: action?.error_message || 'Action denied by operator',
|
|
928
|
-
};
|
|
1068
|
+
return { block: true, blockReason: denialBlockReason(action) };
|
|
929
1069
|
} catch (err) {
|
|
930
1070
|
if (isApprovalTimeout(err)) {
|
|
931
1071
|
// The server keeps the approval open past this bounded wait
|
|
@@ -940,6 +1080,15 @@ async function waitForRequiredApproval(
|
|
|
940
1080
|
`Approve it at ${ctx.config.dashclawUrl}/approvals, then retry this tool call.`,
|
|
941
1081
|
};
|
|
942
1082
|
}
|
|
1083
|
+
if (isApprovalDenial(err)) {
|
|
1084
|
+
// The SDK's error text is not used: SDK versions before 5.40.4 build it
|
|
1085
|
+
// from `error_message`. Re-read the record and take the note from there.
|
|
1086
|
+
if (err.decision === 'expired') {
|
|
1087
|
+
return { block: true, blockReason: 'Approval expired before a decision was made' };
|
|
1088
|
+
}
|
|
1089
|
+
const action = await fetchResolvedAction(ctx, created.actionId);
|
|
1090
|
+
return { block: true, blockReason: denialBlockReason(action) };
|
|
1091
|
+
}
|
|
943
1092
|
return {
|
|
944
1093
|
block: true,
|
|
945
1094
|
blockReason: `Approval denied or wait failed: ${errorMessage(err) || 'denied'}`,
|
|
@@ -947,6 +1096,69 @@ async function waitForRequiredApproval(
|
|
|
947
1096
|
}
|
|
948
1097
|
}
|
|
949
1098
|
|
|
1099
|
+
const HITL_DENY_MARKER = '[HITL Decision: DENY by ';
|
|
1100
|
+
const HITL_DENY_NOTE_PREFIX = '\nReason: ';
|
|
1101
|
+
const DENY_NOTE_FETCH_MS = 5000;
|
|
1102
|
+
|
|
1103
|
+
/**
|
|
1104
|
+
* The note an approver typed when denying, or ''.
|
|
1105
|
+
*
|
|
1106
|
+
* Read ONLY from the marker the approvals route appends to `reasoning`: that
|
|
1107
|
+
* column is not writable through PATCH /api/actions/:id, while `error_message`
|
|
1108
|
+
* is writable by any org key, so relaying it as the block reason would let
|
|
1109
|
+
* another agent speak to this one with the operator's voice. The LAST marker
|
|
1110
|
+
* is the server's; one the action's creator wrote earlier loses to it.
|
|
1111
|
+
*/
|
|
1112
|
+
function operatorDenyNote(action: ActionRecord | undefined): string {
|
|
1113
|
+
const reasoning = action?.reasoning;
|
|
1114
|
+
if (typeof reasoning !== 'string') return '';
|
|
1115
|
+
// approval_expires_at is stamped by the server only on a row created
|
|
1116
|
+
// pending_approval. A row created already failed never met an approver, so a
|
|
1117
|
+
// marker in it was written by whoever created it.
|
|
1118
|
+
if (action?.approval_expires_at == null) return '';
|
|
1119
|
+
const at = reasoning.lastIndexOf(HITL_DENY_MARKER);
|
|
1120
|
+
if (at < 0) return '';
|
|
1121
|
+
const close = reasoning.indexOf(']', at);
|
|
1122
|
+
if (close < 0 || !reasoning.startsWith(HITL_DENY_NOTE_PREFIX, close + 1)) return '';
|
|
1123
|
+
const note = reasoning
|
|
1124
|
+
.slice(close + 1 + HITL_DENY_NOTE_PREFIX.length)
|
|
1125
|
+
// eslint-disable-next-line no-control-regex
|
|
1126
|
+
.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, '')
|
|
1127
|
+
.trim();
|
|
1128
|
+
// Cut by code point: a UTF-16 slice can end on half of a surrogate pair.
|
|
1129
|
+
return Array.from(note).slice(0, 500).join('');
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
function denialBlockReason(action: ActionRecord | undefined): string {
|
|
1133
|
+
if (action?.status === 'expired') return 'Approval expired before a decision was made';
|
|
1134
|
+
const note = operatorDenyNote(action);
|
|
1135
|
+
return note ? `Denied by operator: ${note}` : 'Action denied by operator';
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
function isApprovalDenial(err: unknown): err is { name: string; decision?: unknown } {
|
|
1139
|
+
return typeof err === 'object' && err !== null
|
|
1140
|
+
&& (err as { name?: unknown }).name === 'ApprovalDeniedError';
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
/** Re-read a resolved action, bounded so a slow server cannot outlast the tool-call watchdog. */
|
|
1144
|
+
async function fetchResolvedAction(
|
|
1145
|
+
ctx: OpenActionContext,
|
|
1146
|
+
actionId: string,
|
|
1147
|
+
): Promise<ActionRecord | undefined> {
|
|
1148
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
1149
|
+
try {
|
|
1150
|
+
const fetched = ctx.client.getAction(actionId).catch(() => undefined);
|
|
1151
|
+
const bound = new Promise<undefined>((resolve) => {
|
|
1152
|
+
timer = setTimeout(() => resolve(undefined), DENY_NOTE_FETCH_MS);
|
|
1153
|
+
});
|
|
1154
|
+
return (await Promise.race([fetched, bound]))?.action;
|
|
1155
|
+
} catch {
|
|
1156
|
+
return undefined;
|
|
1157
|
+
} finally {
|
|
1158
|
+
clearTimeout(timer);
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
|
|
950
1162
|
/** Sample the approval at least ~4 times inside the window; keep the SDK's 5s ceiling. */
|
|
951
1163
|
function approvalPollInterval(timeoutMs: number): number {
|
|
952
1164
|
return Math.min(5000, Math.max(50, Math.floor(timeoutMs / 4)));
|