@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.
Files changed (61) hide show
  1. package/AGENTS.md +55 -0
  2. package/LICENSE +21 -0
  3. package/README.md +293 -2
  4. package/SPEC.md +1079 -0
  5. package/bin/scroll.js +8 -0
  6. package/docs/prompt-caching.md +128 -0
  7. package/index.js +33 -0
  8. package/lib/audit.js +358 -0
  9. package/lib/auth.js +849 -0
  10. package/lib/chat-sdk/admin-controller.js +289 -0
  11. package/lib/chat-sdk/debouncer.js +94 -0
  12. package/lib/chat-sdk/group-grants.js +150 -0
  13. package/lib/chat-sdk/index.js +222 -0
  14. package/lib/chat-sdk/long-task-runner.js +413 -0
  15. package/lib/chat-session.js +1788 -0
  16. package/lib/chat-telemetry.js +557 -0
  17. package/lib/codex-app-server.js +851 -0
  18. package/lib/digest.js +112 -0
  19. package/lib/effects.js +157 -0
  20. package/lib/eval.js +408 -0
  21. package/lib/grounding.js +356 -0
  22. package/lib/installers.js +176 -0
  23. package/lib/knowledge.js +335 -0
  24. package/lib/ledger.js +38 -0
  25. package/lib/loop.js +197 -0
  26. package/lib/mcp-client.js +926 -0
  27. package/lib/memory-cli.js +66 -0
  28. package/lib/memory-tracker.js +1472 -0
  29. package/lib/memory.js +1279 -0
  30. package/lib/people-cli.js +81 -0
  31. package/lib/people.js +534 -0
  32. package/lib/permissions.js +272 -0
  33. package/lib/providers.js +1572 -0
  34. package/lib/runtime.js +928 -0
  35. package/lib/sandbox.js +744 -0
  36. package/lib/scheduler.js +402 -0
  37. package/lib/scroll.js +1225 -0
  38. package/lib/skill-cli.js +120 -0
  39. package/lib/skill-eval.js +156 -0
  40. package/lib/skills.js +860 -0
  41. package/lib/style.js +126 -0
  42. package/lib/tool-retriever.js +489 -0
  43. package/lib/tools.js +1833 -0
  44. package/lib/user.js +711 -0
  45. package/lib/vault.js +151 -0
  46. package/package.json +88 -4
  47. package/templates/agent/IDENTITY.md +56 -0
  48. package/templates/agent/SOUL.md +23 -0
  49. package/templates/agent/TOOLS.md +25 -0
  50. package/templates/agent/evals/case-02-citation-discipline.md +29 -0
  51. package/templates/agent/evals/case-03-boundary.md +27 -0
  52. package/templates/agent/evals/case-example.md +43 -0
  53. package/templates/agent/hard-rules.md +11 -0
  54. package/templates/agent/memory/lessons.md +5 -0
  55. package/templates/agent/memory/log/.gitkeep +0 -0
  56. package/templates/external-safety-contract.md +5 -0
  57. package/templates/long-task-planner.md +17 -0
  58. package/templates/work/LOOP.md +37 -0
  59. package/templates/work/WORK.md +50 -0
  60. package/types/chat.d.ts +61 -0
  61. package/types/index.d.ts +112 -0
@@ -0,0 +1,222 @@
1
+ // SCROLL 2.5 -- `@agentpro/scroll/chat` Channel-Agnostic Chat Harness SDK.
2
+ //
3
+ // Unites ChatSessionRuntime, channel-agnostic 3-axis MemoryTracker, Knowledge Retrieval,
4
+ // §47.2 Tool Registry + MCP Manager, Burst Debouncer, Room-Agnostic Group Grants,
5
+ // Long-Task Runner, and pure-JSON AdminController -- with zero channel lock-in and
6
+ // optional dependency-injected `voiceHooks`.
7
+ import path from 'node:path';
8
+ import { pickProvider } from '../providers.js';
9
+ import { openKnowledge } from '../knowledge.js';
10
+ import { createScopedMemoryTracker, buildScopedMemoryPolicy } from '../memory-tracker.js';
11
+ import { createMcpManager } from '../mcp-client.js';
12
+ import { createToolRegistry } from '../tools.js';
13
+ import { createChatSessionRuntime } from '../chat-session.js';
14
+ import { createMessageDebouncer } from './debouncer.js';
15
+ import {
16
+ createGroupGrantStore,
17
+ DEFAULT_DELEGATED_GROUP_TOOLS,
18
+ matchesOwnerDelegationPhrase,
19
+ } from './group-grants.js';
20
+ import { createLongTaskRunner } from './long-task-runner.js';
21
+ import { createAdminController, ADMIN_CALLBACK_NAMESPACE } from './admin-controller.js';
22
+
23
+ export {
24
+ createMessageDebouncer,
25
+ createGroupGrantStore,
26
+ DEFAULT_DELEGATED_GROUP_TOOLS,
27
+ matchesOwnerDelegationPhrase,
28
+ createLongTaskRunner,
29
+ createAdminController,
30
+ ADMIN_CALLBACK_NAMESPACE,
31
+ createScopedMemoryTracker,
32
+ buildScopedMemoryPolicy,
33
+ createScopedMemoryTracker as createMemoryTracker,
34
+ buildScopedMemoryPolicy as buildMemoryPolicy,
35
+ };
36
+
37
+ export async function createScrollChatRuntime({
38
+ agentName,
39
+ deploymentDir,
40
+ stateDir,
41
+ accountId = null,
42
+ ownerIds = [],
43
+ provider = null,
44
+ providerName = 'auto',
45
+ providerOpts = {},
46
+ model = null,
47
+ effort = null,
48
+ authStore = null,
49
+ scheduler = null,
50
+ workerPool = null,
51
+ enableMemory = true,
52
+ memoryChannel = 'chat',
53
+ memoryTracker: customMemoryTracker = null,
54
+ autoSweepEveryTurns = 12,
55
+ enableTools = true,
56
+ enableMcp = false,
57
+ mcpEnforceLock = true,
58
+ mcpAutoPinLock = false,
59
+ enableSkills = true,
60
+ voiceHooks = null,
61
+ multimodalHooks = null,
62
+ hooks = null,
63
+ channelMap = null,
64
+ requestApproval = null,
65
+ webSearchFn = null,
66
+ compactAtChars = 48_000,
67
+ compactAtTokens = null,
68
+ keepRecentTurns = 12,
69
+ dateOrder = 'dmy',
70
+ budget = null,
71
+ acquireLock = true,
72
+ strictToolSupport = true,
73
+ } = {}) {
74
+ const rootDir = path.resolve(deploymentDir || process.cwd());
75
+ const absStateDir = stateDir ? path.resolve(stateDir) : null;
76
+ const effectiveAccountId = accountId || agentName;
77
+ const agentDir = path.join(rootDir, 'agents', agentName);
78
+
79
+ const activeProvider = provider || pickProvider(providerName, {
80
+ model,
81
+ effort,
82
+ authStore,
83
+ cwd: rootDir,
84
+ ...providerOpts,
85
+ });
86
+
87
+ const knowledgeIndex = openKnowledge({ cwd: rootDir });
88
+ let chat = null;
89
+ let memoryTracker = customMemoryTracker || null;
90
+ if (!memoryTracker && enableMemory && absStateDir) {
91
+ memoryTracker = createScopedMemoryTracker({
92
+ rootDir: path.join(absStateDir, 'memory', effectiveAccountId),
93
+ workdir: rootDir,
94
+ agentDir,
95
+ ownerIds,
96
+ channel: memoryChannel,
97
+ autoSweepEveryTurns,
98
+ workerPool,
99
+ onSweepRequest: async ({ sid, sessionId, axis }) => {
100
+ if (!memoryTracker) return { ok: false, skipped: true };
101
+ return memoryTracker.runLlmSweep({
102
+ sid,
103
+ sessionId,
104
+ axis,
105
+ provider: activeProvider,
106
+ model,
107
+ });
108
+ },
109
+ onScrubExternal: ({ chatId, needles }) => {
110
+ try { chat?.scrubHistory?.(chatId, needles); } catch { /* ignore */ }
111
+ },
112
+ onReloadAgent: () => {
113
+ try { chat?.reload?.(); } catch { /* ignore */ }
114
+ },
115
+ });
116
+ }
117
+ const memoryStore = memoryTracker ? memoryTracker.store : null;
118
+
119
+ let tools = null;
120
+ let mcpManager = null;
121
+ let mcpStartupError = null;
122
+ if (enableMcp) {
123
+ try {
124
+ mcpManager = createMcpManager({
125
+ cwd: rootDir,
126
+ agentDir,
127
+ enforceLock: mcpEnforceLock,
128
+ autoPinLock: mcpAutoPinLock,
129
+ onToolsChanged: () => {
130
+ try { tools?.syncMcpTools?.(); } catch { /* ignore */ }
131
+ },
132
+ });
133
+ await mcpManager.connectAll();
134
+ } catch (err) {
135
+ mcpStartupError = String(err?.message || err);
136
+ mcpManager = null;
137
+ }
138
+ }
139
+
140
+ tools = enableTools
141
+ ? createToolRegistry({
142
+ cwd: rootDir,
143
+ agentDir,
144
+ memoryStore,
145
+ knowledgeIndex,
146
+ scheduler,
147
+ workerPool,
148
+ mcpManager,
149
+ requestApproval,
150
+ webSearchFn,
151
+ spillDir: absStateDir ? path.join(absStateDir, 'scratch') : null,
152
+ })
153
+ : null;
154
+ if (tools && memoryTracker && typeof memoryTracker.registerTools === 'function') {
155
+ memoryTracker.registerTools(tools);
156
+ }
157
+ if (tools && mcpManager) {
158
+ try {
159
+ await Promise.resolve(tools.syncMcpTools());
160
+ } catch (err) {
161
+ mcpStartupError = mcpStartupError || String(err?.message || err);
162
+ }
163
+ }
164
+
165
+ chat = createChatSessionRuntime({
166
+ agentName,
167
+ cwd: rootDir,
168
+ deploymentDir: rootDir,
169
+ stateDir: absStateDir,
170
+ provider: activeProvider,
171
+ model,
172
+ authStore,
173
+ tools,
174
+ enableSkills,
175
+ voiceHooks,
176
+ memoryStore,
177
+ memoryTracker,
178
+ knowledgeIndex,
179
+ scheduler,
180
+ workerPool,
181
+ multimodalHooks,
182
+ hooks,
183
+ channelMap,
184
+ compactAtChars,
185
+ compactAtTokens,
186
+ keepRecentTurns,
187
+ dateOrder,
188
+ budget,
189
+ acquireLock,
190
+ strictToolSupport,
191
+ });
192
+
193
+ if (mcpStartupError && chat?.events?.emit) {
194
+ chat.events.emit('mcp.startup_error', { agentName, error: mcpStartupError });
195
+ }
196
+
197
+ async function close() {
198
+ try { memoryTracker?.flushRegistry?.(); } catch { /* ignore */ }
199
+ if (mcpManager) await mcpManager.closeAll().catch(() => {});
200
+ await chat.close();
201
+ }
202
+
203
+ return {
204
+ agentName,
205
+ accountId: effectiveAccountId,
206
+ chat,
207
+ tools,
208
+ mcpManager,
209
+ mcpStartupError,
210
+ memoryStore,
211
+ memoryTracker,
212
+ knowledgeIndex,
213
+ provider: activeProvider,
214
+ reload: () => chat.reload(),
215
+ sendTurn: (opts) => chat.sendTurn(opts),
216
+ abortTurn: (convId) => chat.abortTurn(convId),
217
+ getHistory: (convId) => chat.getHistory(convId),
218
+ clearSession: (convId) => chat.clearSession(convId),
219
+ forkSession: (src, dst, opts) => chat.forkSession(src, dst, opts),
220
+ close,
221
+ };
222
+ }
@@ -0,0 +1,413 @@
1
+ // SCROLL 2.5 -- Channel-Agnostic §50 Multi-Step Background Long-Task Runner.
2
+ // Runs multi-step autonomous workflows asynchronously via `WorkerPool` without blocking live chat.
3
+ // Prompt instructions are loaded from `templates/long-task-planner.md` (Rule 3: zero hardcoded prose).
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import crypto from 'node:crypto';
7
+ import { fileURLToPath } from 'node:url';
8
+
9
+ const __filename = fileURLToPath(import.meta.url);
10
+ const __dirname = path.dirname(__filename);
11
+
12
+ let cachedTemplate = null;
13
+ function loadPlannerSections() {
14
+ if (cachedTemplate) return cachedTemplate;
15
+ const tplPath = path.resolve(__dirname, '..', '..', 'templates', 'long-task-planner.md');
16
+ let raw = '';
17
+ try { raw = fs.readFileSync(tplPath, 'utf8'); } catch { raw = ''; }
18
+ const section = (heading) => {
19
+ const re = new RegExp(`(?:^|\\n)##\\s+${heading}\\s*\\n([\\s\\S]*?)(?=\\n##\\s|$)`, 'i');
20
+ const m = raw.match(re);
21
+ return m ? m[1].trim() : '';
22
+ };
23
+ cachedTemplate = {
24
+ step1: section('Step 1 Instructions'),
25
+ cont: section('Continuation Instructions'),
26
+ synth: section('Final Synthesis Instructions'),
27
+ };
28
+ return cachedTemplate;
29
+ }
30
+
31
+ function interpolate(tpl, vars) {
32
+ return String(tpl || '').replace(/\{\{(\w+)\}\}/g, (_, k) => String(vars[k] ?? ''));
33
+ }
34
+
35
+ export function createLongTaskRunner({
36
+ stateDir = null,
37
+ workerPool,
38
+ channel = 'chat',
39
+ defaultDelegatedTools = null,
40
+ defaultToolsAllow = null,
41
+ stepPromptBuilder = null,
42
+ synthesisPromptBuilder = null,
43
+ onProgress = null,
44
+ onComplete = null,
45
+ maxDefaultSteps = 12,
46
+ maxDefaultMinutes = 20,
47
+ } = {}) {
48
+ if (!workerPool || typeof workerPool.submit !== 'function') {
49
+ throw new Error('createLongTaskRunner: workerPool is required');
50
+ }
51
+ const tasksDir = stateDir ? path.join(path.resolve(stateDir), 'long-tasks') : null;
52
+ if (tasksDir) fs.mkdirSync(tasksDir, { recursive: true, mode: 0o700 });
53
+
54
+ const tasks = new Map();
55
+
56
+ function saveTask(t) {
57
+ if (!tasksDir) return;
58
+ const p = path.join(tasksDir, `${t.id}.json`);
59
+ const tmp = `${p}.tmp.${process.pid}`;
60
+ fs.writeFileSync(tmp, JSON.stringify(t, null, 2) + '\n', { mode: 0o600 });
61
+ fs.renameSync(tmp, p);
62
+ }
63
+
64
+ function snapshot(t) {
65
+ return {
66
+ id: t.id,
67
+ botId: t.botId,
68
+ chatId: t.chatId,
69
+ roomId: t.chatId,
70
+ isGroup: Boolean(t.isGroup),
71
+ channel: t.channel,
72
+ title: t.title,
73
+ goal: t.goal,
74
+ status: t.status,
75
+ step: t.step,
76
+ maxSteps: t.maxSteps,
77
+ maxMinutes: t.maxMinutes,
78
+ startedAt: t.startedAt,
79
+ updatedAt: t.updatedAt,
80
+ finishedAt: t.finishedAt,
81
+ stepsLog: [...t.stepsLog],
82
+ finalReport: t.finalReport,
83
+ error: t.error,
84
+ };
85
+ }
86
+
87
+ function startTask({
88
+ bot = null,
89
+ runtime = null,
90
+ botId = null,
91
+ chatId = null,
92
+ roomId = null,
93
+ isGroup = false,
94
+ channel: taskChannel = channel,
95
+ sender = null,
96
+ title = 'Long Task',
97
+ goal,
98
+ maxSteps = maxDefaultSteps,
99
+ maxMinutes = maxDefaultMinutes,
100
+ delegatedTools = defaultDelegatedTools,
101
+ toolsAllow = defaultToolsAllow,
102
+ reportEverySteps = 3,
103
+ model = null,
104
+ effort = null,
105
+ } = {}) {
106
+ const activeRuntime = runtime || bot?.runtime;
107
+ if (!activeRuntime || typeof activeRuntime.sendTurn !== 'function') {
108
+ throw new Error('longTask.startTask: runtime (or bot.runtime) with sendTurn is required');
109
+ }
110
+ if (!goal || !String(goal).trim()) throw new Error('longTask.startTask: goal is required');
111
+
112
+ const id = `lt_${crypto.randomBytes(4).toString('hex')}`;
113
+ const boundedSteps = Math.max(1, Math.min(30, Number(maxSteps || maxDefaultSteps)));
114
+ const boundedMins = Math.max(1, Math.min(45, Number(maxMinutes || maxDefaultMinutes)));
115
+ const nowIso = new Date().toISOString();
116
+ const targetRoom = String(roomId ?? chatId ?? 'default');
117
+
118
+ const task = {
119
+ id,
120
+ botId: botId || bot?.id || activeRuntime.agentName || 'default',
121
+ chatId: targetRoom,
122
+ isGroup: Boolean(isGroup),
123
+ channel: String(taskChannel || 'chat'),
124
+ title: String(title || 'Long Task').slice(0, 120),
125
+ goal: String(goal).trim().slice(0, 4000),
126
+ status: 'queued',
127
+ step: 0,
128
+ maxSteps: boundedSteps,
129
+ maxMinutes: boundedMins,
130
+ startedAt: nowIso,
131
+ updatedAt: nowIso,
132
+ finishedAt: null,
133
+ stepsLog: [],
134
+ finalReport: null,
135
+ error: null,
136
+ workerJobId: null,
137
+ };
138
+ tasks.set(id, task);
139
+ saveTask(task);
140
+
141
+ const tpl = loadPlannerSections();
142
+
143
+ const job = workerPool.submit({
144
+ id: `wk_${id}`,
145
+ label: `long-task:${task.title}`,
146
+ chatId: task.chatId,
147
+ fn: async ({ signal }) => {
148
+ const deadlineMs = Date.now() + boundedMins * 60_000;
149
+ task.status = 'running';
150
+ task.updatedAt = new Date().toISOString();
151
+ saveTask(task);
152
+
153
+ const convId = `longtask:${id}`;
154
+ let stalledSteps = 0;
155
+ try {
156
+ for (let step = 1; step <= boundedSteps; step++) {
157
+ if (signal.aborted) throw Object.assign(new Error('cancelled'), { name: 'AbortError' });
158
+ if (Date.now() >= deadlineMs) {
159
+ task.stepsLog.push({ step, ts: new Date().toISOString(), summary: 'Reached time ceiling; synthesizing final report.' });
160
+ break;
161
+ }
162
+ task.step = step;
163
+ task.updatedAt = new Date().toISOString();
164
+ saveTask(task);
165
+
166
+ const vars = {
167
+ taskId: id,
168
+ step,
169
+ maxSteps: boundedSteps,
170
+ maxMinutes: boundedMins,
171
+ title: task.title,
172
+ goal: task.goal,
173
+ };
174
+ const stepPrompt = typeof stepPromptBuilder === 'function'
175
+ ? stepPromptBuilder(vars)
176
+ : interpolate(step === 1 ? tpl.step1 : tpl.cont, vars);
177
+
178
+ // Strip recursive long-task launch tools inside background steps
179
+ const stepToolsAllow = Array.isArray(toolsAllow)
180
+ ? toolsAllow.filter((t) => t !== 'start_long_task')
181
+ : toolsAllow;
182
+ const stepDelegatedTools = Array.isArray(delegatedTools)
183
+ ? delegatedTools.filter((t) => t !== 'start_long_task')
184
+ : delegatedTools;
185
+
186
+ const turn = await activeRuntime.sendTurn({
187
+ conversationId: convId,
188
+ text: stepPrompt,
189
+ sender,
190
+ // NEVER downgrade group boundary to `isGroup: false` (prevents leaking Owner USER.md/memory into group!)
191
+ isGroup: Boolean(task.isGroup),
192
+ channel: task.channel,
193
+ model: model || bot?.model,
194
+ effort: effort || bot?.effort || 'low',
195
+ delegatedTools: stepDelegatedTools,
196
+ toolsAllow: stepToolsAllow,
197
+ // NEVER pre-approve financial/destructive calls; each call must pass normal HITL approval!
198
+ signal,
199
+ });
200
+
201
+ const outText = String(turn.text || '').trim();
202
+ const isDone = /(?:^|\n)\s*TASK_DONE\s*$/i.test(outText);
203
+ const isBlocked = /(?:^|\n)\s*TASK_BLOCKED\s*$/i.test(outText);
204
+ const cleanOut = outText.replace(/(?:^|\n)\s*TASK_(?:DONE|BLOCKED)\s*$/i, '').trim();
205
+ const toolsUsed = (turn.toolTraces || []).map((tr) => tr.name);
206
+ task.stepsLog.push({
207
+ step,
208
+ ts: new Date().toISOString(),
209
+ toolsUsed,
210
+ summary: cleanOut.slice(0, 600),
211
+ });
212
+ task.updatedAt = new Date().toISOString();
213
+ saveTask(task);
214
+
215
+ if (isDone) {
216
+ task.finalReport = cleanOut;
217
+ break;
218
+ }
219
+ if (isBlocked) {
220
+ task.status = 'blocked';
221
+ task.error = cleanOut;
222
+ task.finishedAt = new Date().toISOString();
223
+ task.updatedAt = task.finishedAt;
224
+ saveTask(task);
225
+ if (typeof onComplete === 'function') await Promise.resolve(onComplete(snapshot(task))).catch(() => {});
226
+ return snapshot(task);
227
+ }
228
+ if (toolsUsed.length === 0) stalledSteps += 1;
229
+ else stalledSteps = 0;
230
+ if (stalledSteps >= 2) {
231
+ task.status = 'blocked';
232
+ task.error = cleanOut || 'stalled_without_tool_progress';
233
+ task.finishedAt = new Date().toISOString();
234
+ task.updatedAt = task.finishedAt;
235
+ saveTask(task);
236
+ if (typeof onComplete === 'function') await Promise.resolve(onComplete(snapshot(task))).catch(() => {});
237
+ return snapshot(task);
238
+ }
239
+ if (typeof onProgress === 'function' && step % Math.max(1, Number(reportEverySteps || 3)) === 0 && step < boundedSteps) {
240
+ await Promise.resolve(onProgress(snapshot(task), cleanOut)).catch(() => {});
241
+ }
242
+ }
243
+
244
+ if (!task.finalReport) {
245
+ const synthPrompt = typeof synthesisPromptBuilder === 'function'
246
+ ? synthesisPromptBuilder({ taskId: id, title: task.title, goal: task.goal })
247
+ : interpolate(tpl.synth, { taskId: id, title: task.title, goal: task.goal });
248
+ const synth = await activeRuntime.sendTurn({
249
+ conversationId: convId,
250
+ text: synthPrompt,
251
+ sender,
252
+ isGroup: Boolean(task.isGroup),
253
+ channel: task.channel,
254
+ model: model || bot?.model,
255
+ effort: 'low',
256
+ toolsAllow: [],
257
+ signal,
258
+ });
259
+ task.finalReport = String(synth.text || '').trim() || task.stepsLog.map((s) => `Step ${s.step}: ${s.summary}`).join('\n');
260
+ }
261
+
262
+ task.status = 'completed';
263
+ task.finishedAt = new Date().toISOString();
264
+ task.updatedAt = task.finishedAt;
265
+ saveTask(task);
266
+ if (typeof onComplete === 'function') await Promise.resolve(onComplete(snapshot(task))).catch(() => {});
267
+ return snapshot(task);
268
+ } catch (err) {
269
+ task.status = signal.aborted ? 'cancelled' : 'failed';
270
+ task.error = String(err?.message || err);
271
+ task.finishedAt = new Date().toISOString();
272
+ task.updatedAt = task.finishedAt;
273
+ saveTask(task);
274
+ if (typeof onComplete === 'function') await Promise.resolve(onComplete(snapshot(task))).catch(() => {});
275
+ return snapshot(task);
276
+ }
277
+ },
278
+ });
279
+
280
+ task.workerJobId = job.id;
281
+ saveTask(task);
282
+ return snapshot(task);
283
+ }
284
+
285
+ function getTask(taskId) {
286
+ const t = tasks.get(taskId);
287
+ return t ? snapshot(t) : null;
288
+ }
289
+
290
+ function listTasks({ chatId = null, roomId = null, status = null } = {}) {
291
+ const filterRoom = roomId ?? chatId;
292
+ return [...tasks.values()]
293
+ .filter((t) => (!filterRoom || t.chatId === String(filterRoom)) && (!status || t.status === status))
294
+ .sort((a, b) => String(b.startedAt).localeCompare(String(a.startedAt)))
295
+ .map(snapshot);
296
+ }
297
+
298
+ function cancelTask(taskId) {
299
+ const t = tasks.get(taskId);
300
+ if (!t) return { ok: false, reason: 'task_not_found' };
301
+ if (t.workerJobId) workerPool.cancel(t.workerJobId);
302
+ t.status = 'cancelled';
303
+ t.finishedAt = new Date().toISOString();
304
+ t.updatedAt = t.finishedAt;
305
+ saveTask(t);
306
+ return { ok: true, id: taskId, status: 'cancelled' };
307
+ }
308
+
309
+ function registerTools({
310
+ tools,
311
+ bot = null,
312
+ runtime = null,
313
+ ownerIds = [],
314
+ groupGrants = null,
315
+ channel: toolChannel = channel,
316
+ delegatedTools = defaultDelegatedTools,
317
+ toolsAllow = defaultToolsAllow,
318
+ } = {}) {
319
+ const ownerSet = new Set((ownerIds || []).map(String));
320
+ const canLaunch = (ctx) => {
321
+ const rawId = String(ctx.sender?.id || ctx.sender?.channelId || '');
322
+ const stripped = rawId.replace(/^[a-z0-9_-]+:/i, '');
323
+ if ((rawId && ownerSet.has(rawId)) || (stripped && ownerSet.has(stripped))) return true;
324
+ if (ctx.chatId && groupGrants) {
325
+ const g = groupGrants.getActiveGrant(ctx.chatId);
326
+ if (g && g.allowedTools.includes('start_long_task')) return true;
327
+ }
328
+ return false;
329
+ };
330
+
331
+ tools.register({
332
+ name: 'start_long_task',
333
+ description: 'Start a non-blocking multi-step background long task (up to 30 steps / 45 min). Reports progress and sends a final summary when done.',
334
+ risk: 'external_comm',
335
+ parameters: {
336
+ type: 'object',
337
+ properties: {
338
+ title: { type: 'string', description: 'Short task title' },
339
+ goal: { type: 'string', description: 'Detailed goal and step plan for the autonomous loop' },
340
+ maxSteps: { type: 'number', description: 'Max autonomous iterations (1-30, default 10)' },
341
+ maxMinutes: { type: 'number', description: 'Max wall-clock minutes (1-45, default 15)' },
342
+ },
343
+ required: ['title', 'goal'],
344
+ },
345
+ async execute(args, ctx) {
346
+ if (String(ctx.chatId || '').startsWith('longtask:')) {
347
+ return { ok: false, error: 'recursive_long_task_not_allowed' };
348
+ }
349
+ if (!canLaunch(ctx)) return { ok: false, error: 'owner_or_active_group_grant_required' };
350
+ const activeGrant = ctx.chatId && groupGrants ? groupGrants.getActiveGrant(ctx.chatId) : null;
351
+ const t = startTask({
352
+ bot,
353
+ runtime,
354
+ chatId: ctx.chatId || ownerIds[0] || 'default',
355
+ isGroup: Boolean(ctx.turnClassification?.isGroup),
356
+ channel: toolChannel,
357
+ sender: ctx.sender || (ownerIds[0] ? { id: ownerIds[0], name: 'Owner' } : null),
358
+ title: args.title,
359
+ goal: args.goal,
360
+ maxSteps: args.maxSteps || 10,
361
+ maxMinutes: args.maxMinutes || 15,
362
+ delegatedTools: activeGrant ? activeGrant.allowedTools : delegatedTools,
363
+ toolsAllow,
364
+ });
365
+ return {
366
+ ok: true,
367
+ taskId: t.id,
368
+ status: t.status,
369
+ maxSteps: t.maxSteps,
370
+ maxMinutes: t.maxMinutes,
371
+ note: 'Long task started in background; progress and final report will be delivered automatically.',
372
+ };
373
+ },
374
+ });
375
+
376
+ tools.register({
377
+ name: 'long_task_status',
378
+ description: 'Check status and recent step log of background long tasks.',
379
+ risk: 'read_only',
380
+ parameters: {
381
+ type: 'object',
382
+ properties: { taskId: { type: 'string' } },
383
+ },
384
+ async execute(args, ctx) {
385
+ if (args.taskId) return { ok: true, task: getTask(args.taskId) };
386
+ return { ok: true, tasks: listTasks({ chatId: ctx.chatId || null }).slice(0, 10) };
387
+ },
388
+ });
389
+
390
+ tools.register({
391
+ name: 'cancel_long_task',
392
+ description: 'Cancel a running background long task by taskId.',
393
+ risk: 'reversible_write',
394
+ parameters: {
395
+ type: 'object',
396
+ properties: { taskId: { type: 'string' } },
397
+ required: ['taskId'],
398
+ },
399
+ async execute(args, ctx) {
400
+ if (!canLaunch(ctx)) return { ok: false, error: 'owner_or_active_group_grant_required' };
401
+ return cancelTask(args.taskId);
402
+ },
403
+ });
404
+ }
405
+
406
+ return {
407
+ startTask,
408
+ getTask,
409
+ listTasks,
410
+ cancelTask,
411
+ registerTools,
412
+ };
413
+ }