@dashclaw/openclaw-plugin 1.5.0 → 1.6.1

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 CHANGED
@@ -121,8 +121,29 @@ empty because the wait target didn't exist. Fixed in `1.0.1`.
121
121
  | `agentId` | string | `"openclaw"` | Identifier this OpenClaw instance reports to DashClaw. |
122
122
  | `defaultModel` | string | `""` | Fallback model id (e.g. `claude-sonnet-5`, `openai-codex/gpt-5.4`) used when `llm_output` events don't include a `model` field. Without this, unpriced turns land `tokens_in`/`tokens_out` but `cost_estimate` stays `$0`. Env var: `DASHCLAW_DEFAULT_MODEL`. |
123
123
  | `failClosed` | boolean | `true` | If DashClaw is unreachable, block the tool call. Set `false` to fail open. |
124
+ | `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`). |
124
125
  | `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. |
125
126
  | `highRiskTools` | string[] | `[]` | Tool names that should always start at risk score 85 before classification. The classifier may raise the score further (e.g. `rm -rf` → 90) but will never lower it below 85 for tools in this list. |
127
+ | `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`). |
128
+
129
+ ## Automatic identity pairing
130
+
131
+ When an admin clicks **Request pairing** for this agent on the DashClaw
132
+ `/identities` page, the plugin answers on the agent's next tool call — no LLM
133
+ involvement:
134
+
135
+ 1. It reads the agent's unread DashClaw inbox and finds the
136
+ `dashclaw.pairing_request` directive.
137
+ 2. It generates an RSA-2048 keypair locally. The private key is written to
138
+ `~/.dashclaw/identity/<agentId>.pem` (mode 600) and never leaves the
139
+ machine.
140
+ 3. It POSTs the public key to `/api/pairings` and marks the message read.
141
+
142
+ The pairing then appears under **Pending Pairings** on `/identities` for the
143
+ admin's one-click approval — approval is what creates the identity. Disable
144
+ with `autoPairing: false`. To rotate keys, delete the `.pem` file and click
145
+ **Request pairing** again. Auto-pairing is fire-and-forget: it runs once per
146
+ gateway process and can never block or fail a tool call.
126
147
 
127
148
  ## Fail-closed vs fail-open
128
149
 
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Auto-pairing consumer — answers the operator's /identities "Request
3
+ * pairing" click without an LLM in the loop.
4
+ *
5
+ * On the first tool call per gateway process the plugin checks this agent's
6
+ * DashClaw inbox for a `dashclaw.pairing_request` directive (the fenced-JSON
7
+ * contract in app/lib/pairing-request.ts). When one targets this agent it
8
+ * generates an RSA-2048 keypair locally, POSTs the public PEM via the SDK's
9
+ * createPairing, stores the private key at
10
+ * ~/.dashclaw/identity/<agent_id>.pem (mode 600 — same path as the MCP
11
+ * dashclaw_pair tool), and marks the message read. Identity creation still
12
+ * happens only when an admin approves the pairing on /identities.
13
+ *
14
+ * Custody rule: the private key never leaves this machine and is never
15
+ * logged. Failure rule: every error is a console.warn — this path must
16
+ * never throw into or block a tool call.
17
+ */
18
+ import type { DashClaw } from 'dashclaw';
19
+ export declare const PAIRING_REQUEST_KIND = "dashclaw.pairing_request";
20
+ export interface AutoPairConfig {
21
+ dashclawUrl: string;
22
+ dashclawApiKey: string;
23
+ agentId: string;
24
+ autoPairing: boolean;
25
+ }
26
+ /** Test-only: reset the per-process attempt guard. */
27
+ export declare function __resetAutoPairing(): void;
28
+ export declare function identityKeyPath(agentId: string): string;
29
+ export declare function maybeAutoPair(client: DashClaw, config: AutoPairConfig): Promise<void>;
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Auto-pairing consumer — answers the operator's /identities "Request
3
+ * pairing" click without an LLM in the loop.
4
+ *
5
+ * On the first tool call per gateway process the plugin checks this agent's
6
+ * DashClaw inbox for a `dashclaw.pairing_request` directive (the fenced-JSON
7
+ * contract in app/lib/pairing-request.ts). When one targets this agent it
8
+ * generates an RSA-2048 keypair locally, POSTs the public PEM via the SDK's
9
+ * createPairing, stores the private key at
10
+ * ~/.dashclaw/identity/<agent_id>.pem (mode 600 — same path as the MCP
11
+ * dashclaw_pair tool), and marks the message read. Identity creation still
12
+ * happens only when an admin approves the pairing on /identities.
13
+ *
14
+ * Custody rule: the private key never leaves this machine and is never
15
+ * logged. Failure rule: every error is a console.warn — this path must
16
+ * never throw into or block a tool call.
17
+ */
18
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
19
+ import { homedir } from 'node:os';
20
+ import { dirname, join } from 'node:path';
21
+ import { generateKeyPairSync } from 'node:crypto';
22
+ export const PAIRING_REQUEST_KIND = 'dashclaw.pairing_request';
23
+ // One attempt per gateway process per (url, agent). Added BEFORE the first
24
+ // await so concurrent tool calls cannot double-run the flow. Per-process on
25
+ // purpose: a transient failure retries at the next gateway start.
26
+ let attempted = new Set();
27
+ /** Test-only: reset the per-process attempt guard. */
28
+ export function __resetAutoPairing() {
29
+ attempted = new Set();
30
+ }
31
+ export function identityKeyPath(agentId) {
32
+ const safe = agentId.replace(/[^A-Za-z0-9._-]/g, '_');
33
+ return join(homedir(), '.dashclaw', 'identity', `${safe}.pem`);
34
+ }
35
+ /** Same fence contract as app/lib/pairing-request.ts. */
36
+ function directiveTargets(body, agentId) {
37
+ if (typeof body !== 'string')
38
+ return false;
39
+ const match = body.match(/```json\s*([\s\S]*?)```/);
40
+ if (!match || !match[1])
41
+ return false;
42
+ try {
43
+ const parsed = JSON.parse(match[1]);
44
+ return parsed?.kind === PAIRING_REQUEST_KIND && parsed.agent_id === agentId;
45
+ }
46
+ catch {
47
+ return false;
48
+ }
49
+ }
50
+ function apiUrl(config, pathAndQuery) {
51
+ return `${config.dashclawUrl.replace(/\/+$/, '')}${pathAndQuery}`;
52
+ }
53
+ async function fetchUnreadInbox(config) {
54
+ const res = await fetch(apiUrl(config, `/api/messages?agent_id=${encodeURIComponent(config.agentId)}&direction=inbox&unread=true&limit=50`), { headers: { 'x-api-key': config.dashclawApiKey } });
55
+ if (!res.ok)
56
+ throw new Error(`messages GET failed (${res.status})`);
57
+ const data = (await res.json());
58
+ return Array.isArray(data.messages) ? data.messages : [];
59
+ }
60
+ async function markRead(config, messageIds) {
61
+ const res = await fetch(apiUrl(config, '/api/messages'), {
62
+ method: 'PATCH',
63
+ headers: { 'x-api-key': config.dashclawApiKey, 'Content-Type': 'application/json' },
64
+ body: JSON.stringify({ message_ids: messageIds, action: 'read', agent_id: config.agentId }),
65
+ });
66
+ if (!res.ok)
67
+ throw new Error(`messages PATCH failed (${res.status})`);
68
+ }
69
+ export async function maybeAutoPair(client, config) {
70
+ if (!config.autoPairing)
71
+ return;
72
+ const key = `${config.dashclawUrl}|${config.agentId}`;
73
+ if (attempted.has(key))
74
+ return;
75
+ attempted.add(key);
76
+ try {
77
+ const pemPath = identityKeyPath(config.agentId);
78
+ if (existsSync(pemPath)) {
79
+ // Already enrolled or pending. Deleting the pem + clicking Request
80
+ // pairing again is the rotation path.
81
+ return;
82
+ }
83
+ const inbox = await fetchUnreadInbox(config);
84
+ const requests = inbox.filter((m) => directiveTargets(m.body, config.agentId));
85
+ if (requests.length === 0)
86
+ return;
87
+ const { publicKey, privateKey } = generateKeyPairSync('rsa', {
88
+ modulusLength: 2048,
89
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
90
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
91
+ });
92
+ const created = await client.createPairing(publicKey);
93
+ const pairingId = created.pairing?.id ??
94
+ created.id ??
95
+ '(pending)';
96
+ // POST-then-write: a failed POST leaves no pem, so the next gateway
97
+ // start retries cleanly. A failed write AFTER a successful POST is the
98
+ // one loud case — that pending pairing has no usable private key.
99
+ try {
100
+ mkdirSync(dirname(pemPath), { recursive: true });
101
+ writeFileSync(pemPath, privateKey, { mode: 0o600 });
102
+ }
103
+ catch (err) {
104
+ console.warn(`[dashclaw-governance] auto-pairing: submitted pairing ${pairingId} but FAILED to store ` +
105
+ `the private key at ${pemPath}: ${errText(err)}. Reject that pairing on /identities, ` +
106
+ `fix the disk issue, and click Request pairing again.`);
107
+ return; // leave the message unread so a later gateway start retries
108
+ }
109
+ await markRead(config, requests.map((m) => m.id));
110
+ console.log(`[dashclaw-governance] auto-pairing submitted (${pairingId}) — approve it on /identities. ` +
111
+ `Private key stored at ${pemPath} (never sent).`);
112
+ }
113
+ catch (err) {
114
+ console.warn(`[dashclaw-governance] auto-pairing skipped: ${errText(err)}`);
115
+ }
116
+ }
117
+ function errText(err) {
118
+ return err instanceof Error ? err.message : String(err);
119
+ }
package/dist/index.js CHANGED
@@ -21,6 +21,7 @@
21
21
  */
22
22
  import { definePluginEntry, } from 'openclaw/plugin-sdk/plugin-entry';
23
23
  import { DashClaw, } from 'dashclaw';
24
+ import { maybeAutoPair } from './auto-pairing.js';
24
25
  /**
25
26
  * Resolve the DashClaw URL from (in order of precedence):
26
27
  * 1. `config.dashclawUrl` (canonical plugin-config key)
@@ -55,8 +56,10 @@ function resolveConfig(raw) {
55
56
  const cfg = raw ?? {};
56
57
  const env = typeof process !== 'undefined' && process?.env ? process.env : {};
57
58
  const failClosed = cfg.failClosed !== false; // default true
59
+ const autoPairing = cfg.autoPairing !== false; // default true
58
60
  const riskScoreDefault = numberFromConfig(cfg.riskScoreDefault, 50);
59
61
  const highRiskTools = stringSetFromConfig(cfg.highRiskTools);
62
+ const approvalWaitMs = numberFromConfig(cfg.approvalWaitMs, 60_000, false) || 60_000;
60
63
  const dashclawUrl = firstString(cfg.dashclawUrl, cfg.baseUrl, env.DASHCLAW_BASE_URL, env.DASHCLAW_URL);
61
64
  const dashclawApiKey = firstString(cfg.dashclawApiKey, cfg.apiKey, env.DASHCLAW_API_KEY);
62
65
  const agentId = firstString(cfg.agentId, env.DASHCLAW_AGENT_ID) || 'openclaw';
@@ -67,8 +70,10 @@ function resolveConfig(raw) {
67
70
  agentId,
68
71
  defaultModel,
69
72
  failClosed,
73
+ autoPairing,
70
74
  riskScoreDefault,
71
75
  highRiskTools,
76
+ approvalWaitMs,
72
77
  };
73
78
  }
74
79
  // ---------------------------------------------------------------------------
@@ -359,6 +364,9 @@ async function handleBeforeToolCall(event, config) {
359
364
  const client = getBeforeClient(config);
360
365
  if ('result' in client)
361
366
  return client.result;
367
+ // Fire-and-forget: answers a pending operator pairing request once per
368
+ // gateway process. Never blocks or fails the tool call.
369
+ void maybeAutoPair(client.value, config);
362
370
  await maybeStartSession(event, client.value, config);
363
371
  const decision = await guardClassifiedAction(client.value, classification, config);
364
372
  if ('result' in decision)
@@ -451,7 +459,7 @@ async function openActionRecord(ctx) {
451
459
  const created = await createGovernanceAction(ctx);
452
460
  if ('result' in created)
453
461
  return created.result;
454
- const approval = await waitForRequiredApproval(ctx.client, ctx.decision, created.value);
462
+ const approval = await waitForRequiredApproval(ctx, created.value);
455
463
  if (approval)
456
464
  return approval;
457
465
  rememberPendingAction(ctx.key, created.value.actionId, ctx.runId);
@@ -489,13 +497,17 @@ async function createGovernanceAction(ctx) {
489
497
  return { result: undefined };
490
498
  }
491
499
  }
492
- async function waitForRequiredApproval(client, decision, created) {
493
- const needsApproval = decision.decision === 'require_approval' ||
500
+ async function waitForRequiredApproval(ctx, created) {
501
+ const needsApproval = ctx.decision.decision === 'require_approval' ||
494
502
  created.status === 'pending_approval';
495
503
  if (!needsApproval || !created.actionId)
496
504
  return undefined;
505
+ const timeout = ctx.config.approvalWaitMs;
497
506
  try {
498
- const { action } = await client.waitForApproval(created.actionId);
507
+ const { action } = await ctx.client.waitForApproval(created.actionId, {
508
+ timeout,
509
+ interval: approvalPollInterval(timeout),
510
+ });
499
511
  if (isApproved(action))
500
512
  return undefined;
501
513
  return {
@@ -504,12 +516,32 @@ async function waitForRequiredApproval(client, decision, created) {
504
516
  };
505
517
  }
506
518
  catch (err) {
519
+ if (isApprovalTimeout(err)) {
520
+ // The server keeps the approval open past this bounded wait
521
+ // (approval_wait_seconds = 300): the operator can still approve, and a
522
+ // retry of the same call passes via the guard's approval grant and
523
+ // createAction's idempotent-retry dedupe instead of opening a duplicate.
524
+ return {
525
+ block: true,
526
+ blockReason: `Approval not received within ${Math.round(timeout / 1000)}s — ` +
527
+ `action ${created.actionId} is still awaiting the operator. ` +
528
+ `Approve it at ${ctx.config.dashclawUrl}/approvals, then retry this tool call.`,
529
+ };
530
+ }
507
531
  return {
508
532
  block: true,
509
533
  blockReason: `Approval denied or wait failed: ${errorMessage(err) || 'denied'}`,
510
534
  };
511
535
  }
512
536
  }
537
+ /** Sample the approval at least ~4 times inside the window; keep the SDK's 5s ceiling. */
538
+ function approvalPollInterval(timeoutMs) {
539
+ return Math.min(5000, Math.max(50, Math.floor(timeoutMs / 4)));
540
+ }
541
+ /** Matches the SDK's approval-timeout error (a plain Error, distinct from denial). */
542
+ function isApprovalTimeout(err) {
543
+ return errorMessage(err).startsWith('Timed out waiting for approval');
544
+ }
513
545
  function rememberPendingAction(key, actionId, runId) {
514
546
  if (!actionId)
515
547
  return;
@@ -2,7 +2,7 @@
2
2
  "id": "dashclaw-governance",
3
3
  "name": "DashClaw Governance",
4
4
  "description": "Policy enforcement, human-in-the-loop approval, and decision recording for every OpenClaw tool call. Powered by DashClaw.",
5
- "version": "1.5.0",
5
+ "version": "1.6.1",
6
6
  "entry": "src/index.ts",
7
7
  "main": "./src/index.ts",
8
8
  "configSchema": {
@@ -40,6 +40,11 @@
40
40
  "default": true,
41
41
  "description": "If true, block tool calls when DashClaw is unreachable. If false, allow them to proceed."
42
42
  },
43
+ "autoPairing": {
44
+ "type": "boolean",
45
+ "default": true,
46
+ "description": "Automatically answer operator pairing requests from the DashClaw /identities page: generate a local keypair and submit the public key for admin approval. 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)."
47
+ },
43
48
  "riskScoreDefault": {
44
49
  "type": "number",
45
50
  "default": 50,
@@ -50,6 +55,11 @@
50
55
  "items": { "type": "string" },
51
56
  "default": [],
52
57
  "description": "Tool names that should always get risk_score 80+ (e.g. bash, exec, deploy)"
58
+ },
59
+ "approvalWaitMs": {
60
+ "type": "number",
61
+ "default": 60000,
62
+ "description": "How long (ms) a require_approval decision waits for the operator before blocking with a retry hint. Keep below your runtime's per-tool-call watchdog (Codex embedded dynamic-tool RPC kills calls at ~90s). The DashClaw approval stays open ~300s server-side, so approving after the wait and retrying the call still works."
53
63
  }
54
64
  }
55
65
  },
@@ -61,7 +71,9 @@
61
71
  "agentId": { "label": "Agent ID" },
62
72
  "defaultModel": { "label": "Default model (for cost pricing)", "placeholder": "openai-codex/gpt-5.4", "advanced": true },
63
73
  "failClosed": { "label": "Fail-closed when DashClaw unreachable", "advanced": true },
74
+ "autoPairing": { "label": "Auto-answer pairing requests", "advanced": true },
64
75
  "riskScoreDefault": { "label": "Default risk score", "advanced": true },
65
- "highRiskTools": { "label": "High-risk tool names", "advanced": true }
76
+ "highRiskTools": { "label": "High-risk tool names", "advanced": true },
77
+ "approvalWaitMs": { "label": "Approval wait (ms)", "advanced": true }
66
78
  }
67
79
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dashclaw/openclaw-plugin",
3
- "version": "1.5.0",
3
+ "version": "1.6.1",
4
4
  "description": "DashClaw governance for OpenClaw — policy enforcement, human approval, and decision recording for every tool call.",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
package/src/HOOK.md CHANGED
@@ -10,7 +10,7 @@ Intercepts every OpenClaw tool call through a four-step governance loop:
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
- 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.
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
14
  4. **Outcome** — `after_tool_call` records `completed` or `failed` with the error message, giving DashClaw a full intent → policy → outcome trail.
15
15
 
16
16
  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.
@@ -27,7 +27,7 @@ The plugin accepts three interchangeable configuration shapes — pick whichever
27
27
 
28
28
  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
29
 
30
- See the `configSchema` section in `openclaw.plugin.json` for the full list of optional fields (`agentId`, `failClosed`, `riskScoreDefault`, `highRiskTools`).
30
+ See the `configSchema` section in `openclaw.plugin.json` for the full list of optional fields (`agentId`, `failClosed`, `riskScoreDefault`, `highRiskTools`, `approvalWaitMs`).
31
31
 
32
32
  ## Failure modes
33
33
 
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Auto-pairing consumer — answers the operator's /identities "Request
3
+ * pairing" click without an LLM in the loop.
4
+ *
5
+ * On the first tool call per gateway process the plugin checks this agent's
6
+ * DashClaw inbox for a `dashclaw.pairing_request` directive (the fenced-JSON
7
+ * contract in app/lib/pairing-request.ts). When one targets this agent it
8
+ * generates an RSA-2048 keypair locally, POSTs the public PEM via the SDK's
9
+ * createPairing, stores the private key at
10
+ * ~/.dashclaw/identity/<agent_id>.pem (mode 600 — same path as the MCP
11
+ * dashclaw_pair tool), and marks the message read. Identity creation still
12
+ * happens only when an admin approves the pairing on /identities.
13
+ *
14
+ * Custody rule: the private key never leaves this machine and is never
15
+ * logged. Failure rule: every error is a console.warn — this path must
16
+ * never throw into or block a tool call.
17
+ */
18
+
19
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
20
+ import { homedir } from 'node:os';
21
+ import { dirname, join } from 'node:path';
22
+ import { generateKeyPairSync } from 'node:crypto';
23
+ import type { DashClaw } from 'dashclaw';
24
+
25
+ export const PAIRING_REQUEST_KIND = 'dashclaw.pairing_request';
26
+
27
+ export interface AutoPairConfig {
28
+ dashclawUrl: string;
29
+ dashclawApiKey: string;
30
+ agentId: string;
31
+ autoPairing: boolean;
32
+ }
33
+
34
+ interface InboxMessage {
35
+ id: string;
36
+ body?: unknown;
37
+ }
38
+
39
+ // One attempt per gateway process per (url, agent). Added BEFORE the first
40
+ // await so concurrent tool calls cannot double-run the flow. Per-process on
41
+ // purpose: a transient failure retries at the next gateway start.
42
+ let attempted = new Set<string>();
43
+
44
+ /** Test-only: reset the per-process attempt guard. */
45
+ export function __resetAutoPairing(): void {
46
+ attempted = new Set();
47
+ }
48
+
49
+ export function identityKeyPath(agentId: string): string {
50
+ const safe = agentId.replace(/[^A-Za-z0-9._-]/g, '_');
51
+ return join(homedir(), '.dashclaw', 'identity', `${safe}.pem`);
52
+ }
53
+
54
+ /** Same fence contract as app/lib/pairing-request.ts. */
55
+ function directiveTargets(body: unknown, agentId: string): boolean {
56
+ if (typeof body !== 'string') return false;
57
+ const match = body.match(/```json\s*([\s\S]*?)```/);
58
+ if (!match || !match[1]) return false;
59
+ try {
60
+ const parsed = JSON.parse(match[1]) as { kind?: string; agent_id?: string } | null;
61
+ return parsed?.kind === PAIRING_REQUEST_KIND && parsed.agent_id === agentId;
62
+ } catch {
63
+ return false;
64
+ }
65
+ }
66
+
67
+ function apiUrl(config: AutoPairConfig, pathAndQuery: string): string {
68
+ return `${config.dashclawUrl.replace(/\/+$/, '')}${pathAndQuery}`;
69
+ }
70
+
71
+ async function fetchUnreadInbox(config: AutoPairConfig): Promise<InboxMessage[]> {
72
+ const res = await fetch(
73
+ apiUrl(
74
+ config,
75
+ `/api/messages?agent_id=${encodeURIComponent(config.agentId)}&direction=inbox&unread=true&limit=50`
76
+ ),
77
+ { headers: { 'x-api-key': config.dashclawApiKey } }
78
+ );
79
+ if (!res.ok) throw new Error(`messages GET failed (${res.status})`);
80
+ const data = (await res.json()) as { messages?: InboxMessage[] };
81
+ return Array.isArray(data.messages) ? data.messages : [];
82
+ }
83
+
84
+ async function markRead(config: AutoPairConfig, messageIds: string[]): Promise<void> {
85
+ const res = await fetch(apiUrl(config, '/api/messages'), {
86
+ method: 'PATCH',
87
+ headers: { 'x-api-key': config.dashclawApiKey, 'Content-Type': 'application/json' },
88
+ body: JSON.stringify({ message_ids: messageIds, action: 'read', agent_id: config.agentId }),
89
+ });
90
+ if (!res.ok) throw new Error(`messages PATCH failed (${res.status})`);
91
+ }
92
+
93
+ export async function maybeAutoPair(client: DashClaw, config: AutoPairConfig): Promise<void> {
94
+ if (!config.autoPairing) return;
95
+ const key = `${config.dashclawUrl}|${config.agentId}`;
96
+ if (attempted.has(key)) return;
97
+ attempted.add(key);
98
+
99
+ try {
100
+ const pemPath = identityKeyPath(config.agentId);
101
+ if (existsSync(pemPath)) {
102
+ // Already enrolled or pending. Deleting the pem + clicking Request
103
+ // pairing again is the rotation path.
104
+ return;
105
+ }
106
+
107
+ const inbox = await fetchUnreadInbox(config);
108
+ const requests = inbox.filter((m) => directiveTargets(m.body, config.agentId));
109
+ if (requests.length === 0) return;
110
+
111
+ const { publicKey, privateKey } = generateKeyPairSync('rsa', {
112
+ modulusLength: 2048,
113
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
114
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
115
+ });
116
+
117
+ const created = await client.createPairing(publicKey);
118
+ const pairingId =
119
+ (created as { pairing?: { id?: string } }).pairing?.id ??
120
+ (created as { id?: string }).id ??
121
+ '(pending)';
122
+
123
+ // POST-then-write: a failed POST leaves no pem, so the next gateway
124
+ // start retries cleanly. A failed write AFTER a successful POST is the
125
+ // one loud case — that pending pairing has no usable private key.
126
+ try {
127
+ mkdirSync(dirname(pemPath), { recursive: true });
128
+ writeFileSync(pemPath, privateKey, { mode: 0o600 });
129
+ } catch (err) {
130
+ console.warn(
131
+ `[dashclaw-governance] auto-pairing: submitted pairing ${pairingId} but FAILED to store ` +
132
+ `the private key at ${pemPath}: ${errText(err)}. Reject that pairing on /identities, ` +
133
+ `fix the disk issue, and click Request pairing again.`
134
+ );
135
+ return; // leave the message unread so a later gateway start retries
136
+ }
137
+
138
+ await markRead(config, requests.map((m) => m.id));
139
+ console.log(
140
+ `[dashclaw-governance] auto-pairing submitted (${pairingId}) — approve it on /identities. ` +
141
+ `Private key stored at ${pemPath} (never sent).`
142
+ );
143
+ } catch (err) {
144
+ console.warn(`[dashclaw-governance] auto-pairing skipped: ${errText(err)}`);
145
+ }
146
+ }
147
+
148
+ function errText(err: unknown): string {
149
+ return err instanceof Error ? err.message : String(err);
150
+ }
package/src/dashclaw.d.ts CHANGED
@@ -67,6 +67,10 @@ declare module 'dashclaw' {
67
67
  sessionId: string,
68
68
  updates: Record<string, unknown>
69
69
  ): Promise<unknown>;
70
+ createPairing(
71
+ publicKeyPem: string,
72
+ opts?: { algorithm?: string; agentName?: string }
73
+ ): Promise<{ pairing?: { id?: string; status?: string }; [key: string]: unknown }>;
70
74
  }
71
75
 
72
76
  export class ApprovalDeniedError extends Error {
package/src/index.ts CHANGED
@@ -29,6 +29,7 @@ import {
29
29
  type ActionRecord,
30
30
  type GuardDecision,
31
31
  } from 'dashclaw';
32
+ import { maybeAutoPair } from './auto-pairing.js';
32
33
 
33
34
  // ---------------------------------------------------------------------------
34
35
  // Config
@@ -44,8 +45,16 @@ interface PluginConfig {
44
45
  // but no cost" failure mode. Empty string disables the fallback.
45
46
  defaultModel: string;
46
47
  failClosed: boolean;
48
+ autoPairing: boolean;
47
49
  riskScoreDefault: number;
48
50
  highRiskTools: ReadonlySet<string>;
51
+ // Bounded human-approval wait. Codex's embedded dynamic-tool RPC enforces a
52
+ // per-call watchdog (~90s): a longer synchronous wait is killed mid-flight
53
+ // and the tool result (e.g. an outbound message) is silently dropped, so the
54
+ // default stays under that ceiling. The server-side approval window
55
+ // (approval_wait_seconds, 300s) is intentionally longer — see
56
+ // waitForRequiredApproval for the retry-after-approval path.
57
+ approvalWaitMs: number;
49
58
  }
50
59
 
51
60
  /**
@@ -88,8 +97,10 @@ function resolveConfig(raw: Record<string, unknown> | undefined): PluginConfig {
88
97
  const env = typeof process !== 'undefined' && process?.env ? process.env : {};
89
98
 
90
99
  const failClosed = cfg.failClosed !== false; // default true
100
+ const autoPairing = cfg.autoPairing !== false; // default true
91
101
  const riskScoreDefault = numberFromConfig(cfg.riskScoreDefault, 50);
92
102
  const highRiskTools = stringSetFromConfig(cfg.highRiskTools);
103
+ const approvalWaitMs = numberFromConfig(cfg.approvalWaitMs, 60_000, false) || 60_000;
93
104
 
94
105
  const dashclawUrl = firstString(
95
106
  cfg.dashclawUrl,
@@ -114,8 +125,10 @@ function resolveConfig(raw: Record<string, unknown> | undefined): PluginConfig {
114
125
  agentId,
115
126
  defaultModel,
116
127
  failClosed,
128
+ autoPairing,
117
129
  riskScoreDefault,
118
130
  highRiskTools,
131
+ approvalWaitMs,
119
132
  };
120
133
  }
121
134
 
@@ -576,6 +589,10 @@ async function handleBeforeToolCall(
576
589
  const client = getBeforeClient(config);
577
590
  if ('result' in client) return client.result;
578
591
 
592
+ // Fire-and-forget: answers a pending operator pairing request once per
593
+ // gateway process. Never blocks or fails the tool call.
594
+ void maybeAutoPair(client.value, config);
595
+
579
596
  await maybeStartSession(event, client.value, config);
580
597
 
581
598
  const decision = await guardClassifiedAction(client.value, classification, config);
@@ -697,7 +714,7 @@ async function openActionRecord(ctx: OpenActionContext): Promise<HookResult> {
697
714
  const created = await createGovernanceAction(ctx);
698
715
  if ('result' in created) return created.result;
699
716
 
700
- const approval = await waitForRequiredApproval(ctx.client, ctx.decision, created.value);
717
+ const approval = await waitForRequiredApproval(ctx, created.value);
701
718
  if (approval) return approval;
702
719
  rememberPendingAction(ctx.key, created.value.actionId, ctx.runId);
703
720
  return;
@@ -739,23 +756,39 @@ async function createGovernanceAction(
739
756
  }
740
757
 
741
758
  async function waitForRequiredApproval(
742
- client: DashClaw,
743
- decision: GuardDecision,
759
+ ctx: OpenActionContext,
744
760
  created: CreatedAction,
745
761
  ): Promise<HookBlockResult | undefined> {
746
762
  const needsApproval =
747
- decision.decision === 'require_approval' ||
763
+ ctx.decision.decision === 'require_approval' ||
748
764
  created.status === 'pending_approval';
749
765
  if (!needsApproval || !created.actionId) return undefined;
750
766
 
767
+ const timeout = ctx.config.approvalWaitMs;
751
768
  try {
752
- const { action } = await client.waitForApproval(created.actionId);
769
+ const { action } = await ctx.client.waitForApproval(created.actionId, {
770
+ timeout,
771
+ interval: approvalPollInterval(timeout),
772
+ });
753
773
  if (isApproved(action)) return undefined;
754
774
  return {
755
775
  block: true,
756
776
  blockReason: action?.error_message || 'Action denied by operator',
757
777
  };
758
778
  } catch (err) {
779
+ if (isApprovalTimeout(err)) {
780
+ // The server keeps the approval open past this bounded wait
781
+ // (approval_wait_seconds = 300): the operator can still approve, and a
782
+ // retry of the same call passes via the guard's approval grant and
783
+ // createAction's idempotent-retry dedupe instead of opening a duplicate.
784
+ return {
785
+ block: true,
786
+ blockReason:
787
+ `Approval not received within ${Math.round(timeout / 1000)}s — ` +
788
+ `action ${created.actionId} is still awaiting the operator. ` +
789
+ `Approve it at ${ctx.config.dashclawUrl}/approvals, then retry this tool call.`,
790
+ };
791
+ }
759
792
  return {
760
793
  block: true,
761
794
  blockReason: `Approval denied or wait failed: ${errorMessage(err) || 'denied'}`,
@@ -763,6 +796,16 @@ async function waitForRequiredApproval(
763
796
  }
764
797
  }
765
798
 
799
+ /** Sample the approval at least ~4 times inside the window; keep the SDK's 5s ceiling. */
800
+ function approvalPollInterval(timeoutMs: number): number {
801
+ return Math.min(5000, Math.max(50, Math.floor(timeoutMs / 4)));
802
+ }
803
+
804
+ /** Matches the SDK's approval-timeout error (a plain Error, distinct from denial). */
805
+ function isApprovalTimeout(err: unknown): boolean {
806
+ return errorMessage(err).startsWith('Timed out waiting for approval');
807
+ }
808
+
766
809
  function rememberPendingAction(
767
810
  key: string,
768
811
  actionId: string | undefined,