-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathautonomous.ts
More file actions
482 lines (422 loc) · 12.6 KB
/
autonomous.ts
File metadata and controls
482 lines (422 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
import fs from "node:fs/promises";
import path from "node:path";
import process from "node:process";
import { fileURLToPath } from "node:url";
import {
AgentRuntime,
ChannelType,
createCharacter,
createMessageMemory,
logger,
MemoryType,
type Plugin,
parseJSONObjectFromText,
stringToUuid,
type UUID,
} from "@elizaos/core";
import { v4 as uuidv4 } from "uuid";
type ShellService = {
executeCommand(
command: string,
roomId: UUID,
): Promise<{
success: boolean;
exitCode: number | null;
stdout?: string;
stderr?: string;
executedIn?: string;
error?: string;
}>;
};
type AgentDecision =
| { action: "RUN"; command: string; note: string }
| { action: "SLEEP"; sleepMs: number; note: string }
| { action: "STOP"; note: string };
type StepRecord = {
step: number;
decidedAt: number;
goal: string;
decision: AgentDecision;
shell?: {
executed: boolean;
command?: string;
success?: boolean;
exitCode?: number | null;
stdout?: string;
stderr?: string;
executedIn?: string;
error?: string;
};
};
const AUTONOMY_TABLE = "autonomous_steps";
function envString(name: string, fallback: string): string {
const v = process.env[name];
if (typeof v === "string" && v.trim().length > 0) return v.trim();
return fallback;
}
function envNumber(name: string, fallback: number): number {
const v = process.env[name];
if (typeof v !== "string") return fallback;
const parsed = Number(v);
return Number.isFinite(parsed) ? parsed : fallback;
}
function clamp(n: number, min: number, max: number): number {
return Math.min(max, Math.max(min, n));
}
function truncate(text: string, maxLen: number): string {
if (text.length <= maxLen) return text;
return `${text.slice(0, maxLen)}\n...<truncated ${text.length - maxLen} chars>...`;
}
async function exists(filePath: string): Promise<boolean> {
try {
await fs.stat(filePath);
return true;
} catch {
return false;
}
}
function readStringField(
record: Record<string, unknown>,
key: string,
): string | null {
const value = record[key];
if (typeof value === "string") {
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
}
if (typeof value === "number" || typeof value === "boolean") {
return String(value);
}
return null;
}
export function parseDecision(raw: string): AgentDecision | null {
const parsed = parseJSONObjectFromText(raw);
if (!parsed) return null;
const actionRaw = readStringField(parsed, "action")?.toUpperCase();
if (!actionRaw) return null;
const note = readStringField(parsed, "note") ?? "";
switch (actionRaw) {
case "STOP":
return { action: "STOP", note };
case "SLEEP": {
const sleepRaw = readStringField(parsed, "sleepMs");
const sleepMsParsed = sleepRaw ? Number(sleepRaw) : NaN;
if (!Number.isFinite(sleepMsParsed)) return null;
return {
action: "SLEEP",
sleepMs: clamp(sleepMsParsed, 100, 60_000),
note,
};
}
case "RUN": {
const command = readStringField(parsed, "command");
if (!command) return null;
return { action: "RUN", command, note };
}
default:
return null;
}
}
function baseCommand(command: string): string {
const trimmed = command.trim();
const space = trimmed.indexOf(" ");
return space === -1 ? trimmed : trimmed.slice(0, space);
}
export function isCommandAllowed(
command: string,
allowedBaseCommands: readonly string[],
): boolean {
const trimmed = command.trim();
if (trimmed.length === 0) return false;
if (trimmed.includes("\n") || trimmed.includes("\r")) return false;
// Disallow shell meta-characters to avoid `sh -c` execution paths.
const meta = ["|", ">", "<", ";", "&&", "||"];
if (meta.some((m) => trimmed.includes(m))) return false;
const cmd = baseCommand(trimmed);
return allowedBaseCommands.includes(cmd);
}
export function decisionPrompt(params: {
goal: string;
allowedDirectory: string;
allowedCommands: readonly string[];
recentSteps: string;
}): string {
const allowedCmdList = params.allowedCommands.join(", ");
return `
You are an autonomous agent running inside a sandbox directory on the local machine.
GOAL:
${params.goal}
SANDBOX:
- You may ONLY run shell commands inside: ${params.allowedDirectory}
- You may ONLY use these base commands: ${allowedCmdList}
- Never use networking, package managers, or process control.
- If you cannot make progress safely, choose SLEEP.
RECENT HISTORY (most recent last):
${params.recentSteps}
Choose exactly ONE next step and output ONLY this JSON object (no extra text):
{
"action": "RUN|SLEEP|STOP",
"command": "...",
"sleepMs": 1000,
"note": "short reason"
}
Rules:
- If action is RUN, include command and omit sleepMs.
- If action is SLEEP, include sleepMs (100-60000) and omit command.
- If action is STOP, omit both command and sleepMs.
- Keep output short.
`.trim();
}
async function main(): Promise<void> {
const { default: inmemorydbPlugin } = await import(
"@elizaos/plugin-inmemorydb"
);
const { default: localInferencePlugin } = await import(
"@elizaos/plugin-local-inference"
);
const { shellPlugin } = await import("@elizaos/plugin-shell");
const here = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(here, "..", "..", "..");
const defaultSandboxDir = path.join(
repoRoot,
"examples",
"autonomous",
"sandbox",
);
const allowedDirectory = envString(
"SHELL_ALLOWED_DIRECTORY",
defaultSandboxDir,
);
// Ensure sandbox exists before plugin-shell reads env (it throws if missing).
await fs.mkdir(allowedDirectory, { recursive: true });
// If user didn't set it, we still set it so plugin-shell is constrained even if enabled.
process.env.SHELL_ALLOWED_DIRECTORY = allowedDirectory;
const goalFile = envString(
"AUTONOMY_GOAL_FILE",
path.join(allowedDirectory, "GOAL.txt"),
);
const stopFile = envString(
"AUTONOMY_STOP_FILE",
path.join(allowedDirectory, "STOP"),
);
const intervalMs = clamp(
envNumber("AUTONOMY_INTERVAL_MS", 2000),
100,
60_000,
);
const maxSteps = clamp(envNumber("AUTONOMY_MAX_STEPS", 200), 1, 1_000_000);
const allowedCommands = envString(
"AUTONOMY_ALLOWED_COMMANDS",
"ls,pwd,cat,echo,touch,mkdir",
)
.split(",")
.map((s) => s.trim())
.filter((s) => s.length > 0);
const character = createCharacter({
name: "AutonomousLocalAgent",
bio: "A sandboxed autonomous loop agent that uses local inference and a restricted shell.",
settings: {
LLM_MODE: "SMALL",
CHECK_SHOULD_RESPOND: false,
},
});
logger.info(
{
src: "example:autonomous",
allowedDirectory,
goalFile,
stopFile,
intervalMs,
maxSteps,
allowedCommands,
},
"Starting sandboxed autonomous loop",
);
const runtime = new AgentRuntime({
character,
plugins: [inmemorydbPlugin, shellPlugin, localInferencePlugin] as Plugin[],
logLevel: "info",
});
await runtime.initialize();
const shellService = runtime.getService("shell") as ShellService | null;
if (!shellService) {
throw new Error("Shell service not available (plugin-shell not loaded?)");
}
const userId = uuidv4() as UUID;
const autonomousRoomId = stringToUuid("autonomous-room");
const autonomousWorldId = stringToUuid("autonomous-world");
await runtime.ensureConnection({
entityId: userId,
roomId: autonomousRoomId,
worldId: autonomousWorldId,
userName: "Autonomy",
source: "autonomous-loop",
channelId: "autonomous-room",
serverId: "autonomous",
type: ChannelType.DM,
} as Parameters<typeof runtime.ensureConnection>[0]);
if (!runtime.messageService) {
throw new Error("messageService not available on runtime");
}
if (!(await exists(goalFile))) {
const defaultGoal = [
"Explore the sandbox directory safely.",
"Create a short STATUS.txt describing what you found.",
"Keep commands small and only use allowed commands.",
].join("\n");
await fs.writeFile(goalFile, `${defaultGoal}\n`, "utf8");
}
for (let step = 1; step <= maxSteps; step += 1) {
if (await exists(stopFile)) {
logger.info(
{ src: "example:autonomous", stopFile },
"STOP file found; exiting",
);
break;
}
const goal = (await fs.readFile(goalFile, "utf8")).trim();
const recent = await runtime.getMemories({
roomId: autonomousRoomId,
count: 10,
tableName: AUTONOMY_TABLE,
});
const recentSteps = recent
.slice()
.reverse()
.map((m) => (typeof m.content.text === "string" ? m.content.text : ""))
.filter((t) => t.length > 0)
.map((t) => truncate(t, 800))
.join("\n\n---\n\n");
const prompt = decisionPrompt({
goal,
allowedDirectory,
allowedCommands,
recentSteps: recentSteps.length > 0 ? recentSteps : "(none yet)",
});
const message = createMessageMemory({
id: uuidv4() as UUID,
entityId: userId,
roomId: autonomousRoomId,
content: {
text: prompt,
source: "autonomous-loop",
metadata: {
type: "autonomous-prompt",
isAutonomous: true,
channelId: "autonomous",
timestamp: Date.now(),
},
},
});
let rawText = "";
const result = await runtime.messageService.handleMessage(
runtime,
message,
async (content) => {
if (content?.text) rawText += content.text;
return [];
},
);
logger.debug(
{
src: "example:autonomous",
step,
didRespond: result.didRespond,
mode: result.mode,
},
"Message service response",
);
const decision = parseDecision(rawText) ?? {
action: "SLEEP",
sleepMs: 2000,
note: "parse-failed",
};
const record: StepRecord = {
step,
decidedAt: Date.now(),
goal,
decision,
};
if (decision.action === "RUN") {
const trimmed = decision.command.trim();
const allowed = isCommandAllowed(trimmed, allowedCommands);
if (!allowed) {
record.shell = {
executed: false,
command: trimmed,
error: "command-not-allowed",
};
} else {
const result = await shellService.executeCommand(
trimmed,
autonomousRoomId,
);
record.shell = {
executed: true,
command: trimmed,
success: result.success,
exitCode: result.exitCode,
stdout: truncate(result.stdout ?? "", 2000),
stderr: truncate(result.stderr ?? "", 2000),
executedIn: result.executedIn,
error: result.error,
};
}
}
if (decision.action === "SLEEP" || decision.action === "STOP") {
record.shell = { executed: false };
}
const summaryLines: string[] = [];
summaryLines.push(`[step ${step}] ${decision.action}`);
if (decision.note) summaryLines.push(`note: ${decision.note}`);
if (decision.action === "RUN")
summaryLines.push(`command: ${decision.command}`);
if (decision.action === "SLEEP")
summaryLines.push(`sleepMs: ${decision.sleepMs}`);
if (record.shell?.executed) {
summaryLines.push(
`result: success=${String(record.shell.success)} exitCode=${String(record.shell.exitCode)} cwd=${String(
record.shell.executedIn ?? "",
)}`,
);
if (record.shell.stdout)
summaryLines.push(`stdout:\n${record.shell.stdout}`);
if (record.shell.stderr)
summaryLines.push(`stderr:\n${record.shell.stderr}`);
if (record.shell.error) summaryLines.push(`error: ${record.shell.error}`);
} else if (record.shell?.error) {
summaryLines.push(`shell: not executed (${record.shell.error})`);
}
const summaryText = summaryLines.join("\n");
// Persist record summary to in-memory DB for context.
await runtime.createMemory(
{
id: uuidv4() as UUID,
entityId: runtime.agentId,
agentId: runtime.agentId,
roomId: autonomousRoomId,
createdAt: Date.now(),
content: { text: summaryText, source: "autonomous-loop" },
metadata: {
type: MemoryType.CUSTOM,
source: "autonomous-loop",
scope: "room",
timestamp: Date.now(),
tags: ["autonomous", "loop"],
},
},
AUTONOMY_TABLE,
);
process.stdout.write(`\n${summaryText}\n`);
if (decision.action === "STOP") {
break;
}
const sleepFor =
decision.action === "SLEEP" ? decision.sleepMs : intervalMs;
await new Promise<void>((resolve) => setTimeout(resolve, sleepFor));
}
await runtime.stop();
}
if (import.meta.main) {
await main();
}