Files
wehub-resource-sync 426e9eeabd
Benchmark Bridge Tests / benchmark (bunx @biomejs/biome check packages/lifeops-bench/src, benchmark-lint) (push) Waiting to run
Benchmark Bridge Tests / benchmark (bunx vitest run --config packages/lifeops-bench/vitest.config.ts --root packages/lifeops-bench --passWithNoTests, benchmark-tests) (push) Waiting to run
Build Agent Image / build-and-push (push) Waiting to run
Chat shell gestures / Chat shell gesture + parity e2e (push) Waiting to run
ci / test (push) Waiting to run
ci / lint-and-format (push) Waiting to run
ci / build (push) Waiting to run
ci / dev-startup (push) Waiting to run
Cloud Gateway Discord / Test (push) Waiting to run
Cloud Gateway Webhook / Test (push) Waiting to run
Cloud Tests / lint-and-types (push) Waiting to run
Cloud Tests / unit-tests (push) Waiting to run
Cloud Tests / integration-tests (push) Waiting to run
Cloud Tests / e2e-tests (push) Blocked by required conditions
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
Deploy Apps Worker (Product 2) / Determine environment (push) Waiting to run
Deploy Apps Worker (Product 2) / Deploy apps worker to apps-control host (${{ needs.determine-env.outputs.environment }}) (push) Blocked by required conditions
Deploy Eliza Provisioning Worker / Determine environment (push) Waiting to run
Deploy Eliza Provisioning Worker / Deploy worker to Hetzner host (${{ needs.determine-env.outputs.environment }} @ ${{ needs.determine-env.outputs.deployment_sha }}) (push) Blocked by required conditions
Dev Smoke / Classify changed paths (push) Waiting to run
Dev Smoke / bun run dev onboarding chat (push) Blocked by required conditions
Dev Smoke / Vite HMR dependency-level smoke (push) Blocked by required conditions
Electrobun Submodule Guard / electrobun gitlink is fetchable (push) Waiting to run
gitleaks / gitleaks (push) Waiting to run
Markdown Links / Relative Markdown Links (push) Waiting to run
Publish @elizaos/example-code / check_npm (push) Waiting to run
Publish @elizaos/example-code / publish_npm (push) Blocked by required conditions
Publish @elizaos/plugin-elizacloud / verify_version (push) Waiting to run
Publish @elizaos/plugin-elizacloud / publish_npm (push) Blocked by required conditions
Quality (Extended) / Homepage Build (PR smoke) (push) Waiting to run
Quality (Extended) / Comment-only diff guard (push) Waiting to run
Quality (Extended) / Format + Type Safety Ratchet (push) Waiting to run
Quality (Extended) / Develop Gate (secret scan + UI determinism) (push) Waiting to run
Quality (Extended) / Develop Gate (lint) (push) Waiting to run
Sandbox Live Smoke / Sandbox live smoke (push) Waiting to run
Snap Build & Test / Build Snap (amd64) (push) Waiting to run
Snap Build & Test / Build Snap (arm64) (push) Waiting to run
supply-chain / sbom (push) Waiting to run
supply-chain / vulnerability-scan (push) Waiting to run
Build, Push & Deploy to Phala Cloud / build-and-push (push) Waiting to run
Test Packaging / Validate Packaging Configs (push) Waiting to run
Test Packaging / PyPI on Python ${{ matrix.python }} (push) Waiting to run
Test Packaging / Pack & Test JS Tarballs (push) Waiting to run
Test Packaging / elizaos CLI global-install smoke (node + bun) (push) Waiting to run
UI Fixture E2E / ui-fixture-e2e (push) Waiting to run
UI Fixture E2E / fixture-e2e (push) Waiting to run
UI Story Gate / story-gate (push) Waiting to run
vault-ci / test (macos-latest) (push) Waiting to run
vault-ci / test (ubuntu-latest) (push) Waiting to run
vault-ci / test (windows-latest) (push) Waiting to run
vault-ci / app-core wiring tests (push) Waiting to run
verify-patches / verify patches/CHECKSUMS.sha256 (push) Waiting to run
Voice Benchmark Smoke / voice-emotion fixture smoke (push) Waiting to run
Voice Benchmark Smoke / voiceagentbench fixture smoke (push) Waiting to run
Voice Benchmark Smoke / voicebench-quality unit smoke (push) Waiting to run
Voice Benchmark Smoke / voicebench TypeScript unit (no audio) (push) Waiting to run
Voice Benchmark Smoke / voice bench smoke summary (push) Blocked by required conditions
Windows CI / windows ([bun run --cwd packages/app-core test bun run --cwd packages/elizaos test bun run --cwd packages/cloud/shared test], app-and-cli) (push) Waiting to run
Windows CI / windows ([bun run --cwd packages/scenario-runner test bun run --cwd packages/vault test bun run --cwd packages/security test bun run --cwd plugins/plugin-coding-tools test], framework-packages) (push) Waiting to run
Windows CI / windows ([bun run --cwd plugins/plugin-elizacloud test bun run --cwd plugins/plugin-discord test bun run --cwd plugins/plugin-anthropic test bun run --cwd plugins/plugin-openai test bun run --cwd plugins/plugin-app-control test bun run --cwd plugins/pl… (push) Waiting to run
Windows CI / windows ([node packages/scripts/run-turbo.mjs run build --filter=@elizaos/core --filter=@elizaos/shared --filter=@elizaos/agent --concurrency=4 node packages/scripts/run-bash-linux-only.mjs scripts/verify-riscv64-buildpaths.sh node packages/scripts/run… (push) Waiting to run
Windows CI / windows ([node packages/scripts/run-turbo.mjs run typecheck --filter=@elizaos/core --filter=@elizaos/shared --filter=@elizaos/cloud-shared --concurrency=4 bun run --cwd packages/core test bun run --cwd packages/shared test], core-runtime, 75) (push) Waiting to run
Test Packaging / Build & Test PyPI Package (push) Waiting to run
Voice Workbench / headless workbench (mocked backends) (push) Has been cancelled
Voice Workbench / real acoustic lane (nightly, provisioned only) (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 12:43:05 +08:00

487 lines
13 KiB
TypeScript

/**
* Runnable autonomous-agent example that lets an Eliza agent decide between
* bounded shell actions, sleeps, and stopping while recording each decision.
*/
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();
}