@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.
@@ -6,7 +6,7 @@ import path from 'node:path';
6
6
  import { Database } from '../bootstrap/native.js';
7
7
  import { SharingManager, defangLocalPaths } from './sharing.js';
8
8
  import { loadOrCreatePeerKey, fingerprint } from './keys.js';
9
- import { GUEST_TOOLS, unappliedGuests } from './guest-agent.js';
9
+ import { GUEST_TOOLS } from './guest-agent.js';
10
10
 
11
11
  const quiet = { warn() {}, info() {} };
12
12
  const keyIn = () => loadOrCreatePeerKey(fs.mkdtempSync(path.join(os.tmpdir(), 'pk-')));
@@ -22,7 +22,7 @@ function pair() {
22
22
  }
23
23
 
24
24
  /** Owner (Kamil, gateway gwK) shares with requester (Houman, gateway gwH). */
25
- function setup({ reply = p => `jarvis says: ${p.message.split('\n\n').pop()}`, config = {}, cfgExtra = {} } = {}) {
25
+ function setup({ reply = p => `jarvis says: ${p.message.split('\n\n').pop()}`, config = {}, cfgExtra = {}, ownerVersion, reqVersion } = {}) {
26
26
  const kOwner = keyIn(), kReq = keyIn();
27
27
  const ownerCalls = [], ownerSignals = [], reqSignals = [];
28
28
  let owner;
@@ -37,14 +37,32 @@ function setup({ reply = p => `jarvis says: ${p.message.split('\n\n').pop()}`, c
37
37
  });
38
38
  return { runId: params.idempotencyKey, status: 'started' };
39
39
  }
40
- if (method === 'config.get') return { hash: 'h', parsed: config, ...cfgExtra };
40
+ if (method === 'config.get') return { hash: 'h', parsed: { ...config, agents: { ...(config.agents || {}), entries: { ...(config.agents?.entries || {}), ...gw.entries } } }, ...cfgExtra };
41
41
  if (method === 'chat.abort') { setImmediate(() => owner.onGatewayEvent({ event: 'chat', payload: { runId: params.runId, state: 'aborted' } })); return { ok: true }; }
42
+ // A small fake gateway for the contact copies: agents, their config entries, the exec approvals document.
43
+ if (method === 'agents.list') return { agents: gw.agents };
44
+ if (method === 'agents.create') {
45
+ const id = params.agentId || params.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
46
+ gw.agents.push({ id, name: params.name, workspace: params.workspace });
47
+ return { ok: true, agentId: id, name: params.name, workspace: params.workspace };
48
+ }
49
+ if (method === 'agents.delete') { gw.agents = gw.agents.filter(x => x.id !== params.agentId); delete gw.entries[params.agentId]; return { ok: true }; }
50
+ if (method === 'config.patch') {
51
+ for (const [id, e] of Object.entries(JSON.parse(params.raw).agents?.entries || {})) gw.entries[id] = { ...(gw.entries[id] || {}), ...e };
52
+ return { ok: true };
53
+ }
54
+ if (method === 'exec.approvals.get') return { hash: 'a', file: gw.approvals };
55
+ if (method === 'exec.approvals.set') { gw.approvals = params.file; return { ok: true }; }
56
+ if (method === 'skills.status') return { skills: gw.skills.map(name => ({ name })) };
57
+ if (method === 'agents.files.get') return { file: { missing: true } };
42
58
  return { ok: true };
43
59
  };
60
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'gw-'));
61
+ const gw = { root, agents: [{ id: 'jarvis', name: 'Jarvis', workspace: path.join(root, 'ws') }, { id: 'jarvis-guest', name: 'Jarvis (guest)', workspace: path.join(root, 'ws-guest') }, { id: 'main', name: 'Main', workspace: path.join(root, 'ws-main') }], entries: {}, approvals: { version: 1 }, skills: [] };
44
62
  const ownerDb = new Database(':memory:'), reqDb = new Database(':memory:');
45
- owner = new SharingManager({ getDb: () => ownerDb, request: ownerRequest, recovery: { waitMs: 60, pollMs: 5 }, key: kOwner, gatewayId: () => 'gwK', signal: m => ownerSignals.push(m), openPeer: async () => { throw new Error('owner never dials'); }, log: quiet });
63
+ owner = new SharingManager({ getDb: () => ownerDb, request: ownerRequest, recovery: { waitMs: 60, pollMs: 5 }, key: kOwner, gatewayId: () => 'gwK', signal: m => ownerSignals.push(m), openPeer: async () => { throw new Error('owner never dials'); }, log: quiet, ...(ownerVersion !== undefined ? { version: ownerVersion } : {}) });
46
64
  const req = new SharingManager({
47
- getDb: () => reqDb, request: async () => ({}), key: kReq, gatewayId: () => 'gwH', signal: m => reqSignals.push(m), log: quiet, resendBackoffMs: [5, 10],
65
+ getDb: () => reqDb, request: async () => ({}), key: kReq, gatewayId: () => 'gwH', signal: m => reqSignals.push(m), log: quiet, resendBackoffMs: [5, 10], ...(reqVersion !== undefined ? { version: reqVersion } : {}),
48
66
  openPeer: async shareId => {
49
67
  const [a, b] = pair();
50
68
  owner.servePeer({ dc: b, dtls: { local: 'FK', remote: 'FH' }, shareId, requesterGatewayId: 'gwH' });
@@ -63,7 +81,7 @@ function setup({ reply = p => `jarvis says: ${p.message.split('\n\n').pop()}`, c
63
81
  req.setShares([{ ...active, as: 'requester' }]);
64
82
  return active;
65
83
  };
66
- return { owner, req, ownerCalls, ownerSignals, reqSignals, activate, kOwner, kReq, people };
84
+ return { owner, req, ownerCalls, ownerSignals, reqSignals, activate, kOwner, kReq, people, gw };
67
85
  }
68
86
 
69
87
  test('a guest session the owner deleted is made again on the next turn, with its label in "Shared with <name>"', async () => {
@@ -79,7 +97,8 @@ test('a guest session the owner deleted is made again on the next turn, with its
79
97
  await s.req.turn('peer:sh1:jarvis-guest', { turnId: 't2', roomId: 'room1', roomTitle: 'Rivers', message: 'still there?' });
80
98
  const creates = s.ownerCalls.filter(c => c.method === 'sessions.create').map(c => c.params);
81
99
  assert.equal(creates.length, 2);
82
- assert.deepEqual([creates[1].key, creates[1].label, creates[1].category, creates[1].permissionMode], [first.key, first.label, 'Shared with Houman S', 'read-only']);
100
+ // Restricted runs Basic only: no session mode (a mode would override the copy's exec allowlist).
101
+ assert.deepEqual([creates[1].key, creates[1].label, creates[1].category, creates[1].permissionMode], [first.key, first.label, 'Shared with Houman S', undefined]);
83
102
  assert.equal(s.ownerCalls.filter(c => c.method === 'chat.send').at(-1).params.sessionKey, first.key);
84
103
 
85
104
  // Still there: reused, no new session.
@@ -88,7 +107,7 @@ test('a guest session the owner deleted is made again on the next turn, with its
88
107
  assert.equal(s.ownerCalls.filter(c => c.method === 'sessions.create').length, 2);
89
108
  });
90
109
 
91
- test('a shared agent renamed by its owner: the grant is re-issued with the new name, same access and cap', async () => {
110
+ test('a shared agent renamed by its owner: the grant is re-issued with the new name, same access and autonomy', async () => {
92
111
  const s = setup();
93
112
  s.owner.approve('sh1', { agents: [{ id: 'jarvis-guest', name: 'Jarvis' }], access: 'trusted', dailyCap: 7 });
94
113
  s.activate();
@@ -100,7 +119,7 @@ test('a shared agent renamed by its owner: the grant is re-issued with the new n
100
119
  agents = [{ id: 'jarvis', identity: { name: 'Jarvy' } }, { id: 'jarvis-guest', identity: { name: 'Jarvis (guest)' } }];
101
120
  assert.deepEqual(await s.owner.syncAgentNames(), ['sh1']);
102
121
  const g = s.ownerSignals.filter(m => m.type === 'share-grant').at(-1).grant;
103
- assert.deepEqual([g.agents, g.access, g.dailyCap], [[{ id: 'jarvis-guest', name: 'Jarvy' }], 'trusted', 7]);
122
+ assert.deepEqual([g.v, g.agents, g.access, g.autonomy, g.dailyCap], [2, [{ id: 'jarvis-guest', name: 'Jarvy' }], 'trusted', 'bounded', undefined]);
104
123
  s.activate();
105
124
  assert.equal(s.req.remoteAgents()[0].name, 'Jarvy · Kamil', 'the requester sees the new name');
106
125
  assert.deepEqual(await s.owner.syncAgentNames(), [], 'once');
@@ -221,19 +240,20 @@ test('approve → verified on the requester → turn runs in a guest session on
221
240
  assert.deepEqual(deltas, ['jar']);
222
241
 
223
242
  const create = s.ownerCalls.find(c => c.method === 'sessions.create').params;
224
- assert.equal(create.agentId, 'jarvis-guest');
225
- assert.equal(create.permissionMode, 'read-only');
226
- assert.deepEqual(create.toolOverrides, { webSearch: false }); // no MCP servers configured here
243
+ assert.equal(create.agentId, 'jarvis-guest-h-bc35', "Houman's own copy of Jarvis (D3), not the shared guest version");
244
+ assert.equal(create.permissionMode, undefined, 'Restricted = Basic only: no session mode');
245
+ assert.deepEqual(create.toolOverrides, { webSearch: false }); // no MCP servers or skills configured here
227
246
  assert.equal(create.category, 'Shared with Houman S');
228
247
  const send = s.ownerCalls.find(c => c.method === 'chat.send').params;
229
248
  assert.equal(send.suppressCommandInterpretation, true); // guest text is never a slash command
230
- assert.equal(send.expectedPermissionMode, 'read-only');
249
+ assert.equal(send.expectedPermissionMode, null, 'the turn checks the session still has no mode');
231
250
  assert.ok(send.timeoutMs > 0);
232
251
  assert.match(send.message, /is not your owner/);
233
252
 
234
- // Same room reuses the session; daily cap enforced by the owner.
253
+ // Same room reuses the session; the person's daily cap (Bounded: 50) enforced by the owner.
235
254
  await s.req.turn('peer:sh1:jarvis-guest', { turnId: 't2', roomId: 'room1', message: 'again' });
236
255
  assert.equal(s.ownerCalls.filter(c => c.method === 'sessions.create').length, 1);
256
+ s.owner.book.count('h@x.dev', 48);
237
257
  await assert.rejects(s.req.turn('peer:sh1:jarvis-guest', { turnId: 't3', roomId: 'room1', message: 'third' }), e => e.code === 'cap');
238
258
  // An agent that isn't in the grant can't be asked for.
239
259
  await assert.rejects(s.req.turn('peer:sh1:main', { turnId: 't4', roomId: 'room1', message: 'x' }), e => e.code === 'not_shared');
@@ -248,7 +268,8 @@ test('trusted access uses guarded mode; changing the grant re-applies the policy
248
268
  s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }], access: 'restricted' });
249
269
  s.activate();
250
270
  await s.req.turn('peer:sh1:jarvis', { turnId: 't2', roomId: 'r', message: 'hi' });
251
- assert.equal(s.ownerCalls.filter(c => c.method === 'sessions.patch').at(-1).params.permissionMode, 'read-only');
271
+ assert.equal(s.ownerCalls.filter(c => c.method === 'chat.send').at(-1).params.sessionKey.split(':')[1], 'jarvis-guest-h-bc35', 'Trusted and Restricted share the person\'s guest copy');
272
+ assert.equal(s.ownerCalls.filter(c => c.method === 'sessions.patch').at(-1).params.permissionMode, null, 'Basic only clears the mode');
252
273
  });
253
274
 
254
275
  test('requester refuses a grant not signed by the owner key, and a changed owner key', async () => {
@@ -328,30 +349,39 @@ test('guest sessions turn every configured MCP server off, and chat.send checks
328
349
  assert.deepEqual(s.ownerCalls.find(c => c.method === 'chat.send').params.expectedToolOverrides, want);
329
350
  });
330
351
 
331
- test('a guest agent whose restrictions were removed is not served', async () => {
332
- const config = { agents: { entries: { 'jarvis-guest': { tools: GUEST_TOOLS } } } };
333
- const s = setup({ config });
334
- s.owner.markGuestAgent('jarvis-guest');
352
+ test("a person's copy whose policy was edited away is written back before the turn; one that can't be is not served", async () => {
353
+ const s = setup();
335
354
  s.owner.approve('sh1', { agents: [{ id: 'jarvis-guest', name: 'Jarvis' }] });
336
355
  s.activate();
337
356
  await s.req.turn('peer:sh1:jarvis-guest', { turnId: 't1', roomId: 'r', message: 'hi' });
338
- config.agents.entries['jarvis-guest'].tools = { deny: ['message'] }; // edited in the Control UI
339
- await assert.rejects(s.req.turn('peer:sh1:jarvis-guest', { turnId: 't2', roomId: 'r', message: 'hi' }), e => e.code === 'unavailable');
340
- assert.equal(s.ownerCalls.filter(c => c.method === 'chat.send').length, 1);
357
+ const copy = 'jarvis-guest-h-bc35';
358
+ s.gw.entries[copy].tools = { deny: ['message'] }; // edited in the Control UI
359
+ await s.req.turn('peer:sh1:jarvis-guest', { turnId: 't2', roomId: 'r', message: 'hi' });
360
+ assert.equal(s.gw.entries[copy].tools.profile, 'minimal', 'restored');
361
+ // The gateway won't take the write: refused, and the run never starts.
362
+ s.gw.entries[copy].tools = { deny: ['message'] };
363
+ const request = s.owner.request;
364
+ s.owner.request = async (m, p) => (m === 'config.patch' ? { ok: true } : request(m, p));
365
+ await assert.rejects(s.req.turn('peer:sh1:jarvis-guest', { turnId: 't3', roomId: 'r', message: 'hi' }), e => e.code === 'unavailable');
366
+ assert.equal(s.ownerCalls.filter(c => c.method === 'chat.send').length, 2);
341
367
  });
342
368
 
343
- test('a guest whose saved restrictions the running gateway has not applied yet is not served until it has', async () => {
344
- const config = { agents: { entries: { 'jarvis-guest': { tools: GUEST_TOOLS } } } };
369
+ test("a copy whose saved policy the running gateway has not applied yet is not served until it has", async () => {
345
370
  const cfgExtra = { configRevisionHash: 'saved', appliedConfigHash: 'older' };
346
- const s = setup({ config, cfgExtra });
347
- s.owner.markGuestAgent('jarvis-guest');
348
- s.owner.approve('sh1', { agents: [{ id: 'jarvis-guest', name: 'Jarvis' }] });
371
+ const s = setup({ cfgExtra });
372
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }] });
349
373
  s.activate();
350
- unappliedGuests.add('jarvis-guest'); // ensureGuestRestrictions saw "persisted but not applied" (2026.11.4+)
351
- await assert.rejects(s.req.turn('peer:sh1:jarvis-guest', { turnId: 't1', roomId: 'r', message: 'hi' }), e => e.code === 'unavailable');
374
+ // 2026.11.4+: the patch was saved, but a deferred reload hasn't applied it.
375
+ const request = s.owner.request;
376
+ s.owner.request = async (m, p) => {
377
+ if (m !== 'config.patch') return request(m, p);
378
+ await request(m, p);
379
+ throw Object.assign(new Error('saved, not applied'), { gatewayCode: 'UNAVAILABLE', details: { persistedConfig: {} } });
380
+ };
381
+ await assert.rejects(s.req.turn('peer:sh1:jarvis', { turnId: 't1', roomId: 'r', message: 'hi' }), e => e.code === 'unavailable');
352
382
  assert.equal(s.ownerCalls.filter(c => c.method === 'chat.send').length, 0);
353
383
  cfgExtra.appliedConfigHash = 'saved'; // the reload landed
354
- await s.req.turn('peer:sh1:jarvis-guest', { turnId: 't2', roomId: 'r', message: 'hi' });
384
+ await s.req.turn('peer:sh1:jarvis', { turnId: 't2', roomId: 'r', message: 'hi' });
355
385
  assert.equal(s.ownerCalls.filter(c => c.method === 'chat.send').length, 1);
356
386
  });
357
387
 
@@ -543,11 +573,12 @@ test('a reply that fails without text is not counted against the daily cap; one
543
573
  const s = setup({ reply: () => null }); // runs stay open; the test ends them
544
574
  s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }], dailyCap: 5 });
545
575
  s.activate();
546
- // A guest version whose restrictions were removed: refused before it runs, nothing said.
547
- s.owner.markGuestAgent('jarvis');
576
+ // A copy that doesn't hold its policy: refused before it runs, nothing said.
577
+ const request = s.owner.request;
578
+ s.owner.request = async (m, p) => (m === 'config.patch' ? { ok: true } : request(m, p));
548
579
  await assert.rejects(s.req.turn('peer:sh1:jarvis', { turnId: 'f1', roomId: 'room1', message: 'hi' }), e => e.code === 'unavailable');
549
580
  assert.equal(s.owner.list()[0].usedToday, 0);
550
- s.owner._db().prepare('DELETE FROM peer_guest_agents').run();
581
+ s.owner.request = request;
551
582
  // Fails after streaming some text ("jar"): counted.
552
583
  const p = s.req.turn('peer:sh1:jarvis', { turnId: 'f2', roomId: 'room1', message: 'hi' });
553
584
  for (let i = 0; i < 50 && !s.ownerCalls.some(c => c.method === 'chat.send'); i++) await wait(2);
@@ -565,10 +596,7 @@ test("acting for someone: this gateway's agent answers their agent as the versio
565
596
  // Kamil (this gateway, gwK) also uses Houman's main: share sh2, Kamil as requester, Houman's gateway gwH.
566
597
  const theirs = { id: 'sh2', as: 'requester', status: 'active', requester: s.people.owner, owner: s.people.requester, agents: [{ id: 'main-guest', name: 'main' }] };
567
598
  s.owner.setShares([{ ...active, as: 'owner' }, theirs]);
568
- const orig = s.owner.request;
569
- s.owner.request = async (m, p) => (m === 'agents.list'
570
- ? { agents: [{ id: 'jarvis', name: 'Jarvis' }, { id: 'jarvis-guest', name: 'Jarvis (guest)' }, { id: 'dev', name: 'Dev' }] }
571
- : orig(m, p));
599
+ s.gw.agents.push({ id: 'dev', name: 'Dev' });
572
600
 
573
601
  assert.equal(s.owner.actingForName('peer:sh2:main-guest'), 'Houman');
574
602
  const deltas = [];
@@ -576,8 +604,8 @@ test("acting for someone: this gateway's agent answers their agent as the versio
576
604
  assert.equal(r.state, 'final');
577
605
  assert.deepEqual(deltas, ['jar']);
578
606
  const create = s.ownerCalls.find(c => c.method === 'sessions.create').params;
579
- assert.equal(create.agentId, 'jarvis-guest', 'the guest copy, never the real agent');
580
- assert.equal(create.permissionMode, 'read-only');
607
+ assert.equal(create.agentId, 'jarvis-guest-h-bc35', "Houman's copy, never the real agent");
608
+ assert.equal(create.permissionMode, undefined);
581
609
  assert.equal(create.category, 'Shared with Houman S');
582
610
  const send = s.ownerCalls.find(c => c.method === 'chat.send').params;
583
611
  assert.match(send.message, /in your owner's team chat, you are answering Houman S's agent/);
@@ -766,7 +794,7 @@ test('a grant only counts for the gateway it was signed for (the server can\'t p
766
794
 
767
795
  test('peer requests are rate limited per contact (turns, and everything else), without touching normal use', async () => {
768
796
  const s = setup();
769
- s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }], dailyCap: 100 });
797
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }], autonomy: 'bounded' });
770
798
  s.activate();
771
799
  // A normal chat: a handful of replies is fine.
772
800
  for (let i = 0; i < 5; i++) await s.req.turn('peer:sh1:jarvis', { turnId: `n${i}`, roomId: 'r', message: 'hi' });
@@ -942,7 +970,7 @@ test('a resend of a turn its restart cut off (input there, no reply, nothing run
942
970
  s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }], dailyCap: 10 });
943
971
  s.activate();
944
972
  await restartedOwner(s, { reply: null });
945
- s.owner._db().prepare('DELETE FROM peer_usage').run();
973
+ s.owner._db().prepare('DELETE FROM peer_person_usage').run();
946
974
  await assert.rejects(s.req.turn('peer:sh1:jarvis', { turnId: 'team-11', roomId: 'r', message: 'hi' }), e => e.code === 'run_failed' && /interrupted/.test(e.message));
947
975
  assert.equal(s.ownerCalls.filter(c => c.method === 'chat.send').length, 0);
948
976
  assert.equal(s.owner._usage('sh1'), 0);
@@ -1060,3 +1088,236 @@ test('Stop while the gateway resumes a turn: the resumed run is aborted, fenced,
1060
1088
  const abort = s.ownerCalls.find(c => c.method === 'chat.abort' && c.params.runId === 'recovery-run')?.params;
1061
1089
  assert.ok(abort, 'the resumed run was aborted');
1062
1090
  });
1091
+
1092
+ // ── Contact cards (TASK-08) ──────────────────────────────────────────
1093
+
1094
+ test('an older connector on the requester side is refused cleanly: it is told to update, the owner marks them "needs update"', async () => {
1095
+ for (const reqVersion of ['0.2.4', null]) {
1096
+ const s = setup({ reqVersion });
1097
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }] });
1098
+ s.activate();
1099
+ const link = await s.req._link('sh1').catch(e => e); // this test's requester runs our code: it still dials
1100
+ const err = await link.request('turn', { turnId: 't1', agentId: 'jarvis', roomId: 'r', message: 'hi' }, { timeoutMs: 5000 }).catch(e => e);
1101
+ assert.equal(err.code, 'peer_outdated');
1102
+ assert.match(err.message, /^Your ClawChats connector is out of date[^]*openclaw plugins install/, 'what the old side shows');
1103
+ assert.equal(s.ownerCalls.filter(c => c.method === 'chat.send').length, 0, 'nothing ran');
1104
+ const mine = s.owner.list()[0];
1105
+ assert.match(mine.needsUpdate.message, /Houman's ClawChats connector is out of date/);
1106
+ const rooms = await link.request('room.fetch', { roomId: 'x' }, { timeoutMs: 5000 }).catch(e => e);
1107
+ assert.equal(rooms.code, 'peer_outdated', 'no room traffic either');
1108
+ }
1109
+ });
1110
+
1111
+ test('an older connector on the owner side is refused by the requester before any turn, with the update command', async () => {
1112
+ const s = setup({ ownerVersion: '0.2.4' });
1113
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }] });
1114
+ s.activate();
1115
+ const err = await s.req.turn('peer:sh1:jarvis', { turnId: 't1', roomId: 'r', message: 'hi' }).catch(e => e);
1116
+ assert.equal(err.code, 'peer_outdated');
1117
+ assert.match(err.message, /Kamil's ClawChats connector is out of date \(0\.2\.4\)[^]*openclaw plugins install npm:@clawchatsai\/connector --force/);
1118
+ assert.equal(s.ownerCalls.filter(c => c.method === 'chat.send').length, 0);
1119
+ assert.ok(s.req.list()[0].needsUpdate);
1120
+ });
1121
+
1122
+ test('existing shares become contacts: access kept, cap → autonomy, Knowledge None, real agents → Full; grants re-issued as v2', async () => {
1123
+ const s = setup();
1124
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis-guest', name: 'Jarvis' }], access: 'trusted' });
1125
+ s.activate();
1126
+ // As an older connector left it: a v1 grant with a daily cap, and no contact.
1127
+ const db = s.owner._db();
1128
+ const g = { ...JSON.parse(db.prepare('SELECT grant_json FROM peer_grants').get().grant_json), v: 1, dailyCap: 100 };
1129
+ delete g.autonomy;
1130
+ db.prepare('UPDATE peer_grants SET grant_json = ?').run(JSON.stringify(g));
1131
+ s.owner.book.forget('h@x.dev');
1132
+ assert.deepEqual(await s.owner.migrateContacts(), ['h@x.dev']);
1133
+ const c = s.owner.book.get('h@x.dev');
1134
+ assert.deepEqual([c.access, c.autonomy, c.knowledge, c.migrated, c.commands, c.agents], ['trusted', 'extended', 'none', true, 'ask', ['jarvis']]);
1135
+ const re = s.ownerSignals.filter(m => m.type === 'share-grant').at(-1).grant;
1136
+ assert.deepEqual([re.v, re.access, re.autonomy, re.dailyCap, re.agents[0].id], [2, 'trusted', 'extended', undefined, 'jarvis-guest'], 'same agent id: rooms keep working');
1137
+
1138
+ // A share of the real agent: Full agent, confirmed when it was approved.
1139
+ s.owner.book.forget('h@x.dev');
1140
+ db.prepare('UPDATE peer_grants SET grant_json = ?').run(JSON.stringify({ ...g, agents: [{ id: 'jarvis', name: 'Jarvis' }] }));
1141
+ await s.owner.migrateContacts();
1142
+ const f = s.owner.book.get('h@x.dev');
1143
+ assert.deepEqual([f.access, !!f.fullConfirmedAt], ['full', true]);
1144
+ });
1145
+
1146
+ test("autonomy: Notify only refuses turns their agents start; rounds past the tier are refused; the person can always ask", async () => {
1147
+ const s = setup();
1148
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }], access: 'trusted', autonomy: 'notify' });
1149
+ s.activate();
1150
+ const err = await s.req.turn('peer:sh1:jarvis', { turnId: 't1', roomId: 'r', message: 'hi', trigger: 'agent', round: 2 }).catch(e => e);
1151
+ assert.equal(err.code, 'notify_only');
1152
+ assert.equal((await s.req.turn('peer:sh1:jarvis', { turnId: 't2', roomId: 'r', message: 'hi' })).state, 'final');
1153
+ await s.owner.setContact('h@x.dev', 'autonomy', 'bounded');
1154
+ s.activate();
1155
+ assert.equal((await s.req.turn('peer:sh1:jarvis', { turnId: 't3', roomId: 'r', message: 'hi', trigger: 'agent', round: 3 })).state, 'final');
1156
+ assert.equal((await s.req.turn('peer:sh1:jarvis', { turnId: 't4', roomId: 'r', message: 'hi', trigger: 'agent', round: 4 }).catch(e => e)).code, 'rounds');
1157
+ assert.equal(s.owner.limitsFor('gwH').mine.autonomy, 'bounded');
1158
+ assert.deepEqual(s.req.limitsFor('gwK').theirs, { access: 'trusted', autonomy: 'bounded' });
1159
+ });
1160
+
1161
+ test('the card: Private / Always fine reach the prompt; an access change re-issues the grant and swaps the copy (guest → full)', async () => {
1162
+ const s = setup();
1163
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }], access: 'trusted' });
1164
+ s.activate();
1165
+ await s.owner.setContact('h@x.dev', 'private', 'my health');
1166
+ await s.owner.setContact('h@x.dev', 'alwaysFine', 'OpenClaw');
1167
+ await s.req.turn('peer:sh1:jarvis', { turnId: 't1', roomId: 'r', message: 'hi' });
1168
+ const sent = s.ownerCalls.filter(c => c.method === 'chat.send').at(-1).params;
1169
+ assert.match(sent.message, /private from Houman[^]*my health/);
1170
+ assert.match(sent.message, /freely: OpenClaw/);
1171
+ assert.equal(sent.expectedPermissionMode, 'guarded', 'Trusted: Basic + ask me');
1172
+ assert.ok(s.gw.agents.some(a => a.id === 'jarvis-guest-h-bc35'));
1173
+ assert.equal(s.gw.approvals.agents['jarvis-guest-h-bc35'].ask, 'on-miss');
1174
+
1175
+ await assert.rejects(s.owner.setContact('h@x.dev', 'access', 'full'), e => e.code === 'confirm_full');
1176
+ await s.owner.setContact('h@x.dev', 'access', 'full', { confirmFull: true });
1177
+ assert.equal(s.ownerSignals.filter(m => m.type === 'share-grant').at(-1).grant.access, 'full');
1178
+ s.activate();
1179
+ await s.req.turn('peer:sh1:jarvis', { turnId: 't2', roomId: 'r', message: 'hi' });
1180
+ const full = s.gw.agents.find(a => a.id === 'jarvis-full-h-bc35');
1181
+ assert.equal(full.workspace, path.join(s.gw.root, 'ws'), "Full agent: the agent's own workspace (memory)");
1182
+ const tools = s.gw.entries['jarvis-full-h-bc35'].tools;
1183
+ assert.ok(['read', 'write', 'edit', 'apply_patch'].every(t => tools.deny.includes(t)), 'no file tools, memory read-only');
1184
+ for (let i = 0; i < 50 && s.gw.entries['jarvis-guest-h-bc35'].tools.alsoAllow.length; i++) await wait(5);
1185
+ assert.deepEqual(s.gw.entries['jarvis-guest-h-bc35'].tools.alsoAllow, [], 'the guest copy is retired (locked down, kept with its chats)');
1186
+ assert.equal(s.gw.approvals.agents['jarvis-guest-h-bc35'], undefined);
1187
+ });
1188
+
1189
+ test('Knowledge "My notes": the default picks are copied read-only into the person\'s copy; unpicked notes never are', async () => {
1190
+ const s = setup();
1191
+ fs.mkdirSync(path.join(s.gw.root, 'ws/memory/projects'), { recursive: true });
1192
+ fs.writeFileSync(path.join(s.gw.root, 'ws/memory/projects/clawchats.md'), '# ClawChats');
1193
+ fs.writeFileSync(path.join(s.gw.root, 'ws/memory/projects/homelab.md'), '# Homelab: proxmox at 10.0.0.2');
1194
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }], access: 'trusted', contact: { knowledge: 'notes' } });
1195
+ s.activate();
1196
+ await s.req.turn('peer:sh1:jarvis', { turnId: 't1', roomId: 'r', message: 'hi' });
1197
+ const copyWs = s.gw.agents.find(a => a.id === 'jarvis-guest-h-bc35').workspace;
1198
+ assert.deepEqual(fs.readdirSync(path.join(copyWs, 'notes')), ['clawchats.md']);
1199
+ assert.match(s.ownerCalls.filter(c => c.method === 'chat.send').at(-1).params.message, /share the notes in the notes\/ folder of your workspace with Houman S/);
1200
+ const card = await s.owner.contactCard('h@x.dev');
1201
+ assert.deepEqual(card.notes.candidates.map(c => [c.name, c.on]), [['clawchats.md', true], ['homelab.md', false]]);
1202
+ await s.owner.setContact('h@x.dev', 'knowledge', 'none');
1203
+ for (let i = 0; i < 50 && fs.existsSync(path.join(copyWs, 'notes')); i++) await wait(5);
1204
+ assert.equal(fs.existsSync(path.join(copyWs, 'notes')), false, 'None: the copies go');
1205
+ });
1206
+
1207
+ test('Disconnect: their sessions are archived, their copies retired (no tools, no approvals entry), nothing else kept for them', async () => {
1208
+ const s = setup();
1209
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }], access: 'trusted' });
1210
+ s.activate();
1211
+ await s.req.turn('peer:sh1:jarvis', { turnId: 't1', roomId: 'r', message: 'hi' });
1212
+ const key = s.ownerCalls.find(c => c.method === 'sessions.create').params.key;
1213
+ s.owner.revoke('sh1');
1214
+ const r = await s.owner.forgetPerson('h@x.dev');
1215
+ assert.deepEqual(r, { archived: 1, retired: 1 }, 'found through the copy even after the share is gone');
1216
+ assert.ok(s.ownerCalls.some(c => c.method === 'sessions.patch' && c.params.key === key && c.params.archived === true));
1217
+ assert.ok(!s.ownerCalls.some(c => c.method === 'agents.delete'), 'deleting the agent would delete its chats (11.6)');
1218
+ assert.deepEqual([s.gw.entries['jarvis-guest-h-bc35'].tools.alsoAllow, s.gw.entries['jarvis-guest-h-bc35'].tools.exec.mode], [[], 'deny']);
1219
+ assert.equal(s.gw.approvals.agents['jarvis-guest-h-bc35'], undefined);
1220
+ assert.equal(s.owner.book.get('h@x.dev'), null);
1221
+ assert.deepEqual(s.owner.book.copies('h@x.dev').map(c => c.kind), ['retired-guest']);
1222
+ assert.ok(s.owner.guestAgentIds().has('jarvis-guest-h-bc35'), 'still hidden from agent pickers');
1223
+ });
1224
+
1225
+ test('accepting someone again starts from their old card; what the form changed is saved', async () => {
1226
+ const s = setup();
1227
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }], access: 'trusted', contact: { knowledge: 'notes', private: 'health' } });
1228
+ s.owner.revoke('sh1');
1229
+ s.owner.setShares([{ id: 'sh1', as: 'owner', status: 'pending', requester: s.people.requester, owner: s.people.owner, agents: [] }]);
1230
+ const old = s.owner.book.get('h@x.dev');
1231
+ s.owner._db().prepare('DELETE FROM peer_grants').run();
1232
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }], access: 'restricted', autonomy: 'notify', contact: { ...old, access: 'restricted', commands: 'basic', tools: ['read', 'pdf'], private: 'health, money' } });
1233
+ const c = s.owner.book.get('h@x.dev');
1234
+ assert.deepEqual([c.access, c.autonomy, c.commands, c.tools, c.private, c.knowledge], ['restricted', 'notify', 'basic', ['read', 'pdf'], 'health, money', 'notes']);
1235
+ });
1236
+
1237
+ test('"Open one folder" only takes a real folder inside the workspace: not the root, not secrets/ or a folder holding it, no .. or links', async () => {
1238
+ const s = setup();
1239
+ const ws = path.join(s.gw.root, 'ws');
1240
+ for (const d of ['plans', 'secrets', 'outer/secrets']) fs.mkdirSync(path.join(ws, d), { recursive: true });
1241
+ fs.symlinkSync(path.join(ws, 'secrets'), path.join(ws, 'link'));
1242
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }], access: 'full', confirmFull: true });
1243
+ for (const bad of [ws, path.join(ws, 'secrets'), path.join(ws, 'outer'), `${ws}/plans/../secrets`, path.join(ws, 'link'), '/etc', 'plans']) {
1244
+ await assert.rejects(s.owner.setContact('h@x.dev', 'openFolder', bad), Error, bad);
1245
+ }
1246
+ const c = await s.owner.setContact('h@x.dev', 'openFolder', path.join(ws, 'plans'));
1247
+ assert.equal(c.openFolder, path.join(ws, 'plans'));
1248
+ });
1249
+
1250
+ test('"Open one folder" after the session exists: the old session (rooted at the workspace) is archived and a new one is rooted at the folder', async () => {
1251
+ const s = setup();
1252
+ const ws = path.join(s.gw.root, 'ws');
1253
+ fs.mkdirSync(path.join(ws, 'plans'), { recursive: true });
1254
+ const roots = {};
1255
+ const request = s.owner.request;
1256
+ s.owner.request = async (m, p) => {
1257
+ if (m === 'sessions.create') roots[p.key] = p.cwd || ws;
1258
+ if (m === 'sessions.describe') return { session: { key: p.key, sessionRoot: roots[p.key] } };
1259
+ return request(m, p);
1260
+ };
1261
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }], access: 'full', confirmFull: true });
1262
+ s.activate();
1263
+ await s.req.turn('peer:sh1:jarvis', { turnId: 't1', roomId: 'r', message: 'hi' });
1264
+ const first = s.ownerCalls.filter(c => c.method === 'sessions.create').at(-1).params.key;
1265
+ await s.owner.setContact('h@x.dev', 'openFolder', path.join(ws, 'plans'));
1266
+ await s.req.turn('peer:sh1:jarvis', { turnId: 't2', roomId: 'r', message: 'hi' });
1267
+ const second = s.ownerCalls.filter(c => c.method === 'sessions.create').at(-1).params;
1268
+ assert.notEqual(second.key, first);
1269
+ assert.equal(second.cwd, path.join(ws, 'plans'));
1270
+ assert.ok(s.ownerCalls.some(c => c.method === 'sessions.patch' && c.params.key === first && c.params.archived === true));
1271
+ assert.equal(s.ownerCalls.filter(c => c.method === 'chat.send').at(-1).params.sessionKey, second.key);
1272
+ assert.ok(s.gw.entries['jarvis-full-h-bc35'].tools.alsoAllow.includes('read'), 'reading comes with the folder');
1273
+ });
1274
+
1275
+ test('a grant signed with a peer key this gateway no longer has is signed again on start', async () => {
1276
+ const s = setup();
1277
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }], access: 'trusted' });
1278
+ s.activate();
1279
+ s.owner._db().prepare('UPDATE peer_grants SET sig = ?').run('bm90LWEtc2lnbmF0dXJl');
1280
+ const before = s.ownerSignals.filter(m => m.type === 'share-grant').length;
1281
+ await s.owner.migrateContacts();
1282
+ const g = s.ownerSignals.filter(m => m.type === 'share-grant');
1283
+ assert.equal(g.length, before + 1);
1284
+ assert.equal(g.at(-1).grant.access, 'trusted');
1285
+ });
1286
+
1287
+ test('trusting a new key from either direction of the connection also clears the pin on the other share', () => {
1288
+ const s = setup();
1289
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }] });
1290
+ const active = s.activate();
1291
+ assert.equal(s.req.remoteAgents().length, 1); // pins Kamil's key on sh1
1292
+ // Kamil reinstalls: new key, grant signed again with it; Houman's gateway also owns a share to Kamil (sh9).
1293
+ const next = keyIn();
1294
+ const back = { id: 'sh9', status: 'active', as: 'owner', requester: { ...s.people.owner, pubKey: next.publicKey }, owner: s.people.requester, agents: [] };
1295
+ s.req.setShares([{ ...active, as: 'requester', owner: { ...active.owner, pubKey: next.publicKey }, signature: next.signJson(active.grant) }, back]);
1296
+ assert.deepEqual(s.req.remoteAgents(), []);
1297
+ s.req.trustNewKey('sh9'); // the card's banner trusts from the owner-direction share
1298
+ assert.deepEqual(s.req.remoteAgents().map(a => a.agentId), ['peer:sh1:jarvis']);
1299
+ });
1300
+
1301
+ test('a turn that may ask the owner holds the approval connection for its whole run (no tab needed); Basic only does not', async () => {
1302
+ const holds = [];
1303
+ const s = setup({ reply: () => null });
1304
+ s.owner.holdApprovals = async () => { const h = { released: false }; holds.push(h); return () => { h.released = true; }; };
1305
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }], access: 'trusted' }); // Basic + ask me
1306
+ s.activate();
1307
+ const turn = s.req.turn('peer:sh1:jarvis', { turnId: 't1', roomId: 'r', message: 'hi' });
1308
+ for (let i = 0; i < 100 && !s.ownerCalls.some(c => c.method === 'chat.send'); i++) await wait(5);
1309
+ const send = s.ownerCalls.find(c => c.method === 'chat.send').params;
1310
+ assert.deepEqual(holds.map(h => h.released), [false], 'held while the run goes on');
1311
+ assert.equal(send.timeoutMs, 35 * 60_000, 'as long as the gateway keeps an approval pending');
1312
+ s.owner.onGatewayEvent({ event: 'chat', payload: { runId: send.idempotencyKey, state: 'final', message: { content: [{ type: 'text', text: 'ok' }] } } });
1313
+ await turn;
1314
+ assert.deepEqual(holds.map(h => h.released), [true]);
1315
+ await s.owner.setContact('h@x.dev', 'commands', 'basic');
1316
+ const t2 = s.req.turn('peer:sh1:jarvis', { turnId: 't2', roomId: 'r', message: 'hi' });
1317
+ for (let i = 0; i < 100 && s.ownerCalls.filter(c => c.method === 'chat.send').length < 2; i++) await wait(5);
1318
+ const send2 = s.ownerCalls.filter(c => c.method === 'chat.send')[1].params;
1319
+ assert.equal(holds.length, 1, 'Basic only never asks: nothing held');
1320
+ assert.equal(send2.timeoutMs, 10 * 60_000);
1321
+ s.owner.onGatewayEvent({ event: 'chat', payload: { runId: send2.idempotencyKey, state: 'final', message: { content: [{ type: 'text', text: 'ok' }] } } });
1322
+ await t2;
1323
+ });
@@ -0,0 +1,36 @@
1
+ // The connector version a peer must run: contact cards changed the grant and the turn protocol (no compatibility with
2
+ // older connectors; Houman, 2026-11-20). Both sides send their version in the peer hello and refuse an older peer.
3
+
4
+ import fs from 'node:fs';
5
+
6
+ /** The first release with contact cards. */
7
+ export const MIN_PEER_VERSION = '0.3.0';
8
+ export const UPDATE_COMMAND = 'openclaw plugins install npm:@clawchatsai/connector --force';
9
+
10
+ let own = null;
11
+ /** This connector's version (package.json). */
12
+ export function connectorVersion() {
13
+ if (own) return own;
14
+ try { own = JSON.parse(fs.readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version || '0.0.0'; }
15
+ catch { own = '0.0.0'; }
16
+ return own;
17
+ }
18
+
19
+ /** a < b for dotted versions ("0.2.4" < "0.3.0"); prerelease tags are ignored. */
20
+ export function olderThan(a, b) {
21
+ const p = v => String(v || '').split('-')[0].split('.').map(n => parseInt(n, 10) || 0);
22
+ const x = p(a), y = p(b);
23
+ for (let i = 0; i < 3; i++) if ((x[i] || 0) !== (y[i] || 0)) return (x[i] || 0) < (y[i] || 0);
24
+ return false;
25
+ }
26
+
27
+ /** Whether a peer's announced version is too old (no version at all counts as too old). */
28
+ export const peerOutdated = v => typeof v !== 'string' || !v || olderThan(v, MIN_PEER_VERSION);
29
+
30
+ /** What both sides show. `who`: the person whose connector is old, or null for "yours". */
31
+ export function outdatedMessage(who, version) {
32
+ const ran = version ? ` (${version})` : '';
33
+ return who
34
+ ? `${who}'s ClawChats connector is out of date${ran}. Sharing with ${who} needs ${MIN_PEER_VERSION} or newer: ask ${who} to run "${UPDATE_COMMAND}".`
35
+ : `Your ClawChats connector is out of date${ran}. Sharing needs ${MIN_PEER_VERSION} or newer: run "${UPDATE_COMMAND}".`;
36
+ }
@@ -18,7 +18,8 @@
18
18
  // team_mirror host entry id -> local message id in a live copy (each host entry injected once)
19
19
  // team_entries.host_ts/owner_id/ref a mirrored entry's original time, its agent's owner and room-wide agent ref
20
20
  // team_entries author_type 'system': a line like "Kamil joined" (same on every screen)
21
- // team_rooms.mention_only agents answer only when @mentioned (human chats with silent agents)
21
+ // team_rooms.mention_only agents answer only when @mentioned (human chats with silent agents): 0 off, 1 on,
22
+ // 2 automatic (on while another person is in the chat, D12; new rooms)
22
23
  // team_entries.via which of its sessions an agent wrote from: 'owner' (its owner's own session,
23
24
  // here or in its owner's copy) or 'guest:<who>' (a session it ran in for someone else).
24
25
  // NULL on older rows: treated as the session asking, as before.
@@ -33,7 +34,7 @@ function roomRow(r, members, people = []) {
33
34
  return {
34
35
  roomKey: r.room_key,
35
36
  discuss: !!r.discuss,
36
- mentionOnly: !!r.mention_only,
37
+ mentionOnly: r.mention_only === 2 ? null : !!r.mention_only, // null: automatic
37
38
  rounds: r.rounds || DISCUSS_ROUNDS,
38
39
  sourceKey: r.source_key || null,
39
40
  createdAt: r.created_at,
@@ -89,12 +90,12 @@ export function createTeamStore(getGlobalDb) {
89
90
  },
90
91
 
91
92
  /** members: [{ agentId, workKey?, seenAt? }] in display order; sourceKey: the chat it was converted from. */
92
- createRoom(roomKey, memberList, { discuss = false, sourceKey = null, mentionOnly = false } = {}) {
93
+ createRoom(roomKey, memberList, { discuss = false, sourceKey = null, mentionOnly = null } = {}) {
93
94
  const g = db();
94
95
  const now = Date.now();
95
96
  g.exec('BEGIN');
96
97
  try {
97
- g.prepare('INSERT INTO team_rooms (room_key, discuss, source_key, created_at, updated_at, mention_only) VALUES (?, ?, ?, ?, ?, ?)').run(roomKey, discuss ? 1 : 0, sourceKey, now, now, mentionOnly ? 1 : 0);
98
+ g.prepare('INSERT INTO team_rooms (room_key, discuss, source_key, created_at, updated_at, mention_only) VALUES (?, ?, ?, ?, ?, ?)').run(roomKey, discuss ? 1 : 0, sourceKey, now, now, mentionOnly === null ? 2 : mentionOnly ? 1 : 0);
98
99
  memberList.forEach((m, i) => g.prepare('INSERT INTO team_members (room_key, agent_id, work_key, seen_at, position) VALUES (?, ?, ?, ?, ?)').run(roomKey, m.agentId, m.workKey || null, m.seenAt || 0, i));
99
100
  g.exec('COMMIT');
100
101
  } catch (e) { g.exec('ROLLBACK'); throw e; }
@@ -185,7 +186,7 @@ export function createTeamStore(getGlobalDb) {
185
186
  },
186
187
 
187
188
  setMentionOnly(roomKey, on) {
188
- db().prepare('UPDATE team_rooms SET mention_only = ?, updated_at = ? WHERE room_key = ?').run(on ? 1 : 0, Date.now(), roomKey);
189
+ db().prepare('UPDATE team_rooms SET mention_only = ?, updated_at = ? WHERE room_key = ?').run(on === null ? 2 : on ? 1 : 0, Date.now(), roomKey);
189
190
  },
190
191
 
191
192
  setRounds(roomKey, rounds) {