@agentpro/scroll 0.0.0-stage → 2.5.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/AGENTS.md +55 -0
- package/LICENSE +21 -0
- package/README.md +293 -2
- package/SPEC.md +1079 -0
- package/bin/scroll.js +8 -0
- package/docs/prompt-caching.md +128 -0
- package/index.js +33 -0
- package/lib/audit.js +358 -0
- package/lib/auth.js +849 -0
- package/lib/chat-sdk/admin-controller.js +289 -0
- package/lib/chat-sdk/debouncer.js +94 -0
- package/lib/chat-sdk/group-grants.js +150 -0
- package/lib/chat-sdk/index.js +222 -0
- package/lib/chat-sdk/long-task-runner.js +413 -0
- package/lib/chat-session.js +1788 -0
- package/lib/chat-telemetry.js +557 -0
- package/lib/codex-app-server.js +851 -0
- package/lib/digest.js +112 -0
- package/lib/effects.js +157 -0
- package/lib/eval.js +408 -0
- package/lib/grounding.js +356 -0
- package/lib/installers.js +176 -0
- package/lib/knowledge.js +335 -0
- package/lib/ledger.js +38 -0
- package/lib/loop.js +197 -0
- package/lib/mcp-client.js +926 -0
- package/lib/memory-cli.js +66 -0
- package/lib/memory-tracker.js +1472 -0
- package/lib/memory.js +1279 -0
- package/lib/people-cli.js +81 -0
- package/lib/people.js +534 -0
- package/lib/permissions.js +272 -0
- package/lib/providers.js +1572 -0
- package/lib/runtime.js +928 -0
- package/lib/sandbox.js +744 -0
- package/lib/scheduler.js +402 -0
- package/lib/scroll.js +1225 -0
- package/lib/skill-cli.js +120 -0
- package/lib/skill-eval.js +156 -0
- package/lib/skills.js +860 -0
- package/lib/style.js +126 -0
- package/lib/tool-retriever.js +489 -0
- package/lib/tools.js +1833 -0
- package/lib/user.js +711 -0
- package/lib/vault.js +151 -0
- package/package.json +88 -4
- package/templates/agent/IDENTITY.md +56 -0
- package/templates/agent/SOUL.md +23 -0
- package/templates/agent/TOOLS.md +25 -0
- package/templates/agent/evals/case-02-citation-discipline.md +29 -0
- package/templates/agent/evals/case-03-boundary.md +27 -0
- package/templates/agent/evals/case-example.md +43 -0
- package/templates/agent/hard-rules.md +11 -0
- package/templates/agent/memory/lessons.md +5 -0
- package/templates/agent/memory/log/.gitkeep +0 -0
- package/templates/external-safety-contract.md +5 -0
- package/templates/long-task-planner.md +17 -0
- package/templates/work/LOOP.md +37 -0
- package/templates/work/WORK.md +50 -0
- package/types/chat.d.ts +61 -0
- package/types/index.d.ts +112 -0
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
// SCROLL 2.5 -- Pure Transport-Agnostic AdminController (JSON API, zero Telegram UI coupling).
|
|
2
|
+
// Drives Telegram inline keyboards, Web dashboards, Bot Room consoles, Slack slash commands, or CLI.
|
|
3
|
+
// Strict security invariant: destructive/admin commands require a verified owner in DM!
|
|
4
|
+
|
|
5
|
+
export const ADMIN_CALLBACK_NAMESPACE = 'scroll-admin';
|
|
6
|
+
|
|
7
|
+
export function createAdminController({
|
|
8
|
+
bots,
|
|
9
|
+
authStore = null,
|
|
10
|
+
scheduler = null,
|
|
11
|
+
groupGrants = null,
|
|
12
|
+
longTasks = null,
|
|
13
|
+
runCronNowFn = null,
|
|
14
|
+
runDreamNowFn = null,
|
|
15
|
+
ownerIds = [],
|
|
16
|
+
startedAt = Date.now(),
|
|
17
|
+
} = {}) {
|
|
18
|
+
const ownerSet = new Set((ownerIds || []).map(String));
|
|
19
|
+
let globalPaused = false;
|
|
20
|
+
const reviewShortcuts = new Map();
|
|
21
|
+
|
|
22
|
+
function isOwner(actor) {
|
|
23
|
+
if (!actor) return false;
|
|
24
|
+
const rawId = String(actor.senderId ?? actor.id ?? '');
|
|
25
|
+
const stripped = rawId.replace(/^[a-z0-9_-]+:/i, '');
|
|
26
|
+
if (!rawId || (!ownerSet.has(rawId) && !ownerSet.has(stripped))) return false;
|
|
27
|
+
return actor.isDm === true && actor.isGroup !== true;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function assertOwner(actor) {
|
|
31
|
+
if (!isOwner(actor)) {
|
|
32
|
+
const err = new Error('admin_owner_dm_required');
|
|
33
|
+
err.code = 'FORBIDDEN';
|
|
34
|
+
throw err;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function listBots() {
|
|
39
|
+
return [...bots.values()].map((b) => ({
|
|
40
|
+
id: b.id,
|
|
41
|
+
username: b.username || null,
|
|
42
|
+
agentName: b.agentName,
|
|
43
|
+
provider: b.runtime.provider.name,
|
|
44
|
+
model: b.model || b.runtime.provider.model,
|
|
45
|
+
paused: Boolean(b.paused),
|
|
46
|
+
groupPolicy: b.groupPolicy || 'mention',
|
|
47
|
+
knowledgeChunks: b.runtime.knowledgeIndex?.active ? b.runtime.knowledgeIndex.chunks.length : 0,
|
|
48
|
+
memory: b.runtime.memoryTracker && typeof b.runtime.memoryTracker.getStats === 'function'
|
|
49
|
+
? b.runtime.memoryTracker.getStats()
|
|
50
|
+
: null,
|
|
51
|
+
turnsProcessed: Number(b.stats?.turns || 0),
|
|
52
|
+
errors: Number(b.stats?.errors || 0),
|
|
53
|
+
}));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function consolidateAllMemory(actor) {
|
|
57
|
+
assertOwner(actor);
|
|
58
|
+
let totalSubjects = 0;
|
|
59
|
+
const perBot = [];
|
|
60
|
+
for (const b of bots.values()) {
|
|
61
|
+
if (b.runtime?.memoryTracker && typeof b.runtime.memoryTracker.consolidateAll === 'function') {
|
|
62
|
+
const r = b.runtime.memoryTracker.consolidateAll();
|
|
63
|
+
totalSubjects += Number(r.consolidatedSubjects || 0);
|
|
64
|
+
perBot.push({ botId: b.id, consolidatedSubjects: r.consolidatedSubjects || 0 });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return { ok: true, totalSubjects, perBot };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function listAllReviews() {
|
|
71
|
+
const out = [];
|
|
72
|
+
for (const b of bots.values()) {
|
|
73
|
+
const mt = b.runtime?.memoryTracker;
|
|
74
|
+
if (!mt || typeof mt.listPendingReviews !== 'function') continue;
|
|
75
|
+
for (const item of mt.listPendingReviews()) {
|
|
76
|
+
out.push({ botId: b.id, ...item });
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function registerReviewShortcut(shortKey, ref) {
|
|
83
|
+
reviewShortcuts.set(String(shortKey), ref);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function resolveReview(actor, shortKey, decision) {
|
|
87
|
+
assertOwner(actor);
|
|
88
|
+
const ref = reviewShortcuts.get(String(shortKey || ''));
|
|
89
|
+
if (!ref) return { ok: false, reason: 'review_shortcut_expired' };
|
|
90
|
+
const bot = bots.get(ref.botId);
|
|
91
|
+
if (!bot?.runtime?.memoryTracker) return { ok: false, reason: 'bot_not_found' };
|
|
92
|
+
const r = bot.runtime.memoryTracker.resolveReviewItem({ sid: ref.sid, reviewId: ref.reviewId, decision, by: 'owner' });
|
|
93
|
+
if (r.ok) reviewShortcuts.delete(String(shortKey));
|
|
94
|
+
return r;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function getStatus() {
|
|
98
|
+
const uptimeSec = Math.round((Date.now() - startedAt) / 1000);
|
|
99
|
+
return {
|
|
100
|
+
globalPaused,
|
|
101
|
+
uptimeSec,
|
|
102
|
+
bots: listBots(),
|
|
103
|
+
authProfiles: authStore ? authStore.listProfiles() : [],
|
|
104
|
+
cronPaused: scheduler ? scheduler.paused : false,
|
|
105
|
+
cronCount: scheduler ? scheduler.listJobs().length : 0,
|
|
106
|
+
activeGrants: groupGrants ? groupGrants.listActiveGrants() : [],
|
|
107
|
+
longTasks: longTasks ? longTasks.listTasks().slice(0, 10) : [],
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function toggleGlobalPause(actor) {
|
|
112
|
+
assertOwner(actor);
|
|
113
|
+
globalPaused = !globalPaused;
|
|
114
|
+
if (scheduler) scheduler.setPaused(globalPaused);
|
|
115
|
+
return { ok: true, globalPaused };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function toggleBotPause(actor, botId) {
|
|
119
|
+
assertOwner(actor);
|
|
120
|
+
const bot = bots.get(botId);
|
|
121
|
+
if (!bot) throw new Error(`bot_not_found:${botId}`);
|
|
122
|
+
bot.paused = !bot.paused;
|
|
123
|
+
return { ok: true, botId, paused: bot.paused };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function setGroupPolicy(actor, botId, policy) {
|
|
127
|
+
assertOwner(actor);
|
|
128
|
+
if (!['mention', 'all', 'off'].includes(policy)) throw new Error(`invalid_group_policy:${policy}`);
|
|
129
|
+
const bot = bots.get(botId);
|
|
130
|
+
if (!bot) throw new Error(`bot_not_found:${botId}`);
|
|
131
|
+
bot.groupPolicy = policy;
|
|
132
|
+
return { ok: true, botId, groupPolicy: policy };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function switchModel(actor, botId, model) {
|
|
136
|
+
assertOwner(actor);
|
|
137
|
+
const bot = bots.get(botId);
|
|
138
|
+
if (!bot) throw new Error(`bot_not_found:${botId}`);
|
|
139
|
+
bot.model = String(model || '').trim() || null;
|
|
140
|
+
return { ok: true, botId, model: bot.model };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function reloadAgent(actor, botId) {
|
|
144
|
+
assertOwner(actor);
|
|
145
|
+
const bot = bots.get(botId);
|
|
146
|
+
if (!bot) throw new Error(`bot_not_found:${botId}`);
|
|
147
|
+
const info = bot.runtime.reload();
|
|
148
|
+
return { ok: true, botId, ...info };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async function startChatGptLogin(actor, botId) {
|
|
152
|
+
assertOwner(actor);
|
|
153
|
+
const bot = bots.get(botId) || [...bots.values()][0];
|
|
154
|
+
const client = bot?.runtime?.provider?.client;
|
|
155
|
+
if (!client || typeof client.startLogin !== 'function') {
|
|
156
|
+
return { ok: false, reason: 'codex_app_server_not_active' };
|
|
157
|
+
}
|
|
158
|
+
const res = await client.startLogin({ type: 'chatgpt' });
|
|
159
|
+
return { ok: true, ...res };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function listCrons(actor) {
|
|
163
|
+
assertOwner(actor);
|
|
164
|
+
return {
|
|
165
|
+
paused: scheduler ? scheduler.paused : false,
|
|
166
|
+
jobs: scheduler ? scheduler.listJobs() : [],
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function toggleCron(actor, jobId) {
|
|
171
|
+
assertOwner(actor);
|
|
172
|
+
if (!scheduler) throw new Error('scheduler_not_configured');
|
|
173
|
+
const cur = scheduler.getJob(jobId);
|
|
174
|
+
if (!cur) throw new Error(`job_not_found:${jobId}`);
|
|
175
|
+
const next = scheduler.updateJob(jobId, { enabled: !cur.enabled });
|
|
176
|
+
return { ok: true, job: next };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function deleteCron(actor, jobId) {
|
|
180
|
+
assertOwner(actor);
|
|
181
|
+
if (!scheduler) throw new Error('scheduler_not_configured');
|
|
182
|
+
return scheduler.removeJob(jobId);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function readRecentAudit(actor, botId, limit = 10) {
|
|
186
|
+
assertOwner(actor);
|
|
187
|
+
const bot = bots.get(botId);
|
|
188
|
+
if (!bot || !bot.tools) return [];
|
|
189
|
+
return bot.tools.getAuditLog().slice(-Math.max(1, Math.min(30, limit)));
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Pure JSON command executor usable by any UI/channel adapter
|
|
193
|
+
async function executeAction(actor, action, args = {}) {
|
|
194
|
+
assertOwner(actor);
|
|
195
|
+
switch (action) {
|
|
196
|
+
case 'status':
|
|
197
|
+
return { ok: true, action, page: 'home', data: getStatus() };
|
|
198
|
+
case 'global_pause': {
|
|
199
|
+
const res = toggleGlobalPause(actor);
|
|
200
|
+
return { ok: true, action, page: 'home', data: res };
|
|
201
|
+
}
|
|
202
|
+
case 'bot_pause': {
|
|
203
|
+
const res = toggleBotPause(actor, args.botId);
|
|
204
|
+
return { ok: true, action, page: 'bot', botId: args.botId, data: res };
|
|
205
|
+
}
|
|
206
|
+
case 'bot_policy': {
|
|
207
|
+
const res = setGroupPolicy(actor, args.botId, args.policy);
|
|
208
|
+
return { ok: true, action, page: 'bot', botId: args.botId, data: res };
|
|
209
|
+
}
|
|
210
|
+
case 'bot_model': {
|
|
211
|
+
const res = switchModel(actor, args.botId, args.model);
|
|
212
|
+
return { ok: true, action, page: 'bot', botId: args.botId, data: res };
|
|
213
|
+
}
|
|
214
|
+
case 'bot_reload': {
|
|
215
|
+
const res = reloadAgent(actor, args.botId);
|
|
216
|
+
return { ok: true, action, page: 'bot', botId: args.botId, data: res };
|
|
217
|
+
}
|
|
218
|
+
case 'cron_toggle': {
|
|
219
|
+
const res = toggleCron(actor, args.jobId);
|
|
220
|
+
return { ok: true, action, page: 'crons', data: res };
|
|
221
|
+
}
|
|
222
|
+
case 'cron_delete': {
|
|
223
|
+
const res = deleteCron(actor, args.jobId);
|
|
224
|
+
return { ok: true, action, page: 'crons', data: res };
|
|
225
|
+
}
|
|
226
|
+
case 'cron_run': {
|
|
227
|
+
if (typeof runCronNowFn !== 'function') return { ok: false, action, reason: 'cron_runner_not_configured' };
|
|
228
|
+
const res = await runCronNowFn(args.jobId);
|
|
229
|
+
return { ok: Boolean(res?.ok !== false), action, page: 'crons', data: res };
|
|
230
|
+
}
|
|
231
|
+
case 'memory_consolidate': {
|
|
232
|
+
const res = consolidateAllMemory(actor);
|
|
233
|
+
return { ok: true, action, page: 'memory', data: res };
|
|
234
|
+
}
|
|
235
|
+
case 'memory_dream': {
|
|
236
|
+
if (typeof runDreamNowFn !== 'function') return { ok: false, action, reason: 'dream_runner_not_configured' };
|
|
237
|
+
const res = await runDreamNowFn();
|
|
238
|
+
return { ok: true, action, page: 'memory', data: res };
|
|
239
|
+
}
|
|
240
|
+
case 'review_resolve': {
|
|
241
|
+
const res = resolveReview(actor, args.shortKey, args.decision);
|
|
242
|
+
return { ok: Boolean(res?.ok), action, page: 'reviews', data: res };
|
|
243
|
+
}
|
|
244
|
+
case 'grant_revoke': {
|
|
245
|
+
if (!groupGrants) return { ok: false, action, reason: 'group_grants_not_configured' };
|
|
246
|
+
const res = groupGrants.revoke(args.roomId || args.chatId);
|
|
247
|
+
return { ok: Boolean(res?.ok), action, page: 'grants', data: res };
|
|
248
|
+
}
|
|
249
|
+
case 'task_cancel': {
|
|
250
|
+
if (!longTasks) return { ok: false, action, reason: 'long_tasks_not_configured' };
|
|
251
|
+
const res = longTasks.cancelTask(args.taskId);
|
|
252
|
+
return { ok: Boolean(res?.ok), action, page: 'tasks', data: res };
|
|
253
|
+
}
|
|
254
|
+
case 'auth_login': {
|
|
255
|
+
const res = await startChatGptLogin(actor, args.botId);
|
|
256
|
+
return { ok: Boolean(res?.ok), action, page: 'auth', data: res };
|
|
257
|
+
}
|
|
258
|
+
case 'audit': {
|
|
259
|
+
const entries = readRecentAudit(actor, args.botId, args.limit || 10);
|
|
260
|
+
return { ok: true, action, page: 'audit', botId: args.botId, data: { entries } };
|
|
261
|
+
}
|
|
262
|
+
default:
|
|
263
|
+
return { ok: false, action, reason: `unknown_admin_action:${action}` };
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
return {
|
|
268
|
+
get globalPaused() { return globalPaused; },
|
|
269
|
+
isOwner,
|
|
270
|
+
assertOwner,
|
|
271
|
+
listBots,
|
|
272
|
+
getStatus,
|
|
273
|
+
toggleGlobalPause,
|
|
274
|
+
toggleBotPause,
|
|
275
|
+
setGroupPolicy,
|
|
276
|
+
switchModel,
|
|
277
|
+
reloadAgent,
|
|
278
|
+
startChatGptLogin,
|
|
279
|
+
listCrons,
|
|
280
|
+
toggleCron,
|
|
281
|
+
deleteCron,
|
|
282
|
+
consolidateAllMemory,
|
|
283
|
+
listAllReviews,
|
|
284
|
+
registerReviewShortcut,
|
|
285
|
+
resolveReview,
|
|
286
|
+
readRecentAudit,
|
|
287
|
+
executeAction,
|
|
288
|
+
};
|
|
289
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// SCROLL 2.5 -- Channel-agnostic Burst Message Debouncer.
|
|
2
|
+
// Coalesces rapid multi-bubble messages per room/conversation key into a single LLM turn.
|
|
3
|
+
// Fast-paths slash commands (/admin, /clear, /start, etc.) immediately with 0 delay.
|
|
4
|
+
|
|
5
|
+
export function createMessageDebouncer({
|
|
6
|
+
quietMs = 1500,
|
|
7
|
+
maxWaitMs = 5000,
|
|
8
|
+
onFlush,
|
|
9
|
+
immediatePrefix = '/',
|
|
10
|
+
} = {}) {
|
|
11
|
+
if (typeof onFlush !== 'function') {
|
|
12
|
+
throw new Error('createMessageDebouncer: onFlush callback is required');
|
|
13
|
+
}
|
|
14
|
+
const buckets = new Map();
|
|
15
|
+
|
|
16
|
+
function clearBucketTimers(bucket) {
|
|
17
|
+
if (bucket.quietTimer) {
|
|
18
|
+
clearTimeout(bucket.quietTimer);
|
|
19
|
+
bucket.quietTimer = null;
|
|
20
|
+
}
|
|
21
|
+
if (bucket.maxTimer) {
|
|
22
|
+
clearTimeout(bucket.maxTimer);
|
|
23
|
+
bucket.maxTimer = null;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function flushKey(key) {
|
|
28
|
+
const bucket = buckets.get(key);
|
|
29
|
+
if (!bucket) return Promise.resolve();
|
|
30
|
+
buckets.delete(key);
|
|
31
|
+
clearBucketTimers(bucket);
|
|
32
|
+
const items = bucket.items;
|
|
33
|
+
if (!items.length) return Promise.resolve();
|
|
34
|
+
const last = items[items.length - 1];
|
|
35
|
+
const combinedText = items.map((m) => String(m.text || '').trim()).filter(Boolean).join('\n');
|
|
36
|
+
const attachments = items.flatMap((m) => (Array.isArray(m.attachments) ? m.attachments : []));
|
|
37
|
+
const merged = {
|
|
38
|
+
...last,
|
|
39
|
+
text: combinedText,
|
|
40
|
+
attachments,
|
|
41
|
+
burstCount: items.length,
|
|
42
|
+
messageIds: items.map((m) => m.messageId).filter(Boolean),
|
|
43
|
+
};
|
|
44
|
+
return Promise.resolve(onFlush(merged));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function push(key, item, { immediate = false } = {}) {
|
|
48
|
+
const text = String(item?.text || '').trim();
|
|
49
|
+
const isSlash = Boolean(immediatePrefix && text.startsWith(immediatePrefix));
|
|
50
|
+
if (immediate || isSlash || quietMs <= 0) {
|
|
51
|
+
const prev = buckets.has(key) ? flushKey(key) : Promise.resolve();
|
|
52
|
+
return prev.then(() => Promise.resolve(onFlush({
|
|
53
|
+
...item,
|
|
54
|
+
text,
|
|
55
|
+
attachments: Array.isArray(item?.attachments) ? item.attachments : [],
|
|
56
|
+
burstCount: 1,
|
|
57
|
+
messageIds: item?.messageId ? [item.messageId] : [],
|
|
58
|
+
})));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
let bucket = buckets.get(key);
|
|
62
|
+
if (!bucket) {
|
|
63
|
+
bucket = { items: [], quietTimer: null, maxTimer: null, firstAt: Date.now() };
|
|
64
|
+
buckets.set(key, bucket);
|
|
65
|
+
if (maxWaitMs > 0) {
|
|
66
|
+
bucket.maxTimer = setTimeout(() => { flushKey(key).catch(() => {}); }, maxWaitMs);
|
|
67
|
+
if (typeof bucket.maxTimer.unref === 'function') bucket.maxTimer.unref();
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
bucket.items.push(item);
|
|
71
|
+
if (bucket.quietTimer) clearTimeout(bucket.quietTimer);
|
|
72
|
+
bucket.quietTimer = setTimeout(() => { flushKey(key).catch(() => {}); }, quietMs);
|
|
73
|
+
if (typeof bucket.quietTimer.unref === 'function') bucket.quietTimer.unref();
|
|
74
|
+
return Promise.resolve();
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async function flushAll() {
|
|
78
|
+
const keys = [...buckets.keys()];
|
|
79
|
+
for (const k of keys) await flushKey(k);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function close() {
|
|
83
|
+
for (const [, bucket] of buckets) clearBucketTimers(bucket);
|
|
84
|
+
buckets.clear();
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
return {
|
|
88
|
+
push,
|
|
89
|
+
flushKey,
|
|
90
|
+
flushAll,
|
|
91
|
+
close,
|
|
92
|
+
get pendingCount() { return buckets.size; },
|
|
93
|
+
};
|
|
94
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// SCROLL 2.5 -- Room-Agnostic Owner-Delegated Group Session Grants.
|
|
2
|
+
//
|
|
3
|
+
// Scoped, time-bounded, auditable, and revocable tool delegation for multi-participant rooms
|
|
4
|
+
// (Slack channels, Discord channels, Telegram groups, Web rooms, etc.).
|
|
5
|
+
//
|
|
6
|
+
// Security invariants:
|
|
7
|
+
// - Only a verified owner (verified by caller/host) may grant or revoke.
|
|
8
|
+
// - Grants are bound to an explicit roomId (NOT assuming Telegram negative numeric IDs!),
|
|
9
|
+
// an explicit `allowedTools` allowlist, and a bounded TTL (5-480 minutes).
|
|
10
|
+
// - Private owner data (USER.md # About, principal memory) is NEVER unlocked by a group grant.
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import crypto from 'node:crypto';
|
|
14
|
+
|
|
15
|
+
export const DEFAULT_DELEGATED_GROUP_TOOLS = Object.freeze([
|
|
16
|
+
'web_search',
|
|
17
|
+
'web_fetch',
|
|
18
|
+
'knowledge_search',
|
|
19
|
+
'start_long_task',
|
|
20
|
+
'long_task_status',
|
|
21
|
+
'cancel_long_task',
|
|
22
|
+
]);
|
|
23
|
+
|
|
24
|
+
const DEFAULT_OWNER_DELEGATION_RE = /\b(?:allow\s+(?:bot|agent|assistant)\s+(?:tools?|exec|test|actions?)|grant\s+(?:group|room)\s+tools?)\b/i;
|
|
25
|
+
|
|
26
|
+
export function matchesOwnerDelegationPhrase(text, extraPatterns = []) {
|
|
27
|
+
const s = String(text || '');
|
|
28
|
+
if (DEFAULT_OWNER_DELEGATION_RE.test(s)) return true;
|
|
29
|
+
for (const pat of extraPatterns || []) {
|
|
30
|
+
if (pat instanceof RegExp && pat.test(s)) return true;
|
|
31
|
+
}
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function createGroupGrantStore({
|
|
36
|
+
filePath = null,
|
|
37
|
+
defaultAllowedTools = DEFAULT_DELEGATED_GROUP_TOOLS,
|
|
38
|
+
clock = () => Date.now(),
|
|
39
|
+
} = {}) {
|
|
40
|
+
const absPath = filePath ? path.resolve(filePath) : null;
|
|
41
|
+
|
|
42
|
+
function load() {
|
|
43
|
+
if (!absPath || !fs.existsSync(absPath)) return { grants: {} };
|
|
44
|
+
try {
|
|
45
|
+
const j = JSON.parse(fs.readFileSync(absPath, 'utf8'));
|
|
46
|
+
return { grants: j.grants && typeof j.grants === 'object' ? { ...j.grants } : {} };
|
|
47
|
+
} catch {
|
|
48
|
+
return { grants: {} };
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
let state = load();
|
|
53
|
+
|
|
54
|
+
function persist() {
|
|
55
|
+
if (!absPath) return;
|
|
56
|
+
fs.mkdirSync(path.dirname(absPath), { recursive: true, mode: 0o700 });
|
|
57
|
+
const tmp = `${absPath}.tmp.${process.pid}.${crypto.randomBytes(3).toString('hex')}`;
|
|
58
|
+
fs.writeFileSync(tmp, JSON.stringify(state, null, 2) + '\n', { mode: 0o600 });
|
|
59
|
+
fs.renameSync(tmp, absPath);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function grant({
|
|
63
|
+
roomId = null,
|
|
64
|
+
chatId = null,
|
|
65
|
+
isGroup = null,
|
|
66
|
+
grantedBy,
|
|
67
|
+
ttlMinutes = 60,
|
|
68
|
+
allowedTools = defaultAllowedTools,
|
|
69
|
+
note = '',
|
|
70
|
+
} = {}) {
|
|
71
|
+
const id = String(roomId ?? chatId ?? '').trim();
|
|
72
|
+
if (!id) throw new Error('group_grant_requires_room_id');
|
|
73
|
+
// Support explicit boolean `isGroup` for any platform (Slack/Discord/Web/Telegram).
|
|
74
|
+
// If caller omits `isGroup` and passes legacy `chatId` only, allow any non-empty id unless `isGroup === false`.
|
|
75
|
+
if (isGroup === false) {
|
|
76
|
+
throw new Error('group_grant_requires_group_room');
|
|
77
|
+
}
|
|
78
|
+
if (!grantedBy || !String(grantedBy).trim()) {
|
|
79
|
+
throw new Error('group_grant_requires_granted_by');
|
|
80
|
+
}
|
|
81
|
+
const mins = Math.max(5, Math.min(480, Number(ttlMinutes || 60)));
|
|
82
|
+
const nowMs = clock();
|
|
83
|
+
const record = {
|
|
84
|
+
roomId: id,
|
|
85
|
+
chatId: id,
|
|
86
|
+
grantedBy: String(grantedBy),
|
|
87
|
+
allowedTools: [...new Set((allowedTools || defaultAllowedTools).map(String))],
|
|
88
|
+
grantedAt: new Date(nowMs).toISOString(),
|
|
89
|
+
expiresAt: new Date(nowMs + mins * 60_000).toISOString(),
|
|
90
|
+
ttlMinutes: mins,
|
|
91
|
+
note: String(note || '').slice(0, 200),
|
|
92
|
+
};
|
|
93
|
+
state.grants[id] = record;
|
|
94
|
+
persist();
|
|
95
|
+
return { ...record };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function revoke(roomOrChatId) {
|
|
99
|
+
const key = String(roomOrChatId || '').trim();
|
|
100
|
+
if (!key || !state.grants[key]) return { ok: false, removed: false };
|
|
101
|
+
delete state.grants[key];
|
|
102
|
+
persist();
|
|
103
|
+
return { ok: true, removed: true, roomId: key, chatId: key };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function getActiveGrant(roomOrChatId) {
|
|
107
|
+
const key = String(roomOrChatId || '').trim();
|
|
108
|
+
const g = state.grants[key];
|
|
109
|
+
if (!g) return null;
|
|
110
|
+
if (Date.parse(g.expiresAt) <= clock()) {
|
|
111
|
+
delete state.grants[key];
|
|
112
|
+
persist();
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
return {
|
|
116
|
+
...g,
|
|
117
|
+
roomId: g.roomId || key,
|
|
118
|
+
chatId: g.chatId || key,
|
|
119
|
+
remainingMinutes: Math.max(1, Math.ceil((Date.parse(g.expiresAt) - clock()) / 60_000)),
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function listActiveGrants() {
|
|
124
|
+
const out = [];
|
|
125
|
+
const nowMs = clock();
|
|
126
|
+
let pruned = false;
|
|
127
|
+
for (const [k, g] of Object.entries(state.grants)) {
|
|
128
|
+
if (Date.parse(g.expiresAt) <= nowMs) {
|
|
129
|
+
delete state.grants[k];
|
|
130
|
+
pruned = true;
|
|
131
|
+
} else {
|
|
132
|
+
out.push({
|
|
133
|
+
...g,
|
|
134
|
+
roomId: g.roomId || k,
|
|
135
|
+
chatId: g.chatId || k,
|
|
136
|
+
remainingMinutes: Math.max(1, Math.ceil((Date.parse(g.expiresAt) - nowMs) / 60_000)),
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
if (pruned) persist();
|
|
141
|
+
return out;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return {
|
|
145
|
+
grant,
|
|
146
|
+
revoke,
|
|
147
|
+
getActiveGrant,
|
|
148
|
+
listActiveGrants,
|
|
149
|
+
};
|
|
150
|
+
}
|