@clawchatsai/connector 0.2.7 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/server/approval-client.js +9 -1
- package/server/approval-client.test.js +16 -0
- package/server/gateway.js +17 -2
- package/server/index.js +38 -2
- package/server/peer/contact-copy.js +164 -0
- package/server/peer/contact-policy.js +250 -0
- package/server/peer/contact-policy.test.js +119 -0
- package/server/peer/contacts.js +175 -0
- package/server/peer/contacts.test.js +135 -0
- package/server/peer/link.js +7 -3
- package/server/peer/notes-sync.js +126 -0
- package/server/peer/sharing.js +522 -61
- package/server/peer/sharing.test.js +302 -41
- package/server/peer/version.js +36 -0
- package/server/store/team-store.js +6 -5
- package/server/team.js +55 -13
- package/server/team.test.js +46 -12
|
@@ -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]));
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { test } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { Database } from '../bootstrap/native.js';
|
|
7
|
+
import { ContactBook } from './contacts.js';
|
|
8
|
+
import { noteCandidates, checkRepoDoc, resolvePicks, syncNotes, removeNotes, picksSignature } from './notes-sync.js';
|
|
9
|
+
import { olderThan, peerOutdated, outdatedMessage, MIN_PEER_VERSION } from './version.js';
|
|
10
|
+
|
|
11
|
+
const book = () => { const db = new Database(':memory:'); return new ContactBook(() => db); };
|
|
12
|
+
|
|
13
|
+
test('a contact is per person (email, any case); settings save one field at a time, validated', () => {
|
|
14
|
+
const b = book();
|
|
15
|
+
b.create('Kamil@X.dev', { name: 'Kamil' });
|
|
16
|
+
assert.equal(b.get('kamil@x.dev').name, 'Kamil');
|
|
17
|
+
assert.equal(b.create('kamil@x.dev', { access: 'full' }).access, 'trusted', 'create never overwrites');
|
|
18
|
+
assert.throws(() => b.set('kamil@x.dev', 'access', 'root'), /Unknown access/);
|
|
19
|
+
assert.throws(() => b.set('kamil@x.dev', 'autonomy', 'wild'), /Unknown autonomy/);
|
|
20
|
+
assert.throws(() => b.set('kamil@x.dev', 'nope', 1), /Unknown setting/);
|
|
21
|
+
assert.equal(b.set('kamil@x.dev', 'private', 'health').private, 'health');
|
|
22
|
+
assert.deepEqual(b.set('kamil@x.dev', 'mcp', { gmail: 1, x: 0 }).mcp, { gmail: true, x: false });
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
test('Access resets Tools and Commands to that tier; Full needs confirming once', () => {
|
|
26
|
+
const b = book();
|
|
27
|
+
b.create('k@x.dev');
|
|
28
|
+
b.set('k@x.dev', 'tools', ['read']);
|
|
29
|
+
assert.equal(b.set('k@x.dev', 'access', 'restricted').commands, 'basic');
|
|
30
|
+
assert.throws(() => b.set('k@x.dev', 'access', 'full'), e => e.code === 'confirm_full');
|
|
31
|
+
const full = b.set('k@x.dev', 'access', 'full', { confirmFull: true });
|
|
32
|
+
assert.ok(full.fullConfirmedAt);
|
|
33
|
+
assert.deepEqual(full.tools.sort(), ['memory_get', 'memory_search', 'pdf', 'view_image', 'web_fetch', 'web_search']);
|
|
34
|
+
b.set('k@x.dev', 'access', 'trusted');
|
|
35
|
+
assert.equal(b.set('k@x.dev', 'access', 'full').access, 'full', 'confirmed once');
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test('"Open one folder" is Full agent only and needs ask/auto-review commands; Basic list entries are checked', () => {
|
|
39
|
+
const b = book();
|
|
40
|
+
b.create('k@x.dev');
|
|
41
|
+
assert.throws(() => b.set('k@x.dev', 'openFolder', '/w/plans'), /Full agent/);
|
|
42
|
+
b.set('k@x.dev', 'access', 'full', { confirmFull: true });
|
|
43
|
+
b.set('k@x.dev', 'commands', 'basic');
|
|
44
|
+
assert.throws(() => b.set('k@x.dev', 'openFolder', '/w/plans'), /ask me/);
|
|
45
|
+
b.set('k@x.dev', 'commands', 'ask');
|
|
46
|
+
assert.equal(b.set('k@x.dev', 'openFolder', '/w/plans').openFolder, '/w/plans');
|
|
47
|
+
assert.throws(() => b.set('k@x.dev', 'commands', 'basic'), /ask me/);
|
|
48
|
+
assert.throws(() => b.set('k@x.dev', 'basicList', [{ pattern: 'env' }]), e => e.code === 'bad_entry');
|
|
49
|
+
assert.equal(b.set('k@x.dev', 'basicList', [{ pattern: 'hostname' }]).basicList[0].pattern, 'hostname');
|
|
50
|
+
assert.equal(b.set('k@x.dev', 'basicList', null).basicList, null, 'back to the defaults');
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test('one counter per person: day and hour windows, per tier; a failed reply gives its count back', () => {
|
|
54
|
+
const b = book();
|
|
55
|
+
b.create('k@x.dev');
|
|
56
|
+
const now = Date.UTC(2026, 10, 20, 10, 30);
|
|
57
|
+
b.count('k@x.dev', 49, now);
|
|
58
|
+
assert.equal(b.overCap('k@x.dev', 'bounded', now), null);
|
|
59
|
+
b.count('k@x.dev', 1, now);
|
|
60
|
+
assert.match(b.overCap('k@x.dev', 'bounded', now), /Daily limit reached \(50/);
|
|
61
|
+
assert.match(b.overCap('k@x.dev', 'extended', now), /Hourly limit reached \(12/);
|
|
62
|
+
assert.equal(b.overCap('k@x.dev', 'extended', now + 3_600_000), null, 'next hour');
|
|
63
|
+
b.count('k@x.dev', -1, now);
|
|
64
|
+
assert.equal(b.usage('k@x.dev', now).day, 49);
|
|
65
|
+
b.forget('k@x.dev');
|
|
66
|
+
assert.equal(b.get('k@x.dev'), null);
|
|
67
|
+
assert.equal(b.usage('k@x.dev', now).day, 0);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test('notes: only top-level memory/projects/*.md are offered; infrastructure notes start off', () => {
|
|
71
|
+
const ws = fs.mkdtempSync(path.join(os.tmpdir(), 'ws-'));
|
|
72
|
+
fs.mkdirSync(path.join(ws, 'memory/projects/sub'), { recursive: true });
|
|
73
|
+
for (const f of ['clawchats.md', 'homelab.md', 'openclaw-gateway-ops.md', 'vault-notes.md', 'sub/deep.md']) fs.writeFileSync(path.join(ws, 'memory/projects', f), `# ${f}`);
|
|
74
|
+
fs.writeFileSync(path.join(ws, 'memory/2026-11-20.md'), 'daily');
|
|
75
|
+
fs.writeFileSync(path.join(ws, 'MEMORY.md'), 'private');
|
|
76
|
+
const c = noteCandidates([ws]);
|
|
77
|
+
assert.deepEqual(c.map(x => [x.name, x.defaultOn]), [['clawchats.md', true], ['homelab.md', false], ['openclaw-gateway-ops.md', false], ['vault-notes.md', false]]);
|
|
78
|
+
// Picks that aren't candidates or allowed repo docs are dropped (MEMORY.md, a daily note).
|
|
79
|
+
assert.deepEqual(resolvePicks([path.join(ws, 'MEMORY.md'), path.join(ws, 'memory/2026-11-20.md'), c[0].path], c).map(f => f.dest), ['clawchats.md']);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test('notes sync: read-only copies, secrets removed, no symlinks followed, re-synced when a note changes, removed on None', () => {
|
|
83
|
+
const ws = fs.mkdtempSync(path.join(os.tmpdir(), 'ws-'));
|
|
84
|
+
const copyWs = fs.mkdtempSync(path.join(os.tmpdir(), 'copy-'));
|
|
85
|
+
fs.mkdirSync(path.join(ws, 'memory/projects'), { recursive: true });
|
|
86
|
+
const note = path.join(ws, 'memory/projects/clawchats.md');
|
|
87
|
+
fs.writeFileSync(note, 'Deploy key: ANTHROPIC_API_KEY=sk-ant-api03-AbCdEfGhIjKlMnOpQrStUvWx\nStack: node');
|
|
88
|
+
const files = resolvePicks([note], noteCandidates([ws]));
|
|
89
|
+
const r = syncNotes(copyWs, files);
|
|
90
|
+
assert.deepEqual([r.files, r.secretsRemoved], [1, 1]);
|
|
91
|
+
const out = path.join(copyWs, 'notes/clawchats.md');
|
|
92
|
+
assert.doesNotMatch(fs.readFileSync(out, 'utf8'), /sk-ant/);
|
|
93
|
+
assert.equal(fs.statSync(out).mode & 0o777, 0o444);
|
|
94
|
+
const sig = picksSignature(files);
|
|
95
|
+
fs.writeFileSync(note, 'Stack: node 24', { flag: 'w' });
|
|
96
|
+
fs.utimesSync(note, new Date(), new Date(Date.now() + 5000));
|
|
97
|
+
assert.notEqual(picksSignature(files), sig, 'an edit shows as a new signature');
|
|
98
|
+
syncNotes(copyWs, files);
|
|
99
|
+
assert.equal(fs.readFileSync(out, 'utf8'), 'Stack: node 24');
|
|
100
|
+
// A source that turned into a link is skipped.
|
|
101
|
+
fs.rmSync(note); fs.symlinkSync('/etc/hostname', note);
|
|
102
|
+
assert.equal(syncNotes(copyWs, files).files, 0);
|
|
103
|
+
removeNotes(copyWs);
|
|
104
|
+
assert.equal(fs.existsSync(path.join(copyWs, 'notes')), false);
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
test('repo docs: a .md in a git repo, never under ~/.openclaw, never through a link', () => {
|
|
108
|
+
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'home-'));
|
|
109
|
+
const repo = path.join(home, 'repos/app');
|
|
110
|
+
fs.mkdirSync(path.join(repo, '.git'), { recursive: true });
|
|
111
|
+
fs.mkdirSync(path.join(repo, 'specs'));
|
|
112
|
+
fs.writeFileSync(path.join(repo, 'specs/a.md'), '# a');
|
|
113
|
+
fs.writeFileSync(path.join(repo, 'secret.json'), '{}');
|
|
114
|
+
fs.mkdirSync(path.join(home, '.openclaw/workspace/.git'), { recursive: true });
|
|
115
|
+
fs.writeFileSync(path.join(home, '.openclaw/workspace/x.md'), '# x');
|
|
116
|
+
fs.symlinkSync(path.join(repo, 'specs/a.md'), path.join(repo, 'link.md'));
|
|
117
|
+
const ok = checkRepoDoc('~/repos/app/specs/a.md', { home });
|
|
118
|
+
assert.deepEqual([ok.ok, ok.repo, ok.name], [true, repo, 'app/specs/a.md']);
|
|
119
|
+
assert.match(checkRepoDoc(path.join(repo, 'secret.json'), { home }).error, /Markdown/);
|
|
120
|
+
assert.match(checkRepoDoc(path.join(home, '.openclaw/workspace/x.md'), { home }).error, /openclaw/);
|
|
121
|
+
assert.match(checkRepoDoc(path.join(repo, 'link.md'), { home }).error, /link/);
|
|
122
|
+
assert.match(checkRepoDoc(path.join(repo, 'specs/../../app/specs/a.md'), { home }).ok ? 'ok' : 'x', /ok/, 'normalized');
|
|
123
|
+
assert.match(checkRepoDoc('specs/a.md', { home }).error, /full path/);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
test('peer versions: older than the minimum, or none at all, is too old; the message names the update command', () => {
|
|
127
|
+
assert.equal(olderThan('0.2.4', '0.3.0'), true);
|
|
128
|
+
assert.equal(olderThan('0.3.0', '0.3.0'), false);
|
|
129
|
+
assert.equal(olderThan('0.10.0', '0.3.0'), false);
|
|
130
|
+
assert.equal(peerOutdated(null), true);
|
|
131
|
+
assert.equal(peerOutdated('0.2.4'), true);
|
|
132
|
+
assert.equal(peerOutdated(MIN_PEER_VERSION), false);
|
|
133
|
+
assert.match(outdatedMessage('Kamil', '0.2.4'), /Kamil's ClawChats connector is out of date \(0\.2\.4\)[^]*openclaw plugins install npm:@clawchatsai\/connector --force/);
|
|
134
|
+
assert.match(outdatedMessage(null, null), /^Your ClawChats connector is out of date\./);
|
|
135
|
+
});
|
package/server/peer/link.js
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
// signatures don't verify and the link never opens.
|
|
6
6
|
//
|
|
7
7
|
// Wire format (JSON strings):
|
|
8
|
-
// { t: 'hello', v: 1, role, shareId, nonce }
|
|
8
|
+
// { t: 'hello', v: 1, role, shareId, nonce, cv } cv: the sender's connector version (0.3.0+; version.js)
|
|
9
9
|
// { t: 'auth', sig }
|
|
10
10
|
// { t: 'req', id, method, params } → { t: 'res', id, ok, result | error }
|
|
11
11
|
// { t: 'ev', id, event, data } (progress for a request, e.g. streamed text)
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
import crypto from 'node:crypto';
|
|
14
14
|
import { EventEmitter } from 'node:events';
|
|
15
15
|
import { canonicalJson, verifySignature } from './keys.js';
|
|
16
|
+
import { connectorVersion } from './version.js';
|
|
16
17
|
|
|
17
18
|
const HANDSHAKE_MS = 15_000;
|
|
18
19
|
const MAX_FRAME = 256 * 1024;
|
|
@@ -33,12 +34,13 @@ export class PeerLink extends EventEmitter {
|
|
|
33
34
|
* @param {string} o.peerKey the other side's pinned public key (base64 SPKI)
|
|
34
35
|
* @param {{ local: string, remote: string }} o.dtls DTLS fingerprints as this side sees them
|
|
35
36
|
*/
|
|
36
|
-
constructor({ dc, role, shareId, key, peerKey, dtls = { local: '', remote: '' }, handshakeMs = HANDSHAKE_MS, log = console }) {
|
|
37
|
+
constructor({ dc, role, shareId, key, peerKey, dtls = { local: '', remote: '' }, handshakeMs = HANDSHAKE_MS, log = console, version = connectorVersion() }) {
|
|
37
38
|
super();
|
|
38
39
|
Object.assign(this, { dc, role, shareId, key, peerKey, dtls, log });
|
|
39
40
|
this.peerRole = role === 'owner' ? 'requester' : 'owner';
|
|
40
41
|
this.nonce = crypto.randomBytes(24).toString('base64');
|
|
41
42
|
this.peerNonce = null;
|
|
43
|
+
this.peerVersion = null; // the other side's connector version, from its hello (null: too old to send one)
|
|
42
44
|
this.sentAuth = false;
|
|
43
45
|
this.verified = false;
|
|
44
46
|
this.ready = false;
|
|
@@ -53,7 +55,7 @@ export class PeerLink extends EventEmitter {
|
|
|
53
55
|
try { this._onFrame(data); } catch (e) { this.log.warn?.(`[peer] ${this.shareId}: frame handling failed: ${e?.message}`); this._fail('bad frame'); }
|
|
54
56
|
});
|
|
55
57
|
dc.onClosed(() => this._onClosed());
|
|
56
|
-
this._send({ t: 'hello', v: 1, role, shareId, nonce: this.nonce });
|
|
58
|
+
this._send({ t: 'hello', v: 1, role, shareId, nonce: this.nonce, cv: version });
|
|
57
59
|
}
|
|
58
60
|
|
|
59
61
|
/** What `signer` signs: both nonces and both fingerprints, from the signer's point of view. */
|
|
@@ -82,6 +84,8 @@ export class PeerLink extends EventEmitter {
|
|
|
82
84
|
if (m.t === 'hello') {
|
|
83
85
|
if (m.v !== 1 || m.role !== this.peerRole || m.shareId !== this.shareId || typeof m.nonce !== 'string' || this.peerNonce) return this._fail('bad hello');
|
|
84
86
|
this.peerNonce = m.nonce;
|
|
87
|
+
// Rides the DTLS channel the auth below binds, so a relay can't change it.
|
|
88
|
+
if (typeof m.cv === 'string') this.peerVersion = m.cv.slice(0, 40);
|
|
85
89
|
this.sentAuth = true;
|
|
86
90
|
this._send({ t: 'auth', sig: this.key.signJson(JSON.parse(this._statement(this.role, this.nonce, this.peerNonce, this.dtls.local, this.dtls.remote))) });
|
|
87
91
|
} else if (m.t === 'auth') {
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// Knowledge "My notes" (contact card): read-only copies of the notes the owner picked, in a `notes/` folder of each
|
|
2
|
+
// agent copy made for that person. The copy reads them with its own file tools (fs.workspaceOnly keeps it in its
|
|
3
|
+
// folder), so the owner's real memory is never reachable. Copies go through redactSecrets, are written 0444 (the
|
|
4
|
+
// folders stay 0755: a read-only folder would stop the owner's own tools from deleting the copy), and symlinks are
|
|
5
|
+
// never followed. Re-synced when the picks change, on "Sync now", and before a turn when a
|
|
6
|
+
// source file changed.
|
|
7
|
+
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import os from 'node:os';
|
|
11
|
+
import crypto from 'node:crypto';
|
|
12
|
+
import { redactSecrets } from '../util/redact.js';
|
|
13
|
+
|
|
14
|
+
export const NOTES_DIR = 'notes';
|
|
15
|
+
const MAX_FILE = 256 * 1024;
|
|
16
|
+
// Off by default (D10): infrastructure notes, and anything named like it holds credentials.
|
|
17
|
+
const DEFAULT_OFF = /^(homelab|openclaw-gateway-ops)\.md$|secret|credential|password|token|vault/i;
|
|
18
|
+
|
|
19
|
+
/** Notes the card offers from an agent workspace: top-level `memory/projects/*.md` only (never daily notes, MEMORY.md, USER.md, reference/, imports/). */
|
|
20
|
+
export function noteCandidates(workspaces) {
|
|
21
|
+
const out = [];
|
|
22
|
+
for (const ws of new Set((workspaces || []).filter(w => typeof w === 'string' && path.isAbsolute(w)))) {
|
|
23
|
+
const dir = path.join(ws, 'memory', 'projects');
|
|
24
|
+
let names = [];
|
|
25
|
+
try { names = fs.readdirSync(dir, { withFileTypes: true }).filter(d => d.isFile() && d.name.endsWith('.md')).map(d => d.name).sort(); } catch { continue; }
|
|
26
|
+
for (const name of names) {
|
|
27
|
+
const p = path.join(dir, name);
|
|
28
|
+
const st = safeStat(p);
|
|
29
|
+
if (!st) continue;
|
|
30
|
+
out.push({ path: p, name, group: 'projects', root: dir, size: st.size, mtimeMs: st.mtimeMs, defaultOn: !DEFAULT_OFF.test(name) });
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The git repo a path is in (the folder holding `.git`), or null. */
|
|
37
|
+
export function repoOf(p) {
|
|
38
|
+
let dir = path.dirname(p);
|
|
39
|
+
for (let i = 0; i < 30 && dir !== path.dirname(dir); i++, dir = path.dirname(dir)) {
|
|
40
|
+
if (fs.existsSync(path.join(dir, '.git'))) return dir;
|
|
41
|
+
}
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Whether a file may be offered as a repo doc: a Markdown file (no symlink anywhere on its path), inside a git repo, not
|
|
47
|
+
* under ~/.openclaw, at most 256 KB. Returns { ok, path, repo, error }.
|
|
48
|
+
*/
|
|
49
|
+
export function checkRepoDoc(input, { home = os.homedir() } = {}) {
|
|
50
|
+
const raw = String(input || '').trim().replace(/^~(?=\/)/, home);
|
|
51
|
+
if (!path.isAbsolute(raw)) return { ok: false, error: 'Use the full path of a .md file in one of your git repos' };
|
|
52
|
+
const p = path.normalize(raw);
|
|
53
|
+
let real;
|
|
54
|
+
try { real = fs.realpathSync(p); } catch { return { ok: false, error: "That file doesn't exist" }; }
|
|
55
|
+
if (real !== p) return { ok: false, error: "That path goes through a link; use the file's real path" };
|
|
56
|
+
if (!/\.md$/i.test(p)) return { ok: false, error: 'Only Markdown (.md) files' };
|
|
57
|
+
if (p.split(path.sep).some(seg => seg === '.openclaw') || p.startsWith(path.join(home, '.openclaw'))) return { ok: false, error: 'Nothing under ~/.openclaw' };
|
|
58
|
+
const st = safeStat(p);
|
|
59
|
+
if (!st?.isFile()) return { ok: false, error: 'Not a file' };
|
|
60
|
+
if (st.size > MAX_FILE) return { ok: false, error: 'Too big (256 KB at most)' };
|
|
61
|
+
const repo = repoOf(p);
|
|
62
|
+
if (!repo) return { ok: false, error: 'Only files inside a git repo' };
|
|
63
|
+
return { ok: true, path: p, repo, size: st.size, mtimeMs: st.mtimeMs, name: path.relative(path.dirname(repo), p) };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The picked files that exist and are allowed: [{ src, dest (relative to notes/) }]. */
|
|
67
|
+
export function resolvePicks(picks, candidates) {
|
|
68
|
+
const byPath = new Map(candidates.map(c => [c.path, c]));
|
|
69
|
+
const out = [];
|
|
70
|
+
for (const p of picks || []) {
|
|
71
|
+
const cand = byPath.get(p);
|
|
72
|
+
if (cand) { out.push({ src: p, dest: cand.name }); continue; }
|
|
73
|
+
const doc = checkRepoDoc(p);
|
|
74
|
+
if (doc.ok) out.push({ src: doc.path, dest: path.join('repos', doc.name) });
|
|
75
|
+
}
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** What the picked files look like now (to tell whether a re-sync is due). */
|
|
80
|
+
export function picksSignature(files) {
|
|
81
|
+
const h = crypto.createHash('sha256');
|
|
82
|
+
for (const f of files) { const st = safeStat(f.src); h.update(`${f.src}|${f.dest}|${st?.size ?? -1}|${st?.mtimeMs ?? -1}\n`); }
|
|
83
|
+
return h.digest('hex').slice(0, 16);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Write the picked notes into `<workspace>/notes/`, replacing what was there. Returns { files, bytes, secretsRemoved,
|
|
88
|
+
* at, signature }. Never follows symlinks (a source that became one is skipped).
|
|
89
|
+
*/
|
|
90
|
+
export function syncNotes(workspace, files) {
|
|
91
|
+
const root = path.join(workspace, NOTES_DIR);
|
|
92
|
+
if (fs.existsSync(root) && fs.lstatSync(root).isSymbolicLink()) throw new Error('notes folder is a link: refusing');
|
|
93
|
+
makeWritable(root);
|
|
94
|
+
fs.rmSync(root, { recursive: true, force: true });
|
|
95
|
+
fs.mkdirSync(root, { recursive: true });
|
|
96
|
+
let bytes = 0, secretsRemoved = 0, count = 0;
|
|
97
|
+
for (const f of files) {
|
|
98
|
+
const st = fs.lstatSync(f.src, { throwIfNoEntry: false });
|
|
99
|
+
if (!st || !st.isFile() || st.isSymbolicLink() || st.size > MAX_FILE) continue;
|
|
100
|
+
const text = redactSecrets(fs.readFileSync(f.src, 'utf8'), () => { secretsRemoved++; });
|
|
101
|
+
const dest = path.join(root, f.dest);
|
|
102
|
+
if (!dest.startsWith(root + path.sep)) continue;
|
|
103
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
104
|
+
fs.writeFileSync(dest, text, { mode: 0o444 });
|
|
105
|
+
fs.chmodSync(dest, 0o444);
|
|
106
|
+
bytes += Buffer.byteLength(text);
|
|
107
|
+
count++;
|
|
108
|
+
}
|
|
109
|
+
return { files: count, bytes, secretsRemoved, at: Date.now(), signature: picksSignature(files) };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Remove a copy's notes (its folders are read-only). */
|
|
113
|
+
export function removeNotes(workspace) {
|
|
114
|
+
const root = path.join(workspace, NOTES_DIR);
|
|
115
|
+
if (!fs.existsSync(root)) return;
|
|
116
|
+
makeWritable(root);
|
|
117
|
+
fs.rmSync(root, { recursive: true, force: true });
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function makeWritable(dir) {
|
|
121
|
+
if (!fs.existsSync(dir) || fs.lstatSync(dir).isSymbolicLink()) return;
|
|
122
|
+
fs.chmodSync(dir, 0o755);
|
|
123
|
+
for (const e of fs.readdirSync(dir, { withFileTypes: true })) if (e.isDirectory()) makeWritable(path.join(dir, e.name));
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function safeStat(p) { try { return fs.statSync(p); } catch { return null; } }
|