@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/server/peer/sharing.js
CHANGED
|
@@ -18,12 +18,18 @@ import { PeerLink } from './link.js';
|
|
|
18
18
|
import { canonicalJson, verifySignature, fingerprint } from './keys.js';
|
|
19
19
|
import { redactSecrets } from '../util/redact.js';
|
|
20
20
|
import { createChatAbort } from '../util/chat-abort.js';
|
|
21
|
-
import {
|
|
21
|
+
import { ensureGuestRestrictions, findGuestAgent, isGuestAgent } from './guest-agent.js';
|
|
22
|
+
import { ContactBook, personKeyOf } from './contacts.js';
|
|
23
|
+
import { AUTONOMY, ACCESS, sessionMode, toolOverrides as contactOverrides, topicsNote, copyTools, copyToolsHold, copyKind, defaultContact, TOOL_GROUPS, ALWAYS_OFF, BASIC_DEFAULTS, DEFAULT_TOOLS, DEFAULT_COMMANDS } from './contact-policy.js';
|
|
24
|
+
import { ensureContactCopy, retireCopy, reviewerModelFor } from './contact-copy.js';
|
|
25
|
+
import { noteCandidates, resolvePicks, picksSignature, syncNotes, removeNotes, NOTES_DIR } from './notes-sync.js';
|
|
26
|
+
import { peerOutdated, outdatedMessage, connectorVersion } from './version.js';
|
|
22
27
|
|
|
23
28
|
const TURN_TIMEOUT_MS = 10 * 60_000;
|
|
29
|
+
// A turn whose commands may ask the owner: as long as the gateway keeps an approval pending (30 min) plus the run.
|
|
30
|
+
const APPROVAL_TURN_TIMEOUT_MS = 35 * 60_000;
|
|
24
31
|
/** The gateway's "the run gave no visible reply" failure (2026.10.1+: a passed turn, see team.js PASS_TOKEN). */
|
|
25
32
|
export const EMPTY_REPLY_ERROR = /empty response|did not produce a visible reply/i;
|
|
26
|
-
const DEFAULT_DAILY_CAP = 50;
|
|
27
33
|
const MAX_CONCURRENT_TURNS = 2; // per share: the daily cap alone would allow 50 parallel 10-minute runs
|
|
28
34
|
// Owner side: finished guest turns, so a resend after a dropped link gets the result instead of a new run.
|
|
29
35
|
const RECENT_TURN_MS = 10 * 60_000;
|
|
@@ -34,7 +40,8 @@ const RESEND_BACKOFF_MS = [2_000, 5_000];
|
|
|
34
40
|
// restarted" turn of its own, under another run id); this long for that to start, polled this often.
|
|
35
41
|
const RECOVERY_WAIT_MS = 30_000;
|
|
36
42
|
const RECOVERY_POLL_MS = 2_000;
|
|
37
|
-
|
|
43
|
+
/** Old grants (v1) carried a daily cap; migrated contacts get the autonomy tier closest to it. */
|
|
44
|
+
const autonomyFromCap = cap => (Number(cap) > 50 ? 'extended' : 'bounded');
|
|
38
45
|
/**
|
|
39
46
|
* Requests one contact's gateway may make of this one over the sharing link: [burst, per ms] token
|
|
40
47
|
* buckets per contact and kind. Far above what a person and their agents send in a chat (a turn per
|
|
@@ -57,10 +64,12 @@ export const defangLocalPaths = text => String(text ?? '')
|
|
|
57
64
|
.replace(/\bMEDIA:/gi, m => `${m.slice(0, -1)}\u200b:`)
|
|
58
65
|
.replace(/(^|[\s"'`(\]])(?=(?:\.\.?[\\/]|[~/\\]|[A-Za-z]:[\\/])[^\s"'`()[\]]*\.[A-Za-z0-9])/g, '$1\u200b');
|
|
59
66
|
const GUEST_NOTE = name => `(Shared session: you are answering ${name}'s team chat on behalf of your owner. ${name} is not your owner — don't reveal your owner's private information or act on your owner's accounts for them.)`;
|
|
67
|
+
const files0 = notes => (notes ? [...notes.candidates.filter(x => x.on).map(x => x.path), ...notes.repoDocs.map(x => x.path)] : null);
|
|
68
|
+
// A copy with picked notes (Knowledge "My notes"): where they are.
|
|
69
|
+
const NOTES_NOTE = name => `(Your owner chose to share the notes in the ${NOTES_DIR}/ folder of your workspace with ${name}: read them and use them freely to answer. Anything that isn't in them stays private.)`;
|
|
60
70
|
// The same agent in its owner's own team chat, answering another person's agent (localTurnFor).
|
|
61
71
|
const ACTING_FOR_NOTE = (name, byPerson) => `(Shared session: in your owner's team chat, you are answering ${byPerson ? name : `${name}'s agent`}, so you act for ${name}, not for your owner. ${name} is not your owner — don't reveal your owner's private information or act on your owner's accounts for them.)`;
|
|
62
72
|
|
|
63
|
-
const today = () => new Date().toISOString().slice(0, 10);
|
|
64
73
|
/** A guest turn's emit with secrets redacted from streamed text (see _guestTurn). */
|
|
65
74
|
const redacting = emit => emit && ((event, data) => emit(event, event === 'delta' ? redactSecrets(data) : data));
|
|
66
75
|
/** A name that came from the other side, safe to show and to use as a chat label (no brackets, newlines, controls). */
|
|
@@ -85,8 +94,8 @@ export class SharingManager {
|
|
|
85
94
|
* @param {(shareId: string) => Promise<{ dc, dtls }>} o.openPeer open a peer DataChannel (requester)
|
|
86
95
|
* @param {(data: string) => void} o.broadcast frame to this gateway's browsers
|
|
87
96
|
*/
|
|
88
|
-
constructor({ getDb, request, chatAbort = null, key, gatewayId, signal, openPeer, broadcast = () => {}, log = console, resendBackoffMs = RESEND_BACKOFF_MS, recovery = { waitMs: RECOVERY_WAIT_MS, pollMs: RECOVERY_POLL_MS } }) {
|
|
89
|
-
Object.assign(this, { getDb, request, key, gatewayId, signal, openPeer, broadcast, log, resendBackoffMs, recovery });
|
|
97
|
+
constructor({ getDb, request, chatAbort = null, key, gatewayId, signal, openPeer, broadcast = () => {}, log = console, resendBackoffMs = RESEND_BACKOFF_MS, recovery = { waitMs: RECOVERY_WAIT_MS, pollMs: RECOVERY_POLL_MS }, version = connectorVersion(), holdApprovals = null }) {
|
|
98
|
+
Object.assign(this, { getDb, request, key, gatewayId, signal, openPeer, broadcast, log, resendBackoffMs, recovery, version, holdApprovals });
|
|
90
99
|
this.chatAbort = chatAbort || createChatAbort((m, p, t) => this.request(m, p, t)); // Stop, fenced where supported
|
|
91
100
|
this._shares = []; // latest share-list from the signal server
|
|
92
101
|
this.serverEnabled = false; // the signal server sends a share-list only to accounts with sharing on
|
|
@@ -99,6 +108,9 @@ export class SharingManager {
|
|
|
99
108
|
this._turns = new Map();
|
|
100
109
|
this._finished = new Map(); // `${shareId}|${clientTurnId}` -> { same, result | error, at } (RECENT_TURN_MS)
|
|
101
110
|
this._buckets = new Map(); // `${gateway}|${kind}` -> { tokens, at } (PEER_RATES)
|
|
111
|
+
this.book = new ContactBook(getDb); // contact cards: per-person settings, copies, usage (owner side)
|
|
112
|
+
this._peerVersions = new Map(); // their gateway id -> connector version from its last link hello (null: too old to say)
|
|
113
|
+
this._copying = new Map(); // `${person}|${agent}` -> Promise (one copy write at a time)
|
|
102
114
|
this._ready = false;
|
|
103
115
|
}
|
|
104
116
|
|
|
@@ -147,6 +159,7 @@ export class SharingManager {
|
|
|
147
159
|
for (const s of this._localGrants()) if (!live.has(s.share_id) && !this._shares.some(x => x.id === s.share_id && x.status === 'pending')) this._revokeLocal(s.share_id);
|
|
148
160
|
this._changed();
|
|
149
161
|
if (first) setImmediate(() => { try { this.onFirstShares?.(); } catch (e) { this.log.warn?.(`[sharing] ${e.message}`); } });
|
|
162
|
+
if (first) setImmediate(() => this.migrateContacts().catch(e => this.log.warn?.(`[sharing] contact migration: ${e.message}`)));
|
|
150
163
|
this._sharesChanged();
|
|
151
164
|
this._presenceTick();
|
|
152
165
|
}
|
|
@@ -197,13 +210,25 @@ export class SharingManager {
|
|
|
197
210
|
if (s.as === 'owner') {
|
|
198
211
|
const g = this._grant(s.id);
|
|
199
212
|
out.access = g?.grant.access || null;
|
|
200
|
-
out.
|
|
201
|
-
out.
|
|
213
|
+
out.autonomy = g?.grant.autonomy || null;
|
|
214
|
+
out.person = personKeyOf(s.requester?.email) || null;
|
|
215
|
+
const c = out.person && this.book.get(out.person);
|
|
216
|
+
if (c) {
|
|
217
|
+
const u = this.book.usage(c.personKey), t = AUTONOMY[c.autonomy] || AUTONOMY.bounded;
|
|
218
|
+
out.contact = { access: c.access, autonomy: c.autonomy, knowledge: c.knowledge, migrated: c.migrated, usedToday: u.day, usedHour: u.hour, perDay: t.perDay, perHour: t.perHour || null };
|
|
219
|
+
// Read by the older People view (no contact cards): "N of M replies today".
|
|
220
|
+
out.usedToday = u.day;
|
|
221
|
+
out.dailyCap = t.perDay;
|
|
222
|
+
}
|
|
202
223
|
const key = g?.grant.requesterPubKey || s.requester?.pubKey;
|
|
203
224
|
out.theirKey = key ? fingerprint(key) : null;
|
|
204
225
|
out.keyVerified = !!key && this._keyVerified(s.id, key);
|
|
205
226
|
} else {
|
|
206
|
-
|
|
227
|
+
const vg = this._verifiedGrant(s);
|
|
228
|
+
out.verified = !!vg;
|
|
229
|
+
// What they let this side's person do (the popover's "Kamil's for you" line, and the rounds cap).
|
|
230
|
+
out.theirAccess = vg?.access || null;
|
|
231
|
+
out.theirAutonomy = vg ? (AUTONOMY[vg.autonomy] ? vg.autonomy : 'bounded') : null;
|
|
207
232
|
const pin = this._theirKey(s);
|
|
208
233
|
out.theirKey = pin ? fingerprint(pin) : null;
|
|
209
234
|
out.keyVerified = !!pin && this._keyVerified(s.id, pin);
|
|
@@ -214,6 +239,11 @@ export class SharingManager {
|
|
|
214
239
|
out.keyChanged = !!(presented && pinned && presented !== pinned);
|
|
215
240
|
// What "Trust new key" would accept, as fingerprints to compare with the contact out of band.
|
|
216
241
|
if (out.keyChanged) out.keyChange = { was: fingerprint(pinned), now: fingerprint(presented) };
|
|
242
|
+
// Their connector is older than this one accepts (seen on a link): nothing is shared until they update.
|
|
243
|
+
const gw = this._other(s).gatewayId;
|
|
244
|
+
if (gw && this._peerVersions.has(gw) && peerOutdated(this._peerVersions.get(gw))) {
|
|
245
|
+
out.needsUpdate = { version: this._peerVersions.get(gw), message: outdatedMessage(this._other(s).name.split(/\s/)[0], this._peerVersions.get(gw)) };
|
|
246
|
+
}
|
|
217
247
|
return out;
|
|
218
248
|
});
|
|
219
249
|
}
|
|
@@ -240,7 +270,8 @@ export class SharingManager {
|
|
|
240
270
|
const key = s?.as === 'owner' ? s.requester?.pubKey : s?.owner?.pubKey;
|
|
241
271
|
if (!gw || !key) throw new Error('Nothing to trust yet');
|
|
242
272
|
this._db().prepare('INSERT OR REPLACE INTO peer_gateway_keys (gateway_id, pubkey, created_at) VALUES (?, ?, ?)').run(gw, key, Date.now());
|
|
243
|
-
|
|
273
|
+
// Every share with that gateway follows (the card trusts from whichever direction; the pins are per share).
|
|
274
|
+
for (const x of this._shares) if (x.as === 'requester' && x.owner?.gatewayId === gw) this._db().prepare('DELETE FROM peer_pins WHERE share_id = ?').run(x.id);
|
|
244
275
|
this._nameCache = null;
|
|
245
276
|
this._changed();
|
|
246
277
|
this._sharesChanged();
|
|
@@ -308,7 +339,7 @@ export class SharingManager {
|
|
|
308
339
|
|
|
309
340
|
/** Ids of the guest agents this connector made (the gateway may show them under another name). */
|
|
310
341
|
guestAgentIds() {
|
|
311
|
-
return new Set(this._db().prepare('SELECT agent_id FROM peer_guest_agents').all().map(r => r.agent_id));
|
|
342
|
+
return new Set([...this._db().prepare('SELECT agent_id FROM peer_guest_agents').all().map(r => r.agent_id), ...this.book.copyIds()]);
|
|
312
343
|
}
|
|
313
344
|
|
|
314
345
|
markGuestAgent(agentId) {
|
|
@@ -333,14 +364,19 @@ export class SharingManager {
|
|
|
333
364
|
return updated;
|
|
334
365
|
}
|
|
335
366
|
|
|
336
|
-
/**
|
|
337
|
-
|
|
367
|
+
/**
|
|
368
|
+
* Approve (or change) a share: sign and store the grant (v2: agents, access, autonomy), send it to the signal server.
|
|
369
|
+
* The person's contact card is created on first approval (with `contact`: the first-time form's settings) and keeps
|
|
370
|
+
* access, autonomy and agents in step with the grant. `dailyCap` (older ClawChats) maps to an autonomy tier.
|
|
371
|
+
*/
|
|
372
|
+
approve(shareId, { agents, access = 'restricted', autonomy = null, dailyCap = null, contact = null, confirmFull = false } = {}) {
|
|
338
373
|
const s = this._shares.find(x => x.id === shareId && x.as === 'owner' && ['pending', 'active'].includes(x.status));
|
|
339
374
|
if (!s) throw new Error('No such request');
|
|
340
375
|
if (!s.requester?.pubKey || !s.requester?.gatewayId) throw new Error("The requester's gateway hasn't connected with sharing support yet");
|
|
341
376
|
const list = (Array.isArray(agents) ? agents : []).filter(a => a && typeof a.id === 'string' && a.id).map(a => ({ id: a.id, name: String(a.name || a.id).slice(0, 80) }));
|
|
342
377
|
// No agents is fine: a connection can be just for chatting (team chats with people).
|
|
343
|
-
if (!
|
|
378
|
+
if (!ACCESS.includes(access)) throw new Error('Unknown access level');
|
|
379
|
+
autonomy = AUTONOMY[autonomy] ? autonomy : dailyCap != null ? autonomyFromCap(dailyCap) : (this.book.get(s.requester.email)?.autonomy || 'bounded');
|
|
344
380
|
// A changed grant keeps the requester key it was first approved for: the signal server can't swap it.
|
|
345
381
|
const prev = this._db().prepare('SELECT grant_json FROM peer_grants WHERE share_id = ?').get(shareId);
|
|
346
382
|
if (prev && JSON.parse(prev.grant_json).requesterPubKey !== s.requester.pubKey) {
|
|
@@ -354,10 +390,32 @@ export class SharingManager {
|
|
|
354
390
|
// The signal server only activates a grant signed for this gateway's own id; without one it would say no, silently.
|
|
355
391
|
const ownerGatewayId = this.gatewayId();
|
|
356
392
|
if (!ownerGatewayId) throw new Error("This gateway isn't connected to the signal server yet. Try again in a moment.");
|
|
393
|
+
// The contact card: made on first approval, then access/autonomy/agents follow the grant.
|
|
394
|
+
const person = personKeyOf(s.requester.email);
|
|
395
|
+
if (person) {
|
|
396
|
+
const had = this.book.get(person);
|
|
397
|
+
if (access === 'full' && !had?.fullConfirmedAt && !confirmFull && !contact?.fullConfirmedAt) throw Object.assign(new Error('Full agent needs confirming'), { code: 'confirm_full' });
|
|
398
|
+
if (!had) {
|
|
399
|
+
const sources = list.map(a => a.id);
|
|
400
|
+
// Without the card's first-time form (an older ClawChats app), nothing of the owner's notes is shared.
|
|
401
|
+
this.book.create(person, { ...defaultContact(access), ...(contact ? {} : { knowledge: 'none' }), ...(contact || {}), name: cleanName(s.requester.name, 60) || null, access, autonomy, agents: sources, ...(access === 'full' ? { fullConfirmedAt: Date.now() } : {}) });
|
|
402
|
+
} else {
|
|
403
|
+
// Accepting again (they reconnected): the form started from the old card; what was changed on it is saved.
|
|
404
|
+
// Access first: it resets Tools and Commands to that tier, which the form's own values then override.
|
|
405
|
+
if (had.access !== access) this.book.set(person, 'access', access, { confirmFull: true });
|
|
406
|
+
const now = this.book.get(person);
|
|
407
|
+
for (const f of ['knowledge', 'notes', 'repos', 'tools', 'commands', 'skills', 'mcp', 'private', 'alwaysFine', 'basicList']) {
|
|
408
|
+
if (contact && contact[f] !== undefined && JSON.stringify(contact[f]) !== JSON.stringify(now[f])) this.book.set(person, f, contact[f]);
|
|
409
|
+
}
|
|
410
|
+
if (had.autonomy !== autonomy) this.book.set(person, 'autonomy', autonomy);
|
|
411
|
+
const ids = list.map(a => this._sourceIdSync(a.id));
|
|
412
|
+
if (JSON.stringify([...(had.agents || [])].sort()) !== JSON.stringify([...ids].sort())) this.book.set(person, 'agents', ids);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
357
415
|
const grant = {
|
|
358
|
-
v:
|
|
416
|
+
v: 2, shareId, ownerGatewayId, requesterGatewayId: s.requester.gatewayId, requesterPubKey: s.requester.pubKey,
|
|
359
417
|
requesterName: cleanName(s.requester.name || s.requester.email, 60) || null,
|
|
360
|
-
agents: list, access,
|
|
418
|
+
agents: list, access, autonomy, issuedAt: Date.now(),
|
|
361
419
|
};
|
|
362
420
|
const sig = this.key.signJson(grant);
|
|
363
421
|
this._pinGatewayKey(grant.requesterGatewayId, grant.requesterPubKey);
|
|
@@ -378,8 +436,10 @@ export class SharingManager {
|
|
|
378
436
|
this.signal({ type: 'share-revoke', shareId });
|
|
379
437
|
}
|
|
380
438
|
|
|
439
|
+
/** Replies counted today for the person behind a share (one counter per person). */
|
|
381
440
|
_usage(shareId) {
|
|
382
|
-
|
|
441
|
+
const person = this._personOfShare(shareId);
|
|
442
|
+
return person ? this.book.usage(person).day : 0;
|
|
383
443
|
}
|
|
384
444
|
|
|
385
445
|
/** Whether this side would serve a peer connection for the share (checked before any WebRTC setup). */
|
|
@@ -399,14 +459,20 @@ export class SharingManager {
|
|
|
399
459
|
try { dc.close(); } catch { /* gone */ }
|
|
400
460
|
return null;
|
|
401
461
|
}
|
|
402
|
-
const link = new PeerLink({ dc, dtls, role: 'owner', shareId, key: this.key, peerKey: g.grant.requesterPubKey, log: this.log });
|
|
462
|
+
const link = new PeerLink({ dc, dtls, role: 'owner', shareId, key: this.key, peerKey: g.grant.requesterPubKey, log: this.log, version: this.version });
|
|
403
463
|
const gw = g.grant.requesterGatewayId; // the gateway the key this link authenticates was approved for
|
|
404
464
|
this._served.add(link);
|
|
405
465
|
link.on('closed', () => this._served.delete(link));
|
|
406
|
-
|
|
407
|
-
|
|
466
|
+
// A connector older than this one accepts gets every request refused with what to do (it shows the message), and
|
|
467
|
+
// nothing of this side's rooms; checked at the handshake and again before every turn.
|
|
468
|
+
const current = fn => (p, emit) => {
|
|
469
|
+
if (this._checkPeer(link, gw)) return Promise.reject(Object.assign(new Error(outdatedMessage(null, link.peerVersion)), { code: 'peer_outdated' }));
|
|
470
|
+
return fn(p, emit);
|
|
471
|
+
};
|
|
472
|
+
link.handle('agents', current(this._limited(gw, 'agents', async () => ({ agents: this._grant(shareId)?.grant.agents || [] }))));
|
|
473
|
+
link.handle('turn', current(this._limited(gw, 'turn', (p, emit) => this._guestTurn(shareId, { ...p, inOwnerRoom: false, byPerson: false }, emit)))); // only localTurnFor sets these
|
|
408
474
|
link.handle('abort', this._limited(gw, 'abort', async p => this._guestAbort(shareId, p?.turnId)));
|
|
409
|
-
this._wireRooms(link, gw);
|
|
475
|
+
this._wireRooms(link, gw, current);
|
|
410
476
|
return link;
|
|
411
477
|
}
|
|
412
478
|
|
|
@@ -436,14 +502,17 @@ export class SharingManager {
|
|
|
436
502
|
* leave and ask for a fresh copy (room.post / room.leave / room.fetch). `onRoom` (TeamCoordinator)
|
|
437
503
|
* decides; it gets the other side's gateway id, which the link authenticated.
|
|
438
504
|
*/
|
|
439
|
-
_wireRooms(link, otherGatewayId) {
|
|
505
|
+
_wireRooms(link, otherGatewayId, current = fn => fn) {
|
|
440
506
|
for (const method of ['room.sync', 'room.post', 'room.leave', 'room.fetch']) {
|
|
441
|
-
link.handle(method, this._limited(otherGatewayId, method, async p => {
|
|
507
|
+
link.handle(method, current(this._limited(otherGatewayId, method, async p => {
|
|
442
508
|
if (!this.onRoom) throw Object.assign(new Error('team chats are not available'), { code: 'unavailable' });
|
|
443
509
|
return this.onRoom(method, p || {}, otherGatewayId);
|
|
444
|
-
}));
|
|
510
|
+
})));
|
|
445
511
|
}
|
|
446
|
-
const ready = () => {
|
|
512
|
+
const ready = () => {
|
|
513
|
+
if (this._checkPeer(link, otherGatewayId)) return; // too old: no room pushes either way
|
|
514
|
+
try { this.onPeerReady?.(otherGatewayId); } catch (e) { this.log.warn?.(`[sharing] peer ready: ${e.message}`); }
|
|
515
|
+
};
|
|
447
516
|
if (link.ready) setImmediate(ready); else link.once('ready', ready);
|
|
448
517
|
}
|
|
449
518
|
|
|
@@ -587,6 +656,7 @@ export class SharingManager {
|
|
|
587
656
|
async personRequest(personId, method, params, { timeoutMs = 60_000 } = {}) {
|
|
588
657
|
if (!this.contact(personId)) throw Object.assign(new Error('Not connected with them'), { code: 'not_connected' });
|
|
589
658
|
const link = await this._personLink(personId);
|
|
659
|
+
if (this._checkPeer(link, personId)) throw Object.assign(new Error(outdatedMessage(this.contact(personId)?.name?.split(/\s/)[0] || 'Their', link.peerVersion)), { code: 'peer_outdated' });
|
|
590
660
|
return link.request(method, params, { timeoutMs });
|
|
591
661
|
}
|
|
592
662
|
|
|
@@ -613,7 +683,18 @@ export class SharingManager {
|
|
|
613
683
|
if (done?.error) throw Object.assign(new Error(done.error.message), { code: done.error.code, partial: done.error.partial });
|
|
614
684
|
if (done) return { ...done.result };
|
|
615
685
|
}
|
|
616
|
-
|
|
686
|
+
// The person's contact card decides (one counter per person across their gateways, D10).
|
|
687
|
+
const person = this._personOfShare(shareId);
|
|
688
|
+
const contact = person && this._contactFor(person, grant);
|
|
689
|
+
if (!contact) throw Object.assign(new Error('Sharing has ended'), { code: 'revoked' });
|
|
690
|
+
const tier = AUTONOMY[contact.autonomy] || AUTONOMY.bounded;
|
|
691
|
+
// Autonomy: their agents may start a reply of ours only within the tier's rounds (Notify only: never; the person
|
|
692
|
+
// can still ask). The host says what triggered the turn; a host that doesn't say counts as a person asking.
|
|
693
|
+
const round = Math.max(0, Math.floor(Number(p.round) || 0));
|
|
694
|
+
if (p.trigger === 'agent' && tier.rounds === 0) throw Object.assign(new Error(`Your agents don't answer ${firstName({ name: grant.requesterName })}'s agents on their own (Notify only)`), { code: 'notify_only' });
|
|
695
|
+
if (p.trigger === 'agent' && round > tier.rounds) throw Object.assign(new Error(`Agents paused after ${tier.rounds} rounds; reply to continue`), { code: 'rounds' });
|
|
696
|
+
const capped = this.book.overCap(person, contact.autonomy);
|
|
697
|
+
if (capped) throw Object.assign(new Error(capped), { code: 'cap' });
|
|
617
698
|
const running = [...this._turns.values()].filter(t => t.shareId === shareId);
|
|
618
699
|
if (running.length >= MAX_CONCURRENT_TURNS) throw Object.assign(new Error('Too many replies at once; try again shortly'), { code: 'busy' });
|
|
619
700
|
const turnKey = crypto.randomUUID();
|
|
@@ -624,11 +705,11 @@ export class SharingManager {
|
|
|
624
705
|
const turn = { shareId, clientTurnId, same, sessionKey: null, runId: null, sessionId: null, aborted: false, emit: redacting(emit), result: null };
|
|
625
706
|
this._turns.set(turnKey, turn); // counts toward the limit from here on
|
|
626
707
|
// Counted before any await, so parallel turns can't both pass the cap.
|
|
627
|
-
this.
|
|
708
|
+
this.book.count(person, 1);
|
|
628
709
|
this._changed(); // the owner's Sharing view shows today's count
|
|
629
710
|
turn.result = (async () => {
|
|
630
711
|
try {
|
|
631
|
-
const r = await this._runGuestTurn(shareId, grant, agent, roomId, p, (event, data) => turn.emit?.(event, data), turn);
|
|
712
|
+
const r = await this._runGuestTurn(shareId, grant, agent, roomId, p, (event, data) => turn.emit?.(event, data), turn, contact);
|
|
632
713
|
if (typeof r?.text === 'string') r.text = redactSecrets(r.text);
|
|
633
714
|
// What this gateway's agent said for that gateway's room: its copy of the room may show it as ours (team.js).
|
|
634
715
|
if (!p.inOwnerRoom && r?.text) try { this.onGuestReply?.(grant.requesterGatewayId, roomId, shareId, agent.id, r.text); } catch { /* best effort */ }
|
|
@@ -640,7 +721,7 @@ export class SharingManager {
|
|
|
640
721
|
// A reply that failed without saying anything doesn't use up the day's replies. A timeout still
|
|
641
722
|
// counts: it ran for the full turn timeout.
|
|
642
723
|
if (!e.partial && !/timed out/i.test(e.message)) {
|
|
643
|
-
this.
|
|
724
|
+
this.book.count(person, -1);
|
|
644
725
|
this._changed();
|
|
645
726
|
}
|
|
646
727
|
if (recentKey) this._rememberTurn(recentKey, { same, error: { message: e.message, code: e.code, partial: e.partial } });
|
|
@@ -675,29 +756,43 @@ export class SharingManager {
|
|
|
675
756
|
}
|
|
676
757
|
}
|
|
677
758
|
|
|
678
|
-
async _runGuestTurn(shareId, grant, agent, roomId, p, emit, turn) {
|
|
759
|
+
async _runGuestTurn(shareId, grant, agent, roomId, p, emit, turn, contact) {
|
|
760
|
+
// The person's own copy of the agent (D3), brought up to the card's policy; notes synced if they changed.
|
|
761
|
+
const sourceId = await this._sourceId(agent.id);
|
|
762
|
+
if (Array.isArray(contact.agents) && !contact.agents.map(id => this._sourceIdSync(id)).includes(sourceId)) throw Object.assign(new Error('That agent is not shared'), { code: 'not_shared' });
|
|
763
|
+
const copyId = await this._ensureCopy(contact, sourceId, firstName({ name: grant.requesterName }));
|
|
679
764
|
const cfg = await this.request('config.get', {}, 30_000);
|
|
680
|
-
// A
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
765
|
+
// A copy whose policy was edited away (e.g. in the Control UI) and couldn't be restored isn't served.
|
|
766
|
+
// Saved but not applied: the running gateway still has the old policy until its reload lands (the check the
|
|
767
|
+
// gateway's own CLI uses: configRevisionHash vs appliedConfigHash; missing hashes count as applied).
|
|
768
|
+
const applied = !cfg?.configRevisionHash || !cfg?.appliedConfigHash || cfg.configRevisionHash === cfg.appliedConfigHash;
|
|
769
|
+
if (applied) this._pendingCopies?.delete(copyId);
|
|
770
|
+
if (!copyToolsHold(cfg?.parsed?.agents?.entries?.[copyId]?.tools, copyTools(contact, { reviewerModel: reviewerModelFor(cfg?.parsed) }))
|
|
771
|
+
|| this._pendingCopies?.has(copyId)) {
|
|
772
|
+
this.log.warn?.(`[sharing] ${copyId} doesn't hold its contact policy: refusing turn for ${shareId}`);
|
|
684
773
|
throw Object.assign(new Error(`${agent.name} isn't available right now`), { code: 'unavailable' });
|
|
685
774
|
}
|
|
775
|
+
this.book.touchCopy(copyId);
|
|
686
776
|
|
|
687
777
|
// Their full name, as the approval screen shows it ("Shared with Houman Test").
|
|
688
778
|
const name = String(grant.requesterName || 'Someone').replace(/[\n\r]/g, ' ').trim().slice(0, 60) || 'Someone';
|
|
689
|
-
const permissionMode =
|
|
690
|
-
|
|
691
|
-
const
|
|
692
|
-
const
|
|
693
|
-
const sessionKey = await this._guestSession(shareId, roomId, agent.id, { name, roomTitle: String(p.roomTitle || 'team chat').slice(0, 80), permissionMode, toolOverrides });
|
|
779
|
+
const permissionMode = sessionMode(contact);
|
|
780
|
+
const skillNames = await this._skillNames(copyId);
|
|
781
|
+
const toolOverrides = contactOverrides(contact, { skillNames, mcpServers: Object.keys(cfg?.parsed?.mcp?.servers || {}) });
|
|
782
|
+
const sessionKey = await this._guestSession(shareId, roomId, copyId, { name, roomTitle: String(p.roomTitle || 'team chat').slice(0, 80), permissionMode, toolOverrides, cwd: contact.access === 'full' ? contact.openFolder : null });
|
|
694
783
|
// Made from the requester's turn id when there is one: a resend (after a dropped link, or after this connector
|
|
695
784
|
// restarted) reuses the idempotency key, so the gateway answers with the first run instead of starting another.
|
|
696
785
|
const runId = turn.clientTurnId
|
|
697
786
|
? `peer-${crypto.createHash('sha256').update(`${shareId}|${turn.clientTurnId}`).digest('hex').slice(0, 32)}`
|
|
698
787
|
: `peer-${crypto.randomUUID()}`;
|
|
788
|
+
// Commands that may ask the owner ("Basic + ask me", or Auto-review's unsure cases): the approval connection stays up
|
|
789
|
+
// for this turn, so the gateway keeps the approval pending until the owner answers (no tab open needed), and the
|
|
790
|
+
// turn may run as long as that approval can wait.
|
|
791
|
+
const asks = contact.commands === 'ask' || contact.commands === 'auto';
|
|
792
|
+
const turnTimeout = asks ? APPROVAL_TURN_TIMEOUT_MS : TURN_TIMEOUT_MS;
|
|
793
|
+
const releaseApprovals = asks && this.holdApprovals ? await this.holdApprovals().catch(() => null) : null;
|
|
699
794
|
const done = new Promise(resolve => {
|
|
700
|
-
const timer = setTimeout(() => { this._runs.delete(runId); resolve({ state: 'error', errorMessage: 'timed out' }); },
|
|
795
|
+
const timer = setTimeout(() => { this._runs.delete(runId); resolve({ state: 'error', errorMessage: 'timed out' }); }, turnTimeout + 30_000);
|
|
701
796
|
timer.unref?.();
|
|
702
797
|
this._runs.set(runId, { resolve, timer, text: '', emit, sessionKey });
|
|
703
798
|
});
|
|
@@ -709,7 +804,8 @@ export class SharingManager {
|
|
|
709
804
|
// transcript decides, not the ack. 2026.9.7 forgets its chat.send dedupe on a gateway restart and would start a
|
|
710
805
|
// run with no new input (a reply to nothing). Only this connector reloaded, so its run is still going: the send
|
|
711
806
|
// below is answered "in_flight" and the run's events finish the turn.
|
|
712
|
-
const
|
|
807
|
+
const notes = [p.inOwnerRoom ? ACTING_FOR_NOTE(name, p.byPerson) : GUEST_NOTE(name), contact.access !== 'full' && contact.knowledge === 'notes' ? NOTES_NOTE(name) : '', topicsNote(contact, name.split(/\s/)[0])].filter(Boolean);
|
|
808
|
+
const sent = defangLocalPaths(`${notes.join('\n')}\n\n${p.message}`);
|
|
713
809
|
if (turn.clientTurnId) {
|
|
714
810
|
const earlier = await this._replyTo(sessionKey, runId);
|
|
715
811
|
if (earlier && earlier.input.trim() !== sent.trim()) throw Object.assign(new Error('That turn was already sent with another message'), { code: 'bad_request' });
|
|
@@ -719,7 +815,7 @@ export class SharingManager {
|
|
|
719
815
|
}
|
|
720
816
|
const ack = await this.request('chat.send', {
|
|
721
817
|
sessionKey, message: sent, deliver: false, idempotencyKey: runId,
|
|
722
|
-
timeoutMs:
|
|
818
|
+
timeoutMs: turnTimeout, suppressCommandInterpretation: true,
|
|
723
819
|
expectedPermissionMode: permissionMode, expectedToolOverrides: toolOverrides,
|
|
724
820
|
}, 30_000).catch(e => {
|
|
725
821
|
// The same key with another message (2026.11.5+): the requester has to resend the identical one.
|
|
@@ -741,36 +837,382 @@ export class SharingManager {
|
|
|
741
837
|
if (!r.text && EMPTY_REPLY_ERROR.test(r.errorMessage || '')) return { state: 'final', text: '' };
|
|
742
838
|
throw Object.assign(new Error(r.errorMessage || 'The agent run failed'), { code: 'run_failed', partial: r.text || '' });
|
|
743
839
|
} finally {
|
|
840
|
+
releaseApprovals?.();
|
|
744
841
|
const run = this._runs.get(runId);
|
|
745
842
|
if (run) { clearTimeout(run.timer); this._runs.delete(runId); }
|
|
746
843
|
for (const [id, r] of this._approvalRuns || []) if (r === runId) this._approvalRuns.delete(id);
|
|
747
844
|
}
|
|
748
845
|
}
|
|
749
846
|
|
|
847
|
+
|
|
848
|
+
// ── Contact cards (owner side) ─────────────────────────────────────
|
|
849
|
+
|
|
850
|
+
/** The person (lowercased email) who asked for a share this gateway owns. */
|
|
851
|
+
_personOfShare(shareId) {
|
|
852
|
+
const s = this._shares.find(x => x.id === shareId && x.as === 'owner');
|
|
853
|
+
return personKeyOf(s?.requester?.email) || null;
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
/** The person's contact; one made from their grant if migration hasn't run yet (a turn right after the update). */
|
|
857
|
+
_contactFor(person, grant) {
|
|
858
|
+
return this.book.get(person) || this.book.create(person, {
|
|
859
|
+
...defaultContact(grant.access === 'trusted' ? 'trusted' : 'restricted'), knowledge: 'none', migrated: true,
|
|
860
|
+
name: grant.requesterName || null, autonomy: AUTONOMY[grant.autonomy] ? grant.autonomy : autonomyFromCap(grant.dailyCap),
|
|
861
|
+
agents: (grant.agents || []).map(a => this._sourceIdSync(a.id)),
|
|
862
|
+
});
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
/** The original agent behind a shared id: grants made before contact cards name the shared guest version ("main-guest"). */
|
|
866
|
+
_sourceIdSync(id, agents = this._agentsCache || []) {
|
|
867
|
+
const known = this.guestAgentIds();
|
|
868
|
+
const a = agents.find(x => x.id === id);
|
|
869
|
+
if (a && isGuestAgent(a, known)) {
|
|
870
|
+
const src = agents.find(o => o.id !== id && !isGuestAgent(o, known) && findGuestAgent(agents, o.id, known)?.id === id);
|
|
871
|
+
if (src) return src.id;
|
|
872
|
+
}
|
|
873
|
+
if (!a && known.has(id) && /-guest$/.test(id)) return id.replace(/-guest$/, '');
|
|
874
|
+
return id;
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
async _agents() {
|
|
878
|
+
this._agentsCache = (await this.request('agents.list', {}))?.agents || [];
|
|
879
|
+
return this._agentsCache;
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
async _sourceId(id) { return this._sourceIdSync(id, await this._agents()); }
|
|
883
|
+
|
|
884
|
+
/** The person's copy of an agent, written to the card's policy (one write at a time per copy); its notes synced. */
|
|
885
|
+
async _ensureCopy(contact, sourceId, first) {
|
|
886
|
+
const key = `${contact.personKey}|${sourceId}`;
|
|
887
|
+
while (this._copying.has(key)) await this._copying.get(key).catch(() => {});
|
|
888
|
+
const job = (async () => {
|
|
889
|
+
const c = this.book.get(contact.personKey) || contact;
|
|
890
|
+
const kind = copyKind(c);
|
|
891
|
+
const r = await ensureContactCopy({ request: this.request, contact: c, agentId: sourceId, firstName: first, known: this.book.copy(c.personKey, sourceId, kind), log: this.log });
|
|
892
|
+
this.book.putCopy(c.personKey, sourceId, kind, r.copyId, r.hash);
|
|
893
|
+
if (r.pending) (this._pendingCopies ??= new Set()).add(r.copyId); // saved, not applied yet: not served until it is
|
|
894
|
+
if (r.created) this._changed(); // agent pickers hide it
|
|
895
|
+
if (kind === 'guest') await this._syncNotesFor(c, r.copyId);
|
|
896
|
+
return r.copyId;
|
|
897
|
+
})();
|
|
898
|
+
this._copying.set(key, job);
|
|
899
|
+
try { return await job; } finally { this._copying.delete(key); }
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
/** Workspaces of the agents shared with a person (where "My notes" come from). */
|
|
903
|
+
async _noteCandidates(contact) {
|
|
904
|
+
const agents = await this._agents();
|
|
905
|
+
const known = this.guestAgentIds();
|
|
906
|
+
const shared = agents.filter(a => !isGuestAgent(a, known) && (!Array.isArray(contact.agents) || contact.agents.map(id => this._sourceIdSync(id, agents)).includes(a.id)));
|
|
907
|
+
return noteCandidates(shared.map(a => a.workspace));
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
/** The files a contact's notes are made of: their picks, or the defaults (all project notes but the infra ones). */
|
|
911
|
+
async _notePicks(contact) {
|
|
912
|
+
const cands = await this._noteCandidates(contact);
|
|
913
|
+
const picks = Array.isArray(contact.notes) ? contact.notes : cands.filter(c => c.defaultOn).map(c => c.path);
|
|
914
|
+
return { cands, files: resolvePicks(picks, cands) };
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
/** Copy the picked notes into a guest copy's folder when they changed (or `force`); "None" removes them. */
|
|
918
|
+
async _syncNotesFor(contact, copyId, { force = false } = {}) {
|
|
919
|
+
const ws = (this._agentsCache || []).find(a => a.id === copyId)?.workspace || (await this._agents()).find(a => a.id === copyId)?.workspace;
|
|
920
|
+
if (!ws || !ws.startsWith('/')) return null;
|
|
921
|
+
if (contact.knowledge !== 'notes') { removeNotes(ws); return null; }
|
|
922
|
+
const { files } = await this._notePicks(contact);
|
|
923
|
+
const sig = picksSignature(files);
|
|
924
|
+
const last = contact.notesSync?.copies?.[copyId];
|
|
925
|
+
if (!force && last === sig) return contact.notesSync;
|
|
926
|
+
const r = syncNotes(ws, files);
|
|
927
|
+
const summary = { ...r, copies: { ...(contact.notesSync?.copies || {}), [copyId]: r.signature } };
|
|
928
|
+
this.book.setNotesSync(contact.personKey, summary);
|
|
929
|
+
return summary;
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
async _skillNames(agentId) {
|
|
933
|
+
const hit = this._skillsCache;
|
|
934
|
+
if (hit && hit.agentId === agentId && Date.now() - hit.at < 60_000) return hit.names;
|
|
935
|
+
const r = await this.request('skills.status', { agentId }, 30_000).catch(() => null);
|
|
936
|
+
const names = (r?.skills || []).map(x => x?.name || x?.skillKey).filter(n => typeof n === 'string' && n);
|
|
937
|
+
this._skillsCache = { agentId, at: Date.now(), names };
|
|
938
|
+
return names;
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
/**
|
|
942
|
+
* Existing shares become contacts (once, on the first share list): access kept, a daily cap above 50 → Extended,
|
|
943
|
+
* else Bounded; a real-agent share becomes Full agent (confirmed when it was approved); Knowledge starts as None.
|
|
944
|
+
* Grants are re-issued as v2 so the other side sees the autonomy tier.
|
|
945
|
+
*/
|
|
946
|
+
async migrateContacts() {
|
|
947
|
+
const grants = this._localGrants();
|
|
948
|
+
if (!grants.length) return [];
|
|
949
|
+
const agents = await this._agents();
|
|
950
|
+
const known = this.guestAgentIds();
|
|
951
|
+
const made = [];
|
|
952
|
+
for (const r of grants) {
|
|
953
|
+
const s = this._shares.find(x => x.id === r.share_id && x.as === 'owner');
|
|
954
|
+
const person = personKeyOf(s?.requester?.email);
|
|
955
|
+
if (!person) continue;
|
|
956
|
+
let grant; try { grant = JSON.parse(r.grant_json); } catch { continue; }
|
|
957
|
+
if (!this.book.get(person)) {
|
|
958
|
+
const ids = (grant.agents || []).map(a => a.id);
|
|
959
|
+
const real = ids.some(id => { const a = agents.find(x => x.id === id); return a && !isGuestAgent(a, known); });
|
|
960
|
+
const access = real ? 'full' : grant.access === 'trusted' ? 'trusted' : 'restricted';
|
|
961
|
+
this.book.create(person, {
|
|
962
|
+
...defaultContact(access), knowledge: 'none', migrated: true, name: grant.requesterName || null,
|
|
963
|
+
autonomy: AUTONOMY[grant.autonomy] ? grant.autonomy : autonomyFromCap(grant.dailyCap),
|
|
964
|
+
agents: ids.map(id => this._sourceIdSync(id, agents)), ...(access === 'full' ? { fullConfirmedAt: r.created_at } : {}),
|
|
965
|
+
});
|
|
966
|
+
made.push(person);
|
|
967
|
+
}
|
|
968
|
+
// Signed with a key this gateway no longer has (its peer key was replaced): the same grant is signed again,
|
|
969
|
+
// or the other side, once it trusts the new key, still couldn't verify it.
|
|
970
|
+
const stale = s.status === 'active' && !verifySignature(this.key.publicKey, canonicalJson(grant), r.sig);
|
|
971
|
+
if ((grant.v !== 2 || stale) && s.status === 'active') {
|
|
972
|
+
const c = this.book.get(person);
|
|
973
|
+
try { this.approve(r.share_id, { agents: grant.agents, access: c.access, autonomy: c.autonomy, confirmFull: true }); }
|
|
974
|
+
catch (e) { this.log.warn?.(`[sharing] re-issue ${r.share_id}: ${e.message}`); }
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
if (made.length) { this.log.info?.(`[sharing] contacts made from existing shares: ${made.join(', ')}`); this._changed(); }
|
|
978
|
+
return made;
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
/** Owner shares with this person that have a grant, newest first. */
|
|
982
|
+
_ownerSharesOf(person) {
|
|
983
|
+
return this._shares.filter(s => s.as === 'owner' && personKeyOf(s.requester?.email) === person && this._grant(s.id));
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
/** Everything the contact card shows for a person (Settings → People → name). */
|
|
987
|
+
async contactCard(personKey) {
|
|
988
|
+
const person = personKeyOf(personKey);
|
|
989
|
+
const shares = this._shares.filter(s => this._sharingPerson(s) === person);
|
|
990
|
+
if (!shares.length && !this.book.get(person)) throw Object.assign(new Error('Not a contact'), { code: 'not_found' });
|
|
991
|
+
const c = this.book.get(person);
|
|
992
|
+
const agents = await this._agents();
|
|
993
|
+
const known = this.guestAgentIds();
|
|
994
|
+
const cfg = await this.request('config.get', {}, 30_000).catch(() => null);
|
|
995
|
+
const own = agents.filter(a => !isGuestAgent(a, known));
|
|
996
|
+
const skillNames = await this._skillNames(own.find(a => a.default)?.id || own[0]?.id || 'main');
|
|
997
|
+
const skillInfo = await this.request('skills.status', { agentId: own[0]?.id }, 30_000).then(r => r?.skills || [], () => []);
|
|
998
|
+
const gateways = new Map();
|
|
999
|
+
for (const s of shares) {
|
|
1000
|
+
const o = this._other(s);
|
|
1001
|
+
if (!o.gatewayId) continue;
|
|
1002
|
+
const g = gateways.get(o.gatewayId) || { gatewayId: o.gatewayId, shareIds: [], online: false, theirAgents: [], version: this._peerVersions.get(o.gatewayId) ?? undefined };
|
|
1003
|
+
g.shareIds.push(s.id);
|
|
1004
|
+
if (s.as === 'requester') g.theirAgents = (this._verifiedGrant(s)?.agents || []).map(a => cleanName(a.name || a.id));
|
|
1005
|
+
g.online ||= [...this._links.values(), ...this._served].some(l => l.ready && !l.closed && (l.shareId === s.id));
|
|
1006
|
+
gateways.set(o.gatewayId, g);
|
|
1007
|
+
}
|
|
1008
|
+
// Before Accept there is no contact yet: the first-time form starts from the defaults (Trusted, My notes).
|
|
1009
|
+
const view = c || { ...defaultContact('trusted'), personKey: person, agents: null };
|
|
1010
|
+
let notes = null;
|
|
1011
|
+
{
|
|
1012
|
+
const { cands, files } = await this._notePicks(view);
|
|
1013
|
+
const picked = new Set(files.map(f => f.src));
|
|
1014
|
+
notes = {
|
|
1015
|
+
candidates: cands.map(x => ({ path: x.path, name: x.name, size: x.size, mtimeMs: x.mtimeMs, on: picked.has(x.path), defaultOn: x.defaultOn })),
|
|
1016
|
+
repoDocs: files.filter(f => !cands.some(x => x.path === f.src)).map(f => ({ path: f.src, name: f.dest.replace(/^repos\//, '') })),
|
|
1017
|
+
sync: c?.notesSync ? { files: c.notesSync.files, bytes: c.notesSync.bytes, secretsRemoved: c.notesSync.secretsRemoved, at: c.notesSync.at } : null,
|
|
1018
|
+
};
|
|
1019
|
+
}
|
|
1020
|
+
const u = c ? this.book.usage(person) : { day: 0, hour: 0 };
|
|
1021
|
+
return {
|
|
1022
|
+
person, contact: c, usage: { ...u, ...(c ? AUTONOMY[c.autonomy] : {}) }, gateways: [...gateways.values()],
|
|
1023
|
+
agents: own.map(a => ({ id: a.id, name: a.identity?.name || a.name || a.id })),
|
|
1024
|
+
skills: skillNames.map(n => { const i = skillInfo.find(x => (x?.name || x?.skillKey) === n); return { name: n, description: String(i?.description || '').slice(0, 160) }; }),
|
|
1025
|
+
mcpServers: Object.keys(cfg?.parsed?.mcp?.servers || {}).sort().map(n => ({ name: n, enabled: cfg.parsed.mcp.servers[n]?.enabled !== false })),
|
|
1026
|
+
notes, copies: this.book.copies(person), sessions: this._guestSessionKeysOf(person),
|
|
1027
|
+
reviewerModel: reviewerModelFor(cfg?.parsed),
|
|
1028
|
+
// What the card draws its controls from (one source with the policy the copies get).
|
|
1029
|
+
catalog: { toolGroups: TOOL_GROUPS, alwaysOff: ALWAYS_OFF, basicDefaults: BASIC_DEFAULTS, defaultTools: DEFAULT_TOOLS, defaultCommands: DEFAULT_COMMANDS, autonomy: AUTONOMY, draft: c ? null : { ...view, notes: files0(notes) } },
|
|
1030
|
+
};
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
/**
|
|
1034
|
+
* What the two contact cards between this gateway and a person allow (team.js room limits): `mine` = this side's
|
|
1035
|
+
* card for them, `theirs` = their grant to this side. { mine: { access, autonomy } | null, theirs: … | null }.
|
|
1036
|
+
*/
|
|
1037
|
+
limitsFor(gatewayId) {
|
|
1038
|
+
const email = this.contact(gatewayId)?.email;
|
|
1039
|
+
const c = email ? this.book.get(email) : null;
|
|
1040
|
+
const theirs = this._shares.map(s => (s.as === 'requester' && this._ownerGateway(s) === gatewayId ? this._verifiedGrant(s) : null)).find(Boolean);
|
|
1041
|
+
return {
|
|
1042
|
+
mine: c ? { access: c.access, autonomy: c.autonomy } : null,
|
|
1043
|
+
theirs: theirs ? { access: theirs.access, autonomy: AUTONOMY[theirs.autonomy] ? theirs.autonomy : 'bounded' } : null,
|
|
1044
|
+
};
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
/** The person of a share, either direction. */
|
|
1048
|
+
_sharingPerson(s) { return personKeyOf(s.as === 'owner' ? s.requester?.email : s.owner?.email); }
|
|
1049
|
+
|
|
1050
|
+
/**
|
|
1051
|
+
* Change one card setting. Access, autonomy and agents re-issue the person's grants; anything a copy holds updates
|
|
1052
|
+
* that person's existing copies in the background (new ones are made on first use). Returns the contact.
|
|
1053
|
+
*/
|
|
1054
|
+
async setContact(personKey, field, value, { confirmFull = false } = {}) {
|
|
1055
|
+
const person = personKeyOf(personKey);
|
|
1056
|
+
const before = this.book.get(person);
|
|
1057
|
+
if (!before) throw Object.assign(new Error('Not a contact'), { code: 'not_found' });
|
|
1058
|
+
if (field === 'agents') value = (Array.isArray(value) ? value : []).map(String);
|
|
1059
|
+
if (field === 'openFolder' && value) value = await this._checkFolder(before, value);
|
|
1060
|
+
const c = this.book.set(person, field, value, { confirmFull });
|
|
1061
|
+
if (['access', 'autonomy', 'agents'].includes(field)) {
|
|
1062
|
+
const names = new Map((await this._agents()).map(a => [a.id, a.identity?.name || a.name || a.id]));
|
|
1063
|
+
for (const s of this._ownerSharesOf(person)) {
|
|
1064
|
+
const g = this._grant(s.id).grant;
|
|
1065
|
+
// Agents keep the id they were shared under (rooms on the other side refer to it).
|
|
1066
|
+
const list = (c.agents || []).map(id => g.agents.find(a => this._sourceIdSync(a.id) === id) || { id, name: String(names.get(id) || id).slice(0, 80) });
|
|
1067
|
+
this.approve(s.id, { agents: list, access: c.access, autonomy: c.autonomy, confirmFull: true });
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
if (field === 'access' && copyKind(before) !== copyKind(c)) this._dropCopies(person, copyKind(before)).catch(e => this.log.warn?.(`[sharing] ${e.message}`));
|
|
1071
|
+
this._refreshCopies(person).catch(e => this.log.warn?.(`[sharing] copies for ${person}: ${e.message}`));
|
|
1072
|
+
this._changed();
|
|
1073
|
+
return c;
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
/**
|
|
1077
|
+
* "Open one folder" (§12): a real folder inside a shared agent's workspace, never the workspace itself, never one
|
|
1078
|
+
* that is or holds secrets/, no links or `..` on the way. Returns its real path.
|
|
1079
|
+
*/
|
|
1080
|
+
async _checkFolder(contact, folder) {
|
|
1081
|
+
const fs = await import('node:fs');
|
|
1082
|
+
const path = await import('node:path');
|
|
1083
|
+
const raw = String(folder || '');
|
|
1084
|
+
if (!path.isAbsolute(raw) || raw.split(/[\\/]/).includes('..')) throw new Error('Pick a folder inside your workspace');
|
|
1085
|
+
let real; try { real = fs.realpathSync(raw); } catch { throw new Error("That folder doesn't exist"); }
|
|
1086
|
+
if (real !== path.normalize(raw).replace(/\/+$/, '')) throw new Error("That path goes through a link; use the folder's real path");
|
|
1087
|
+
const roots = (await this._agents()).filter(a => !Array.isArray(contact.agents) || contact.agents.map(id => this._sourceIdSync(id)).includes(a.id)).map(a => a.workspace).filter(Boolean);
|
|
1088
|
+
const root = roots.find(r => real.startsWith(`${r.replace(/\/+$/, '')}/`));
|
|
1089
|
+
if (!root) throw new Error('Pick a folder inside your workspace, not the workspace itself');
|
|
1090
|
+
if (real.split('/').includes('secrets') || fs.existsSync(path.join(real, 'secrets'))) throw new Error('Not secrets/, nor a folder that holds it');
|
|
1091
|
+
return real;
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
/** Make the person's copies of every agent they can use (after Accept/Save), so their first message doesn't wait on it. */
|
|
1095
|
+
prepareCopies(shareId) {
|
|
1096
|
+
const person = this._personOfShare(shareId);
|
|
1097
|
+
const c = person && this.book.get(person);
|
|
1098
|
+
if (!c) return;
|
|
1099
|
+
const g = this._grant(shareId)?.grant;
|
|
1100
|
+
(async () => {
|
|
1101
|
+
for (const a of g?.agents || []) await this._ensureCopy(this.book.get(person), await this._sourceId(a.id), firstName({ name: c.name || person }));
|
|
1102
|
+
})().catch(e => this.log.warn?.(`[sharing] copies for ${person}: ${e.message}`));
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
/** Bring a person's existing copies up to their card (config write, approvals, notes). */
|
|
1106
|
+
async _refreshCopies(person) {
|
|
1107
|
+
const c = this.book.get(person);
|
|
1108
|
+
if (!c) return;
|
|
1109
|
+
const first = firstName({ name: c.name || person });
|
|
1110
|
+
for (const r of this.book.copies(person).filter(x => x.kind === copyKind(c))) {
|
|
1111
|
+
if (Array.isArray(c.agents) && !c.agents.map(id => this._sourceIdSync(id)).includes(r.agentId)) continue;
|
|
1112
|
+
await this._ensureCopy(c, r.agentId, first);
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
/** Copies of the other kind after an access change: retired (locked down, kept with their chats), not deleted. */
|
|
1117
|
+
async _dropCopies(person, kind) {
|
|
1118
|
+
for (const r of this.book.copies(person).filter(x => x.kind === kind)) {
|
|
1119
|
+
await retireCopy(this.request, r.copyId);
|
|
1120
|
+
this.book.retireCopyRow(r.copyId);
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
/** Sync now (card): rewrite every guest copy's notes. Returns the summary. */
|
|
1125
|
+
async syncNotesNow(personKey) {
|
|
1126
|
+
const c = this.book.get(personKey);
|
|
1127
|
+
if (!c) throw Object.assign(new Error('Not a contact'), { code: 'not_found' });
|
|
1128
|
+
let summary = null;
|
|
1129
|
+
for (const r of this.book.copies(c.personKey).filter(x => x.kind === 'guest')) summary = await this._syncNotesFor(this.book.get(c.personKey), r.copyId, { force: true }) || summary;
|
|
1130
|
+
if (!summary && c.knowledge === 'notes') {
|
|
1131
|
+
const { files } = await this._notePicks(c);
|
|
1132
|
+
summary = { files: files.length, bytes: 0, secretsRemoved: 0, at: null, pending: true }; // copied on their first message
|
|
1133
|
+
}
|
|
1134
|
+
this._changed();
|
|
1135
|
+
return summary;
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
/**
|
|
1139
|
+
* Disconnect (spec §8.3): their guest sessions are archived, then their copies, approvals entries, notes and every
|
|
1140
|
+
* peer_* row for them go. The shares themselves are revoked by the caller (both directions).
|
|
1141
|
+
*/
|
|
1142
|
+
async forgetPerson(personKey) {
|
|
1143
|
+
const person = personKeyOf(personKey);
|
|
1144
|
+
const keys = this._guestSessionKeysOf(person);
|
|
1145
|
+
let archived = 0;
|
|
1146
|
+
for (const key of keys) if (await this._archive(key)) archived++;
|
|
1147
|
+
// Copies are retired, not deleted: deleting an agent deletes its sessions (2026.11.6), and these chats are kept.
|
|
1148
|
+
let retired = 0;
|
|
1149
|
+
for (const r of this.book.copies(person).filter(x => !x.kind.startsWith('retired'))) {
|
|
1150
|
+
try {
|
|
1151
|
+
if (r.kind === 'guest') { const ws = (await this._agents()).find(a => a.id === r.copyId)?.workspace; if (ws?.startsWith('/')) removeNotes(ws); }
|
|
1152
|
+
if (await retireCopy(this.request, r.copyId)) retired++;
|
|
1153
|
+
} catch (e) { this.log.warn?.(`[sharing] retire ${r.copyId}: ${e.message}`); }
|
|
1154
|
+
}
|
|
1155
|
+
const db = this._db();
|
|
1156
|
+
for (const key of keys) db.prepare('DELETE FROM peer_sessions WHERE session_key = ?').run(key);
|
|
1157
|
+
this.book.forget(person);
|
|
1158
|
+
this._guestKeys = null;
|
|
1159
|
+
this._changed();
|
|
1160
|
+
return { archived, retired };
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
// ── Peer versions ──────────────────────────────────────────────────
|
|
1164
|
+
|
|
1165
|
+
/** Note a linked gateway's connector version; true when it's too old to share with. */
|
|
1166
|
+
_checkPeer(link, gatewayId) {
|
|
1167
|
+
const v = link.peerVersion ?? null;
|
|
1168
|
+
if (gatewayId && this._peerVersions.get(gatewayId) !== v) { this._peerVersions.set(gatewayId, v); this._changed(); }
|
|
1169
|
+
return peerOutdated(v);
|
|
1170
|
+
}
|
|
1171
|
+
|
|
750
1172
|
async _guestAbort(shareId, turnId) {
|
|
751
1173
|
for (const t of this._turns.values()) if (t.shareId === shareId && turnId && t.clientTurnId === turnId) this._abortTurn(t);
|
|
752
1174
|
return { ok: true };
|
|
753
1175
|
}
|
|
754
1176
|
|
|
1177
|
+
/**
|
|
1178
|
+
* Archive a session. 2026.11.x needs the session id it expects (a lifecycle patch); 9.x has no such field.
|
|
1179
|
+
* Returns whether it worked.
|
|
1180
|
+
*/
|
|
1181
|
+
async _archive(key, sessionId = null) {
|
|
1182
|
+
const id = sessionId || await this.request('sessions.describe', { key }, 5000).then(r => r?.session?.sessionId || null, () => null);
|
|
1183
|
+
const patch = p => this.request('sessions.patch', p).then(() => true);
|
|
1184
|
+
return patch({ key, archived: true, ...(id ? { expectedSessionId: id } : {}) })
|
|
1185
|
+
.catch(e => (/expectedSessionId|unexpected property|additional/i.test(e.message) && id ? patch({ key, archived: true }) : false))
|
|
1186
|
+
.catch(() => false);
|
|
1187
|
+
}
|
|
1188
|
+
|
|
755
1189
|
/** The (share, room, agent) session on this gateway: visible to the owner in "Shared with <name>". */
|
|
756
|
-
async _guestSession(shareId, roomId, agentId, { name, roomTitle, permissionMode, toolOverrides }) {
|
|
1190
|
+
async _guestSession(shareId, roomId, agentId, { name, roomTitle, permissionMode, toolOverrides, cwd = null }) {
|
|
757
1191
|
const db = this._db();
|
|
758
1192
|
const row = db.prepare('SELECT session_key FROM peer_sessions WHERE share_id = ? AND room_id = ? AND agent_id = ?').get(shareId, roomId, agentId);
|
|
759
1193
|
// The owner may have deleted it from their chat list: then it's made again (same key, so the
|
|
760
1194
|
// room keeps pointing at it), in "Shared with <name>" with its label, instead of the gateway
|
|
761
1195
|
// bringing it back as an untitled chat that ClawChats hides.
|
|
762
|
-
const
|
|
763
|
-
|
|
764
|
-
|
|
1196
|
+
const described = row && await this.request('sessions.describe', { key: row.session_key }, 5000).then(r => r, () => ({ unknown: true }));
|
|
1197
|
+
const exists = row && !(described && 'session' in described && !described.session);
|
|
1198
|
+
// A session's root is fixed when it's made. "Open one folder" opened (or moved) after that: the old session (rooted
|
|
1199
|
+
// at the whole workspace, secrets/ included) is archived and a new one is made at the folder. Unknown: never reused.
|
|
1200
|
+
const root = described?.session?.sessionRoot;
|
|
1201
|
+
const wrongRoot = exists && cwd && (described.unknown || !root || root.replace(/\/+$/, '') !== cwd.replace(/\/+$/, ''));
|
|
1202
|
+
if (wrongRoot) await this._archive(row.session_key, described?.session?.sessionId);
|
|
1203
|
+
if (exists && !wrongRoot) {
|
|
1204
|
+
// Re-apply the policy each turn: the owner may have changed the card since. Basic only and Off clear the mode
|
|
1205
|
+
// (null): a session mode would override the copy's exec allowlist (spike run 1).
|
|
765
1206
|
await this.request('sessions.patch', { key: row.session_key, permissionMode, toolOverrides }).catch(() => {});
|
|
766
1207
|
return row.session_key;
|
|
767
1208
|
}
|
|
768
|
-
const key = row?.session_key || `agent:${agentId}:dashboard:${crypto.randomUUID()}`;
|
|
1209
|
+
const key = (!wrongRoot && row?.session_key) || `agent:${agentId}:dashboard:${crypto.randomUUID()}`;
|
|
769
1210
|
const category = this.funnelOf(this._shares.find(x => x.id === shareId && x.as === 'owner')?.requester?.email, name);
|
|
770
1211
|
// Labels are unique per gateway, and untitled rooms all fall back to "team chat": tag each room.
|
|
771
1212
|
const tag = crypto.createHash('sha256').update(`${shareId}|${roomId}`).digest('hex').slice(0, 6);
|
|
772
1213
|
const create = label => this.request('sessions.create', {
|
|
773
|
-
key, agentId, permissionMode, toolOverrides, label: label.slice(0, 200), category,
|
|
1214
|
+
key, agentId, ...(permissionMode ? { permissionMode } : {}), toolOverrides, label: label.slice(0, 200), category,
|
|
1215
|
+
...(cwd ? { cwd } : {}), // Full agent's "Open one folder": the session root (§12)
|
|
774
1216
|
});
|
|
775
1217
|
try { await create(`${name} · ${roomTitle} · ${tag}`); }
|
|
776
1218
|
catch (e) {
|
|
@@ -907,8 +1349,13 @@ export class SharingManager {
|
|
|
907
1349
|
if (!s.owner.gatewayId || s.grant.ownerGatewayId !== s.owner.gatewayId) return null;
|
|
908
1350
|
const db = this._db();
|
|
909
1351
|
const pinRow = db.prepare('SELECT owner_pubkey, owner_gateway_id FROM peer_pins WHERE share_id = ?').get(s.id);
|
|
910
|
-
|
|
1352
|
+
let pin = pinRow?.owner_pubkey;
|
|
911
1353
|
const gwPin = this._gatewayKey(s.owner.gatewayId);
|
|
1354
|
+
// The owner already trusted this gateway's new key (trustNewKey): a share's older pin follows it.
|
|
1355
|
+
if (pin && gwPin && pin !== gwPin && gwPin === s.owner.pubKey) {
|
|
1356
|
+
db.prepare('UPDATE peer_pins SET owner_pubkey = ? WHERE share_id = ?').run(gwPin, s.id);
|
|
1357
|
+
pin = gwPin;
|
|
1358
|
+
}
|
|
912
1359
|
if ((pin && pin !== s.owner.pubKey) || (gwPin && gwPin !== s.owner.pubKey)) {
|
|
913
1360
|
const was = pin && pin !== s.owner.pubKey ? pin : gwPin;
|
|
914
1361
|
if (!(this._warnedKeys ??= new Set()).has(`${s.id}|${s.owner.pubKey}`)) {
|
|
@@ -953,8 +1400,12 @@ export class SharingManager {
|
|
|
953
1400
|
if (!grant) throw Object.assign(new Error('This share is not active'), { code: 'revoked' });
|
|
954
1401
|
const p = (async () => {
|
|
955
1402
|
const { dc, dtls } = await this.openPeer(shareId);
|
|
956
|
-
const link = new PeerLink({ dc, dtls, role: 'requester', shareId, key: this.key, peerKey: s.owner.pubKey, log: this.log });
|
|
1403
|
+
const link = new PeerLink({ dc, dtls, role: 'requester', shareId, key: this.key, peerKey: s.owner.pubKey, log: this.log, version: this.version });
|
|
957
1404
|
await new Promise((resolve, reject) => { link.once('ready', resolve); link.once('closed', () => reject(new Error(`Couldn't reach ${firstName(s.owner)}'s gateway`))); });
|
|
1405
|
+
if (this._checkPeer(link, grant.ownerGatewayId)) {
|
|
1406
|
+
link.close();
|
|
1407
|
+
throw Object.assign(new Error(outdatedMessage(firstName(s.owner), link.peerVersion)), { code: 'peer_outdated' });
|
|
1408
|
+
}
|
|
958
1409
|
this._links.set(shareId, link);
|
|
959
1410
|
link.on('closed', () => { if (this._links.get(shareId) === link) this._links.delete(shareId); });
|
|
960
1411
|
this._wireRooms(link, grant.ownerGatewayId); // the gateway the key this link authenticated signed for
|
|
@@ -970,18 +1421,22 @@ export class SharingManager {
|
|
|
970
1421
|
* turn's timeout): the owner attaches it to the run still going there, or answers from the finished one, so the
|
|
971
1422
|
* turn never runs twice. `stopped()`: the room was stopped, so it isn't sent again.
|
|
972
1423
|
*/
|
|
973
|
-
async turn(agentId, { turnId, roomId, roomTitle, message }, { onDelta, onStatus, stopped = () => false } = {}) {
|
|
1424
|
+
async turn(agentId, { turnId, roomId, roomTitle, message, trigger = 'person', round = 0 }, { onDelta, onStatus, stopped = () => false } = {}) {
|
|
974
1425
|
const id = SharingManager.parseRemoteId(agentId);
|
|
975
1426
|
if (!id) throw new Error('not a shared agent');
|
|
976
|
-
|
|
1427
|
+
// trigger/round: what started this turn (a person's message, or another agent's reply in round N), for the
|
|
1428
|
+
// owner's autonomy tier.
|
|
1429
|
+
const params = { turnId, agentId: id.remoteId, roomId, roomTitle, message, trigger, round };
|
|
977
1430
|
const onEvent = (event, data) => {
|
|
978
1431
|
if (event === 'delta' && typeof data === 'string') onDelta?.(data);
|
|
979
1432
|
else if (event === 'status' && data && typeof data === 'object') onStatus?.(data);
|
|
980
1433
|
};
|
|
981
|
-
const deadline = Date.now() +
|
|
1434
|
+
const deadline = Date.now() + APPROVAL_TURN_TIMEOUT_MS + 60_000; // the owner ends the turn sooner when it can't ask
|
|
982
1435
|
for (let resend = 0; ; resend++) {
|
|
983
1436
|
try {
|
|
984
1437
|
const link = await this._link(id.shareId);
|
|
1438
|
+
const s = this._shares.find(x => x.id === id.shareId);
|
|
1439
|
+
if (this._checkPeer(link, this._ownerGateway(s))) throw Object.assign(new Error(outdatedMessage(firstName(s?.owner), link.peerVersion)), { code: 'peer_outdated' });
|
|
985
1440
|
return await link.request('turn', params, { onEvent, timeoutMs: deadline - Date.now() });
|
|
986
1441
|
} catch (e) {
|
|
987
1442
|
// Only a dropped link (or, while resending, the link not back yet): local errors, without a code. Never
|
|
@@ -1053,7 +1508,7 @@ export class SharingManager {
|
|
|
1053
1508
|
if (!live || !Array.isArray(grant.agents)) continue;
|
|
1054
1509
|
const next = grant.agents.map(a => ({ id: a.id, name: String(shown(a.id) || a.name).slice(0, 80) }));
|
|
1055
1510
|
if (next.every((a, i) => a.name === grant.agents[i].name)) continue;
|
|
1056
|
-
try { this.approve(r.share_id, { agents: next, access: grant.access, dailyCap: grant.dailyCap }); reissued.push(r.share_id); }
|
|
1511
|
+
try { this.approve(r.share_id, { agents: next, access: grant.access, autonomy: grant.autonomy, dailyCap: grant.autonomy ? null : grant.dailyCap, confirmFull: true }); reissued.push(r.share_id); }
|
|
1057
1512
|
catch (e) { this.log?.warn?.(`[sharing] rename ${r.share_id}: ${e.message}`); }
|
|
1058
1513
|
}
|
|
1059
1514
|
return reissued;
|
|
@@ -1105,15 +1560,17 @@ export class SharingManager {
|
|
|
1105
1560
|
return ids;
|
|
1106
1561
|
}
|
|
1107
1562
|
|
|
1108
|
-
/** Our agents' guest sessions for this person, including ones from shares since ended. */
|
|
1563
|
+
/** Our agents' guest sessions for this person, including ones from shares since ended (and their own copies' sessions). */
|
|
1109
1564
|
_guestSessionKeysOf(email) {
|
|
1110
1565
|
const ids = this.gatewayIdsOf(email);
|
|
1111
|
-
const
|
|
1112
|
-
|
|
1566
|
+
const copies = new Set(this.book.copies(email).map(c => c.copyId));
|
|
1567
|
+
const keys = new Set();
|
|
1568
|
+
for (const r of this._db().prepare('SELECT p.session_key, p.agent_id, g.grant_json FROM peer_sessions p LEFT JOIN peer_grants g ON g.share_id = p.share_id').all()) {
|
|
1569
|
+
if (copies.has(r.agent_id)) { keys.add(r.session_key); continue; }
|
|
1113
1570
|
let gw; try { gw = JSON.parse(r.grant_json).requesterGatewayId; } catch { continue; }
|
|
1114
|
-
if (ids.has(gw)) keys.
|
|
1571
|
+
if (ids.has(gw)) keys.add(r.session_key);
|
|
1115
1572
|
}
|
|
1116
|
-
return keys;
|
|
1573
|
+
return [...keys];
|
|
1117
1574
|
}
|
|
1118
1575
|
|
|
1119
1576
|
/** The guest session that answers `who` in a team chat here (TeamCoordinator lanes): one per share, like _guestSession. */
|
|
@@ -1128,14 +1585,18 @@ export class SharingManager {
|
|
|
1128
1585
|
* that person (its guest copy, normally) under their grant: access level, daily cap, its own
|
|
1129
1586
|
* session in "Shared with <name>". Returns null when that agent isn't shared with them.
|
|
1130
1587
|
*/
|
|
1131
|
-
async localTurnFor(localAgentId, remoteAgentId, { turnId, roomId, roomTitle, message }, { onDelta } = {}) {
|
|
1588
|
+
async localTurnFor(localAgentId, remoteAgentId, { turnId, roomId, roomTitle, message, round = 0 }, { onDelta } = {}) {
|
|
1132
1589
|
const g = this._grantToOwnerOf(remoteAgentId);
|
|
1133
1590
|
if (!g) return null;
|
|
1134
1591
|
const agents = (await this.request('agents.list', {}))?.agents || [];
|
|
1135
1592
|
const guestId = findGuestAgent(agents, localAgentId, this.guestAgentIds())?.id;
|
|
1136
1593
|
const shared = g.grant.agents.find(a => a.id === guestId) || g.grant.agents.find(a => a.id === localAgentId);
|
|
1137
1594
|
if (!shared) return null;
|
|
1138
|
-
|
|
1595
|
+
const byPerson = String(remoteAgentId).startsWith('person:');
|
|
1596
|
+
// Their gateway is too old to share with: nothing runs for them here either.
|
|
1597
|
+
const gw = byPerson ? remoteAgentId.slice('person:'.length) : this.ownerOf(remoteAgentId);
|
|
1598
|
+
if (gw && this._peerVersions.has(gw) && peerOutdated(this._peerVersions.get(gw))) throw Object.assign(new Error(outdatedMessage(firstName({ name: g.grant.requesterName }), this._peerVersions.get(gw))), { code: 'peer_outdated' });
|
|
1599
|
+
return this._guestTurn(g.shareId, { turnId, agentId: shared.id, roomId, roomTitle, message, inOwnerRoom: true, byPerson, trigger: byPerson ? 'person' : 'agent', round },
|
|
1139
1600
|
(event, data) => { if (event === 'delta' && typeof data === 'string') onDelta?.(data); });
|
|
1140
1601
|
}
|
|
1141
1602
|
|