clawlet 0.2.1 → 0.4.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/src/agent.ts CHANGED
@@ -1,27 +1,25 @@
1
1
  import {
2
- tool,
3
- addToolInputExamplesMiddleware,
4
2
  streamText,
5
- generateText,
6
- wrapLanguageModel,
7
3
  stepCountIs,
8
- jsonSchema,
9
4
  type ModelMessage,
10
- extractReasoningMiddleware,
11
- type ToolSet,
5
+ type LanguageModel,
12
6
  } from 'ai';
13
- import { createOpenAICompatible } from '@ai-sdk/openai-compatible';
14
7
  import 'dotenv/config';
15
- import { hermesToolMiddleware } from '@ai-sdk-tool/parser';
16
8
  import { AgentMemory } from './memory.js';
17
- import { readFile, writeFile, copyFile, access, mkdir } from 'node:fs/promises';
9
+ import { readFile, copyFile, access, mkdir } from 'node:fs/promises';
18
10
  import path from 'path';
19
11
  import { fileURLToPath } from 'node:url';
12
+ import { logger } from './logger.js';
13
+ import { createTools } from './tools.js';
20
14
 
21
15
  // Resolve the package root directory (where template/ lives), independent of cwd
22
16
  const __filename = fileURLToPath(import.meta.url);
23
17
  const __dirname = path.dirname(__filename);
24
18
  const PACKAGE_ROOT = path.resolve(__dirname, '..');
19
+ const GENERATE_TEXT_TEMPERATURE = 0.6;
20
+ const GENERATE_TEXT_TOP_P = 0.95;
21
+ const GENERATE_TEXT_MAX_OUTPUT_TOKENS = 16384;
22
+ const GENERATE_TEXT_MAX_STEPS = 30;
25
23
 
26
24
  // --- ADAPTER INTERFACES ---
27
25
 
@@ -37,65 +35,12 @@ export interface OutputAdapter {
37
35
  onError(error: Error): void;
38
36
  }
39
37
 
40
- // --- MODEL SETUP ---
41
- const localProvider = createOpenAICompatible({
42
- name: 'mlx',
43
- baseURL: 'http://localhost:8000/v1',
44
- });
45
-
46
- const localModel = wrapLanguageModel({
47
- model: localProvider.languageModel('qwen-local'),
48
- middleware: [
49
- hermesToolMiddleware,
50
- addToolInputExamplesMiddleware({
51
- prefix: 'Input Examples:',
52
- }),
53
- extractReasoningMiddleware({
54
- tagName: "think"
55
- })
56
- ]
57
- });
58
-
59
38
  // --- HELPERS ---
60
39
 
61
40
  function getTodayString(): string {
62
41
  return new Date().toISOString().split('T')[0] ?? '';
63
42
  }
64
43
 
65
- // --- SETTINGS HELPERS ---
66
-
67
- const SETTINGS_PATH = `${process.cwd()}/settings.json`;
68
-
69
- interface ConnectionBearer {
70
- idToken: string;
71
- refreshToken?: string;
72
- refreshUrl?: string;
73
- }
74
-
75
- interface ConnectionEntry {
76
- bearer: ConnectionBearer;
77
- }
78
-
79
- interface SettingsFile {
80
- connections: Record<string, ConnectionEntry>;
81
- }
82
-
83
- async function readSettings(): Promise<SettingsFile> {
84
- try {
85
- const raw = await readFile(SETTINGS_PATH, 'utf-8');
86
- const parsed = JSON.parse(raw);
87
- if (parsed && typeof parsed === 'object') {
88
- if (!parsed.connections) parsed.connections = {};
89
- return parsed as SettingsFile;
90
- }
91
- } catch {}
92
- return { connections: {} };
93
- }
94
-
95
- async function writeSettings(settings: SettingsFile): Promise<void> {
96
- await writeFile(SETTINGS_PATH, JSON.stringify(settings, null, 2), 'utf-8');
97
- }
98
-
99
44
  // --- SYSTEM PROMPT BUILDER ---
100
45
 
101
46
  async function buildSystemPrompt(memory: AgentMemory): Promise<string> {
@@ -159,7 +104,8 @@ You must obey these rules above all else.
159
104
  - Use \`connection.request\` for authenticated API calls (Bearer token is auto-injected).
160
105
 
161
106
  3. **EXECUTION**:
162
- - Use \`fs.readFile\` and \`fs.writeFile\` to log *significant* events to append oday's memory file (as per AGENTS.md rules).
107
+ - Use \`fs.readFile\` and \`fs.writeFile\` to log *significant* events to append today's memory file (as per AGENTS.md rules).
108
+ - Make sure to use valid JSON when generating tool_call xml tags.
163
109
  - **Text > Brain**: If you learn something, write it down immediately.
164
110
 
165
111
  # AVAILABLE WORKSPACE (Files)
@@ -170,870 +116,12 @@ ${agentsDoc}
170
116
  `;
171
117
  }
172
118
 
173
- // --- PERMISSION HELPERS ---
174
-
175
- function matchesPermissionPattern(actual: string, pattern: string): boolean {
176
- const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*');
177
- return new RegExp(`^${escaped}$`).test(actual);
178
- }
179
-
180
- function createSandboxedTools(
181
- allTools: ReturnType<typeof createTools>,
182
- permissions: Record<string, Array<Record<string, string>>>
183
- ): Record<string, any> {
184
- const sandboxed: Record<string, any> = {};
185
-
186
- Object.entries(permissions).forEach(([toolName, rules]) => {
187
- const hasAllowed = rules.some((r: any) => r.allowed === 'true' || r.allowed === true);
188
- if (!hasAllowed) return;
189
-
190
- const originalTool = (allTools as any)[toolName];
191
- if (!originalTool) return;
192
-
193
- sandboxed[toolName] = tool({
194
- description: originalTool.description,
195
- inputSchema: originalTool.inputSchema,
196
- execute: async (args: any) => {
197
- for (const key in args) {
198
- if (!rules.some(r => matchesPermissionPattern(args[key], r[key] || '*'))) {
199
- console.log(` 🚫 Permission denied: ${key} not allowed for this skill with value ${args[key]}. ${JSON.stringify(args)} for permission: ${JSON.stringify(rules)}`);
200
-
201
- return JSON.stringify({ error: `Permission denied: ${key} not allowed for this skill with value ${args[key]}.` });
202
- }
203
- };
204
- return originalTool.execute(args);
205
- },
206
- });
207
- });
208
-
209
-
210
- return sandboxed;
211
- }
212
-
213
- // --- TOOLS (built from memory) ---
214
-
215
- function createTools(memory: AgentMemory) {
216
- return {
217
- now: tool({
218
- description: 'Get current time and date',
219
- execute: async () => {
220
- return new Date().toISOString();
221
- }
222
- }),
223
-
224
- 'http.request': tool({
225
- description: 'Execute HTTP requests. Provide method (GET/POST/PUT/DELETE), url, optional headers object, and optional unescaped body string. Returns status, statusText and data.',
226
- inputSchema: jsonSchema({
227
- type: 'object',
228
- properties: {
229
- method: { type: 'string', enum: ['GET', 'POST', 'PUT', 'DELETE'], description: 'HTTP method' },
230
- url: { type: 'string', description: 'URL to request' },
231
- headers: { type: 'object', additionalProperties: { type: 'string' }, description: 'Optional headers' },
232
- body: { type: 'string', description: 'Optional unescaped body string' },
233
- },
234
- required: ['url'],
235
- }),
236
- execute: async ({ method, url, headers, body }: { method?: string, url: string, headers?: Record<string, string>, body?: string }) => {
237
- const executeMethod = method ? method : 'GET';
238
- console.log(` 🌐 [HTTP] ${executeMethod} ${url}`);
239
- try {
240
- let parsedBody = body;
241
- if (typeof body === 'string') {
242
- try { parsedBody = JSON.parse(body); } catch {}
243
- }
244
-
245
- const res = await fetch(url, {
246
- method: executeMethod,
247
- headers: { 'Content-Type': 'application/json', ...headers },
248
- body: parsedBody ? JSON.stringify(parsedBody) : null
249
- });
250
-
251
- const text = await res.text();
252
- return JSON.stringify({
253
- status: res.status,
254
- statusText: res.statusText,
255
- data: text.length > 2000 ? text.substring(0, 2000) + "..." : text
256
- });
257
- } catch (e: any) { return JSON.stringify({ error: e.message }); }
258
- },
259
- }),
260
-
261
- 'http.get': tool({
262
- description: 'Shortcut for GET requests. Provide url and optional headers.',
263
- inputSchema: jsonSchema({
264
- type: 'object',
265
- properties: {
266
- url: { type: 'string', description: 'URL to request' },
267
- headers: { type: 'object', additionalProperties: { type: 'string' }, description: 'Optional headers' },
268
- },
269
- required: ['url'],
270
- }),
271
- execute: async ({ url, headers }: { url: string, headers?: Record<string, string> }) => {
272
- console.log(` 🌐 [HTTP] GET ${url}`);
273
- try {
274
- const res = await fetch(url, {
275
- headers: { 'Content-Type': 'application/json', ...headers },
276
- });
277
- const text = await res.text();
278
- return JSON.stringify({
279
- status: res.status,
280
- statusText: res.statusText,
281
- data: text.length > 2000 ? text.substring(0, 2000) + "..." : text
282
- });
283
- } catch (e: any) { return JSON.stringify({ error: e.message }); }
284
- },
285
- }),
286
-
287
- 'http.post': tool({
288
- description: 'Shortcut for POST requests. Provide url, optional unescaped body string, and optional headers.',
289
- inputSchema: jsonSchema({
290
- type: 'object',
291
- properties: {
292
- url: { type: 'string', description: 'URL to request' },
293
- body: { type: 'string', description: 'Optional unescaped body string' },
294
- headers: { type: 'object', additionalProperties: { type: 'string' }, description: 'Optional headers' },
295
- },
296
- required: ['url'],
297
- }),
298
- execute: async ({ url, body, headers }: { url: string, body?: string, headers?: Record<string, string> }) => {
299
- console.log(` 🌐 [HTTP] POST ${url}`);
300
- try {
301
- let parsedBody = body;
302
- if (typeof body === 'string') {
303
- try { parsedBody = JSON.parse(body); } catch {}
304
- }
305
- const res = await fetch(url, {
306
- method: 'POST',
307
- headers: { 'Content-Type': 'application/json', ...headers },
308
- body: parsedBody ? JSON.stringify(parsedBody) : null
309
- });
310
- const text = await res.text();
311
- console.log(` -> ${res.status}`);
312
- return JSON.stringify({
313
- status: res.status,
314
- statusText: res.statusText,
315
- data: text.length > 2000 ? text.substring(0, 2000) + "..." : text
316
- });
317
- } catch (e: any) { return JSON.stringify({ error: e.message }); }
318
- },
319
- }),
320
-
321
- 'http.download': tool({
322
- description: 'Download a file from a URL and save it to the workspace. Provide url and an optional filename (defaults to the last path segment of the URL).',
323
- inputSchema: jsonSchema({
324
- type: 'object',
325
- properties: {
326
- url: { type: 'string', description: 'URL to download from' },
327
- filename: { type: 'string', description: 'Filename to save as in the workspace' },
328
- },
329
- required: ['url'],
330
- }),
331
- execute: async ({ url, filename }: { url: string, filename?: string }) => {
332
- const name = filename || url.split('/').pop() || 'download';
333
- console.log(` ⬇️ [HTTP] download ${url} -> ${name}`);
334
- try {
335
- const res = await fetch(url);
336
- if (!res.ok) return JSON.stringify({ error: `HTTP ${res.status} ${res.statusText}` });
337
-
338
- const buffer = await res.arrayBuffer();
339
- const content = Buffer.from(buffer);
340
-
341
- // Store as base64 for binary files, as string for text
342
- const contentType = res.headers.get('content-type') || '';
343
- if (contentType.includes('text') || contentType.includes('json') || contentType.includes('xml')) {
344
- await memory.workspace.setItem(name, new TextDecoder().decode(content));
345
- } else {
346
- await memory.workspace.setItemRaw(name, content);
347
- }
348
-
349
- return JSON.stringify({
350
- status: res.status,
351
- filename: name,
352
- size: content.byteLength,
353
- contentType,
354
- });
355
- } catch (e: any) { return JSON.stringify({ error: e.message }); }
356
- },
357
- }),
358
-
359
- 'kv.set': tool({
360
- description: 'Store a key-value pair (e.g. API keys, config). Provide "key" and "value".',
361
- inputSchema: jsonSchema({
362
- type: 'object',
363
- properties: {
364
- key: { type: 'string', description: 'The key to store' },
365
- value: { type: 'string', description: 'The value to store' },
366
- },
367
- required: ['key', 'value'],
368
- }),
369
- execute: async ({ key, value }: { key: string, value: string }) => {
370
- console.log(` 🔑 [KV] set ${key}`);
371
- try {
372
- await memory.secrets.set(key, value);
373
- return `Success: Saved ${key}.`;
374
- } catch (e: any) { return `Error: ${e.message}`; }
375
- },
376
- }),
377
-
378
- 'kv.get': tool({
379
- description: 'Retrieve a value by key from the key-value store.',
380
- inputSchema: jsonSchema({
381
- type: 'object',
382
- properties: {
383
- key: { type: 'string', description: 'The key to retrieve' },
384
- },
385
- required: ['key'],
386
- }),
387
- execute: async ({ key }: { key: string }) => {
388
- console.log(` 🔑 [KV] get ${key}`);
389
- try {
390
- const result = await memory.secrets.get(key);
391
- return result ?? "NOT_FOUND";
392
- } catch (e: any) { return `Error: ${e.message}`; }
393
- }
394
- }),
395
-
396
- 'kv.list': tool({
397
- description: 'List all keys in the key-value store.',
398
- execute: async () => {
399
- console.log(` 🔑 [KV] list`);
400
- try {
401
- const keys = await memory.secrets.listKeys();
402
- return keys.join(', ') || "EMPTY_STORE";
403
- } catch (e: any) { return `Error: ${e.message}`; }
404
- },
405
- }),
406
-
407
- 'kv.delete': tool({
408
- description: 'Delete a key from the key-value store.',
409
- inputSchema: jsonSchema({
410
- type: 'object',
411
- properties: {
412
- key: { type: 'string', description: 'The key to delete' },
413
- },
414
- required: ['key'],
415
- }),
416
- execute: async ({ key }: { key: string }) => {
417
- console.log(` 🔑 [KV] delete ${key}`);
418
- try {
419
- await memory.secrets.delete(key);
420
- return `Success: Deleted ${key}.`;
421
- } catch (e: any) { return `Error: ${e.message}`; }
422
- },
423
- }),
424
-
425
- 'kv.has': tool({
426
- description: 'Check if a key exists in the key-value store. Returns true or false.',
427
- inputSchema: jsonSchema({
428
- type: 'object',
429
- properties: {
430
- key: { type: 'string', description: 'The key to check' },
431
- },
432
- required: ['key'],
433
- }),
434
- execute: async ({ key }: { key: string }) => {
435
- console.log(` 🔑 [KV] has ${key}`);
436
- try {
437
- const exists = await memory.secrets.has(key);
438
- return exists ? "true" : "false";
439
- } catch (e: any) { return `Error: ${e.message}`; }
440
- },
441
- }),
442
-
443
- 'fs.listDir': tool({
444
- description: 'List all files in the workspace (including memory logs and skills).',
445
- execute: async () => {
446
- console.log(` 📂 [FS] listDir`);
447
- try {
448
- const keys = await memory.workspace.getKeys();
449
- return keys.join('\n') || "No files found.";
450
- } catch (e: any) { return `Error: ${e.message}`; }
451
- }
452
- }),
453
-
454
- 'fs.readFile': tool({
455
- description: 'Read a file from the workspace. "path" must be one of the keys from fs.listDir (e.g. "memory:2026-02-08.md").',
456
- inputSchema: jsonSchema({
457
- type: 'object',
458
- properties: {
459
- path: { type: 'string', description: 'Path/key of the file to read' },
460
- },
461
- required: ['path'],
462
- }),
463
- execute: async ({ path }: { path: string }) => {
464
- console.log(` 📖 [FS] readFile ${path}`);
465
- try {
466
- const content = await memory.workspace.getItem(path);
467
- if (content === null || content === undefined) return "File not found. Create it first with fs.writeFile if needed.";
468
- return String(content);
469
- } catch (e: any) { return "Error reading file: " + e.message; }
470
- }
471
- }),
472
-
473
- 'fs.writeFile': tool({
474
- description: 'Write or update a file in the workspace. "path" is the key/path (e.g. "memory:2026-02-08.md"), "content" is the full content.',
475
- inputSchema: jsonSchema({
476
- type: 'object',
477
- properties: {
478
- path: { type: 'string', description: 'Path/key of the file to write' },
479
- content: { type: 'string', description: 'Full file content' },
480
- },
481
- required: ['path', 'content'],
482
- }),
483
- execute: async ({ path, content }: { path: string, content: string }) => {
484
- console.log(` ✍️ [FS] writeFile ${path}`);
485
- try {
486
- await memory.workspace.setItem(path, content);
487
- return `Success: Wrote to ${path}`;
488
- } catch (e: any) { return "Error writing file: " + e.message; }
489
- }
490
- }),
491
-
492
- 'fs.edit': tool({
493
- description: 'Smart edit: Replaces a specific string in a file with a new string. Use this for small, targeted changes instead of rewriting the whole file. The "find" text must be an exact, unique match.',
494
- inputSchema: jsonSchema({
495
- type: 'object',
496
- properties: {
497
- path: { type: 'string', description: 'Path/key of the file to edit' },
498
- find: { type: 'string', description: 'The EXACT text block to search for. Must be unique in the file.' },
499
- replace: { type: 'string', description: 'The new text to replace it with.' },
500
- },
501
- required: ['path', 'find', 'replace'],
502
- }),
503
- execute: async ({ path, find, replace }: { path: string, find: string, replace: string }) => {
504
- console.log(` ✏️ [FS] edit ${path}`);
505
- try {
506
- const content = await memory.workspace.getItem(path);
507
- if (content === null || content === undefined) return `Error: File "${path}" not found.`;
508
-
509
- const fileText = String(content);
510
- if (!fileText.includes(find)) {
511
- return `Error: The text to replace was not found in "${path}". Check whitespace and indentation exactly.`;
512
- }
513
-
514
- const parts = fileText.split(find);
515
- if (parts.length > 2) {
516
- return `Error: Ambiguous match. Found ${parts.length - 1} occurrences. Provide more surrounding context in "find" to make it unique.`;
517
- }
518
-
519
- const newContent = fileText.replace(find, replace);
520
- await memory.workspace.setItem(path, newContent);
521
- return `Success: Edited "${path}". Replaced 1 occurrence.`;
522
- } catch (e: any) { return "Error editing file: " + e.message; }
523
- }
524
- }),
525
-
526
- 'fs.delete': tool({
527
- description: 'Delete a file. If the file is outside .trash/, it is moved to .trash/ (soft delete). If the file is already inside .trash/, it is permanently removed.',
528
- inputSchema: jsonSchema({
529
- type: 'object',
530
- properties: {
531
- path: { type: 'string', description: 'Path/key of the file to delete' },
532
- },
533
- required: ['path'],
534
- }),
535
- execute: async ({ path }: { path: string }) => {
536
- try {
537
- const content = await memory.workspace.getItem(path);
538
- if (content === null || content === undefined) return "File not found.";
539
-
540
- if (path.startsWith('.trash:') || path.startsWith('.trash/')) {
541
- // Already in trash — hard delete
542
- console.log(` 🗑️ [FS] permanentDelete ${path}`);
543
- await memory.workspace.removeItem(path);
544
- return `Success: Permanently deleted ${path}`;
545
- } else {
546
- // Move to .trash/
547
- const trashPath = `.trash:${path}`;
548
- console.log(` 🗑️ [FS] softDelete ${path} -> ${trashPath}`);
549
- await memory.workspace.setItem(trashPath, content);
550
- await memory.workspace.removeItem(path);
551
- return `Success: Moved ${path} to ${trashPath}`;
552
- }
553
- } catch (e: any) { return "Error deleting file: " + e.message; }
554
- }
555
- }),
556
-
557
- 'fs.move': tool({
558
- description: 'Move/rename a file in the workspace. Reads from "from", writes to "to", then removes the original.',
559
- inputSchema: jsonSchema({
560
- type: 'object',
561
- properties: {
562
- from: { type: 'string', description: 'Source path/key' },
563
- to: { type: 'string', description: 'Destination path/key' },
564
- },
565
- required: ['from', 'to'],
566
- }),
567
- execute: async ({ from, to }: { from: string, to: string }) => {
568
- console.log(` 📦 [FS] move ${from} -> ${to}`);
569
- try {
570
- const content = await memory.workspace.getItem(from);
571
- if (content === null || content === undefined) return `File not found: ${from}`;
572
- await memory.workspace.setItem(to, content);
573
- await memory.workspace.removeItem(from);
574
- return `Success: Moved ${from} to ${to}`;
575
- } catch (e: any) { return "Error moving file: " + e.message; }
576
- }
577
- }),
578
-
579
- 'fs.exists': tool({
580
- description: 'Check if a file exists in the workspace. Returns true or false.',
581
- inputSchema: jsonSchema({
582
- type: 'object',
583
- properties: {
584
- path: { type: 'string', description: 'Path/key of the file to check' },
585
- },
586
- required: ['path'],
587
- }),
588
- execute: async ({ path }: { path: string }) => {
589
- console.log(` 🔍 [FS] exists ${path}`);
590
- try {
591
- const exists = await memory.workspace.hasItem(path);
592
- return exists ? "true" : "false";
593
- } catch (e: any) { return `Error: ${e.message}`; }
594
- }
595
- }),
596
-
597
- 'fs.stat': tool({
598
- description: 'Get metadata about a file in the workspace (e.g. mtime, size). Returns JSON with available metadata.',
599
- inputSchema: jsonSchema({
600
- type: 'object',
601
- properties: {
602
- path: { type: 'string', description: 'Path/key of the file' },
603
- },
604
- required: ['path'],
605
- }),
606
- execute: async ({ path }: { path: string }) => {
607
- console.log(` 📊 [FS] stat ${path}`);
608
- try {
609
- const exists = await memory.workspace.hasItem(path);
610
- if (!exists) return "File not found.";
611
- const meta = await memory.workspace.getMeta(path);
612
- return JSON.stringify(meta);
613
- } catch (e: any) { return `Error: ${e.message}`; }
614
- }
615
- }),
616
-
617
- 'skill.install': tool({
618
- description: 'Install a skill from a remote URL. Downloads SKILL.md, parses it for additional files to download, analyzes required tool permissions, and saves everything to workspace under skills/<name>/.',
619
- inputSchema: jsonSchema({
620
- type: 'object',
621
- properties: {
622
- name: { type: 'string', description: 'Skill name (e.g. "moltbook", "tavily"). Used as the folder name under skills/.' },
623
- url: { type: 'string', description: 'URL to the remote SKILL.md file.' },
624
- },
625
- required: ['name', 'url'],
626
- }),
627
- execute: async ({ name, url }: { name: string; url: string }) => {
628
- console.log(` 📦 [SKILL] Installing skill "${name}" from ${url}`);
629
-
630
- // Phase 0: Validate name
631
- if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
632
- return JSON.stringify({ error: 'Invalid skill name. Use only letters, numbers, hyphens, underscores.' });
633
- }
634
-
635
- const skillBasePath = `skills:${name}`;
636
-
637
- // Phase 1: Download SKILL.md
638
- console.log(` 📦 [SKILL] Step 1/4: Downloading SKILL.md...`);
639
- let skillMdContent: string;
640
- try {
641
- const res = await fetch(url);
642
- if (!res.ok) {
643
- return JSON.stringify({ error: `Failed to download SKILL.md: HTTP ${res.status} ${res.statusText}` });
644
- }
645
- skillMdContent = await res.text();
646
- } catch (e: any) {
647
- return JSON.stringify({ error: `Network error downloading SKILL.md: ${e.message}` });
648
- }
649
- await memory.workspace.setItem(`${skillBasePath}:SKILL.md`, skillMdContent);
650
- console.log(` 📦 [SKILL] Saved SKILL.md (${skillMdContent.length} bytes)`);
651
-
652
- // Phase 2: Extract additional files via LLM
653
- console.log(` 📦 [SKILL] Step 2/4: Analyzing for additional files...`);
654
- let additionalFiles: Array<{ url: string; filename: string }> = [];
655
- try {
656
- const { text: installJson } = await generateText({
657
- model: localModel,
658
- messages: [
659
- {
660
- role: 'system',
661
- content: `You are a skill file analyzer. Given a SKILL.md file, extract all additional files that need to be downloaded for complete installation. Look for:
662
- - File tables listing URLs and filenames
663
- - Install instructions with curl/download commands
664
- - References to companion files (HEARTBEAT.md, MESSAGING.md, RULES.md, package.json, etc.)
665
-
666
- Return ONLY a JSON array. Each element: {"url": "<download_url>", "filename": "<local_filename>"}.
667
- Do NOT include SKILL.md itself. If no additional files, return [].`,
668
- },
669
- { role: 'user', content: skillMdContent },
670
- ],
671
- temperature: 0.1,
672
- });
673
- const match = installJson.match(/\[[\s\S]*\]/);
674
- if (match) additionalFiles = JSON.parse(match[0]);
675
- } catch (e: any) {
676
- console.log(` ⚠️ [SKILL] Could not parse additional files: ${e.message}`);
677
- }
678
-
679
- // Phase 3: Download additional files
680
- console.log(` 📦 [SKILL] Step 3/4: Downloading ${additionalFiles.length} additional files...`);
681
- const downloadResults: Array<{ filename: string; status: string }> = [];
682
- for (const file of additionalFiles) {
683
- try {
684
- const res = await fetch(file.url);
685
- if (!res.ok) {
686
- downloadResults.push({ filename: file.filename, status: `failed: HTTP ${res.status}` });
687
- continue;
688
- }
689
- const content = await res.text();
690
- await memory.workspace.setItem(`${skillBasePath}:${file.filename}`, content);
691
- downloadResults.push({ filename: file.filename, status: 'ok' });
692
- console.log(` 📦 [SKILL] Downloaded ${file.filename}`);
693
- } catch (e: any) {
694
- downloadResults.push({ filename: file.filename, status: `failed: ${e.message}` });
695
- }
696
- }
697
-
698
- // Phase 4: Analyze permissions via LLM
699
- console.log(` 📦 [SKILL] Step 4/4: Analyzing required permissions...`);
700
- let skillPermissions: Record<string, Array<Record<string, string>>> = {};
701
- try {
702
- const { text: permJson } = await generateText({
703
- model: localModel,
704
- messages: [
705
- {
706
- role: 'system',
707
- content: `You are a security analyzer for AI agent skills. Analyze this SKILL.md and determine what tools and permissions it needs.
708
-
709
- Available tools: "http.request", "http.get", "http.post", "http.download", "connection.list", "connection.request", "connection.create", "kv.set", "kv.get", "kv.list", "kv.delete", "kv.has", "fs.readFile", "fs.writeFile", "fs.edit", "fs.delete", "fs.move", "fs.listDir", "fs.exists", "fs.stat"
710
-
711
- IMPORTANT: If the skill requires API keys or authentication, use "connection.create" and "connection.request" instead of "kv.*" tools. Connections handle registration, token storage, and authenticated requests automatically.
712
-
713
- For HTTP tools, include "url" (pattern with * wildcard) and "method".
714
- For connection tools, include "url" pattern and "name" of the connection.
715
- For KV tools, include "key" pattern. Only use kv.* for non-auth data (preferences, config, caches).
716
- For FS tools, include "path" pattern.
717
-
718
- Return ONLY a JSON object mapping tool names to arrays of permission rules. Example:
719
- {"connection.create": [{"name": "example", "url": "https://api.example.com/register"}], "connection.request": [{"name": "example", "url": "https://api.example.com/*", "method": "*"}]}`,
720
- },
721
- { role: 'user', content: skillMdContent },
722
- ],
723
- temperature: 0.1,
724
- });
725
- const match = permJson.match(/\{[\s\S]*\}/);
726
- if (match) skillPermissions = JSON.parse(match[0]);
727
- } catch (e: any) {
728
- console.log(` ⚠️ [SKILL] Could not analyze permissions: ${e.message}`);
729
- }
730
-
731
- // Phase 5: Write permissions.json at project root
732
- const permissionsPath = `${process.cwd()}/permissions.json`;
733
- let permissionsFile: { skills: Record<string, Record<string, Array<Record<string, string>>>> } = { skills: {} };
734
- try {
735
- const existing = await readFile(permissionsPath, 'utf-8');
736
- const parsed = JSON.parse(existing);
737
- if (parsed && typeof parsed === 'object') {
738
- permissionsFile = parsed;
739
- if (!permissionsFile.skills) permissionsFile.skills = {};
740
- }
741
- } catch {
742
- // File doesn't exist yet, start fresh
743
- }
744
- permissionsFile.skills[name] = skillPermissions;
745
- try {
746
- await writeFile(permissionsPath, JSON.stringify(permissionsFile, null, 2), 'utf-8');
747
- console.log(` 📦 [SKILL] Updated permissions.json`);
748
- } catch (e: any) {
749
- console.log(` ⚠️ [SKILL] Could not write permissions.json: ${e.message}`);
750
- }
751
-
752
- return JSON.stringify({
753
- success: true,
754
- skill: name,
755
- files: [
756
- { filename: 'SKILL.md', status: 'ok' },
757
- ...downloadResults,
758
- ],
759
- permissions: skillPermissions,
760
- message: `Skill "${name}" installed with ${downloadResults.filter(r => r.status === 'ok').length + 1} files.`,
761
- });
762
- },
763
- }),
764
-
765
- 'connection.list': tool({
766
- description: 'List all available connections (configured API credentials). Returns comma-separated connection names.',
767
- execute: async () => {
768
- console.log(` 🔌 [CONN] list`);
769
- try {
770
- const settings = await readSettings();
771
- const names = Object.keys(settings.connections);
772
- return names.length > 0 ? names.join(',') : 'NO_CONNECTIONS';
773
- } catch (e: any) { return `Error: ${e.message}`; }
774
- },
775
- }),
776
-
777
- 'connection.request': tool({
778
- description: 'Execute an authenticated HTTP request using a named connection. The connection\'s Bearer token is automatically injected into the Authorization header. If the connection does not exist, returns an error prompting you to create it first with connection.create.',
779
- inputSchema: jsonSchema({
780
- type: 'object',
781
- properties: {
782
- name: { type: 'string', description: 'Connection name (e.g. "petstore", "moltbook")' },
783
- url: { type: 'string', description: 'URL to request' },
784
- method: { type: 'string', enum: ['GET', 'POST', 'PUT', 'DELETE'], description: 'HTTP method (default: GET)' },
785
- headers: { type: 'object', additionalProperties: { type: 'string' }, description: 'Optional additional headers' },
786
- body: { type: 'string', description: 'Optional request body string' },
787
- },
788
- required: ['name', 'url'],
789
- }),
790
- execute: async ({ name, url, method, headers, body }: { name: string; url: string; method?: string; headers?: Record<string, string>; body?: string }) => {
791
- console.log(` 🔌 [CONN] request "${name}" ${method || 'GET'} ${url}`);
792
- const settings = await readSettings();
793
- const conn = settings.connections[name];
794
-
795
- if (!conn) {
796
- return JSON.stringify({
797
- error: `Connection "${name}" not found. Available connections: ${Object.keys(settings.connections).join(', ') || 'none'}. Use connection.create to set up this connection first.`,
798
- });
799
- }
800
-
801
- const executeMethod = method || 'GET';
802
- try {
803
- let parsedBody = body;
804
- if (typeof body === 'string') {
805
- try { parsedBody = JSON.parse(body); } catch {}
806
- }
807
-
808
- const res = await fetch(url, {
809
- method: executeMethod,
810
- headers: {
811
- 'Content-Type': 'application/json',
812
- 'Authorization': `Bearer ${conn.bearer.idToken}`,
813
- ...headers,
814
- },
815
- body: parsedBody ? JSON.stringify(parsedBody) : null,
816
- });
817
-
818
- const text = await res.text();
819
- console.log(` -> ${res.status}`);
820
- return JSON.stringify({
821
- status: res.status,
822
- statusText: res.statusText,
823
- data: text.length > 2000 ? text.substring(0, 2000) + '...' : text,
824
- });
825
- } catch (e: any) { return JSON.stringify({ error: e.message }); }
826
- },
827
- }),
828
-
829
- 'connection.create': tool({
830
- description: 'Create a new connection by calling a registration endpoint. Sends the request, extracts the API key from the response, and stores the connection in settings.json. The "type" must be "Bearer". The response should contain the API key and optionally a refresh token/URL.',
831
- inputSchema: jsonSchema({
832
- type: 'object',
833
- properties: {
834
- name: { type: 'string', description: 'Connection name (e.g. "moltbook", "petstore")' },
835
- url: { type: 'string', description: 'Registration endpoint URL' },
836
- method: { type: 'string', enum: ['GET', 'POST', 'PUT'], description: 'HTTP method (default: POST)' },
837
- headers: { type: 'object', additionalProperties: { type: 'string' }, description: 'Optional headers' },
838
- body: { type: 'string', description: 'Optional request body string' },
839
- type: { type: 'string', enum: ['Bearer'], description: 'Auth type. Currently only "Bearer" is supported.' },
840
- tokenPath: { type: 'string', description: 'JSON path to the API key in the response (e.g. "agent.api_key"). Dot-separated. Defaults to "api_key".' },
841
- refreshTokenPath: { type: 'string', description: 'Optional JSON path to the refresh token in the response (e.g. "agent.verification_code").' },
842
- refreshUrl: { type: 'string', description: 'Optional URL for token refresh.' },
843
- },
844
- required: ['name', 'url', 'type'],
845
- }),
846
- execute: async ({ name, url, method, headers, body, type, tokenPath, refreshTokenPath, refreshUrl }: {
847
- name: string; url: string; method?: string; headers?: Record<string, string>; body?: string;
848
- type: string; tokenPath?: string; refreshTokenPath?: string; refreshUrl?: string;
849
- }) => {
850
- console.log(` 🔌 [CONN] create "${name}" via ${method || 'POST'} ${url}`);
851
-
852
- if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
853
- return JSON.stringify({ error: 'Invalid connection name. Use only letters, numbers, hyphens, underscores.' });
854
- }
855
-
856
- if (type !== 'Bearer') {
857
- return JSON.stringify({ error: `Unsupported auth type "${type}". Only "Bearer" is supported.` });
858
- }
859
-
860
- // Execute registration request
861
- const executeMethod = method || 'POST';
862
- let responseData: any;
863
- let responseText: string;
864
- try {
865
- let parsedBody = body;
866
- if (typeof body === 'string') {
867
- try { parsedBody = JSON.parse(body); } catch {}
868
- }
869
-
870
- const res = await fetch(url, {
871
- method: executeMethod,
872
- headers: { 'Content-Type': 'application/json', ...headers },
873
- body: parsedBody ? JSON.stringify(parsedBody) : null,
874
- });
875
-
876
- responseText = await res.text();
877
- console.log(` -> ${res.status}`);
878
-
879
- if (!res.ok) {
880
- return JSON.stringify({ error: `Registration failed: HTTP ${res.status} ${res.statusText}`, data: responseText.substring(0, 500) });
881
- }
882
-
883
- responseData = JSON.parse(responseText);
884
- } catch (e: any) {
885
- return JSON.stringify({ error: `Registration request failed: ${e.message}` });
886
- }
887
-
888
- // Extract token from response using dot-path
889
- const tPath = tokenPath || 'api_key';
890
- let idToken: string | undefined;
891
- try {
892
- idToken = tPath.split('.').reduce((obj: any, key: string) => obj?.[key], responseData);
893
- } catch {}
894
-
895
- if (!idToken || typeof idToken !== 'string') {
896
- return JSON.stringify({
897
- error: `Could not extract token at path "${tPath}" from response.`,
898
- response: responseText!.substring(0, 500),
899
- });
900
- }
901
-
902
- // Extract optional refresh token
903
- let refreshToken: string | undefined;
904
- if (refreshTokenPath) {
905
- try {
906
- refreshToken = refreshTokenPath.split('.').reduce((obj: any, key: string) => obj?.[key], responseData);
907
- } catch {}
908
- }
909
-
910
- // Save to settings.json
911
- const settings = await readSettings();
912
- settings.connections[name] = {
913
- bearer: {
914
- idToken,
915
- ...(refreshToken ? { refreshToken } : {}),
916
- ...(refreshUrl ? { refreshUrl } : {}),
917
- },
918
- };
919
- await writeSettings(settings);
920
- console.log(` 🔌 [CONN] Saved connection "${name}" to settings.json`);
921
-
922
- return JSON.stringify({
923
- success: true,
924
- connection: name,
925
- response: responseData,
926
- message: `Connection "${name}" created and saved. Bearer token stored.`,
927
- });
928
- },
929
- }),
930
-
931
- 'skill.prompt': tool({
932
- description: 'Chat with an installed skill in a sandboxed environment. The skill runs with its own message history and only the tools allowed by permissions.json (entries with "allowed": true).',
933
- inputSchema: jsonSchema({
934
- type: 'object',
935
- properties: {
936
- name: { type: 'string', description: 'Skill name (must be installed via skill.install).' },
937
- prompt: { type: 'string', description: 'The prompt/message to send to the skill.' },
938
- },
939
- required: ['name', 'prompt'],
940
- }),
941
- execute: async ({ name, prompt }: { name: string; prompt: string }) => {
942
- console.log(` 💬 [SKILL.PROMPT] Starting chat with "${name}"`);
943
-
944
- // 1. Validate name
945
- if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
946
- return JSON.stringify({ error: 'Invalid skill name.' });
947
- }
948
-
949
- // 2. Read SKILL.md as system prompt
950
- const skillMd = await memory.workspace.getItem(`skills:${name}:SKILL.md`);
951
- if (!skillMd) {
952
- return JSON.stringify({ error: `Skill "${name}" not found. Install it first with skill.install.` });
953
- }
954
-
955
- // 3. Read permissions.json
956
- const permissionsPath = `${process.cwd()}/permissions.json`;
957
- let skillPermissions: Record<string, Array<Record<string, string>>> = {};
958
- try {
959
- const raw = await readFile(permissionsPath, 'utf-8');
960
- const parsed = JSON.parse(raw);
961
- skillPermissions = parsed?.skills?.[name] ?? {};
962
- } catch {
963
- return JSON.stringify({ error: `No permissions found for skill "${name}". Run skill.install first.` });
964
- }
965
-
966
- // 4. Build sandboxed tools (only tools with "allowed": true, HTTP tools get URL guards)
967
- const allTools = createTools(memory);
968
- const sandboxed = createSandboxedTools(allTools, skillPermissions);
969
-
970
- if (Object.keys(sandboxed).length === 0) {
971
- console.log(` 🔒 [SKILL.PROMPT] "${name}": no tools allowed, text-only mode`);
972
- } else {
973
- console.log(` 🔒 [SKILL.PROMPT] "${name}": sandboxed tools: ${Object.keys(sandboxed).join(', ')}`);
974
- }
975
-
976
- // 5. Load per-skill message history (single table, partitioned by name)
977
- const messages: ModelMessage[] = []; // await memory.skillHistory.getAll(name);
978
-
979
- // Inject system prompt if this is a fresh history
980
- if (messages.length === 0) {
981
- messages.push({ role: 'system', content: String(skillMd) });
982
- }
983
-
984
- // Add user prompt
985
- messages.push({ role: 'user', content: prompt });
986
-
987
- // 6. Run skill via streamText (agentic — multi-step tool use, up to 15 steps)
988
- console.log(` 💬 [SKILL.PROMPT] Running "${name}" with prompt: ${prompt.substring(0, 80)}...`);
989
- try {
990
- const result = streamText({
991
- model: localModel,
992
- messages,
993
- tools: Object.keys(sandboxed).length > 0 ? sandboxed : {},
994
- temperature: 0.6,
995
- topP: 0.95,
996
- stopWhen: stepCountIs(30),
997
- onStepFinish: (step) => {
998
- if (step.toolCalls.length > 0) {
999
- const toolNames = step.toolCalls.map(t => t.toolName).join(', ');
1000
- console.log(` 🛠️ [SKILL.PROMPT/${name}] Executed: ${toolNames}`);
1001
- }
1002
- },
1003
- });
1004
-
1005
- // Consume the full stream and collect the response
1006
- let fullResponse = "";
1007
- for await (const delta of result.textStream) {
1008
- fullResponse += delta;
1009
- }
1010
-
1011
- // Persist messages to skill history after stream completes
1012
- const responseMessages = (await result.response).messages;
1013
-
1014
- await memory.skillHistory.push(name, { role: 'user', content: prompt });
1015
- for (const msg of responseMessages) {
1016
- if (typeof msg.content !== "string") {
1017
- msg.content = msg.content.filter((part) => part.type !== 'reasoning');
1018
- }
1019
- await memory.skillHistory.push(name, msg);
1020
- }
1021
-
1022
- return fullResponse || JSON.stringify({ success: true, response: '(no text response — tool actions only)' });
1023
- } catch (e: any) {
1024
- console.error(` ❌ [SKILL.PROMPT] Error:`, e);
1025
- return JSON.stringify({ error: `Skill chat failed: ${e.message}` });
1026
- }
1027
- },
1028
- }),
1029
- };
1030
- }
1031
-
1032
119
  // --- AGENT RUNNER ---
1033
120
 
1034
121
  async function runAgent(
1035
122
  input: string,
1036
123
  memory: AgentMemory,
124
+ model: LanguageModel,
1037
125
  messages: ModelMessage[],
1038
126
  tools: ReturnType<typeof createTools>,
1039
127
  onResponseChunk?: (chunk: string) => void
@@ -1042,20 +130,29 @@ async function runAgent(
1042
130
  messages.push(message);
1043
131
 
1044
132
  try {
133
+ let overallInputTokens = 0;
134
+ let overallOutputTokens = 0;
135
+ let overallSteps = 0;
1045
136
  const result = await streamText({
1046
- model: localModel,
137
+ model,
1047
138
  system: await buildSystemPrompt(memory),
1048
139
  messages,
1049
140
  tools,
1050
- temperature: 0.6,
1051
- topP: 0.95,
1052
- stopWhen: stepCountIs(30),
141
+ temperature: GENERATE_TEXT_TEMPERATURE,
142
+ topP: GENERATE_TEXT_TOP_P,
143
+ maxOutputTokens: GENERATE_TEXT_MAX_OUTPUT_TOKENS,
144
+ stopWhen: stepCountIs(GENERATE_TEXT_MAX_STEPS),
1053
145
 
1054
146
  onStepFinish: (step) => {
1055
147
  if (step.toolCalls.length > 0) {
1056
148
  const names = step.toolCalls.map(t => t.toolName).join(', ');
1057
- console.log(` 🛠️ [Executed: ${names}] `);
149
+ logger.debug({ tools: names, tokens: step.usage.totalTokens }, 'Agent executed tools');
150
+ } else {
151
+ logger.debug({ tokens: step.usage.totalTokens }, 'Agent finalized step');
1058
152
  }
153
+ overallSteps += 1;
154
+ overallInputTokens += step.usage.inputTokens || 0;
155
+ overallOutputTokens += step.usage.outputTokens || 0
1059
156
  },
1060
157
  });
1061
158
 
@@ -1068,25 +165,31 @@ async function runAgent(
1068
165
  }
1069
166
  }
1070
167
 
168
+ const inputTokenPrice = process.env.AI_GATEWAY_INPUT_TOKEN_PRICE;
169
+ const outputTokenPrice = process.env.AI_GATEWAY_OUTPUT_TOKEN_PRICE;
170
+ if (inputTokenPrice && outputTokenPrice) {
171
+ const price = (parseFloat(inputTokenPrice) * overallInputTokens + parseFloat(outputTokenPrice) * overallOutputTokens) / 1000000;
172
+ logger.info({ steps: overallSteps, inputTokens: overallInputTokens, outputTokens: overallOutputTokens, cost: price }, 'Agent run completed');
173
+ } else {
174
+ logger.info({ steps: overallSteps, inputTokens: overallInputTokens, outputTokens: overallOutputTokens }, 'Agent run completed');
175
+ }
176
+
1071
177
  const responseMessages = (await result.response).messages;
1072
178
  messages.push(...responseMessages);
1073
179
 
1074
180
  return responseMessages;
1075
181
 
1076
182
  } catch (e) {
1077
- console.error("\n❌ Error:", e);
183
+ logger.error({ err: e }, 'Agent run error');
1078
184
  return [];
1079
185
  }
1080
186
  }
1081
187
 
1082
- // --- COMPACTION CONFIG ---
1083
- const COMPACT_THRESHOLD = 25; // Trigger compaction when history reaches this many items
1084
- const COMPACT_RANGE = 10; // Number of messages to summarize (items 1..10, skipping system prompt at 0)
1085
-
1086
188
  // --- MAIN EXPORTED CLASS ---
1087
189
 
1088
190
  export class Agent {
1089
191
  private memory: AgentMemory;
192
+ private model: LanguageModel;
1090
193
  private messages: ModelMessage[] = [];
1091
194
  private tools: ReturnType<typeof createTools>;
1092
195
  private inputAdapters: InputAdapter[] = [];
@@ -1096,9 +199,10 @@ export class Agent {
1096
199
  private initialized = false;
1097
200
  private bootstrapPrompt: string | null = null;
1098
201
 
1099
- constructor(memory?: AgentMemory) {
1100
- this.memory = memory ?? new AgentMemory();
1101
- this.tools = createTools(this.memory);
202
+ constructor(memory: AgentMemory, model: LanguageModel) {
203
+ this.memory = memory;
204
+ this.model = model;
205
+ this.tools = createTools(this.memory, this.model);
1102
206
  }
1103
207
 
1104
208
  addInput(adapter: InputAdapter): this {
@@ -1140,9 +244,9 @@ export class Agent {
1140
244
  try {
1141
245
  await mkdir(workspaceDir, { recursive: true });
1142
246
  await copyFile(templatePath, agentsMdPath);
1143
- console.log(` 📋 Copied AGENTS.template -> workspace/AGENTS.md`);
247
+ logger.info('Copied AGENTS.template -> workspace/AGENTS.md');
1144
248
  } catch (e: any) {
1145
- console.error(` ⚠️ Failed to copy AGENTS.template: ${e.message}`);
249
+ logger.error({ err: e }, 'Failed to copy AGENTS.template');
1146
250
  }
1147
251
  }
1148
252
 
@@ -1162,78 +266,22 @@ export class Agent {
1162
266
  try {
1163
267
  const bootstrapPath = path.join(PACKAGE_ROOT, 'template', 'BOOTSTRAP.md');
1164
268
  this.bootstrapPrompt = await readFile(bootstrapPath, 'utf-8');
1165
- console.log(` 🚀 Bootstrap mode: SOUL.md, IDENTITY.md, or USER.md missing. Running BOOTSTRAP.md first.`);
269
+ logger.info('Bootstrap mode: SOUL.md, IDENTITY.md, or USER.md missing. Running BOOTSTRAP.md first.');
1166
270
  } catch (e: any) {
1167
- console.error(` ⚠️ Failed to read BOOTSTRAP.md: ${e.message}`);
271
+ logger.error({ err: e }, 'Failed to read BOOTSTRAP.md');
1168
272
  }
1169
273
  }
1170
274
 
1171
275
  // Load history from DB
1172
- const savedMessages : ModelMessage[] = []; // (await this.memory.history.getAll());
276
+ const savedMessages : ModelMessage[] = await this.memory.history.getAll("main-session");
1173
277
  if (savedMessages.length > 0) {
1174
278
  this.messages = savedMessages as ModelMessage[];
1175
- console.log(` 📜 Loaded ${savedMessages.length} messages from history.`);
279
+ logger.info({ count: savedMessages.length }, 'Loaded messages from history');
1176
280
  } else {
1177
- console.log(` 📜 Did not load any messages from history.`);
281
+ logger.debug('No messages loaded from history');
1178
282
  }
1179
283
  }
1180
284
 
1181
- /**
1182
- * Compacts history when it reaches COMPACT_THRESHOLD items.
1183
- * Summarizes items 1..COMPACT_RANGE (the system prompt is not included) into a single message
1184
- * using the LLM, then replaces in-memory + persisted history.
1185
- * Result: summary message + remaining messages.
1186
- */
1187
- private async compactHistory() {
1188
- if (this.messages.length < COMPACT_THRESHOLD) return;
1189
-
1190
- console.log(` 🗜️ Compacting history: ${this.messages.length} messages -> summarizing first ${COMPACT_RANGE} (after system prompt)...`);
1191
-
1192
- const toSummarize = this.messages.slice(0, COMPACT_RANGE);
1193
- const remaining = this.messages.slice(COMPACT_RANGE);
1194
-
1195
- // Build a transcript for the LLM to summarize
1196
- const transcript = toSummarize.map(m => {
1197
- const role = m.role ?? 'unknown';
1198
- const content = typeof m.content === 'string'
1199
- ? m.content
1200
- : JSON.stringify(m.content);
1201
- return `[${role}]: ${content}`;
1202
- }).join('\n\n');
1203
-
1204
- try {
1205
- const { text: summary } = await generateText({
1206
- model: localModel,
1207
- messages: [
1208
- {
1209
- role: 'system',
1210
- content: 'You are a conversation summarizer. Summarize the following conversation transcript concisely, preserving key facts, decisions, tool results, and context that would be needed to continue the conversation. Be factual and dense. Do not add commentary.',
1211
- },
1212
- {
1213
- role: 'user',
1214
- content: `Summarize this conversation transcript:\n\n${transcript}`,
1215
- },
1216
- ],
1217
- temperature: 0.3,
1218
- });
1219
-
1220
- const summaryMessage: ModelMessage = {
1221
- role: 'assistant',
1222
- content: `[Conversation Summary — compacted ${COMPACT_RANGE} messages]\n\n${summary}`,
1223
- };
1224
-
1225
- // Rebuild in-memory messages: summary + remaining
1226
- this.messages = [summaryMessage, ...remaining];
1227
-
1228
- // Persist: clear DB and re-write all messages
1229
- await this.memory.history.clear();
1230
- await this.memory.history.pushMany(this.messages);
1231
-
1232
- console.log(` ✅ Compacted to ${this.messages.length} messages.`);
1233
- } catch (e) {
1234
- console.error(' ❌ Compaction failed, keeping original history:', e);
1235
- }
1236
- }
1237
285
 
1238
286
  private async processQueue() {
1239
287
  if (this.processing || this.inputQueue.length === 0) return;
@@ -1246,7 +294,7 @@ export class Agent {
1246
294
  out.onAgentStart(label);
1247
295
  }
1248
296
 
1249
- await this.compactHistory();
297
+ this.messages = await this.memory.compactHistory("main-session", this.model);
1250
298
 
1251
299
  // Bootstrap: if bootstrapPrompt is set, run it instead of normal chat
1252
300
  // until the required files (SOUL.md, IDENTITY.md, USER.md) are created
@@ -1289,8 +337,8 @@ export class Agent {
1289
337
 
1290
338
  let fullResponse = "";
1291
339
  try {
1292
- const newMessages = await runAgent(input, this.memory, this.messages, this.tools, (chunk) => {
1293
- fullResponse += chunk;
340
+ const newMessages = await runAgent(input, this.memory, this.model, this.messages, this.tools, (chunk) => {
341
+ fullResponse += chunk;
1294
342
  for (const out of this.outputAdapters) {
1295
343
  out.onResponseChunk(chunk);
1296
344
  }
@@ -1300,7 +348,7 @@ export class Agent {
1300
348
  if (typeof msg.content !== "string") {
1301
349
  msg.content = msg.content.filter((part) => part.type !== 'reasoning');
1302
350
  }
1303
- await this.memory.history.push(msg);
351
+ await this.memory.history.push("main-session", msg);
1304
352
  }
1305
353
 
1306
354
  for (const out of this.outputAdapters) {
@@ -1308,7 +356,7 @@ export class Agent {
1308
356
  }
1309
357
 
1310
358
  // Compact history if it's grown past the threshold
1311
- await this.compactHistory();
359
+ this.messages = await this.memory.compactHistory("main-session", this.model);
1312
360
  } catch (error: any) {
1313
361
  for (const out of this.outputAdapters) {
1314
362
  out.onError(error);