@clawchatsai/connector 0.2.3 → 0.2.4
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/package.json +1 -1
- package/server/approval-retry.js +121 -0
- package/server/approval-retry.test.js +153 -0
- package/server/index.js +4 -1
package/package.json
CHANGED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// Lost Allows (OpenClaw bug, seen on 2026.9.7 and 2026.11.6, known-gaps/approval-wait-access-revision.md in the
|
|
2
|
+
// clawchats repo; not reported upstream): any session create/delete/spawn bumps the gateway-wide access revision
|
|
3
|
+
// (src/gateway/server-methods/session-change-event.ts emitSessionsChanged), and every exec approval still waiting
|
|
4
|
+
// then fails its wait once decided (approval-request-authority.ts assertPolicyCurrent: "Approval requester authority
|
|
5
|
+
// changed"). The user's Allow is recorded, but the agent gets "Exec denied (gateway id=…, approval-request-failed)"
|
|
6
|
+
// and the command never runs. The agent's wait is the gateway's own call, so it can't be repeated from here.
|
|
7
|
+
//
|
|
8
|
+
// Workaround: after a user's Allow, the session's transcript is checked for that failure. If it is there, the
|
|
9
|
+
// decision is kept for that exact command (same session, command text, host, node, cwd) for a short time and used
|
|
10
|
+
// once: once the run has replied, the agent is asked to run it again, and its new approval gets the kept decision.
|
|
11
|
+
// Nothing the user didn't allow is ever approved: a different command, session or a second request still asks.
|
|
12
|
+
// Runs started anywhere (ClawChats, channels, subagents) are covered: their tool events don't reach this
|
|
13
|
+
// connection, the approval events and the transcript do.
|
|
14
|
+
|
|
15
|
+
export const LOST_ALLOW_RE = /^Exec denied \((?:gateway|node=\S+) id=([^,)\s]+), approval-request-failed\)/;
|
|
16
|
+
const ALLOW = new Set(['allow-once', 'allow-always']);
|
|
17
|
+
const KEEP_MS = 120_000; // how long a lost Allow waits for the agent's rerun
|
|
18
|
+
const CHECKS_MS = [1500, 4000, 10_000]; // transcript checks after an Allow (the failure lands right after it)
|
|
19
|
+
const REPLY_WAIT_MS = 30_000; // ask for the rerun after this even if the run hasn't replied
|
|
20
|
+
|
|
21
|
+
const sleep = ms => new Promise(r => { const t = setTimeout(r, ms); t.unref?.(); });
|
|
22
|
+
const textOf = content => typeof content === 'string' ? content
|
|
23
|
+
: (Array.isArray(content) ? content : []).filter(c => c?.type === 'text').map(c => c.text).join('\n');
|
|
24
|
+
|
|
25
|
+
export class LostAllowRetry {
|
|
26
|
+
/**
|
|
27
|
+
* @param {object} o
|
|
28
|
+
* @param {(method: string, params?: object, timeoutMs?: number) => Promise<any>} o.request the connector's own gateway RPC
|
|
29
|
+
*/
|
|
30
|
+
constructor({ request, keepMs = KEEP_MS, checksMs = CHECKS_MS, replyWaitMs = REPLY_WAIT_MS, pollMs = 1500, now = Date.now, log = console }) {
|
|
31
|
+
this.request = request;
|
|
32
|
+
this.keepMs = keepMs;
|
|
33
|
+
this.checksMs = checksMs;
|
|
34
|
+
this.replyWaitMs = replyWaitMs;
|
|
35
|
+
this.pollMs = pollMs;
|
|
36
|
+
this.now = now;
|
|
37
|
+
this.log = log;
|
|
38
|
+
this._kept = []; // { approvalId, sessionKey, command, host, nodeId, cwd, decision, expiresAt, used }
|
|
39
|
+
this._seen = new Set(); // allowed approval ids already checked
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Approval events (approval-client connection). */
|
|
43
|
+
onApprovalEvent(msg) {
|
|
44
|
+
const p = msg?.payload || {};
|
|
45
|
+
if (msg?.event === 'exec.approval.resolved' && ALLOW.has(p.decision) && p.id && !this._seen.has(p.id)) {
|
|
46
|
+
this._seen.add(p.id);
|
|
47
|
+
if (this._seen.size > 500) this._seen = new Set([...this._seen].slice(-200));
|
|
48
|
+
this._check(p.id).catch(e => this.log.warn?.(`[approvals] lost allow check ${p.id}: ${e.message}`));
|
|
49
|
+
} else if (msg?.event === 'exec.approval.requested') {
|
|
50
|
+
this._rerun(p);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** An agent's rerun of a lost Allow gets the user's decision, once. */
|
|
55
|
+
_rerun({ id, request: r = {} }) {
|
|
56
|
+
this._prune();
|
|
57
|
+
const k = this._kept.find(k => !k.used && k.sessionKey === r.sessionKey && k.command === r.command
|
|
58
|
+
&& k.host === (r.host ?? null) && k.nodeId === (r.nodeId ?? null) && (k.cwd === null || k.cwd === (r.cwd ?? null)));
|
|
59
|
+
if (!k || !id) return;
|
|
60
|
+
const allowed = Array.isArray(r.allowedDecisions) ? r.allowedDecisions : [...ALLOW];
|
|
61
|
+
const decision = allowed.includes(k.decision) ? k.decision : allowed.includes('allow-once') ? 'allow-once' : null;
|
|
62
|
+
if (!decision) return;
|
|
63
|
+
k.used = true;
|
|
64
|
+
this.log.log?.(`[approvals] lost allow ${k.approvalId}: rerun ${id} resolved ${decision} (the user's earlier decision)`);
|
|
65
|
+
this.request('exec.approval.resolve', { id, decision }, 15_000)
|
|
66
|
+
.catch(e => this.log.warn?.(`[approvals] resolving rerun ${id}: ${e.message}`));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The transcript entry where the agent's exec of `approvalId` came back approval-request-failed (index), or -1. */
|
|
70
|
+
_failureIn(messages, approvalId) {
|
|
71
|
+
return messages.findIndex(m => m?.role === 'toolResult' && LOST_ALLOW_RE.exec(textOf(m.content))?.[1] === approvalId);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async _history(sessionKey) {
|
|
75
|
+
return (await this.request('chat.history', { sessionKey, limit: 30 }, 15_000))?.messages || [];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async _check(approvalId) {
|
|
79
|
+
// Only a user's Allow is kept; the record also gives the session and the exact command.
|
|
80
|
+
const items = (await this.request('approval.history', { limit: 50 }, 15_000))?.items || [];
|
|
81
|
+
const rec = items.find(i => i.id === approvalId);
|
|
82
|
+
const pr = rec?.presentation || {};
|
|
83
|
+
const sessionKey = rec?.source?.sessionKey;
|
|
84
|
+
if (rec?.status !== 'allowed' || rec.reason !== 'user' || !ALLOW.has(rec.decision) || pr.kind !== 'exec' || !pr.commandText || !sessionKey) return;
|
|
85
|
+
let messages = [];
|
|
86
|
+
let at = -1;
|
|
87
|
+
let waited = 0;
|
|
88
|
+
for (const ms of this.checksMs) {
|
|
89
|
+
await sleep(ms - waited);
|
|
90
|
+
waited = ms;
|
|
91
|
+
messages = await this._history(sessionKey);
|
|
92
|
+
at = this._failureIn(messages, approvalId);
|
|
93
|
+
if (at >= 0) break;
|
|
94
|
+
}
|
|
95
|
+
if (at < 0) return; // the command ran (or failed some other way)
|
|
96
|
+
const details = messages[at].details || {};
|
|
97
|
+
const kept = { approvalId, sessionKey, command: pr.commandText, host: pr.host ?? null, nodeId: pr.nodeId ?? null,
|
|
98
|
+
cwd: typeof details.cwd === 'string' ? details.cwd : null, decision: rec.decision, expiresAt: this.now() + this.keepMs, used: false };
|
|
99
|
+
this._kept.push(kept);
|
|
100
|
+
this.log.log?.(`[approvals] lost allow ${approvalId} (${rec.decision}) in ${sessionKey}: asking the agent to rerun`);
|
|
101
|
+
// Ask once the run has replied after the failure: an agent that retries on its own uses the kept Allow, and then
|
|
102
|
+
// no note is sent.
|
|
103
|
+
const end = this.now() + this.replyWaitMs;
|
|
104
|
+
while (!kept.used && this.now() < end) {
|
|
105
|
+
const i = this._failureIn(messages, approvalId);
|
|
106
|
+
if (i >= 0 && messages.slice(i + 1).some(m => m?.role === 'assistant' && textOf(m.content).trim())) break;
|
|
107
|
+
await sleep(this.pollMs);
|
|
108
|
+
messages = await this._history(sessionKey).catch(() => messages);
|
|
109
|
+
}
|
|
110
|
+
if (kept.used || this.now() > kept.expiresAt) return;
|
|
111
|
+
await this.request('chat.send', {
|
|
112
|
+
sessionKey, deliver: false, idempotencyKey: `cc-lost-allow-${approvalId}`,
|
|
113
|
+
message: `[ClawChats] The command you just ran was allowed, but the gateway lost the approval before it ran (OpenClaw bug: a session changed while it waited). Run exactly the same command again; the user's Allow will be applied to it:\n${pr.commandText}`,
|
|
114
|
+
}, 30_000);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
_prune() {
|
|
118
|
+
const t = this.now();
|
|
119
|
+
this._kept = this._kept.filter(k => !k.used && k.expiresAt >= t);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { test } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { LostAllowRetry, LOST_ALLOW_RE } from './approval-retry.js';
|
|
4
|
+
|
|
5
|
+
const SK = 'agent:main:chat-1';
|
|
6
|
+
const CWD = '/home/u/.openclaw/workspace';
|
|
7
|
+
const quiet = { log() {}, warn() {} };
|
|
8
|
+
const settle = () => new Promise(r => setTimeout(r, 30));
|
|
9
|
+
|
|
10
|
+
function historyItem(over = {}) {
|
|
11
|
+
return {
|
|
12
|
+
id: 'a1', status: 'allowed', reason: 'user', decision: 'allow-once',
|
|
13
|
+
presentation: { kind: 'exec', commandText: 'touch /tmp/x', host: 'gateway', nodeId: null },
|
|
14
|
+
source: { agentId: 'main', sessionKey: SK }, ...over,
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
const user = { role: 'user', content: 'run touch /tmp/x' };
|
|
18
|
+
const failedResult = (id = 'a1', reason = 'approval-request-failed') => ({
|
|
19
|
+
role: 'toolResult', toolName: 'exec', isError: true, details: { cwd: CWD },
|
|
20
|
+
content: [{ type: 'text', text: `Exec denied (gateway id=${id}, ${reason}): touch /tmp/x\nCommand did not run: approval request failed.` }],
|
|
21
|
+
});
|
|
22
|
+
const reply = { role: 'assistant', content: [{ type: 'text', text: 'failed: approval request failed' }] };
|
|
23
|
+
|
|
24
|
+
/** transcript: the chat.history messages, or a function of the call count. */
|
|
25
|
+
function setup({ items = [historyItem()], transcript = [user, failedResult(), reply], ...opts } = {}) {
|
|
26
|
+
const calls = [];
|
|
27
|
+
let reads = 0;
|
|
28
|
+
const request = async (method, params) => {
|
|
29
|
+
calls.push({ method, params });
|
|
30
|
+
if (method === 'approval.history') return { items };
|
|
31
|
+
if (method === 'chat.history') return { messages: typeof transcript === 'function' ? transcript(reads++) : transcript };
|
|
32
|
+
return {};
|
|
33
|
+
};
|
|
34
|
+
const r = new LostAllowRetry({ request, log: quiet, checksMs: [0, 5], replyWaitMs: 200, ...opts });
|
|
35
|
+
return { r, calls, sent: m => calls.filter(c => c.method === m) };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const allowed = (id = 'a1', decision = 'allow-once') => ({ type: 'event', event: 'exec.approval.resolved', payload: { id, decision } });
|
|
39
|
+
const rerun = (id = 'a2', over = {}) => ({
|
|
40
|
+
type: 'event', event: 'exec.approval.requested',
|
|
41
|
+
payload: { id, request: { command: 'touch /tmp/x', cwd: CWD, host: 'gateway', nodeId: null, sessionKey: SK, allowedDecisions: ['allow-once', 'deny'], ...over } },
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
test('the failure text, gateway and node hosts', () => {
|
|
45
|
+
assert.equal(LOST_ALLOW_RE.exec('Exec denied (gateway id=4aef-1, approval-request-failed): ls')[1], '4aef-1');
|
|
46
|
+
assert.equal(LOST_ALLOW_RE.exec('Exec denied (node=mac id=b2, approval-request-failed): ls')[1], 'b2');
|
|
47
|
+
assert.equal(LOST_ALLOW_RE.exec('Exec denied (gateway id=c3, user-denied): ls'), null);
|
|
48
|
+
assert.equal(LOST_ALLOW_RE.exec('Exec denied (gateway id=c3, approval-timeout): ls'), null);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test('a lost user Allow: rerun note once the run replied, the rerun gets the same decision once', async () => {
|
|
52
|
+
const { r, sent } = setup();
|
|
53
|
+
r.onApprovalEvent(allowed());
|
|
54
|
+
await settle();
|
|
55
|
+
const [note] = sent('chat.send');
|
|
56
|
+
assert.equal(note.params.sessionKey, SK);
|
|
57
|
+
assert.equal(note.params.idempotencyKey, 'cc-lost-allow-a1');
|
|
58
|
+
assert.match(note.params.message, /touch \/tmp\/x/);
|
|
59
|
+
r.onApprovalEvent(rerun('a2'));
|
|
60
|
+
assert.deepEqual(sent('exec.approval.resolve').map(c => c.params), [{ id: 'a2', decision: 'allow-once' }]);
|
|
61
|
+
r.onApprovalEvent(rerun('a3'));
|
|
62
|
+
assert.equal(sent('exec.approval.resolve').length, 1, 'used once: a second request still asks');
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test('the note waits for the run to reply after the failure', async () => {
|
|
66
|
+
const { r, sent } = setup({ transcript: n => n < 3 ? [user, failedResult()] : [user, failedResult(), reply], replyWaitMs: 5000, pollMs: 40 });
|
|
67
|
+
r.onApprovalEvent(allowed());
|
|
68
|
+
await settle();
|
|
69
|
+
assert.equal(sent('chat.send').length, 0);
|
|
70
|
+
await new Promise(res => setTimeout(res, 200));
|
|
71
|
+
assert.equal(sent('chat.send').length, 1);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test('the agent retrying by itself before replying uses the Allow, and no note is sent', async () => {
|
|
75
|
+
const { r, sent } = setup({ transcript: [user, failedResult()], replyWaitMs: 100, pollMs: 20 });
|
|
76
|
+
r.onApprovalEvent(allowed());
|
|
77
|
+
await settle();
|
|
78
|
+
r.onApprovalEvent(rerun('a2'));
|
|
79
|
+
await new Promise(res => setTimeout(res, 150));
|
|
80
|
+
assert.equal(sent('exec.approval.resolve').length, 1);
|
|
81
|
+
assert.equal(sent('chat.send').length, 0);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
test('an Allow whose command ran is left alone', async () => {
|
|
85
|
+
const { r, sent } = setup({ transcript: [user, { role: 'toolResult', content: [{ type: 'text', text: '' }] }, reply] });
|
|
86
|
+
r.onApprovalEvent(allowed());
|
|
87
|
+
await settle();
|
|
88
|
+
r.onApprovalEvent(rerun('a2'));
|
|
89
|
+
assert.equal(sent('chat.send').length + sent('exec.approval.resolve').length, 0);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
test('Always allow is carried over when the rerun offers it, else allow-once', async () => {
|
|
93
|
+
const a = setup({ items: [historyItem({ decision: 'allow-always' })] });
|
|
94
|
+
a.r.onApprovalEvent(allowed('a1', 'allow-always'));
|
|
95
|
+
await settle();
|
|
96
|
+
a.r.onApprovalEvent(rerun('a2', { allowedDecisions: ['allow-once', 'allow-always', 'deny'] }));
|
|
97
|
+
assert.equal(a.sent('exec.approval.resolve')[0].params.decision, 'allow-always');
|
|
98
|
+
const b = setup({ items: [historyItem({ decision: 'allow-always' })] });
|
|
99
|
+
b.r.onApprovalEvent(allowed('a1', 'allow-always'));
|
|
100
|
+
await settle();
|
|
101
|
+
b.r.onApprovalEvent(rerun('a2'));
|
|
102
|
+
assert.equal(b.sent('exec.approval.resolve')[0].params.decision, 'allow-once');
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
test('nothing is approved that the user did not allow', async () => {
|
|
106
|
+
for (const item of [
|
|
107
|
+
historyItem({ status: 'denied', decision: 'deny' }),
|
|
108
|
+
historyItem({ reason: 'timeout', decision: null, status: 'expired' }),
|
|
109
|
+
historyItem({ id: 'other' }),
|
|
110
|
+
historyItem({ presentation: { kind: 'plugin', commandText: 'touch /tmp/x' } }),
|
|
111
|
+
]) {
|
|
112
|
+
const { r, sent } = setup({ items: [item] });
|
|
113
|
+
r.onApprovalEvent(allowed());
|
|
114
|
+
await settle();
|
|
115
|
+
r.onApprovalEvent(rerun('a2'));
|
|
116
|
+
assert.equal(sent('chat.send').length + sent('exec.approval.resolve').length, 0, JSON.stringify(item));
|
|
117
|
+
}
|
|
118
|
+
// A Deny or an expiry is never even looked at.
|
|
119
|
+
const { r, calls } = setup();
|
|
120
|
+
r.onApprovalEvent({ event: 'exec.approval.resolved', payload: { id: 'a1', decision: 'deny' } });
|
|
121
|
+
r.onApprovalEvent({ event: 'exec.approval.resolved', payload: { id: 'a1', decision: null } });
|
|
122
|
+
await settle();
|
|
123
|
+
assert.equal(calls.length, 0);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
test('a rerun that differs in command, session, host, node or cwd still asks', async () => {
|
|
127
|
+
for (const over of [{ command: 'touch /tmp/y' }, { sessionKey: 'agent:main:other' }, { host: 'node' }, { nodeId: 'mac' }, { cwd: '/' }]) {
|
|
128
|
+
const { r, sent } = setup();
|
|
129
|
+
r.onApprovalEvent(allowed());
|
|
130
|
+
await settle();
|
|
131
|
+
r.onApprovalEvent(rerun('a2', over));
|
|
132
|
+
assert.equal(sent('exec.approval.resolve').length, 0, JSON.stringify(over));
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
test('each Allow is checked once', async () => {
|
|
137
|
+
const { r, sent } = setup();
|
|
138
|
+
r.onApprovalEvent(allowed());
|
|
139
|
+
r.onApprovalEvent(allowed());
|
|
140
|
+
await settle();
|
|
141
|
+
assert.equal(sent('approval.history').length, 1);
|
|
142
|
+
assert.equal(sent('chat.send').length, 1);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
test('a kept Allow expires', async () => {
|
|
146
|
+
let t = 1000;
|
|
147
|
+
const { r, sent } = setup({ now: () => t, keepMs: 5000 });
|
|
148
|
+
r.onApprovalEvent(allowed());
|
|
149
|
+
await settle();
|
|
150
|
+
t += 6000;
|
|
151
|
+
r.onApprovalEvent(rerun('a2'));
|
|
152
|
+
assert.equal(sent('exec.approval.resolve').length, 0);
|
|
153
|
+
});
|
package/server/index.js
CHANGED
|
@@ -8,6 +8,7 @@ import { Database } from './bootstrap/native.js';
|
|
|
8
8
|
import { GATEWAY_WS_URL, AUTH_TOKEN, discoverWorkspaceDir } from './config.js';
|
|
9
9
|
import { DebugLogger } from './debug.js';
|
|
10
10
|
import { GatewayClient } from './gateway.js';
|
|
11
|
+
import { LostAllowRetry } from './approval-retry.js';
|
|
11
12
|
import { withGatewayRetry } from './util/gateway-retry.js';
|
|
12
13
|
import { createChatAbort } from './util/chat-abort.js';
|
|
13
14
|
import { handleServeFile, handleWorkspaceList, handleWorkspaceFileRead, handleWorkspaceFileWrite, handleWorkspaceFileDelete, handleWorkspaceUpload, handleWorkspaceCreate, handleWorkspaceMove, handleWorkspaceCopy } from './controllers/filesystem.js';
|
|
@@ -95,8 +96,10 @@ export function createApp(config = {}) {
|
|
|
95
96
|
}) : null;
|
|
96
97
|
// Team chats: several agents in one thread (server/team.js).
|
|
97
98
|
const team = new TeamCoordinator({ store: createTeamStore(() => globalDbCache.get()), request: gwRequest, chatAbort, broadcast, titler: createTitler(config.llm), remote: sharing });
|
|
99
|
+
// Exec Allows the gateway lost after a session change (OpenClaw 2026.9.7+; server/approval-retry.js).
|
|
100
|
+
const lostAllows = new LostAllowRetry({ request: gwRequest });
|
|
98
101
|
gatewayClient.onEvent = msg => { team.onGatewayEvent(msg); sharing?.onGatewayEvent(msg); };
|
|
99
|
-
gatewayClient.onApprovalEvent = msg => sharing?.onApprovalEvent(msg);
|
|
102
|
+
gatewayClient.onApprovalEvent = msg => { sharing?.onApprovalEvent(msg); lostAllows.onApprovalEvent(msg); };
|
|
100
103
|
gatewayClient.onConnected = () => { sharing?.migrateGuestAgents().catch(e => console.warn(`[sharing] guest migration failed: ${e.message}`)); };
|
|
101
104
|
gatewayClient.lens = new SessionLens({ broadcast, request: gwRequest, extras, team });
|
|
102
105
|
// Renamed agents: shares re-issued with the new names, copies of rooms here told (peer/sharing.js, team.js).
|