@clawchatsai/connector 0.2.7 → 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/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/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
|
+
}
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
// What one contact (a person this gateway shares with) may make this gateway's agents do: the contact card's settings,
|
|
2
|
+
// their defaults per Access tier, and how each maps onto the gateway's enforcement layers (clawchats specs, contact
|
|
3
|
+
// card spec CONTACT-CARD-DESIGN.md §3-4):
|
|
4
|
+
// - the agent copy made for that person (`agents.entries.<copy>.tools`: profile, alsoAllow, deny, exec, fs);
|
|
5
|
+
// - the copy's exec approvals entry (basic-commands allowlist);
|
|
6
|
+
// - each guest session (permissionMode, toolOverrides: skills, mcpServers, webSearch);
|
|
7
|
+
// - the agent's instructions (Private / Always fine: instruction only).
|
|
8
|
+
// Pure functions only: contacts.js stores the settings, guest-agent.js writes the copy, sharing.js runs the turns.
|
|
9
|
+
|
|
10
|
+
import crypto from 'node:crypto';
|
|
11
|
+
import { GUEST_TOOLS_DENY } from './guest-agent.js';
|
|
12
|
+
|
|
13
|
+
export const ACCESS = ['restricted', 'trusted', 'full'];
|
|
14
|
+
export const COMMANDS = ['off', 'basic', 'ask', 'auto'];
|
|
15
|
+
export const KNOWLEDGE = ['none', 'notes'];
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Autonomy tiers (D10): how much this gateway's agents answer the person's agents on their own. One counter per
|
|
19
|
+
* person counts both their own questions and agent replies. `rounds` caps agent-to-agent rounds per human message
|
|
20
|
+
* (0: agents never answer the person's agents; the person can still ask).
|
|
21
|
+
*/
|
|
22
|
+
export const AUTONOMY = Object.freeze({
|
|
23
|
+
notify: Object.freeze({ rounds: 0, perDay: 50 }),
|
|
24
|
+
bounded: Object.freeze({ rounds: 3, perDay: 50 }),
|
|
25
|
+
extended: Object.freeze({ rounds: 10, perDay: 288, perHour: 12 }),
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Tools on the card, grouped as the card shows them. `personal`: reaches the owner's accounts. Commands are set by the
|
|
30
|
+
* Commands tier, not ticked. Always-off tools are never allowed for a contact, whatever is ticked.
|
|
31
|
+
*/
|
|
32
|
+
export const TOOL_GROUPS = Object.freeze([
|
|
33
|
+
{ id: 'files', title: 'Files', tools: ['read', 'write', 'edit', 'apply_patch'] },
|
|
34
|
+
{ id: 'commands', title: 'Commands', tools: ['exec', 'process'], byCommands: true },
|
|
35
|
+
{ id: 'web', title: 'Web', tools: ['web_search', 'web_fetch'] },
|
|
36
|
+
{ id: 'media', title: 'Media', tools: ['view_image', 'pdf', 'image_generate', 'tts'] },
|
|
37
|
+
{ id: 'memory', title: 'Memory', tools: ['memory_search', 'memory_get', 'wiki_search'] },
|
|
38
|
+
{ id: 'accounts', title: 'Reaches your accounts', tools: ['message', 'browser', 'nodes', 'computer', 'talk_voice'], personal: true },
|
|
39
|
+
{ id: 'gateway', title: 'Your gateway', tools: ['sessions_list', 'sessions_history', 'subagents', 'cron', 'canvas', 'dashboard'] },
|
|
40
|
+
]);
|
|
41
|
+
export const ALWAYS_OFF = Object.freeze(['gateway', 'openclaw', 'plugins', 'secrets', 'skill_workshop', 'agents_list']);
|
|
42
|
+
const TICKABLE = new Set(TOOL_GROUPS.filter(g => !g.byCommands).flatMap(g => g.tools));
|
|
43
|
+
const FILE_TOOLS = ['read', 'write', 'edit', 'apply_patch'];
|
|
44
|
+
const WRITE_TOOLS = ['write', 'edit', 'apply_patch'];
|
|
45
|
+
// The groups a copy denies as a whole (from the old guest policy), with the tools in each a contact could tick.
|
|
46
|
+
// A ticked tool lifts its group's deny; the group's other members are then denied one by one.
|
|
47
|
+
const GROUP_MEMBERS = Object.freeze({
|
|
48
|
+
'group:fs': FILE_TOOLS,
|
|
49
|
+
'group:web': ['web_search', 'x_search', 'web_fetch'],
|
|
50
|
+
'group:memory': ['memory_search', 'memory_get'],
|
|
51
|
+
'group:ui': ['browser', 'screen', 'theme', 'dashboard', 'terminal', 'portal', 'canvas', 'show_widget'],
|
|
52
|
+
'group:nodes': ['nodes', 'computer'],
|
|
53
|
+
'group:messaging': ['message'],
|
|
54
|
+
'group:automation': ['automations', 'cron', 'gateway', 'plugins', 'openclaw'],
|
|
55
|
+
'group:sessions': ['sessions', 'sessions_list', 'sessions_history', 'sessions_search', 'conversations_list', 'conversations_send',
|
|
56
|
+
'conversations_turn', 'sessions_send', 'sessions_spawn', 'sessions_yield', 'subagents', 'session_status', 'suggest_task', 'dismiss_task'],
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
export const DEFAULT_SKILLS = Object.freeze(['weather', 'diagram-maker', 'visualize']);
|
|
60
|
+
|
|
61
|
+
/** Tools ticked by default per Access tier (§3). */
|
|
62
|
+
export const DEFAULT_TOOLS = Object.freeze({
|
|
63
|
+
restricted: Object.freeze(['read', 'view_image', 'pdf']),
|
|
64
|
+
trusted: Object.freeze(['read', 'write', 'edit', 'apply_patch', 'view_image', 'pdf', 'web_search', 'web_fetch']),
|
|
65
|
+
full: Object.freeze(['memory_search', 'memory_get', 'view_image', 'pdf', 'web_search', 'web_fetch']),
|
|
66
|
+
});
|
|
67
|
+
export const DEFAULT_COMMANDS = Object.freeze({ restricted: 'basic', trusted: 'ask', full: 'ask' });
|
|
68
|
+
|
|
69
|
+
/** A new contact's settings (first-time accept: Trusted, Bounded, My notes with the default picks). */
|
|
70
|
+
export function defaultContact(access = 'trusted') {
|
|
71
|
+
return {
|
|
72
|
+
access, autonomy: 'bounded', knowledge: 'notes', notes: null, repos: [], agents: null,
|
|
73
|
+
tools: [...DEFAULT_TOOLS[access]], commands: DEFAULT_COMMANDS[access], basicList: null,
|
|
74
|
+
skills: [...DEFAULT_SKILLS], mcp: {}, mcpToolsDeny: {}, private: '', alwaysFine: '', openFolder: null,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* The tools a contact may actually get: ticked ∩ tickable, with the tier's hard limits. Full agent never writes
|
|
80
|
+
* (memory read-only, D7) and reads files only when one folder is opened (§12: secrets/ lives in the workspace).
|
|
81
|
+
*/
|
|
82
|
+
export function effectiveTools(c) {
|
|
83
|
+
let t = (Array.isArray(c.tools) ? c.tools : []).filter(x => TICKABLE.has(x));
|
|
84
|
+
if (c.access === 'full') {
|
|
85
|
+
// Reading is "Open one folder" itself, not a tick (the session root keeps it to that folder).
|
|
86
|
+
t = t.filter(x => !WRITE_TOOLS.includes(x) && x !== 'read');
|
|
87
|
+
if (c.openFolder) t.push('read');
|
|
88
|
+
} else {
|
|
89
|
+
t = t.filter(x => !['memory_search', 'memory_get', 'wiki_search'].includes(x)); // copies have no memory of the owner's
|
|
90
|
+
}
|
|
91
|
+
return [...new Set(t)].sort();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Copy exec settings per Commands tier (§4). `reviewerModel` only for Auto-review. */
|
|
95
|
+
export function execConfig(commands, reviewerModel = null) {
|
|
96
|
+
const mode = { off: 'deny', basic: 'allowlist', ask: 'ask', auto: 'auto' }[commands] || 'deny';
|
|
97
|
+
return {
|
|
98
|
+
mode, strictInlineEval: true, safeBins: ['head', 'tail', 'wc', 'cut', 'uniq', 'tr'],
|
|
99
|
+
...(mode === 'auto' && reviewerModel ? { reviewer: { model: reviewerModel } } : {}),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* The session's permission mode per Commands tier. Basic only and Off run with none (null): a session mode overrides
|
|
105
|
+
* the copy's exec policy, and a `guarded` session would turn allowlist misses back into approval cards (spike run 1).
|
|
106
|
+
* "Open one folder" needs a mode for its session root: refused for Off/Basic (card) and kept at guarded here.
|
|
107
|
+
*/
|
|
108
|
+
export function sessionMode(c) {
|
|
109
|
+
if (c.commands === 'ask') return 'guarded';
|
|
110
|
+
if (c.commands === 'auto') return 'workspace';
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The copy's `tools` config: an allowlist on the minimal profile, everything else denied on top. */
|
|
115
|
+
export function copyTools(c, { reviewerModel = null, autoApproveChanges = true } = {}) {
|
|
116
|
+
const allowed = effectiveTools(c);
|
|
117
|
+
const execOn = c.commands !== 'off';
|
|
118
|
+
const mcpOn = Object.values(c.mcp || {}).some(Boolean);
|
|
119
|
+
const alsoAllow = [...allowed, ...(execOn ? ['exec', 'process'] : []), ...(mcpOn ? ['bundle-mcp'] : [])];
|
|
120
|
+
const lifted = new Set(alsoAllow);
|
|
121
|
+
const deny = new Set();
|
|
122
|
+
for (const d of [...GUEST_TOOLS_DENY, ...ALWAYS_OFF]) {
|
|
123
|
+
const members = GROUP_MEMBERS[d];
|
|
124
|
+
if (members && members.some(m => lifted.has(m))) { for (const m of members) if (!lifted.has(m)) deny.add(m); continue; }
|
|
125
|
+
if (d === 'group:plugins' && (mcpOn || lifted.has('memory_search') || lifted.has('memory_get'))) continue; // MCP, memory-core
|
|
126
|
+
if (!lifted.has(d)) deny.add(d);
|
|
127
|
+
}
|
|
128
|
+
for (const g of TOOL_GROUPS) for (const t of g.tools) if (!lifted.has(t)) deny.add(t);
|
|
129
|
+
if (!execOn) { deny.add('exec'); deny.add('process'); deny.add('group:runtime'); }
|
|
130
|
+
for (const t of ALWAYS_OFF) deny.add(t);
|
|
131
|
+
return {
|
|
132
|
+
profile: 'minimal', alsoAllow: alsoAllow.sort(), deny: [...deny].sort(),
|
|
133
|
+
fs: { workspaceOnly: true },
|
|
134
|
+
exec: execConfig(c.commands, reviewerModel),
|
|
135
|
+
...(autoApproveChanges ? { openclaw: { autoApproveChanges: false } } : {}),
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Whether a copy's configured tools still hold the policy written for it (else its turns are refused). */
|
|
140
|
+
export function copyToolsHold(tools, want) {
|
|
141
|
+
if (!tools || tools.profile !== want.profile || tools.allow) return false;
|
|
142
|
+
if (tools.fs?.workspaceOnly !== true) return false;
|
|
143
|
+
const also = new Set(Array.isArray(tools.alsoAllow) ? tools.alsoAllow : []);
|
|
144
|
+
const deny = new Set(Array.isArray(tools.deny) ? tools.deny : []);
|
|
145
|
+
if ([...also].some(t => !want.alsoAllow.includes(t))) return false;
|
|
146
|
+
if (want.deny.some(t => !deny.has(t))) return false;
|
|
147
|
+
return (tools.exec?.mode || null) === want.exec.mode;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// ── Basic commands (§4 "Default basic list") ─────────────────────────
|
|
151
|
+
|
|
152
|
+
/** Default list: bare command + anchored argPattern; `args` is what the card shows. */
|
|
153
|
+
export const BASIC_DEFAULTS = Object.freeze([
|
|
154
|
+
{ pattern: 'openclaw', argPattern: '^(--version|-V)$', args: '--version' },
|
|
155
|
+
{ pattern: 'uname', argPattern: '^(-[asrmnvpio]+)?$', args: '-a, -r, -m …' },
|
|
156
|
+
{ pattern: 'uptime', argPattern: '^(-p|-s)?$', args: '(none), -p' },
|
|
157
|
+
{ pattern: 'df', argPattern: '^(-h|-hT|-h -T)?$', args: '-h' },
|
|
158
|
+
{ pattern: 'free', argPattern: '^(-h|-m|-g)?$', args: '-h' },
|
|
159
|
+
{ pattern: 'nproc', argPattern: '^$', args: '(none)' },
|
|
160
|
+
{ pattern: 'lscpu', argPattern: '^$', args: '(none)' },
|
|
161
|
+
{ pattern: 'date', argPattern: '^$', args: '(none)' },
|
|
162
|
+
{ pattern: 'cat', argPattern: '^/etc/os-release$', args: '/etc/os-release only' },
|
|
163
|
+
{ pattern: 'node', argPattern: '^(--version|-v|-V)$', args: '--version' },
|
|
164
|
+
{ pattern: 'npm', argPattern: '^(--version|-v|-V)$', args: '--version' },
|
|
165
|
+
{ pattern: 'python3', argPattern: '^(--version|-v|-V)$', args: '--version' },
|
|
166
|
+
]);
|
|
167
|
+
const GIT_ARGS = '(log( --oneline)?( -n ?[0-9]{1,3}| -[0-9]{1,3})?|status( -s| --short)?|describe --tags|rev-parse --short HEAD|branch --show-current)';
|
|
168
|
+
const reEscape = s => String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
169
|
+
|
|
170
|
+
/** One git entry per repo picked under Knowledge (D4): read-only subcommands, in that repo only. */
|
|
171
|
+
export function gitEntries(repos) {
|
|
172
|
+
return (Array.isArray(repos) ? repos : []).filter(r => typeof r === 'string' && r.startsWith('/'))
|
|
173
|
+
.map(r => ({ pattern: 'git', argPattern: `^-C ${reEscape(r.replace(/\/+$/, ''))} ${GIT_ARGS}$`, args: `-C ${r} log, status, describe…`, repo: r }));
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// Commands that read anything, run code or reach out: only with an anchored argPattern.
|
|
177
|
+
const RISKY = /^(cat|less|more|head|tail|env|printenv|bash|sh|zsh|dash|fish|python[0-9.]*|node|deno|bun|perl|ruby|php|curl|wget|ssh|scp|nc|ncat|openclaw|sudo|find|xargs|docker|journalctl|systemctl)$/;
|
|
178
|
+
const anchored = p => typeof p === 'string' && p.startsWith('^') && p.endsWith('$') && !/(^|[^\\])\.\*/.test(p);
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Check one entry of an edited basic list: { ok, error?, warning? }. A bare command name only (no paths or globs), an
|
|
182
|
+
* argPattern that compiles, and for anything risky an anchored one with no `.*`.
|
|
183
|
+
*/
|
|
184
|
+
export function validateBasicEntry({ pattern, argPattern } = {}) {
|
|
185
|
+
const cmd = String(pattern || '').trim();
|
|
186
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(cmd)) return { ok: false, error: 'Use a bare command name, like "uptime" (no paths or wildcards)' };
|
|
187
|
+
if (argPattern != null && argPattern !== '') {
|
|
188
|
+
try { new RegExp(argPattern); } catch { return { ok: false, error: 'The arguments pattern isn\'t a valid regular expression' }; }
|
|
189
|
+
}
|
|
190
|
+
if (RISKY.test(cmd) && !anchored(argPattern)) {
|
|
191
|
+
return { ok: false, error: `"${cmd}" can read files, run code or reach out: give it an exact arguments pattern (^…$, no .*)` };
|
|
192
|
+
}
|
|
193
|
+
if (!argPattern) return { ok: true, warning: `Any arguments to "${cmd}" will run without asking` };
|
|
194
|
+
if (/\.openclaw/.test(argPattern)) return { ok: true, warning: 'This pattern mentions .openclaw, where your gateway config and secrets live' };
|
|
195
|
+
return { ok: true };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** The list the copy's approvals entry allows: the edited or default list, plus the git entries. */
|
|
199
|
+
export function basicList(c) {
|
|
200
|
+
const base = Array.isArray(c.basicList) ? c.basicList.filter(e => validateBasicEntry(e).ok) : BASIC_DEFAULTS;
|
|
201
|
+
return [...base.map(({ pattern, argPattern, args }) => ({ pattern, argPattern: argPattern || undefined, args })), ...gitEntries(c.repos)];
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** The copy's entry in the exec approvals document (`agents.<copy>`). */
|
|
205
|
+
export function approvalsEntry(c) {
|
|
206
|
+
const ask = c.commands === 'ask' || c.commands === 'auto' ? 'on-miss' : 'off';
|
|
207
|
+
return {
|
|
208
|
+
security: c.commands === 'off' ? 'deny' : 'allowlist', ask, askFallback: 'deny', autoAllowSkills: false,
|
|
209
|
+
allowlist: c.commands === 'off' ? [] : basicList(c).map(({ pattern, argPattern }) => (argPattern ? { pattern, argPattern } : { pattern })),
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// ── Session overrides ──────────────────────────────────────────────
|
|
214
|
+
|
|
215
|
+
/** `toolOverrides` for the person's sessions: every known skill/MCP server set explicitly, so new ones start off. */
|
|
216
|
+
export function toolOverrides(c, { skillNames = [], mcpServers = [] } = {}) {
|
|
217
|
+
const on = new Set(Array.isArray(c.skills) ? c.skills : []);
|
|
218
|
+
const skills = Object.fromEntries([...new Set(skillNames)].sort().map(n => [n, on.has(n)]));
|
|
219
|
+
const mcp = Object.fromEntries([...new Set(mcpServers)].sort().map(n => [n, !!c.mcp?.[n]]));
|
|
220
|
+
const deny = Object.fromEntries(Object.entries(c.mcpToolsDeny || {}).filter(([s, l]) => mcp[s] && Array.isArray(l) && l.length).map(([s, l]) => [s, [...l].sort()]));
|
|
221
|
+
return {
|
|
222
|
+
webSearch: effectiveTools(c).includes('web_search'),
|
|
223
|
+
...(Object.keys(skills).length ? { skills } : {}),
|
|
224
|
+
...(Object.keys(mcp).length ? { mcpServers: mcp } : {}),
|
|
225
|
+
...(Object.keys(deny).length ? { mcpToolsDeny: deny } : {}),
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Private / Always fine, for the agent's instructions while that person is in the conversation (instruction only). */
|
|
230
|
+
export function topicsNote(c, name) {
|
|
231
|
+
const clean = s => String(s || '').replace(/[\u0000-\u0008\u000b-\u001f]/g, ' ').trim().slice(0, 1000);
|
|
232
|
+
const priv = clean(c.private), fine = clean(c.alwaysFine);
|
|
233
|
+
const lines = [];
|
|
234
|
+
if (priv) lines.push(`Your owner keeps these topics private from ${name} and ${name}'s agents: don't discuss them, and say so briefly if asked: ${priv}`);
|
|
235
|
+
if (fine) lines.push(`Your owner is happy for you to share these with ${name} freely: ${fine}`);
|
|
236
|
+
return lines.map(l => `(${l})`).join('\n');
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** A stable hash of everything written to a copy (config + approvals), to tell when it must be rewritten. */
|
|
240
|
+
export function policyHash(obj) {
|
|
241
|
+
const canon = v => (Array.isArray(v) ? v.map(canon) : v && typeof v === 'object' ? Object.fromEntries(Object.keys(v).sort().map(k => [k, canon(v[k])])) : v);
|
|
242
|
+
return crypto.createHash('sha256').update(JSON.stringify(canon(obj))).digest('hex').slice(0, 16);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** Copy ids: `<agent>-guest-<slug>` / `<agent>-full-<slug>` (D3). The slug is the email's local part plus a short hash. */
|
|
246
|
+
export function copySlug(personKey) {
|
|
247
|
+
const local = String(personKey || '').split('@')[0].toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 20) || 'contact';
|
|
248
|
+
return `${local}-${crypto.createHash('sha256').update(String(personKey)).digest('hex').slice(0, 4)}`;
|
|
249
|
+
}
|
|
250
|
+
export const copyKind = c => (c.access === 'full' ? 'full' : 'guest');
|