@clawchatsai/connector 0.2.6 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +2 -19
- package/dist/shim.d.ts +7 -0
- package/dist/shim.js +27 -0
- package/package.json +1 -1
- package/server/approval-client.js +9 -1
- package/server/approval-client.test.js +16 -0
- package/server/gateway.js +17 -2
- package/server/index.js +38 -2
- package/server/peer/contact-copy.js +164 -0
- package/server/peer/contact-policy.js +250 -0
- package/server/peer/contact-policy.test.js +119 -0
- package/server/peer/contacts.js +175 -0
- package/server/peer/contacts.test.js +135 -0
- package/server/peer/link.js +7 -3
- package/server/peer/notes-sync.js +126 -0
- package/server/peer/sharing.js +522 -61
- package/server/peer/sharing.test.js +302 -41
- package/server/peer/version.js +36 -0
- package/server/store/team-store.js +6 -5
- package/server/team.js +55 -13
- package/server/team.test.js +46 -12
package/dist/index.js
CHANGED
|
@@ -16,7 +16,7 @@ import * as os from 'node:os';
|
|
|
16
16
|
import * as path from 'node:path';
|
|
17
17
|
import { createRequire } from 'node:module';
|
|
18
18
|
import { SignalingClient } from './signaling-client.js';
|
|
19
|
-
import { dispatchRpc } from './shim.js';
|
|
19
|
+
import { dispatchRpc, rpcResponseBody } from './shim.js';
|
|
20
20
|
import { attachBrowserChannel, revokeStaleChannels, loadAuthState } from './auth-handler.js';
|
|
21
21
|
import { readConfig, writeConfig, updateConfig, readAuthConfig, removeBackupCode, writeFileAtomic, addDevice, touchDevice } from './config-store.js';
|
|
22
22
|
import { listDevices, revokeDevice, showFingerprint } from './devices-cli.js';
|
|
@@ -788,24 +788,7 @@ async function handleRpcMessage(dc, msg, ctx) {
|
|
|
788
788
|
};
|
|
789
789
|
try {
|
|
790
790
|
const response = await dispatchRpc(rpcReq, app.handleRequest);
|
|
791
|
-
|
|
792
|
-
// so the browser transport can reconstruct a proper Blob with correct MIME type
|
|
793
|
-
const contentType = response.headers['content-type'] || '';
|
|
794
|
-
const isBinaryResponse = /^(image|audio|video|application\/octet-stream|application\/pdf)/.test(contentType);
|
|
795
|
-
let responseBody;
|
|
796
|
-
if (isBinaryResponse && response.rawBody) {
|
|
797
|
-
// Encode raw bytes as base64 in a _binary envelope.
|
|
798
|
-
// The transport layer on the browser side already handles this format,
|
|
799
|
-
// reconstructing a proper Blob with the correct MIME type.
|
|
800
|
-
responseBody = {
|
|
801
|
-
_binary: true,
|
|
802
|
-
contentType,
|
|
803
|
-
data: response.rawBody.toString('base64'),
|
|
804
|
-
};
|
|
805
|
-
}
|
|
806
|
-
else {
|
|
807
|
-
responseBody = response.body;
|
|
808
|
-
}
|
|
791
|
+
const responseBody = rpcResponseBody(response);
|
|
809
792
|
const responseMsg = {
|
|
810
793
|
type: 'rpc-res',
|
|
811
794
|
id: response.id,
|
package/dist/shim.d.ts
CHANGED
|
@@ -55,6 +55,13 @@ declare class FakeRes extends Writable {
|
|
|
55
55
|
writeHead(statusCode: number, headers?: Record<string, string | number>): this;
|
|
56
56
|
end(chunk?: unknown, encoding?: unknown, _cb?: unknown): this;
|
|
57
57
|
}
|
|
58
|
+
export declare function isTextContentType(contentType: string): boolean;
|
|
59
|
+
/**
|
|
60
|
+
* The rpc-res body for a response: the text as-is, or a `{ _binary, contentType, data }` envelope
|
|
61
|
+
* (base64) that the browser transport turns back into a Blob. Text goes as text only when its bytes
|
|
62
|
+
* are valid UTF-8, so a Latin-1 CSV still arrives byte-exact. No body or no content type: text.
|
|
63
|
+
*/
|
|
64
|
+
export declare function rpcResponseBody(response: RpcResponse): unknown;
|
|
58
65
|
/**
|
|
59
66
|
* Dispatch an RPC request through handleRequest and return the response.
|
|
60
67
|
*/
|
package/dist/shim.js
CHANGED
|
@@ -140,6 +140,33 @@ function tryJsonParse(buf) {
|
|
|
140
140
|
return buf.toString('base64');
|
|
141
141
|
}
|
|
142
142
|
}
|
|
143
|
+
// Content types sent over the DataChannel as a UTF-8 string; everything else is base64-wrapped.
|
|
144
|
+
// An allowlist, not a binary list: an unknown type (zip, docx, kmz, …) decoded as UTF-8 turns every
|
|
145
|
+
// byte >= 0x80 into U+FFFD. image/svg+xml stays binary: the browser builds typed Blobs from it.
|
|
146
|
+
const TEXT_CONTENT_TYPE = /^(text\/|application\/(json|xml|javascript|x-www-form-urlencoded|yaml)$|application\/[^/]+\+(json|xml)$)/;
|
|
147
|
+
const strictUtf8 = new TextDecoder('utf-8', { fatal: true });
|
|
148
|
+
export function isTextContentType(contentType) {
|
|
149
|
+
return TEXT_CONTENT_TYPE.test(contentType.split(';')[0].trim().toLowerCase());
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* The rpc-res body for a response: the text as-is, or a `{ _binary, contentType, data }` envelope
|
|
153
|
+
* (base64) that the browser transport turns back into a Blob. Text goes as text only when its bytes
|
|
154
|
+
* are valid UTF-8, so a Latin-1 CSV still arrives byte-exact. No body or no content type: text.
|
|
155
|
+
*/
|
|
156
|
+
export function rpcResponseBody(response) {
|
|
157
|
+
const contentType = response.headers['content-type'] || '';
|
|
158
|
+
const raw = response.rawBody;
|
|
159
|
+
if (!contentType || !raw?.length)
|
|
160
|
+
return response.body;
|
|
161
|
+
if (isTextContentType(contentType)) {
|
|
162
|
+
try {
|
|
163
|
+
strictUtf8.decode(raw);
|
|
164
|
+
return response.body;
|
|
165
|
+
}
|
|
166
|
+
catch { /* not UTF-8: send the bytes */ }
|
|
167
|
+
}
|
|
168
|
+
return { _binary: true, contentType, data: raw.toString('base64') };
|
|
169
|
+
}
|
|
143
170
|
/**
|
|
144
171
|
* Dispatch an RPC request through handleRequest and return the response.
|
|
145
172
|
*/
|
package/package.json
CHANGED
|
@@ -6,7 +6,8 @@ import { WebSocket as WS } from 'ws';
|
|
|
6
6
|
// client is connected, an approval waits for a decision instead of expiring at once with
|
|
7
7
|
// "no-approval-route". The connector's main connection is always up, so it must not be one.
|
|
8
8
|
// Like an open Control UI tab, this second connection declares the cap only while a browser is
|
|
9
|
-
// attached (GatewayClient.browsersChanged)
|
|
9
|
+
// attached (GatewayClient.browsersChanged), or while a contact's guest turn may need its owner's approval
|
|
10
|
+
// (GatewayClient.holdApprovals: "Basic + ask me" must wait for the owner even with no tab open). Only approval events leave it; everything else the
|
|
10
11
|
// gateway broadcasts to it is dropped (the main connection already delivers those).
|
|
11
12
|
export const APPROVAL_EVENT_RE = /^(exec|plugin|openclaw)\.approval\.(requested|resolved)$/;
|
|
12
13
|
|
|
@@ -37,6 +38,13 @@ export class ApprovalClient {
|
|
|
37
38
|
this._connect();
|
|
38
39
|
}
|
|
39
40
|
|
|
41
|
+
/** Resolves true once connected as an approval client (false after `ms`). */
|
|
42
|
+
async waitConnected(ms = 5000) {
|
|
43
|
+
const end = Date.now() + ms;
|
|
44
|
+
while (!this.connected && Date.now() < end) await new Promise(r => setTimeout(r, 100));
|
|
45
|
+
return this.connected;
|
|
46
|
+
}
|
|
47
|
+
|
|
40
48
|
stop() {
|
|
41
49
|
this.running = false;
|
|
42
50
|
this.connected = false;
|
|
@@ -104,3 +104,19 @@ test('local WebSocket browsers count too; close() stops the approval-client conn
|
|
|
104
104
|
assert.equal(gw.approvalConns().length, 1);
|
|
105
105
|
await new Promise(r => gw.wss.close(r));
|
|
106
106
|
});
|
|
107
|
+
|
|
108
|
+
test('a guest turn that may ask its owner holds the approval-client connection with no browser attached, then lets it go', async () => {
|
|
109
|
+
const gw = await fakeGateway();
|
|
110
|
+
const c = client(gw.url, 50);
|
|
111
|
+
c.connect();
|
|
112
|
+
await wait(150);
|
|
113
|
+
assert.equal(gw.approvalConns().length, 0, 'no browser, no hold: none');
|
|
114
|
+
const release = await c.holdApprovals();
|
|
115
|
+
assert.equal(c.approvalClient.connected, true, 'connected before the turn sends anything');
|
|
116
|
+
assert.equal(gw.approvalConns().filter(x => !x.closed).length, 1);
|
|
117
|
+
release(); release(); // once is enough
|
|
118
|
+
await wait(200);
|
|
119
|
+
assert.equal(gw.approvalConns().filter(x => !x.closed).length, 0, 'closed after the grace period');
|
|
120
|
+
c.close();
|
|
121
|
+
await new Promise(r => gw.wss.close(r));
|
|
122
|
+
});
|
package/server/gateway.js
CHANGED
|
@@ -57,6 +57,7 @@ export class GatewayClient {
|
|
|
57
57
|
this._externalBrowserCount = () => 0;
|
|
58
58
|
this._approvalGraceMs = approvalClientGraceMs;
|
|
59
59
|
this._approvalStopTimer = null;
|
|
60
|
+
this._approvalHolds = 0; // guest turns that may wait for this gateway's owner to approve (holdApprovals)
|
|
60
61
|
this.approvalClient = new ApprovalClient({
|
|
61
62
|
gatewayWsUrl,
|
|
62
63
|
debugLogger,
|
|
@@ -79,10 +80,24 @@ export class GatewayClient {
|
|
|
79
80
|
/** Browsers attached over the DataChannel (src/index.ts); local WebSocket browsers are counted here. */
|
|
80
81
|
setExternalBrowserCount(fn) { this._externalBrowserCount = fn; this.browsersChanged(); }
|
|
81
82
|
|
|
82
|
-
/**
|
|
83
|
+
/**
|
|
84
|
+
* A contact's guest turn that may ask this gateway's owner to approve a command: while one runs, the approval-client
|
|
85
|
+
* connection stays up even with no browser attached, so the gateway keeps the approval pending (its 30-minute
|
|
86
|
+
* window) for the owner to answer when they open ClawChats, instead of refusing at once ("no-approval-route").
|
|
87
|
+
* Returns a release function; resolves once connected (or after a few seconds).
|
|
88
|
+
*/
|
|
89
|
+
async holdApprovals() {
|
|
90
|
+
this._approvalHolds++;
|
|
91
|
+
this.browsersChanged();
|
|
92
|
+
await this.approvalClient.waitConnected(5000);
|
|
93
|
+
let released = false;
|
|
94
|
+
return () => { if (released) return; released = true; this._approvalHolds--; this.browsersChanged(); };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** A browser attached or left, or a guest turn holds approvals: keep the approval-client connection while any is. */
|
|
83
98
|
browsersChanged() {
|
|
84
99
|
if (this._closed) return;
|
|
85
|
-
const count = this.browserClients.size + this._externalBrowserCount();
|
|
100
|
+
const count = this.browserClients.size + this._externalBrowserCount() + this._approvalHolds;
|
|
86
101
|
if (count > 0) {
|
|
87
102
|
clearTimeout(this._approvalStopTimer);
|
|
88
103
|
this._approvalStopTimer = null;
|
package/server/index.js
CHANGED
|
@@ -35,6 +35,8 @@ import { SearchIndexer } from './search/indexer.js';
|
|
|
35
35
|
import { createTagStore } from './tags/store.js';
|
|
36
36
|
import { Tagger } from './tags/tagger.js';
|
|
37
37
|
import { readLegacyThreadSummaries } from './store/legacy-threads.js';
|
|
38
|
+
import { checkRepoDoc } from './peer/notes-sync.js';
|
|
39
|
+
import { connectorVersion } from './peer/version.js';
|
|
38
40
|
import { send, sendError, parseBody, uuid, matchRoute, setCors } from './util/http.js';
|
|
39
41
|
|
|
40
42
|
// PORT is passed via createApp(config.port); env var is read by plugin host (src/index.ts).
|
|
@@ -98,6 +100,7 @@ export function createApp(config = {}) {
|
|
|
98
100
|
// plugin host (src/index.ts) supplies the signal server link and the peer transport (config.peer).
|
|
99
101
|
const peerKey = loadOrCreatePeerKey(DATA_DIR);
|
|
100
102
|
const sharing = config.peer ? new SharingManager({
|
|
103
|
+
holdApprovals: () => gatewayClient.holdApprovals(),
|
|
101
104
|
getDb: () => globalDbCache.get(), request: gwRequest, chatAbort, key: peerKey, broadcast,
|
|
102
105
|
gatewayId: config.peer.gatewayId, signal: config.peer.signal, openPeer: config.peer.openPeer,
|
|
103
106
|
}) : null;
|
|
@@ -318,7 +321,36 @@ export function createApp(config = {}) {
|
|
|
318
321
|
if (method === 'GET' && urlPath === '/api/sharing') {
|
|
319
322
|
// Enabled once the signal server has sharing on for this account (it then sends share lists).
|
|
320
323
|
if (!sharing?.serverEnabled) return send(res, 200, { enabled: false, shares: [], remoteAgents: [] });
|
|
321
|
-
return send(res, 200, { enabled: true, fingerprint: peerKey.fingerprint, shares: sharing.list(), remoteAgents: sharing.remoteAgents(), contacts: sharing.contacts(), me: sharing.gatewayId?.() || null, guestAgentIds: [...sharing.guestAgentIds()] });
|
|
324
|
+
return send(res, 200, { enabled: true, fingerprint: peerKey.fingerprint, shares: sharing.list(), remoteAgents: sharing.remoteAgents(), contacts: sharing.contacts(), me: sharing.gatewayId?.() || null, guestAgentIds: [...sharing.guestAgentIds()], version: connectorVersion(), features: { contactCards: 1 } });
|
|
325
|
+
}
|
|
326
|
+
// Contact cards (peer/sharing.js contactCard/setContact): one person's settings, by lowercased email.
|
|
327
|
+
if ((p = matchRoute(method, urlPath, 'GET /api/sharing/contact/:person'))) {
|
|
328
|
+
if (!sharing) return sendError(res, 404, 'Sharing is not available');
|
|
329
|
+
try { return send(res, 200, await sharing.contactCard(p.person)); }
|
|
330
|
+
catch (e) { return sendError(res, e.code === 'not_found' ? 404 : 400, e.message); }
|
|
331
|
+
}
|
|
332
|
+
if ((p = matchRoute(method, urlPath, 'PUT /api/sharing/contact/:person'))) {
|
|
333
|
+
if (!sharing) return sendError(res, 404, 'Sharing is not available');
|
|
334
|
+
const { field, value, confirmFull } = await parseBody(req);
|
|
335
|
+
try { return send(res, 200, { contact: await sharing.setContact(p.person, field, value, { confirmFull: !!confirmFull }) }); }
|
|
336
|
+
catch (e) { return sendError(res, e.code === 'not_found' ? 404 : 400, e.message); }
|
|
337
|
+
}
|
|
338
|
+
if ((p = matchRoute(method, urlPath, 'POST /api/sharing/contact/:person/sync'))) {
|
|
339
|
+
if (!sharing) return sendError(res, 404, 'Sharing is not available');
|
|
340
|
+
try { return send(res, 200, { sync: await sharing.syncNotesNow(p.person) }); }
|
|
341
|
+
catch (e) { return sendError(res, 400, e.message); }
|
|
342
|
+
}
|
|
343
|
+
// Disconnect: after the shares are revoked, everything kept for the person goes (copies, approvals, notes, rows).
|
|
344
|
+
if ((p = matchRoute(method, urlPath, 'POST /api/sharing/contact/:person/forget'))) {
|
|
345
|
+
if (!sharing) return sendError(res, 404, 'Sharing is not available');
|
|
346
|
+
try { return send(res, 200, await sharing.forgetPerson(p.person)); }
|
|
347
|
+
catch (e) { return sendError(res, 400, e.message); }
|
|
348
|
+
}
|
|
349
|
+
// "Add a repo doc…": is this file allowed as a note? (a .md file in a git repo, not under ~/.openclaw, no links)
|
|
350
|
+
if (method === 'POST' && urlPath === '/api/sharing/check-doc') {
|
|
351
|
+
const { path: file } = await parseBody(req);
|
|
352
|
+
const r = checkRepoDoc(file);
|
|
353
|
+
return r.ok ? send(res, 200, r) : sendError(res, 400, r.error);
|
|
322
354
|
}
|
|
323
355
|
// The project a person's chats go to (peer/sharing.js funnel). Keyed by email.
|
|
324
356
|
if (method === 'GET' && urlPath === '/api/sharing/funnel') return send(res, 200, { funnel: sharing?.funnels() || {} });
|
|
@@ -334,7 +366,11 @@ export function createApp(config = {}) {
|
|
|
334
366
|
}
|
|
335
367
|
if ((p = matchRoute(method, urlPath, 'POST /api/sharing/:id/approve'))) {
|
|
336
368
|
if (!sharing) return sendError(res, 404, 'Sharing is not available');
|
|
337
|
-
try {
|
|
369
|
+
try {
|
|
370
|
+
const grant = sharing.approve(p.id, await parseBody(req));
|
|
371
|
+
sharing.prepareCopies(p.id); // in the background: the copies are ready before their first message (D9)
|
|
372
|
+
return send(res, 200, { grant });
|
|
373
|
+
}
|
|
338
374
|
catch (e) { return sendError(res, 400, e.message); }
|
|
339
375
|
}
|
|
340
376
|
if (method === 'POST' && urlPath === '/api/sharing/guest-agent') {
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// The agent copies made per person (D3): `<agent>-guest-<slug>` (Restricted/Trusted: its own folder, the original's
|
|
2
|
+
// personality, the picked notes) and `<agent>-full-<slug>` (Full agent: the original's workspace, memory read-only, no
|
|
3
|
+
// file tools unless one folder is opened). Each copy carries the contact's tool policy in its config entry and its basic
|
|
4
|
+
// commands in the exec approvals document. Writes are idempotent by policy hash (contacts.js peer_copy).
|
|
5
|
+
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { copyTools, approvalsEntry, policyHash, copySlug } from './contact-policy.js';
|
|
8
|
+
import { persistedButNotApplied } from './guest-agent.js';
|
|
9
|
+
|
|
10
|
+
const PERSONALITY_FILES = ['SOUL.md', 'IDENTITY.md'];
|
|
11
|
+
const agentName = a => a?.identity?.name || a?.name || a?.id;
|
|
12
|
+
const wait = ms => new Promise(r => setTimeout(r, ms));
|
|
13
|
+
const isValidation = e => /invalid|unexpected property|must not have additional|unknown (key|field)|unrecognized/i.test(e?.message || '');
|
|
14
|
+
|
|
15
|
+
export const copyIdFor = (agentId, personKey, kind) => `${agentId}-${kind}-${copySlug(personKey)}`;
|
|
16
|
+
|
|
17
|
+
/** A small model for Auto-review (one call per command): Haiku when the gateway has Anthropic models, else the agent's own. */
|
|
18
|
+
export function reviewerModelFor(cfg) {
|
|
19
|
+
const refs = JSON.stringify([cfg?.agents?.defaults?.model, cfg?.agents?.defaults?.models, cfg?.agents?.entries && Object.values(cfg.agents.entries).map(a => a?.model)]);
|
|
20
|
+
return /"anthropic\//.test(refs) ? 'anthropic/claude-haiku-4-5' : null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Create or update one person's copy of one agent. Returns { copyId, created, changed }.
|
|
25
|
+
* @param {object} o
|
|
26
|
+
* @param {(m, p, t?) => Promise<any>} o.request gateway RPC (operator.admin)
|
|
27
|
+
* @param {object} o.contact contacts.js contact
|
|
28
|
+
* @param {string} o.agentId the original agent
|
|
29
|
+
* @param {string} o.firstName the person's first name (copy display name)
|
|
30
|
+
* @param {object|null} o.known { copyId, policyHash } from peer_copy
|
|
31
|
+
*/
|
|
32
|
+
export async function ensureContactCopy({ request, contact, agentId, firstName, known = null, log = console }) {
|
|
33
|
+
const kind = contact.access === 'full' ? 'full' : 'guest';
|
|
34
|
+
const agents = (await request('agents.list', {}))?.agents || [];
|
|
35
|
+
const src = agents.find(a => a.id === agentId);
|
|
36
|
+
if (!src) throw new Error(`unknown agent: ${agentId}`);
|
|
37
|
+
let cfg = await request('config.get', {}, 30_000);
|
|
38
|
+
const reviewerModel = reviewerModelFor(cfg?.parsed);
|
|
39
|
+
const tools = copyTools(contact, { reviewerModel });
|
|
40
|
+
const approvals = approvalsEntry(contact);
|
|
41
|
+
const hash = policyHash({ tools, approvals, kind });
|
|
42
|
+
|
|
43
|
+
let copyId = known?.copyId && agents.some(a => a.id === known.copyId) ? known.copyId : null;
|
|
44
|
+
let created = false;
|
|
45
|
+
if (!copyId) {
|
|
46
|
+
const wantId = copyIdFor(agentId, contact.personKey, kind);
|
|
47
|
+
copyId = agents.some(a => a.id === wantId) ? wantId : null;
|
|
48
|
+
if (!copyId) {
|
|
49
|
+
copyId = await createCopy(request, src, { wantId, kind, firstName });
|
|
50
|
+
created = true;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (!created && known?.policyHash === hash && copyId === known.copyId && toolsWritten(cfg, copyId, tools)) return { copyId, created, changed: false, hash };
|
|
54
|
+
|
|
55
|
+
// Policy first: if anything after this fails, the copy is still locked down.
|
|
56
|
+
const pending = await patchTools(request, copyId, tools, cfg);
|
|
57
|
+
await setApprovals(request, copyId, approvals);
|
|
58
|
+
if (created) {
|
|
59
|
+
if (!(await waitForAgent(request, copyId))) throw new Error("The gateway didn't load the copy yet; try again");
|
|
60
|
+
if (kind === 'guest') await copyPersonality(request, src.id, copyId);
|
|
61
|
+
}
|
|
62
|
+
log.info?.(`[sharing] copy ${copyId} for ${contact.personKey}: ${created ? 'created' : 'updated'}`);
|
|
63
|
+
return { copyId, created, changed: true, hash, pending };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function createCopy(request, src, { wantId, kind, firstName }) {
|
|
67
|
+
const name = `${agentName(src)} (${kind === 'full' ? 'full' : 'guest'} · ${firstName})`;
|
|
68
|
+
const model = typeof src.model === 'string' ? src.model : src.model?.primary;
|
|
69
|
+
// Guest: its own folder beside the original's workspace (never inside it). Full: the original's workspace (§12).
|
|
70
|
+
const base = typeof src.workspace === 'string' && src.workspace.startsWith('/') ? src.workspace.replace(/\/+$/, '') : null;
|
|
71
|
+
const workspace = kind === 'full' ? base : base ? path.join(path.dirname(base), `workspace-${wantId}`) : undefined;
|
|
72
|
+
const params = { name, ...(workspace ? { workspace } : {}), ...(model ? { model } : {}), ...(src.identity?.emoji ? { emoji: src.identity.emoji } : {}) };
|
|
73
|
+
try {
|
|
74
|
+
return (await request('agents.create', { ...params, agentId: wantId }, 60_000)).agentId;
|
|
75
|
+
} catch (e) {
|
|
76
|
+
if (!isValidation(e)) throw e;
|
|
77
|
+
// 2026.9.x: no agentId; the id comes from the name. Two people with the same first name: the second gets the
|
|
78
|
+
// slug's short hash in its name (and so in its id).
|
|
79
|
+
try { return (await request('agents.create', params, 60_000)).agentId; }
|
|
80
|
+
catch (e2) {
|
|
81
|
+
if (!/exist|already|duplicate|taken|in use/i.test(e2.message)) throw e2;
|
|
82
|
+
return (await request('agents.create', { ...params, name: `${params.name.slice(0, -1)} ${wantId.slice(-4)})` }, 60_000)).agentId;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function toolsWritten(cfg, copyId, tools) {
|
|
88
|
+
const have = cfg?.parsed?.agents?.entries?.[copyId]?.tools;
|
|
89
|
+
// 2026.9.x has no tools.openclaw (patchTools drops it there).
|
|
90
|
+
if (have && !have.openclaw && tools.openclaw) { const { openclaw, ...rest } = tools; tools = rest; }
|
|
91
|
+
return JSON.stringify(sortDeep(have || null)) === JSON.stringify(sortDeep(tools));
|
|
92
|
+
}
|
|
93
|
+
const sortDeep = v => (Array.isArray(v) ? v.map(sortDeep) : v && typeof v === 'object' ? Object.fromEntries(Object.keys(v).sort().map(k => [k, sortDeep(v[k])])) : v);
|
|
94
|
+
|
|
95
|
+
async function patchTools(request, copyId, tools, cfg) {
|
|
96
|
+
const send = async (t, c) => request('config.patch', {
|
|
97
|
+
raw: JSON.stringify({ agents: { entries: { [copyId]: { tools: t } } } }),
|
|
98
|
+
...(c?.hash ? { baseHash: c.hash } : {}),
|
|
99
|
+
replacePaths: ['', '.alsoAllow', '.deny', '.exec', '.exec.safeBins'].map(p => `agents.entries.${copyId}.tools${p}`),
|
|
100
|
+
note: `ClawChats sharing: contact policy for ${copyId}`,
|
|
101
|
+
}, 60_000);
|
|
102
|
+
// Returns true when the gateway saved the policy but hasn't applied it yet (2026.11.4+: a deferred reload).
|
|
103
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
104
|
+
try { await send(tools, cfg); return false; }
|
|
105
|
+
catch (e) {
|
|
106
|
+
if (persistedButNotApplied(e, copyId)) return true;
|
|
107
|
+
if (/hash|changed since|conflict/i.test(e.message) && attempt < 2) { cfg = await request('config.get', {}, 30_000); continue; }
|
|
108
|
+
if (isValidation(e) && tools.openclaw) { const { openclaw, ...rest } = tools; tools = rest; continue; } // older gateway
|
|
109
|
+
throw e;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Merge the copy's entry into the exec approvals document (other agents' entries untouched). */
|
|
115
|
+
export async function setApprovals(request, copyId, entry) {
|
|
116
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
117
|
+
const snap = await request('exec.approvals.get', {}, 30_000);
|
|
118
|
+
const file = snap?.file && typeof snap.file === 'object' ? structuredClone(snap.file) : { version: 1 };
|
|
119
|
+
file.agents = { ...(file.agents || {}) };
|
|
120
|
+
if (entry === null) delete file.agents[copyId];
|
|
121
|
+
else file.agents[copyId] = { ...(file.agents[copyId] || {}), ...entry };
|
|
122
|
+
try { await request('exec.approvals.set', { file, ...(snap?.hash ? { baseHash: snap.hash } : {}) }, 30_000); return; }
|
|
123
|
+
catch (e) { if (attempt === 2 || !/hash|stale|changed/i.test(e.message)) throw e; }
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Retire a copy (Disconnect): every tool denied, commands off, its approvals entry removed. The agent stays, because
|
|
129
|
+
* deleting an agent deletes its sessions too (2026.11.6, checked live), and the owner keeps those chats (archived).
|
|
130
|
+
* A later reconnect with the same person rewrites it to the new card.
|
|
131
|
+
*/
|
|
132
|
+
export const RETIRED_TOOLS = Object.freeze({
|
|
133
|
+
profile: 'minimal', alsoAllow: [],
|
|
134
|
+
deny: ['group:fs', 'group:runtime', 'group:web', 'group:memory', 'group:media', 'group:ui', 'group:nodes', 'group:messaging',
|
|
135
|
+
'group:automation', 'group:sessions', 'group:agents', 'group:plugins', 'group:openclaw', 'gateway', 'openclaw', 'bundle-mcp'],
|
|
136
|
+
fs: { workspaceOnly: true }, exec: { mode: 'deny' },
|
|
137
|
+
});
|
|
138
|
+
export async function retireCopy(request, copyId) {
|
|
139
|
+
await setApprovals(request, copyId, null).catch(() => {});
|
|
140
|
+
const cfg = await request('config.get', {}, 30_000);
|
|
141
|
+
if (!cfg?.parsed?.agents?.entries?.[copyId] && !((await request('agents.list', {}))?.agents || []).some(a => a.id === copyId)) return false;
|
|
142
|
+
await patchTools(request, copyId, RETIRED_TOOLS, cfg);
|
|
143
|
+
return true;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async function waitForAgent(request, agentId, { tries = 120, ms = 250 } = {}) {
|
|
147
|
+
for (let i = 0; i < tries; i++) {
|
|
148
|
+
if (((await request('agents.list', {}))?.agents || []).some(a => a.id === agentId)) return true;
|
|
149
|
+
await wait(ms);
|
|
150
|
+
}
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async function copyPersonality(request, srcId, destId) {
|
|
155
|
+
for (const file of PERSONALITY_FILES) {
|
|
156
|
+
const got = await request('agents.files.get', { agentId: srcId, name: file }).catch(() => null);
|
|
157
|
+
const content = got?.file && !got.file.missing ? got.file.content : null;
|
|
158
|
+
if (typeof content !== 'string' || !content.trim()) continue;
|
|
159
|
+
for (let i = 0; i < 5; i++) {
|
|
160
|
+
try { await request('agents.files.set', { agentId: destId, name: file, content }); break; }
|
|
161
|
+
catch (e) { if (i === 4 || !/not found/i.test(e.message)) break; await wait(400); }
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|