@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
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
// What one contact (a person this gateway shares with) may make this gateway's agents do: the contact card's settings,
|
|
2
|
+
// their defaults per Access tier, and how each maps onto the gateway's enforcement layers (clawchats specs, contact
|
|
3
|
+
// card spec CONTACT-CARD-DESIGN.md §3-4):
|
|
4
|
+
// - the agent copy made for that person (`agents.entries.<copy>.tools`: profile, alsoAllow, deny, exec, fs);
|
|
5
|
+
// - the copy's exec approvals entry (basic-commands allowlist);
|
|
6
|
+
// - each guest session (permissionMode, toolOverrides: skills, mcpServers, webSearch);
|
|
7
|
+
// - the agent's instructions (Private / Always fine: instruction only).
|
|
8
|
+
// Pure functions only: contacts.js stores the settings, guest-agent.js writes the copy, sharing.js runs the turns.
|
|
9
|
+
|
|
10
|
+
import crypto from 'node:crypto';
|
|
11
|
+
import { GUEST_TOOLS_DENY } from './guest-agent.js';
|
|
12
|
+
|
|
13
|
+
export const ACCESS = ['restricted', 'trusted', 'full'];
|
|
14
|
+
export const COMMANDS = ['off', 'basic', 'ask', 'auto'];
|
|
15
|
+
export const KNOWLEDGE = ['none', 'notes'];
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Autonomy tiers (D10): how much this gateway's agents answer the person's agents on their own. One counter per
|
|
19
|
+
* person counts both their own questions and agent replies. `rounds` caps agent-to-agent rounds per human message
|
|
20
|
+
* (0: agents never answer the person's agents; the person can still ask).
|
|
21
|
+
*/
|
|
22
|
+
export const AUTONOMY = Object.freeze({
|
|
23
|
+
notify: Object.freeze({ rounds: 0, perDay: 50 }),
|
|
24
|
+
bounded: Object.freeze({ rounds: 3, perDay: 50 }),
|
|
25
|
+
extended: Object.freeze({ rounds: 10, perDay: 288, perHour: 12 }),
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Tools on the card, grouped as the card shows them. `personal`: reaches the owner's accounts. Commands are set by the
|
|
30
|
+
* Commands tier, not ticked. Always-off tools are never allowed for a contact, whatever is ticked.
|
|
31
|
+
*/
|
|
32
|
+
export const TOOL_GROUPS = Object.freeze([
|
|
33
|
+
{ id: 'files', title: 'Files', tools: ['read', 'write', 'edit', 'apply_patch'] },
|
|
34
|
+
{ id: 'commands', title: 'Commands', tools: ['exec', 'process'], byCommands: true },
|
|
35
|
+
{ id: 'web', title: 'Web', tools: ['web_search', 'web_fetch'] },
|
|
36
|
+
{ id: 'media', title: 'Media', tools: ['view_image', 'pdf', 'image_generate', 'tts'] },
|
|
37
|
+
{ id: 'memory', title: 'Memory', tools: ['memory_search', 'memory_get', 'wiki_search'] },
|
|
38
|
+
{ id: 'accounts', title: 'Reaches your accounts', tools: ['message', 'browser', 'nodes', 'computer', 'talk_voice'], personal: true },
|
|
39
|
+
{ id: 'gateway', title: 'Your gateway', tools: ['sessions_list', 'sessions_history', 'subagents', 'cron', 'canvas', 'dashboard'] },
|
|
40
|
+
]);
|
|
41
|
+
export const ALWAYS_OFF = Object.freeze(['gateway', 'openclaw', 'plugins', 'secrets', 'skill_workshop', 'agents_list']);
|
|
42
|
+
const TICKABLE = new Set(TOOL_GROUPS.filter(g => !g.byCommands).flatMap(g => g.tools));
|
|
43
|
+
const FILE_TOOLS = ['read', 'write', 'edit', 'apply_patch'];
|
|
44
|
+
const WRITE_TOOLS = ['write', 'edit', 'apply_patch'];
|
|
45
|
+
// The groups a copy denies as a whole (from the old guest policy), with the tools in each a contact could tick.
|
|
46
|
+
// A ticked tool lifts its group's deny; the group's other members are then denied one by one.
|
|
47
|
+
const GROUP_MEMBERS = Object.freeze({
|
|
48
|
+
'group:fs': FILE_TOOLS,
|
|
49
|
+
'group:web': ['web_search', 'x_search', 'web_fetch'],
|
|
50
|
+
'group:memory': ['memory_search', 'memory_get'],
|
|
51
|
+
'group:ui': ['browser', 'screen', 'theme', 'dashboard', 'terminal', 'portal', 'canvas', 'show_widget'],
|
|
52
|
+
'group:nodes': ['nodes', 'computer'],
|
|
53
|
+
'group:messaging': ['message'],
|
|
54
|
+
'group:automation': ['automations', 'cron', 'gateway', 'plugins', 'openclaw'],
|
|
55
|
+
'group:sessions': ['sessions', 'sessions_list', 'sessions_history', 'sessions_search', 'conversations_list', 'conversations_send',
|
|
56
|
+
'conversations_turn', 'sessions_send', 'sessions_spawn', 'sessions_yield', 'subagents', 'session_status', 'suggest_task', 'dismiss_task'],
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
export const DEFAULT_SKILLS = Object.freeze(['weather', 'diagram-maker', 'visualize']);
|
|
60
|
+
|
|
61
|
+
/** Tools ticked by default per Access tier (§3). */
|
|
62
|
+
export const DEFAULT_TOOLS = Object.freeze({
|
|
63
|
+
restricted: Object.freeze(['read', 'view_image', 'pdf']),
|
|
64
|
+
trusted: Object.freeze(['read', 'write', 'edit', 'apply_patch', 'view_image', 'pdf', 'web_search', 'web_fetch']),
|
|
65
|
+
full: Object.freeze(['memory_search', 'memory_get', 'view_image', 'pdf', 'web_search', 'web_fetch']),
|
|
66
|
+
});
|
|
67
|
+
export const DEFAULT_COMMANDS = Object.freeze({ restricted: 'basic', trusted: 'ask', full: 'ask' });
|
|
68
|
+
|
|
69
|
+
/** A new contact's settings (first-time accept: Trusted, Bounded, My notes with the default picks). */
|
|
70
|
+
export function defaultContact(access = 'trusted') {
|
|
71
|
+
return {
|
|
72
|
+
access, autonomy: 'bounded', knowledge: 'notes', notes: null, repos: [], agents: null,
|
|
73
|
+
tools: [...DEFAULT_TOOLS[access]], commands: DEFAULT_COMMANDS[access], basicList: null,
|
|
74
|
+
skills: [...DEFAULT_SKILLS], mcp: {}, mcpToolsDeny: {}, private: '', alwaysFine: '', openFolder: null,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* The tools a contact may actually get: ticked ∩ tickable, with the tier's hard limits. Full agent never writes
|
|
80
|
+
* (memory read-only, D7) and reads files only when one folder is opened (§12: secrets/ lives in the workspace).
|
|
81
|
+
*/
|
|
82
|
+
export function effectiveTools(c) {
|
|
83
|
+
let t = (Array.isArray(c.tools) ? c.tools : []).filter(x => TICKABLE.has(x));
|
|
84
|
+
if (c.access === 'full') {
|
|
85
|
+
// Reading is "Open one folder" itself, not a tick (the session root keeps it to that folder).
|
|
86
|
+
t = t.filter(x => !WRITE_TOOLS.includes(x) && x !== 'read');
|
|
87
|
+
if (c.openFolder) t.push('read');
|
|
88
|
+
} else {
|
|
89
|
+
t = t.filter(x => !['memory_search', 'memory_get', 'wiki_search'].includes(x)); // copies have no memory of the owner's
|
|
90
|
+
}
|
|
91
|
+
return [...new Set(t)].sort();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Copy exec settings per Commands tier (§4). `reviewerModel` only for Auto-review. */
|
|
95
|
+
export function execConfig(commands, reviewerModel = null) {
|
|
96
|
+
const mode = { off: 'deny', basic: 'allowlist', ask: 'ask', auto: 'auto' }[commands] || 'deny';
|
|
97
|
+
return {
|
|
98
|
+
mode, strictInlineEval: true, safeBins: ['head', 'tail', 'wc', 'cut', 'uniq', 'tr'],
|
|
99
|
+
...(mode === 'auto' && reviewerModel ? { reviewer: { model: reviewerModel } } : {}),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* The session's permission mode per Commands tier. Basic only and Off run with none (null): a session mode overrides
|
|
105
|
+
* the copy's exec policy, and a `guarded` session would turn allowlist misses back into approval cards (spike run 1).
|
|
106
|
+
* "Open one folder" needs a mode for its session root: refused for Off/Basic (card) and kept at guarded here.
|
|
107
|
+
*/
|
|
108
|
+
export function sessionMode(c) {
|
|
109
|
+
if (c.commands === 'ask') return 'guarded';
|
|
110
|
+
if (c.commands === 'auto') return 'workspace';
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The copy's `tools` config: an allowlist on the minimal profile, everything else denied on top. */
|
|
115
|
+
export function copyTools(c, { reviewerModel = null, autoApproveChanges = true } = {}) {
|
|
116
|
+
const allowed = effectiveTools(c);
|
|
117
|
+
const execOn = c.commands !== 'off';
|
|
118
|
+
const mcpOn = Object.values(c.mcp || {}).some(Boolean);
|
|
119
|
+
const alsoAllow = [...allowed, ...(execOn ? ['exec', 'process'] : []), ...(mcpOn ? ['bundle-mcp'] : [])];
|
|
120
|
+
const lifted = new Set(alsoAllow);
|
|
121
|
+
const deny = new Set();
|
|
122
|
+
for (const d of [...GUEST_TOOLS_DENY, ...ALWAYS_OFF]) {
|
|
123
|
+
const members = GROUP_MEMBERS[d];
|
|
124
|
+
if (members && members.some(m => lifted.has(m))) { for (const m of members) if (!lifted.has(m)) deny.add(m); continue; }
|
|
125
|
+
if (d === 'group:plugins' && (mcpOn || lifted.has('memory_search') || lifted.has('memory_get'))) continue; // MCP, memory-core
|
|
126
|
+
if (!lifted.has(d)) deny.add(d);
|
|
127
|
+
}
|
|
128
|
+
for (const g of TOOL_GROUPS) for (const t of g.tools) if (!lifted.has(t)) deny.add(t);
|
|
129
|
+
if (!execOn) { deny.add('exec'); deny.add('process'); deny.add('group:runtime'); }
|
|
130
|
+
for (const t of ALWAYS_OFF) deny.add(t);
|
|
131
|
+
return {
|
|
132
|
+
profile: 'minimal', alsoAllow: alsoAllow.sort(), deny: [...deny].sort(),
|
|
133
|
+
fs: { workspaceOnly: true },
|
|
134
|
+
exec: execConfig(c.commands, reviewerModel),
|
|
135
|
+
...(autoApproveChanges ? { openclaw: { autoApproveChanges: false } } : {}),
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Whether a copy's configured tools still hold the policy written for it (else its turns are refused). */
|
|
140
|
+
export function copyToolsHold(tools, want) {
|
|
141
|
+
if (!tools || tools.profile !== want.profile || tools.allow) return false;
|
|
142
|
+
if (tools.fs?.workspaceOnly !== true) return false;
|
|
143
|
+
const also = new Set(Array.isArray(tools.alsoAllow) ? tools.alsoAllow : []);
|
|
144
|
+
const deny = new Set(Array.isArray(tools.deny) ? tools.deny : []);
|
|
145
|
+
if ([...also].some(t => !want.alsoAllow.includes(t))) return false;
|
|
146
|
+
if (want.deny.some(t => !deny.has(t))) return false;
|
|
147
|
+
return (tools.exec?.mode || null) === want.exec.mode;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// ── Basic commands (§4 "Default basic list") ─────────────────────────
|
|
151
|
+
|
|
152
|
+
/** Default list: bare command + anchored argPattern; `args` is what the card shows. */
|
|
153
|
+
export const BASIC_DEFAULTS = Object.freeze([
|
|
154
|
+
{ pattern: 'openclaw', argPattern: '^(--version|-V)$', args: '--version' },
|
|
155
|
+
{ pattern: 'uname', argPattern: '^(-[asrmnvpio]+)?$', args: '-a, -r, -m …' },
|
|
156
|
+
{ pattern: 'uptime', argPattern: '^(-p|-s)?$', args: '(none), -p' },
|
|
157
|
+
{ pattern: 'df', argPattern: '^(-h|-hT|-h -T)?$', args: '-h' },
|
|
158
|
+
{ pattern: 'free', argPattern: '^(-h|-m|-g)?$', args: '-h' },
|
|
159
|
+
{ pattern: 'nproc', argPattern: '^$', args: '(none)' },
|
|
160
|
+
{ pattern: 'lscpu', argPattern: '^$', args: '(none)' },
|
|
161
|
+
{ pattern: 'date', argPattern: '^$', args: '(none)' },
|
|
162
|
+
{ pattern: 'cat', argPattern: '^/etc/os-release$', args: '/etc/os-release only' },
|
|
163
|
+
{ pattern: 'node', argPattern: '^(--version|-v|-V)$', args: '--version' },
|
|
164
|
+
{ pattern: 'npm', argPattern: '^(--version|-v|-V)$', args: '--version' },
|
|
165
|
+
{ pattern: 'python3', argPattern: '^(--version|-v|-V)$', args: '--version' },
|
|
166
|
+
]);
|
|
167
|
+
const GIT_ARGS = '(log( --oneline)?( -n ?[0-9]{1,3}| -[0-9]{1,3})?|status( -s| --short)?|describe --tags|rev-parse --short HEAD|branch --show-current)';
|
|
168
|
+
const reEscape = s => String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
169
|
+
|
|
170
|
+
/** One git entry per repo picked under Knowledge (D4): read-only subcommands, in that repo only. */
|
|
171
|
+
export function gitEntries(repos) {
|
|
172
|
+
return (Array.isArray(repos) ? repos : []).filter(r => typeof r === 'string' && r.startsWith('/'))
|
|
173
|
+
.map(r => ({ pattern: 'git', argPattern: `^-C ${reEscape(r.replace(/\/+$/, ''))} ${GIT_ARGS}$`, args: `-C ${r} log, status, describe…`, repo: r }));
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// Commands that read anything, run code or reach out: only with an anchored argPattern.
|
|
177
|
+
const RISKY = /^(cat|less|more|head|tail|env|printenv|bash|sh|zsh|dash|fish|python[0-9.]*|node|deno|bun|perl|ruby|php|curl|wget|ssh|scp|nc|ncat|openclaw|sudo|find|xargs|docker|journalctl|systemctl)$/;
|
|
178
|
+
const anchored = p => typeof p === 'string' && p.startsWith('^') && p.endsWith('$') && !/(^|[^\\])\.\*/.test(p);
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Check one entry of an edited basic list: { ok, error?, warning? }. A bare command name only (no paths or globs), an
|
|
182
|
+
* argPattern that compiles, and for anything risky an anchored one with no `.*`.
|
|
183
|
+
*/
|
|
184
|
+
export function validateBasicEntry({ pattern, argPattern } = {}) {
|
|
185
|
+
const cmd = String(pattern || '').trim();
|
|
186
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(cmd)) return { ok: false, error: 'Use a bare command name, like "uptime" (no paths or wildcards)' };
|
|
187
|
+
if (argPattern != null && argPattern !== '') {
|
|
188
|
+
try { new RegExp(argPattern); } catch { return { ok: false, error: 'The arguments pattern isn\'t a valid regular expression' }; }
|
|
189
|
+
}
|
|
190
|
+
if (RISKY.test(cmd) && !anchored(argPattern)) {
|
|
191
|
+
return { ok: false, error: `"${cmd}" can read files, run code or reach out: give it an exact arguments pattern (^…$, no .*)` };
|
|
192
|
+
}
|
|
193
|
+
if (!argPattern) return { ok: true, warning: `Any arguments to "${cmd}" will run without asking` };
|
|
194
|
+
if (/\.openclaw/.test(argPattern)) return { ok: true, warning: 'This pattern mentions .openclaw, where your gateway config and secrets live' };
|
|
195
|
+
return { ok: true };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** The list the copy's approvals entry allows: the edited or default list, plus the git entries. */
|
|
199
|
+
export function basicList(c) {
|
|
200
|
+
const base = Array.isArray(c.basicList) ? c.basicList.filter(e => validateBasicEntry(e).ok) : BASIC_DEFAULTS;
|
|
201
|
+
return [...base.map(({ pattern, argPattern, args }) => ({ pattern, argPattern: argPattern || undefined, args })), ...gitEntries(c.repos)];
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** The copy's entry in the exec approvals document (`agents.<copy>`). */
|
|
205
|
+
export function approvalsEntry(c) {
|
|
206
|
+
const ask = c.commands === 'ask' || c.commands === 'auto' ? 'on-miss' : 'off';
|
|
207
|
+
return {
|
|
208
|
+
security: c.commands === 'off' ? 'deny' : 'allowlist', ask, askFallback: 'deny', autoAllowSkills: false,
|
|
209
|
+
allowlist: c.commands === 'off' ? [] : basicList(c).map(({ pattern, argPattern }) => (argPattern ? { pattern, argPattern } : { pattern })),
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// ── Session overrides ──────────────────────────────────────────────
|
|
214
|
+
|
|
215
|
+
/** `toolOverrides` for the person's sessions: every known skill/MCP server set explicitly, so new ones start off. */
|
|
216
|
+
export function toolOverrides(c, { skillNames = [], mcpServers = [] } = {}) {
|
|
217
|
+
const on = new Set(Array.isArray(c.skills) ? c.skills : []);
|
|
218
|
+
const skills = Object.fromEntries([...new Set(skillNames)].sort().map(n => [n, on.has(n)]));
|
|
219
|
+
const mcp = Object.fromEntries([...new Set(mcpServers)].sort().map(n => [n, !!c.mcp?.[n]]));
|
|
220
|
+
const deny = Object.fromEntries(Object.entries(c.mcpToolsDeny || {}).filter(([s, l]) => mcp[s] && Array.isArray(l) && l.length).map(([s, l]) => [s, [...l].sort()]));
|
|
221
|
+
return {
|
|
222
|
+
webSearch: effectiveTools(c).includes('web_search'),
|
|
223
|
+
...(Object.keys(skills).length ? { skills } : {}),
|
|
224
|
+
...(Object.keys(mcp).length ? { mcpServers: mcp } : {}),
|
|
225
|
+
...(Object.keys(deny).length ? { mcpToolsDeny: deny } : {}),
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Private / Always fine, for the agent's instructions while that person is in the conversation (instruction only). */
|
|
230
|
+
export function topicsNote(c, name) {
|
|
231
|
+
const clean = s => String(s || '').replace(/[\u0000-\u0008\u000b-\u001f]/g, ' ').trim().slice(0, 1000);
|
|
232
|
+
const priv = clean(c.private), fine = clean(c.alwaysFine);
|
|
233
|
+
const lines = [];
|
|
234
|
+
if (priv) lines.push(`Your owner keeps these topics private from ${name} and ${name}'s agents: don't discuss them, and say so briefly if asked: ${priv}`);
|
|
235
|
+
if (fine) lines.push(`Your owner is happy for you to share these with ${name} freely: ${fine}`);
|
|
236
|
+
return lines.map(l => `(${l})`).join('\n');
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** A stable hash of everything written to a copy (config + approvals), to tell when it must be rewritten. */
|
|
240
|
+
export function policyHash(obj) {
|
|
241
|
+
const canon = v => (Array.isArray(v) ? v.map(canon) : v && typeof v === 'object' ? Object.fromEntries(Object.keys(v).sort().map(k => [k, canon(v[k])])) : v);
|
|
242
|
+
return crypto.createHash('sha256').update(JSON.stringify(canon(obj))).digest('hex').slice(0, 16);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** Copy ids: `<agent>-guest-<slug>` / `<agent>-full-<slug>` (D3). The slug is the email's local part plus a short hash. */
|
|
246
|
+
export function copySlug(personKey) {
|
|
247
|
+
const local = String(personKey || '').split('@')[0].toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 20) || 'contact';
|
|
248
|
+
return `${local}-${crypto.createHash('sha256').update(String(personKey)).digest('hex').slice(0, 4)}`;
|
|
249
|
+
}
|
|
250
|
+
export const copyKind = c => (c.access === 'full' ? 'full' : 'guest');
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { test } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { defaultContact, copyTools, copyToolsHold, effectiveTools, sessionMode, approvalsEntry, validateBasicEntry, basicList, gitEntries, toolOverrides, topicsNote, ALWAYS_OFF, copySlug } from './contact-policy.js';
|
|
4
|
+
|
|
5
|
+
test('tier defaults: Restricted = Basic only, Trusted = Basic + ask me, Full = Basic + ask me; autonomy Bounded; default skills', () => {
|
|
6
|
+
assert.deepEqual([defaultContact('restricted').commands, defaultContact('trusted').commands, defaultContact('full').commands], ['basic', 'ask', 'ask']);
|
|
7
|
+
assert.equal(defaultContact().access, 'trusted');
|
|
8
|
+
assert.equal(defaultContact().autonomy, 'bounded');
|
|
9
|
+
assert.equal(defaultContact().knowledge, 'notes');
|
|
10
|
+
assert.deepEqual(defaultContact().skills, ['weather', 'diagram-maker', 'visualize']);
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
test('a copy is an allowlist on the minimal profile: ticked tools only, the always-off list and the owner\'s accounts denied', () => {
|
|
14
|
+
for (const access of ['restricted', 'trusted', 'full']) {
|
|
15
|
+
const t = copyTools(defaultContact(access));
|
|
16
|
+
assert.equal(t.profile, 'minimal');
|
|
17
|
+
assert.equal(t.fs.workspaceOnly, true);
|
|
18
|
+
assert.deepEqual(t.openclaw, { autoApproveChanges: false });
|
|
19
|
+
assert.equal(t.exec.strictInlineEval, true);
|
|
20
|
+
for (const x of ALWAYS_OFF) { assert.ok(t.deny.includes(x), `${access}: ${x} denied`); assert.ok(!t.alsoAllow.includes(x)); }
|
|
21
|
+
for (const x of ['message', 'browser', 'nodes', 'computer', 'talk_voice', 'cron', 'sessions_list']) assert.ok(t.deny.includes(x), `${access}: ${x}`);
|
|
22
|
+
}
|
|
23
|
+
const r = copyTools(defaultContact('restricted'));
|
|
24
|
+
assert.deepEqual(r.alsoAllow, ['exec', 'pdf', 'process', 'read', 'view_image']);
|
|
25
|
+
assert.ok(r.deny.includes('write') && r.deny.includes('web_search'));
|
|
26
|
+
assert.equal(r.exec.mode, 'allowlist');
|
|
27
|
+
const tr = copyTools(defaultContact('trusted'));
|
|
28
|
+
assert.ok(['write', 'edit', 'apply_patch', 'web_search', 'web_fetch'].every(x => tr.alsoAllow.includes(x)));
|
|
29
|
+
assert.ok(!tr.deny.includes('group:fs') && !tr.deny.includes('group:web'), 'a ticked tool lifts its group deny');
|
|
30
|
+
assert.equal(tr.exec.mode, 'ask');
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test('Full agent: memory read-only (no write tools ever), no file tools unless one folder is opened', () => {
|
|
34
|
+
const c = { ...defaultContact('full'), tools: ['read', 'write', 'memory_search', 'memory_get'] };
|
|
35
|
+
assert.deepEqual(effectiveTools(c), ['memory_get', 'memory_search']);
|
|
36
|
+
const t = copyTools(c);
|
|
37
|
+
for (const x of ['read', 'write', 'edit', 'apply_patch']) assert.ok(t.deny.includes(x), x);
|
|
38
|
+
assert.ok(!t.deny.includes('group:plugins'), 'memory-core tools are plugin tools');
|
|
39
|
+
assert.deepEqual(effectiveTools({ ...c, openFolder: '/w/plans' }), ['memory_get', 'memory_search', 'read']);
|
|
40
|
+
assert.deepEqual(effectiveTools({ ...c, tools: ['memory_get'], openFolder: '/w/plans' }), ['memory_get', 'read'], 'opening a folder is what allows read');
|
|
41
|
+
// Copies (Restricted/Trusted) never get the owner's memory tools, whatever is ticked.
|
|
42
|
+
assert.deepEqual(effectiveTools({ ...defaultContact('trusted'), tools: ['memory_search', 'read'] }), ['read']);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test('Commands tiers: session mode and copy exec mode (Basic only runs with no session mode, spike run 2)', () => {
|
|
46
|
+
const at = commands => ({ ...defaultContact('trusted'), commands });
|
|
47
|
+
assert.deepEqual(['off', 'basic', 'ask', 'auto'].map(c => sessionMode(at(c))), [null, null, 'guarded', 'workspace']);
|
|
48
|
+
assert.deepEqual(['off', 'basic', 'ask', 'auto'].map(c => copyTools(at(c)).exec.mode), ['deny', 'allowlist', 'ask', 'auto']);
|
|
49
|
+
const off = copyTools(at('off'));
|
|
50
|
+
assert.ok(off.deny.includes('exec') && !off.alsoAllow.includes('exec'));
|
|
51
|
+
assert.deepEqual(copyTools(at('auto'), { reviewerModel: 'anthropic/claude-haiku-4-5' }).exec.reviewer, { model: 'anthropic/claude-haiku-4-5' });
|
|
52
|
+
assert.equal(copyTools(at('ask'), { reviewerModel: 'x' }).exec.reviewer, undefined);
|
|
53
|
+
assert.deepEqual(approvalsEntry(at('basic')).ask, 'off');
|
|
54
|
+
assert.deepEqual(approvalsEntry(at('ask')).ask, 'on-miss');
|
|
55
|
+
assert.equal(approvalsEntry(at('off')).security, 'deny');
|
|
56
|
+
assert.equal(approvalsEntry(at('basic')).autoAllowSkills, false);
|
|
57
|
+
assert.equal(approvalsEntry(at('basic')).askFallback, 'deny');
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
test('basic list: anchored patterns, git per picked repo, no openclaw status', () => {
|
|
61
|
+
const e = approvalsEntry({ ...defaultContact('restricted'), repos: ['/home/k/repos/clawchats'] });
|
|
62
|
+
const oc = e.allowlist.find(x => x.pattern === 'openclaw');
|
|
63
|
+
assert.ok(new RegExp(oc.argPattern).test('--version'));
|
|
64
|
+
assert.ok(!new RegExp(oc.argPattern).test('status'));
|
|
65
|
+
const cat = new RegExp(e.allowlist.find(x => x.pattern === 'cat').argPattern);
|
|
66
|
+
assert.ok(cat.test('/etc/os-release') && !cat.test('/home/k/.openclaw/openclaw.json'));
|
|
67
|
+
const git = new RegExp(e.allowlist.find(x => x.pattern === 'git').argPattern);
|
|
68
|
+
assert.ok(git.test('-C /home/k/repos/clawchats log --oneline -n 5'));
|
|
69
|
+
assert.ok(git.test('-C /home/k/repos/clawchats status -s'));
|
|
70
|
+
assert.ok(!git.test('-C /home/k/repos/other log'));
|
|
71
|
+
assert.ok(!git.test('-C /home/k/repos/clawchats show HEAD:.env'));
|
|
72
|
+
assert.ok(e.allowlist.every(x => !x.argPattern || (x.argPattern.startsWith('^') && x.argPattern.endsWith('$'))));
|
|
73
|
+
assert.equal(gitEntries(['relative/path']).length, 0);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test('Edit list refuses risky commands without an exact pattern, and warns on .openclaw', () => {
|
|
77
|
+
for (const cmd of ['cat', 'env', 'printenv', 'bash', 'sh', 'python3', 'node', 'curl', 'wget', 'ssh', 'openclaw']) {
|
|
78
|
+
assert.equal(validateBasicEntry({ pattern: cmd }).ok, false, cmd);
|
|
79
|
+
assert.equal(validateBasicEntry({ pattern: cmd, argPattern: '^.*$' }).ok, false, `${cmd} with .*`);
|
|
80
|
+
}
|
|
81
|
+
assert.equal(validateBasicEntry({ pattern: 'cat', argPattern: '^/etc/hostname$' }).ok, true);
|
|
82
|
+
assert.equal(validateBasicEntry({ pattern: '/bin/ls' }).ok, false, 'no paths');
|
|
83
|
+
assert.equal(validateBasicEntry({ pattern: 'ls*' }).ok, false, 'no globs');
|
|
84
|
+
assert.equal(validateBasicEntry({ pattern: 'hostname' }).ok, true);
|
|
85
|
+
assert.match(validateBasicEntry({ pattern: 'hostname' }).warning, /Any arguments/);
|
|
86
|
+
assert.match(validateBasicEntry({ pattern: 'cat', argPattern: '^/home/k/\\.openclaw/x$' }).warning, /\.openclaw/);
|
|
87
|
+
assert.equal(validateBasicEntry({ pattern: 'uptime', argPattern: '(' }).ok, false);
|
|
88
|
+
// A stored list keeps only valid entries.
|
|
89
|
+
assert.deepEqual(basicList({ basicList: [{ pattern: 'env' }, { pattern: 'uptime', argPattern: '^$' }], repos: [] }).map(x => x.pattern), ['uptime']);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
test('session overrides: every known skill and MCP server set explicitly (new ones start off); web search follows the tick', () => {
|
|
93
|
+
const c = { ...defaultContact('trusted'), mcp: { 'chrome-devtools': true }, mcpToolsDeny: { 'chrome-devtools': ['evaluate_script'], gmail: ['x'] } };
|
|
94
|
+
assert.deepEqual(toolOverrides(c, { skillNames: ['weather', 'github'], mcpServers: ['gmail', 'chrome-devtools'] }), {
|
|
95
|
+
webSearch: true, skills: { github: false, weather: true },
|
|
96
|
+
mcpServers: { 'chrome-devtools': true, gmail: false }, mcpToolsDeny: { 'chrome-devtools': ['evaluate_script'] },
|
|
97
|
+
});
|
|
98
|
+
assert.deepEqual(toolOverrides(defaultContact('restricted')), { webSearch: false });
|
|
99
|
+
assert.ok(copyTools(c).alsoAllow.includes('bundle-mcp'), 'an MCP server on needs its plugin tools allowed');
|
|
100
|
+
assert.ok(!copyTools(defaultContact('trusted')).alsoAllow.includes('bundle-mcp'));
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
test('Private / Always fine become one instruction line; nothing when both are empty', () => {
|
|
104
|
+
assert.equal(topicsNote(defaultContact(), 'Kamil'), '');
|
|
105
|
+
const n = topicsNote({ private: 'my health', alwaysFine: 'OpenClaw' }, 'Kamil');
|
|
106
|
+
assert.match(n, /private from Kamil[^]*my health/);
|
|
107
|
+
assert.match(n, /share these with Kamil freely: OpenClaw/);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
test('a copy holds its policy only while nothing was widened; ids are per person', () => {
|
|
111
|
+
const want = copyTools(defaultContact('trusted'));
|
|
112
|
+
assert.equal(copyToolsHold(JSON.parse(JSON.stringify(want)), want), true);
|
|
113
|
+
assert.equal(copyToolsHold({ ...want, alsoAllow: [...want.alsoAllow, 'message'] }, want), false);
|
|
114
|
+
assert.equal(copyToolsHold({ ...want, deny: want.deny.filter(x => x !== 'gateway') }, want), false);
|
|
115
|
+
assert.equal(copyToolsHold({ ...want, exec: { ...want.exec, mode: 'full' } }, want), false);
|
|
116
|
+
assert.equal(copyToolsHold({ ...want, fs: {} }, want), false);
|
|
117
|
+
assert.notEqual(copySlug('kamil@a.dev'), copySlug('kamil@b.dev'));
|
|
118
|
+
assert.match(copySlug('Kamil.G@x.dev'), /^kamil-g-[0-9a-f]{4}$/);
|
|
119
|
+
});
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// Contacts: the per-person settings of the contact card (owner side), the agent copies made for each person, and one
|
|
2
|
+
// usage counter per person (D10). Keyed by the person's lowercased email: one person can have several gateways (D8),
|
|
3
|
+
// and every share with any of them uses the same settings. Local only: none of it goes into the signed grant except
|
|
4
|
+
// access and autonomy.
|
|
5
|
+
|
|
6
|
+
import { ACCESS, AUTONOMY, COMMANDS, KNOWLEDGE, defaultContact, DEFAULT_TOOLS, DEFAULT_COMMANDS, validateBasicEntry } from './contact-policy.js';
|
|
7
|
+
|
|
8
|
+
const JSON_FIELDS = ['notes', 'repos', 'agents', 'tools', 'basicList', 'skills', 'mcp', 'mcpToolsDeny'];
|
|
9
|
+
const COLUMNS = { basicList: 'basic_list', alwaysFine: 'always_fine', openFolder: 'open_folder', mcpToolsDeny: 'mcp_tools_deny', private: 'private_text' };
|
|
10
|
+
const col = f => COLUMNS[f] || f;
|
|
11
|
+
export const personKeyOf = email => String(email || '').trim().toLowerCase();
|
|
12
|
+
|
|
13
|
+
const today = (now = Date.now()) => new Date(now).toISOString().slice(0, 10);
|
|
14
|
+
const thisHour = (now = Date.now()) => new Date(now).toISOString().slice(0, 13);
|
|
15
|
+
|
|
16
|
+
export class ContactBook {
|
|
17
|
+
constructor(getDb) { this.getDb = getDb; this._ready = false; }
|
|
18
|
+
|
|
19
|
+
db() {
|
|
20
|
+
const g = this.getDb();
|
|
21
|
+
if (!this._ready) {
|
|
22
|
+
g.exec(`CREATE TABLE IF NOT EXISTS peer_contact (person_key TEXT PRIMARY KEY, name TEXT, access TEXT NOT NULL, autonomy TEXT NOT NULL,
|
|
23
|
+
knowledge TEXT NOT NULL, notes TEXT, repos TEXT, agents TEXT, tools TEXT, commands TEXT NOT NULL, basic_list TEXT, skills TEXT, mcp TEXT,
|
|
24
|
+
mcp_tools_deny TEXT, private_text TEXT, always_fine TEXT, open_folder TEXT, full_confirmed_at INTEGER, migrated INTEGER NOT NULL DEFAULT 0,
|
|
25
|
+
notes_sync TEXT, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL)`);
|
|
26
|
+
g.exec(`CREATE TABLE IF NOT EXISTS peer_copy (person_key TEXT NOT NULL, agent_id TEXT NOT NULL, kind TEXT NOT NULL, copy_id TEXT NOT NULL,
|
|
27
|
+
policy_hash TEXT, created_at INTEGER NOT NULL, last_used_at INTEGER, PRIMARY KEY (person_key, agent_id, kind))`);
|
|
28
|
+
g.exec('CREATE TABLE IF NOT EXISTS peer_person_usage (person_key TEXT NOT NULL, win TEXT NOT NULL, n INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (person_key, win))');
|
|
29
|
+
this._ready = true;
|
|
30
|
+
}
|
|
31
|
+
return g;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
_row(r) {
|
|
35
|
+
if (!r) return null;
|
|
36
|
+
const c = { personKey: r.person_key, name: r.name, access: r.access, autonomy: r.autonomy, knowledge: r.knowledge, commands: r.commands,
|
|
37
|
+
private: r.private_text || '', alwaysFine: r.always_fine || '', openFolder: r.open_folder || null, fullConfirmedAt: r.full_confirmed_at || null,
|
|
38
|
+
migrated: !!r.migrated, notesSync: r.notes_sync ? JSON.parse(r.notes_sync) : null, updatedAt: r.updated_at };
|
|
39
|
+
for (const f of JSON_FIELDS) { try { c[f] = r[col(f)] == null ? null : JSON.parse(r[col(f)]); } catch { c[f] = null; } }
|
|
40
|
+
c.repos ||= []; c.tools ||= []; c.skills ||= []; c.mcp ||= {}; c.mcpToolsDeny ||= {};
|
|
41
|
+
return c;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
get(personKey) { return this._row(this.db().prepare('SELECT * FROM peer_contact WHERE person_key = ?').get(personKeyOf(personKey))); }
|
|
45
|
+
all() { return this.db().prepare('SELECT * FROM peer_contact').all().map(r => this._row(r)); }
|
|
46
|
+
|
|
47
|
+
/** Create a contact (first-time accept or migration). Returns it; an existing one is returned unchanged. */
|
|
48
|
+
create(personKey, fields = {}) {
|
|
49
|
+
const key = personKeyOf(personKey);
|
|
50
|
+
if (!key) throw new Error('A contact needs an email');
|
|
51
|
+
const have = this.get(key);
|
|
52
|
+
if (have) return have;
|
|
53
|
+
const c = { ...defaultContact(fields.access || 'trusted'), ...fields };
|
|
54
|
+
const now = Date.now();
|
|
55
|
+
this.db().prepare(`INSERT INTO peer_contact (person_key, name, access, autonomy, knowledge, notes, repos, agents, tools, commands, basic_list, skills, mcp,
|
|
56
|
+
mcp_tools_deny, private_text, always_fine, open_folder, full_confirmed_at, migrated, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
57
|
+
.run(key, c.name || null, c.access, c.autonomy, c.knowledge, js(c.notes), js(c.repos), js(c.agents), js(c.tools), c.commands, js(c.basicList),
|
|
58
|
+
js(c.skills), js(c.mcp), js(c.mcpToolsDeny), c.private || '', c.alwaysFine || '', c.openFolder || null, c.fullConfirmedAt || null, c.migrated ? 1 : 0, now, now);
|
|
59
|
+
return this.get(key);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Change one setting (the card saves per control). Validates the value; changing Access resets Tools and Commands to
|
|
64
|
+
* that tier's defaults (they're presets of the tier) and needs `confirmFull` the first time it goes to Full agent.
|
|
65
|
+
*/
|
|
66
|
+
set(personKey, field, value, { confirmFull = false } = {}) {
|
|
67
|
+
const c = this.get(personKey);
|
|
68
|
+
if (!c) throw new Error('Not a contact');
|
|
69
|
+
const patch = {};
|
|
70
|
+
switch (field) {
|
|
71
|
+
case 'access':
|
|
72
|
+
if (!ACCESS.includes(value)) throw new Error('Unknown access level');
|
|
73
|
+
if (value === 'full' && !c.fullConfirmedAt && !confirmFull) throw Object.assign(new Error('Full agent needs confirming'), { code: 'confirm_full' });
|
|
74
|
+
Object.assign(patch, { access: value, tools: [...DEFAULT_TOOLS[value]], commands: DEFAULT_COMMANDS[value], openFolder: null });
|
|
75
|
+
if (value === 'full' && !c.fullConfirmedAt) patch.fullConfirmedAt = Date.now();
|
|
76
|
+
break;
|
|
77
|
+
case 'autonomy': if (!AUTONOMY[value]) throw new Error('Unknown autonomy'); patch.autonomy = value; break;
|
|
78
|
+
case 'knowledge': if (!KNOWLEDGE.includes(value)) throw new Error('Unknown knowledge setting'); patch.knowledge = value; break;
|
|
79
|
+
case 'commands':
|
|
80
|
+
if (!COMMANDS.includes(value)) throw new Error('Unknown commands setting');
|
|
81
|
+
if (c.openFolder && (value === 'off' || value === 'basic')) throw new Error('"Open one folder" needs Commands set to "ask me" or "auto-review"');
|
|
82
|
+
patch.commands = value; break;
|
|
83
|
+
case 'tools': patch.tools = strings(value, 40); break;
|
|
84
|
+
case 'skills': patch.skills = strings(value, 500); break;
|
|
85
|
+
case 'agents': patch.agents = strings(value, 50); break;
|
|
86
|
+
case 'notes': patch.notes = strings(value, 200); break;
|
|
87
|
+
case 'repos': patch.repos = strings(value, 20).filter(r => r.startsWith('/')); break;
|
|
88
|
+
case 'mcp': patch.mcp = boolMap(value); break;
|
|
89
|
+
case 'mcpToolsDeny': patch.mcpToolsDeny = Object.fromEntries(Object.entries(value || {}).map(([k, v]) => [String(k), strings(v, 200)])); break;
|
|
90
|
+
case 'basicList': {
|
|
91
|
+
if (value === null) { patch.basicList = null; break; }
|
|
92
|
+
if (!Array.isArray(value)) throw new Error('basicList must be a list');
|
|
93
|
+
const list = value.slice(0, 60).map(e => ({ pattern: String(e?.pattern || '').trim(), argPattern: e?.argPattern ? String(e.argPattern) : '', args: e?.args ? String(e.args).slice(0, 80) : '' }));
|
|
94
|
+
for (const e of list) { const v = validateBasicEntry(e); if (!v.ok) throw Object.assign(new Error(v.error), { code: 'bad_entry', entry: e.pattern }); }
|
|
95
|
+
patch.basicList = list; break;
|
|
96
|
+
}
|
|
97
|
+
case 'private': patch.private = String(value || '').slice(0, 2000); break;
|
|
98
|
+
case 'alwaysFine': patch.alwaysFine = String(value || '').slice(0, 2000); break;
|
|
99
|
+
case 'openFolder':
|
|
100
|
+
if (value && c.access !== 'full') throw new Error('"Open one folder" is for Full agent');
|
|
101
|
+
if (value && (c.commands === 'off' || c.commands === 'basic')) throw new Error('"Open one folder" needs Commands set to "ask me" or "auto-review"');
|
|
102
|
+
patch.openFolder = value ? String(value) : null; break;
|
|
103
|
+
case 'name': patch.name = String(value || '').slice(0, 80) || null; break;
|
|
104
|
+
case 'migrated': patch.migrated = value ? 1 : 0; break;
|
|
105
|
+
default: throw new Error(`Unknown setting: ${field}`);
|
|
106
|
+
}
|
|
107
|
+
this._write(c.personKey, patch);
|
|
108
|
+
return this.get(c.personKey);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
_write(personKey, patch) {
|
|
112
|
+
const sets = [], vals = [];
|
|
113
|
+
for (const [f, v] of Object.entries(patch)) {
|
|
114
|
+
const name = f === 'fullConfirmedAt' ? 'full_confirmed_at' : col(f);
|
|
115
|
+
sets.push(`${name} = ?`);
|
|
116
|
+
vals.push(JSON_FIELDS.includes(f) ? js(v) : v);
|
|
117
|
+
}
|
|
118
|
+
sets.push('updated_at = ?'); vals.push(Date.now());
|
|
119
|
+
this.db().prepare(`UPDATE peer_contact SET ${sets.join(', ')} WHERE person_key = ?`).run(...vals, personKeyOf(personKey));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
setNotesSync(personKey, summary) { this.db().prepare('UPDATE peer_contact SET notes_sync = ? WHERE person_key = ?').run(js(summary), personKeyOf(personKey)); }
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Everything kept for a person goes (Disconnect). Their copies are retired by the caller first and stay listed as
|
|
126
|
+
* kind 'retired-guest' / 'retired-full' (hidden from agent pickers, never served: there's no grant and no contact).
|
|
127
|
+
*/
|
|
128
|
+
forget(personKey) {
|
|
129
|
+
const key = personKeyOf(personKey);
|
|
130
|
+
const db = this.db();
|
|
131
|
+
db.prepare('DELETE FROM peer_contact WHERE person_key = ?').run(key);
|
|
132
|
+
db.prepare("UPDATE OR REPLACE peer_copy SET kind = 'retired-' || kind, policy_hash = NULL WHERE person_key = ? AND kind NOT LIKE 'retired-%'").run(key);
|
|
133
|
+
db.prepare('DELETE FROM peer_person_usage WHERE person_key = ?').run(key);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// ── Copies ──
|
|
137
|
+
copies(personKey = null) {
|
|
138
|
+
const rows = personKey ? this.db().prepare('SELECT * FROM peer_copy WHERE person_key = ?').all(personKeyOf(personKey)) : this.db().prepare('SELECT * FROM peer_copy').all();
|
|
139
|
+
return rows.map(r => ({ personKey: r.person_key, agentId: r.agent_id, kind: r.kind, copyId: r.copy_id, policyHash: r.policy_hash, lastUsedAt: r.last_used_at }));
|
|
140
|
+
}
|
|
141
|
+
copy(personKey, agentId, kind) { return this.copies(personKey).find(r => r.agentId === agentId && r.kind === kind) || null; }
|
|
142
|
+
copyIds() { return new Set(this.db().prepare('SELECT copy_id FROM peer_copy').all().map(r => r.copy_id)); }
|
|
143
|
+
putCopy(personKey, agentId, kind, copyId, policyHash) {
|
|
144
|
+
this.db().prepare(`INSERT INTO peer_copy (person_key, agent_id, kind, copy_id, policy_hash, created_at) VALUES (?, ?, ?, ?, ?, ?)
|
|
145
|
+
ON CONFLICT(person_key, agent_id, kind) DO UPDATE SET copy_id = excluded.copy_id, policy_hash = excluded.policy_hash`).run(personKeyOf(personKey), agentId, kind, copyId, policyHash, Date.now());
|
|
146
|
+
}
|
|
147
|
+
touchCopy(copyId) { this.db().prepare('UPDATE peer_copy SET last_used_at = ? WHERE copy_id = ?').run(Date.now(), copyId); }
|
|
148
|
+
dropCopy(copyId) { this.db().prepare('DELETE FROM peer_copy WHERE copy_id = ?').run(copyId); }
|
|
149
|
+
/** A copy no longer in use (its access tier changed, or Disconnect): kept, locked down, hidden. */
|
|
150
|
+
retireCopyRow(copyId) { this.db().prepare("UPDATE OR REPLACE peer_copy SET kind = 'retired-' || kind, policy_hash = NULL WHERE copy_id = ? AND kind NOT LIKE 'retired-%'").run(copyId); }
|
|
151
|
+
|
|
152
|
+
// ── One counter per person (D10) ──
|
|
153
|
+
usage(personKey, now = Date.now()) {
|
|
154
|
+
const g = this.db().prepare('SELECT win, n FROM peer_person_usage WHERE person_key = ? AND win IN (?, ?)').all(personKeyOf(personKey), `d:${today(now)}`, `h:${thisHour(now)}`);
|
|
155
|
+
return { day: g.find(r => r.win.startsWith('d:'))?.n || 0, hour: g.find(r => r.win.startsWith('h:'))?.n || 0 };
|
|
156
|
+
}
|
|
157
|
+
/** Over the tier's limit? Returns the reason, else null. */
|
|
158
|
+
overCap(personKey, autonomy, now = Date.now()) {
|
|
159
|
+
const t = AUTONOMY[autonomy] || AUTONOMY.bounded;
|
|
160
|
+
const u = this.usage(personKey, now);
|
|
161
|
+
if (u.day >= t.perDay) return `Daily limit reached (${t.perDay} replies)`;
|
|
162
|
+
if (t.perHour && u.hour >= t.perHour) return `Hourly limit reached (${t.perHour} replies an hour)`;
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
count(personKey, delta = 1, now = Date.now()) {
|
|
166
|
+
const st = this.db().prepare(`INSERT INTO peer_person_usage (person_key, win, n) VALUES (?, ?, MAX(0, ?)) ON CONFLICT(person_key, win) DO UPDATE SET n = MAX(0, n + ?)`);
|
|
167
|
+
for (const w of [`d:${today(now)}`, `h:${thisHour(now)}`]) st.run(personKeyOf(personKey), w, delta, delta);
|
|
168
|
+
// Old windows go: a day of hours is enough.
|
|
169
|
+
this.db().prepare("DELETE FROM peer_person_usage WHERE (win LIKE 'h:%' AND win < ?) OR (win LIKE 'd:%' AND win < ?)").run(`h:${thisHour(now - 86_400_000)}`, `d:${today(now - 7 * 86_400_000)}`);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const js = v => (v === undefined || v === null ? null : JSON.stringify(v));
|
|
174
|
+
const strings = (v, max) => (Array.isArray(v) ? [...new Set(v.filter(x => typeof x === 'string' && x).map(x => x.slice(0, 500)))].slice(0, max) : []);
|
|
175
|
+
const boolMap = v => Object.fromEntries(Object.entries(v && typeof v === 'object' ? v : {}).map(([k, b]) => [String(k).slice(0, 100), !!b]));
|