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

193 lines
7.2 KiB
TypeScript

/**
* SHELL_HISTORY provider — injects recent shell activity into agent context: the
* last commands with stdout/stderr/exit codes, the current and allowed working
* directories, and recent file operations. Fires only in terminal/code contexts
* and reads its state from ShellService.
*/
import {
addHeader,
type IAgentRuntime,
logger,
type Memory,
type Provider,
type State,
} from "@elizaos/core";
import { requireProviderSpec } from "../generated/specs/spec-helpers";
import type { ShellService } from "../services/shellService";
import type { CommandHistoryEntry, FileOperation } from "../types";
const MAX_OUTPUT_LENGTH = 8000;
const TRUNCATE_SEGMENT_LENGTH = 4000;
const spec = requireProviderSpec("SHELL_HISTORY");
export const shellHistoryProvider: Provider = {
name: spec.name,
description:
"Provides recent shell command history, current working directory, and file operations within the restricted environment",
descriptionCompressed: "Recent shell history, cwd, and file ops in restricted env.",
position: 99,
contexts: ["terminal", "code"],
contextGate: { anyOf: ["terminal", "code"] },
cacheStable: false,
cacheScope: "turn",
// Shell history / cwd / file ops are host-operator context — admin+ only.
// (#12094 item 3: the gate lives on the provider so it can't drift.)
roleGate: { minRole: "ADMIN" },
dynamic: true,
get: async (runtime: IAgentRuntime, message: Memory, _state: State) => {
try {
const shellService = runtime.getService<ShellService>("shell");
if (!shellService) {
logger.warn("[shellHistoryProvider] Shell service not found");
return {
values: {
shellHistory: "Shell service is not available",
currentWorkingDirectory: "N/A",
allowedDirectory: "N/A",
},
text: addHeader("# Shell Status", "Shell service is not available"),
data: { historyCount: 0, cwd: "N/A", allowedDir: "N/A" },
};
}
const conversationId = message.roomId || message.agentId;
if (!conversationId) {
return {
text: "No conversation ID available",
values: { historyCount: 0, cwd: "N/A", allowedDir: "N/A" },
data: { historyCount: 0, cwd: "N/A", allowedDir: "N/A" },
};
}
const history = shellService.getCommandHistory(conversationId, 10);
const cwd = shellService.getCurrentDirectory(conversationId);
const allowedDir = shellService.getAllowedDirectory();
let historyText = "No commands in history.";
if (history.length > 0) {
historyText = history
.map((entry: CommandHistoryEntry) => {
let entryStr = `[${new Date(entry.timestamp).toISOString()}] ${entry.workingDirectory}> ${entry.command}`;
if (entry.stdout) {
if (entry.stdout.length > MAX_OUTPUT_LENGTH) {
entryStr += `\n Output: ${entry.stdout.substring(0, TRUNCATE_SEGMENT_LENGTH)}\n ... [TRUNCATED] ...\n ${entry.stdout.substring(entry.stdout.length - TRUNCATE_SEGMENT_LENGTH)}`;
} else {
entryStr += `\n Output: ${entry.stdout}`;
}
}
if (entry.stderr) {
if (entry.stderr.length > MAX_OUTPUT_LENGTH) {
entryStr += `\n Error: ${entry.stderr.substring(0, TRUNCATE_SEGMENT_LENGTH)}\n ... [TRUNCATED] ...\n ${entry.stderr.substring(entry.stderr.length - TRUNCATE_SEGMENT_LENGTH)}`;
} else {
entryStr += `\n Error: ${entry.stderr}`;
}
}
entryStr += `\n Exit Code: ${entry.exitCode}`;
if (entry.fileOperations && entry.fileOperations.length > 0) {
entryStr += "\n File Operations:";
entry.fileOperations.forEach((op: FileOperation) => {
if (op.secondaryTarget) {
entryStr += `\n - ${op.type}: ${op.target}${op.secondaryTarget}`;
} else {
entryStr += `\n - ${op.type}: ${op.target}`;
}
});
}
return entryStr;
})
.join("\n\n");
}
const recentFileOps = history
.filter(
(entry: CommandHistoryEntry) => entry.fileOperations && entry.fileOperations.length > 0
)
.flatMap((entry: CommandHistoryEntry) => entry.fileOperations ?? [])
.slice(-5);
let fileOpsText = "";
if (recentFileOps.length > 0) {
fileOpsText =
"\n\n" +
addHeader(
"# Recent File Operations",
recentFileOps
.map((op: FileOperation) => {
if (op.secondaryTarget) {
return `- ${op.type}: ${op.target}${op.secondaryTarget}`;
}
return `- ${op.type}: ${op.target}`;
})
.join("\n")
);
}
const text = `Current Directory: ${cwd}
Allowed Directory: ${allowedDir}
${addHeader("# Shell History (Last 10)", historyText)}${fileOpsText}`;
return {
values: {
shellHistory: historyText,
currentWorkingDirectory: cwd,
allowedDirectory: allowedDir,
},
text,
data: {
historyCount: history.length,
cwd,
allowedDir,
},
};
} catch (error) {
// error-policy:J4 designed unavailable render; the provider emits a
// distinguishable "Shell history is unavailable: <msg>" status AND reports
// the failure via reportError — never a healthy-looking empty history.
//
// Surface the failure through the runtime diagnostic boundary AND as a
// model-visible status line. A bare `catch {}` that returned an empty
// string here hid real ShellService failures from both the operator logs
// and the planner loop, presenting success-shaped empty output instead of
// an error the model could react to (#12273/#12799).
//
// `runtime.reportError` (#12263) is the diagnostic boundary for provider
// failures: it logs with a `[scope]` prefix, emits ERROR_REPORTED, feeds
// the RECENT_ERRORS provider (so repeated shell-history backend failures
// become observable to the agent), and drives owner escalation. It never
// throws. Fall back to logger.error on runtimes/test doubles that predate
// it so the failure is never silently swallowed.
const errMsg = error instanceof Error ? error.message : String(error);
if (typeof runtime?.reportError === "function") {
runtime.reportError("shellHistoryProvider", error, {
roomId: message.roomId,
agentId: message.agentId,
});
} else {
logger.error(
{ src: "shellHistoryProvider", error },
`[shellHistoryProvider] Failed to build shell history context: ${errMsg}`
);
}
const statusText = `Shell history is unavailable: ${errMsg}`;
return {
values: {
shellHistory: statusText,
currentWorkingDirectory: "N/A",
allowedDirectory: "N/A",
},
text: addHeader("# Shell Status", statusText),
data: { historyCount: 0, cwd: "N/A", allowedDir: "N/A", error: errMsg },
};
}
},
};
export default shellHistoryProvider;