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