@dashclaw/openclaw-plugin 1.6.4 → 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/dist/index.js +72 -4
- package/openclaw.plugin.json +1 -1
- package/package.json +2 -2
- package/src/HOOK.md +1 -1
- package/src/dashclaw.d.ts +5 -4
- package/src/index.ts +273 -204
package/dist/index.js
CHANGED
|
@@ -762,10 +762,7 @@ async function waitForRequiredApproval(ctx, created) {
|
|
|
762
762
|
});
|
|
763
763
|
if (isApproved(action))
|
|
764
764
|
return undefined;
|
|
765
|
-
return {
|
|
766
|
-
block: true,
|
|
767
|
-
blockReason: action?.error_message || 'Action denied by operator',
|
|
768
|
-
};
|
|
765
|
+
return { block: true, blockReason: denialBlockReason(action) };
|
|
769
766
|
}
|
|
770
767
|
catch (err) {
|
|
771
768
|
if (isApprovalTimeout(err)) {
|
|
@@ -780,12 +777,83 @@ async function waitForRequiredApproval(ctx, created) {
|
|
|
780
777
|
`Approve it at ${ctx.config.dashclawUrl}/approvals, then retry this tool call.`,
|
|
781
778
|
};
|
|
782
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
|
+
}
|
|
783
789
|
return {
|
|
784
790
|
block: true,
|
|
785
791
|
blockReason: `Approval denied or wait failed: ${errorMessage(err) || 'denied'}`,
|
|
786
792
|
};
|
|
787
793
|
}
|
|
788
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
|
+
}
|
|
789
857
|
/** Sample the approval at least ~4 times inside the window; keep the SDK's 5s ceiling. */
|
|
790
858
|
function approvalPollInterval(timeoutMs) {
|
|
791
859
|
return Math.min(5000, Math.max(50, Math.floor(timeoutMs / 4)));
|
package/openclaw.plugin.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"id": "dashclaw-governance",
|
|
3
3
|
"name": "DashClaw Governance",
|
|
4
4
|
"description": "Policy checks, remote approvals, and execution claims at OpenClaw's supported tool hook boundary.",
|
|
5
|
-
"version": "1.6.
|
|
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,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dashclaw/openclaw-plugin",
|
|
3
|
-
"version": "1.6.
|
|
3
|
+
"version": "1.6.5",
|
|
4
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",
|
|
@@ -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
package/src/dashclaw.d.ts
CHANGED
|
@@ -15,10 +15,10 @@ declare module 'dashclaw' {
|
|
|
15
15
|
export interface GuardDecision {
|
|
16
16
|
decision: 'allow' | 'block' | 'warn' | 'require_approval';
|
|
17
17
|
action_id: string;
|
|
18
|
-
reason?: string;
|
|
19
|
-
signals?: string[];
|
|
20
|
-
execution_claim_required?: boolean;
|
|
21
|
-
claim_protocol?: number;
|
|
18
|
+
reason?: string;
|
|
19
|
+
signals?: string[];
|
|
20
|
+
execution_claim_required?: boolean;
|
|
21
|
+
claim_protocol?: number;
|
|
22
22
|
}
|
|
23
23
|
|
|
24
24
|
export interface ActionRecord {
|
|
@@ -59,6 +59,7 @@ declare module 'dashclaw' {
|
|
|
59
59
|
actionId: string,
|
|
60
60
|
opts?: { timeout?: number; interval?: number }
|
|
61
61
|
): Promise<WaitForApprovalResult>;
|
|
62
|
+
getAction(actionId: string): Promise<{ action?: ActionRecord; [key: string]: unknown }>;
|
|
62
63
|
recordAssumption(assumption: Record<string, unknown>): Promise<unknown>;
|
|
63
64
|
createSession(
|
|
64
65
|
agentId?: string,
|
package/src/index.ts
CHANGED
|
@@ -29,8 +29,8 @@ import {
|
|
|
29
29
|
type ActionRecord,
|
|
30
30
|
type GuardDecision,
|
|
31
31
|
} from 'dashclaw';
|
|
32
|
-
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
33
|
-
import { randomUUID } from 'node:crypto';
|
|
32
|
+
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
33
|
+
import { randomUUID } from 'node:crypto';
|
|
34
34
|
import { resolve as resolvePath } from 'node:path';
|
|
35
35
|
import { maybeAutoPair } from './auto-pairing.js';
|
|
36
36
|
import { runLivenessProbe, shouldProbeNow, PROBE_AGENT_ID } from './liveness-probe.js';
|
|
@@ -47,10 +47,10 @@ interface PluginConfig {
|
|
|
47
47
|
// field. Without this, the server's `estimateCost` treats the usage as
|
|
48
48
|
// unpriceable and stores `cost_estimate = 0` — producing the "tokens
|
|
49
49
|
// but no cost" failure mode. Empty string disables the fallback.
|
|
50
|
-
defaultModel: string;
|
|
51
|
-
failClosed: boolean;
|
|
52
|
-
requireExecutionClaims: boolean;
|
|
53
|
-
autoPairing: boolean;
|
|
50
|
+
defaultModel: string;
|
|
51
|
+
failClosed: boolean;
|
|
52
|
+
requireExecutionClaims: boolean;
|
|
53
|
+
autoPairing: boolean;
|
|
54
54
|
riskScoreDefault: number;
|
|
55
55
|
highRiskTools: ReadonlySet<string>;
|
|
56
56
|
// Bounded human-approval wait. Codex's embedded dynamic-tool RPC enforces a
|
|
@@ -86,7 +86,7 @@ function stringSetFromConfig(value: unknown): ReadonlySet<string> {
|
|
|
86
86
|
);
|
|
87
87
|
}
|
|
88
88
|
|
|
89
|
-
function numberFromConfig(
|
|
89
|
+
function numberFromConfig(
|
|
90
90
|
value: unknown,
|
|
91
91
|
fallback: number,
|
|
92
92
|
allowNegative = true,
|
|
@@ -94,19 +94,19 @@ function numberFromConfig(
|
|
|
94
94
|
if (typeof value !== 'number') return fallback;
|
|
95
95
|
if (!Number.isFinite(value)) return fallback;
|
|
96
96
|
if (!allowNegative && value < 0) return fallback;
|
|
97
|
-
return value;
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
function enabledEnvFlag(value: unknown): boolean {
|
|
101
|
-
return typeof value === 'string' && ['1', 'true'].includes(value.toLowerCase());
|
|
102
|
-
}
|
|
97
|
+
return value;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function enabledEnvFlag(value: unknown): boolean {
|
|
101
|
+
return typeof value === 'string' && ['1', 'true'].includes(value.toLowerCase());
|
|
102
|
+
}
|
|
103
103
|
|
|
104
104
|
function resolveConfig(raw: Record<string, unknown> | undefined): PluginConfig {
|
|
105
105
|
const cfg = raw ?? {};
|
|
106
106
|
const env = typeof process !== 'undefined' && process?.env ? process.env : {};
|
|
107
107
|
|
|
108
|
-
const failClosed = cfg.failClosed !== false; // default true
|
|
109
|
-
const requireExecutionClaims = enabledEnvFlag(env.DASHCLAW_REQUIRE_EXECUTION_CLAIMS);
|
|
108
|
+
const failClosed = cfg.failClosed !== false; // default true
|
|
109
|
+
const requireExecutionClaims = enabledEnvFlag(env.DASHCLAW_REQUIRE_EXECUTION_CLAIMS);
|
|
110
110
|
const autoPairing = cfg.autoPairing !== false; // default true
|
|
111
111
|
const riskScoreDefault = numberFromConfig(cfg.riskScoreDefault, 50);
|
|
112
112
|
const highRiskTools = stringSetFromConfig(cfg.highRiskTools);
|
|
@@ -133,10 +133,10 @@ function resolveConfig(raw: Record<string, unknown> | undefined): PluginConfig {
|
|
|
133
133
|
dashclawUrl,
|
|
134
134
|
dashclawApiKey,
|
|
135
135
|
agentId,
|
|
136
|
-
defaultModel,
|
|
137
|
-
failClosed,
|
|
138
|
-
requireExecutionClaims,
|
|
139
|
-
autoPairing,
|
|
136
|
+
defaultModel,
|
|
137
|
+
failClosed,
|
|
138
|
+
requireExecutionClaims,
|
|
139
|
+
autoPairing,
|
|
140
140
|
riskScoreDefault,
|
|
141
141
|
highRiskTools,
|
|
142
142
|
approvalWaitMs,
|
|
@@ -673,10 +673,10 @@ interface AgentEndContext {
|
|
|
673
673
|
runId?: string;
|
|
674
674
|
}
|
|
675
675
|
|
|
676
|
-
interface CreatedAction {
|
|
677
|
-
actionId: string;
|
|
678
|
-
status?: string;
|
|
679
|
-
}
|
|
676
|
+
interface CreatedAction {
|
|
677
|
+
actionId: string;
|
|
678
|
+
status?: string;
|
|
679
|
+
}
|
|
680
680
|
|
|
681
681
|
function registerGovernanceGate(api: OpenClawPluginApi, config: PluginConfig): void {
|
|
682
682
|
api.on('before_tool_call', async (event, _ctx) =>
|
|
@@ -738,16 +738,16 @@ async function handleBeforeToolCall(
|
|
|
738
738
|
event: ToolCallEvent,
|
|
739
739
|
config: PluginConfig,
|
|
740
740
|
): Promise<HookResult> {
|
|
741
|
-
const { toolName, params, toolCallId, runId } = event;
|
|
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
|
-
}
|
|
741
|
+
const { toolName, params, toolCallId, runId } = event;
|
|
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
|
+
}
|
|
751
751
|
const workspace = typeof event.workspace === 'string' ? event.workspace : undefined;
|
|
752
752
|
const classification = classifyToolCall(toolName, params, config, workspace);
|
|
753
753
|
|
|
@@ -817,31 +817,31 @@ async function maybeStartSession(
|
|
|
817
817
|
}
|
|
818
818
|
}
|
|
819
819
|
|
|
820
|
-
async function guardClassifiedAction(
|
|
821
|
-
client: DashClaw,
|
|
822
|
-
classification: ActionClassification,
|
|
823
|
-
config: PluginConfig,
|
|
824
|
-
): Promise<{ value: ClaimAwareGuardDecision } | { result: HookResult }> {
|
|
825
|
-
try {
|
|
826
|
-
const raw = await client.guard({
|
|
827
|
-
action_type: classification.actionType,
|
|
828
|
-
risk_score: classification.riskScore,
|
|
829
|
-
declared_goal: classification.declaredGoal,
|
|
830
|
-
reversible: classification.reversible,
|
|
831
|
-
systems_touched: classification.systemsTouched,
|
|
832
|
-
client_capabilities: ['execution_claims'],
|
|
833
|
-
...(classification.act ? { act: classification.act } : {}),
|
|
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
|
+
async function guardClassifiedAction(
|
|
821
|
+
client: DashClaw,
|
|
822
|
+
classification: ActionClassification,
|
|
823
|
+
config: PluginConfig,
|
|
824
|
+
): Promise<{ value: ClaimAwareGuardDecision } | { result: HookResult }> {
|
|
825
|
+
try {
|
|
826
|
+
const raw = await client.guard({
|
|
827
|
+
action_type: classification.actionType,
|
|
828
|
+
risk_score: classification.riskScore,
|
|
829
|
+
declared_goal: classification.declaredGoal,
|
|
830
|
+
reversible: classification.reversible,
|
|
831
|
+
systems_touched: classification.systemsTouched,
|
|
832
|
+
client_capabilities: ['execution_claims'],
|
|
833
|
+
...(classification.act ? { act: classification.act } : {}),
|
|
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 };
|
|
845
845
|
} catch (err) {
|
|
846
846
|
const msg = errorMessage(err) || 'unknown error';
|
|
847
847
|
if (config.failClosed) {
|
|
@@ -854,40 +854,40 @@ async function guardClassifiedAction(
|
|
|
854
854
|
}
|
|
855
855
|
console.warn(`[dashclaw-governance] guard call failed (fail-open): ${msg}`);
|
|
856
856
|
return { result: undefined };
|
|
857
|
-
}
|
|
858
|
-
}
|
|
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
|
-
}
|
|
857
|
+
}
|
|
858
|
+
}
|
|
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
891
|
|
|
892
892
|
function blockResultForDecision(
|
|
893
893
|
decision: GuardDecision,
|
|
@@ -907,27 +907,27 @@ function blockResultForDecision(
|
|
|
907
907
|
return undefined;
|
|
908
908
|
}
|
|
909
909
|
|
|
910
|
-
interface OpenActionContext {
|
|
910
|
+
interface OpenActionContext {
|
|
911
911
|
client: DashClaw;
|
|
912
912
|
classification: ActionClassification;
|
|
913
|
-
decision: ClaimAwareGuardDecision;
|
|
913
|
+
decision: ClaimAwareGuardDecision;
|
|
914
914
|
toolName: string;
|
|
915
915
|
key: string;
|
|
916
916
|
runId?: string;
|
|
917
917
|
config: PluginConfig;
|
|
918
918
|
}
|
|
919
919
|
|
|
920
|
-
async function openActionRecord(ctx: OpenActionContext): Promise<HookResult> {
|
|
920
|
+
async function openActionRecord(ctx: OpenActionContext): Promise<HookResult> {
|
|
921
921
|
const created = await createGovernanceAction(ctx);
|
|
922
922
|
if ('result' in created) return created.result;
|
|
923
923
|
|
|
924
|
-
const approval = await waitForRequiredApproval(ctx, created.value);
|
|
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
|
-
}
|
|
930
|
-
rememberPendingAction(ctx.key, created.value.actionId, ctx.runId);
|
|
924
|
+
const approval = await waitForRequiredApproval(ctx, created.value);
|
|
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
|
+
}
|
|
930
|
+
rememberPendingAction(ctx.key, created.value.actionId, ctx.runId);
|
|
931
931
|
return;
|
|
932
932
|
}
|
|
933
933
|
|
|
@@ -940,24 +940,24 @@ async function createGovernanceAction(
|
|
|
940
940
|
const created = await ctx.client.createAction({
|
|
941
941
|
action_type: actionType,
|
|
942
942
|
declared_goal: declaredGoal,
|
|
943
|
-
risk_score: riskScore,
|
|
944
|
-
reversible,
|
|
945
|
-
systems_touched: systemsTouched,
|
|
946
|
-
client_capabilities: ['execution_claims'],
|
|
947
|
-
...(ctx.classification.act ? { act: ctx.classification.act } : {}),
|
|
943
|
+
risk_score: riskScore,
|
|
944
|
+
reversible,
|
|
945
|
+
systems_touched: systemsTouched,
|
|
946
|
+
client_capabilities: ['execution_claims'],
|
|
947
|
+
...(ctx.classification.act ? { act: ctx.classification.act } : {}),
|
|
948
948
|
metadata: { openclaw_tool_name: ctx.toolName },
|
|
949
949
|
});
|
|
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 } };
|
|
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 } };
|
|
961
961
|
} catch (err) {
|
|
962
962
|
const msg = errorMessage(err) || 'unknown';
|
|
963
963
|
console.warn(`[dashclaw-governance] createAction failed: ${msg}`);
|
|
@@ -970,93 +970,93 @@ async function createGovernanceAction(
|
|
|
970
970
|
};
|
|
971
971
|
}
|
|
972
972
|
return { result: undefined };
|
|
973
|
-
}
|
|
974
|
-
}
|
|
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
|
-
}
|
|
973
|
+
}
|
|
974
|
+
}
|
|
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
1051
|
|
|
1052
1052
|
async function waitForRequiredApproval(
|
|
1053
1053
|
ctx: OpenActionContext,
|
|
1054
1054
|
created: CreatedAction,
|
|
1055
1055
|
): Promise<HookBlockResult | undefined> {
|
|
1056
|
-
const needsApproval =
|
|
1057
|
-
ctx.decision.decision === 'require_approval' ||
|
|
1058
|
-
created.status === 'pending_approval';
|
|
1059
|
-
if (!needsApproval) return undefined;
|
|
1056
|
+
const needsApproval =
|
|
1057
|
+
ctx.decision.decision === 'require_approval' ||
|
|
1058
|
+
created.status === 'pending_approval';
|
|
1059
|
+
if (!needsApproval) return undefined;
|
|
1060
1060
|
|
|
1061
1061
|
const timeout = ctx.config.approvalWaitMs;
|
|
1062
1062
|
try {
|
|
@@ -1065,10 +1065,7 @@ async function waitForRequiredApproval(
|
|
|
1065
1065
|
interval: approvalPollInterval(timeout),
|
|
1066
1066
|
});
|
|
1067
1067
|
if (isApproved(action)) return undefined;
|
|
1068
|
-
return {
|
|
1069
|
-
block: true,
|
|
1070
|
-
blockReason: action?.error_message || 'Action denied by operator',
|
|
1071
|
-
};
|
|
1068
|
+
return { block: true, blockReason: denialBlockReason(action) };
|
|
1072
1069
|
} catch (err) {
|
|
1073
1070
|
if (isApprovalTimeout(err)) {
|
|
1074
1071
|
// The server keeps the approval open past this bounded wait
|
|
@@ -1083,6 +1080,15 @@ async function waitForRequiredApproval(
|
|
|
1083
1080
|
`Approve it at ${ctx.config.dashclawUrl}/approvals, then retry this tool call.`,
|
|
1084
1081
|
};
|
|
1085
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
|
+
}
|
|
1086
1092
|
return {
|
|
1087
1093
|
block: true,
|
|
1088
1094
|
blockReason: `Approval denied or wait failed: ${errorMessage(err) || 'denied'}`,
|
|
@@ -1090,6 +1096,69 @@ async function waitForRequiredApproval(
|
|
|
1090
1096
|
}
|
|
1091
1097
|
}
|
|
1092
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
|
+
|
|
1093
1162
|
/** Sample the approval at least ~4 times inside the window; keep the SDK's 5s ceiling. */
|
|
1094
1163
|
function approvalPollInterval(timeoutMs: number): number {
|
|
1095
1164
|
return Math.min(5000, Math.max(50, Math.floor(timeoutMs / 4)));
|