66 lines
1.6 KiB
TypeScript
Raw Normal View History

2026-01-17 01:31:39 +00:00
/**
* Example internal hook handler: Log all commands to a file
*
* This handler demonstrates how to create a hook that logs all command events
* to a centralized log file for audit/debugging purposes.
*
* To enable this handler, add it to your config:
*
* ```json
* {
* "hooks": {
* "internal": {
* "enabled": true,
* "handlers": [
* {
* "event": "command",
* "module": "./hooks/handlers/command-logger.ts"
* }
* ]
* }
* }
* }
* ```
*/
2026-01-17 01:55:42 +00:00
import fs from "node:fs/promises";
import path from "node:path";
import os from "node:os";
import type { InternalHookHandler } from "../../internal-hooks.js";
2026-01-17 01:31:39 +00:00
/**
* Log all command events to a file
*/
const logCommand: InternalHookHandler = async (event) => {
// Only trigger on command events
2026-01-17 01:55:42 +00:00
if (event.type !== "command") {
2026-01-17 01:31:39 +00:00
return;
}
try {
// Create log directory
2026-01-17 01:55:42 +00:00
const logDir = path.join(os.homedir(), ".clawdbot", "logs");
2026-01-17 01:31:39 +00:00
await fs.mkdir(logDir, { recursive: true });
// Append to command log file
2026-01-17 01:55:42 +00:00
const logFile = path.join(logDir, "commands.log");
const logLine =
JSON.stringify({
timestamp: event.timestamp.toISOString(),
action: event.action,
sessionKey: event.sessionKey,
senderId: event.context.senderId ?? "unknown",
source: event.context.commandSource ?? "unknown",
}) + "\n";
2026-01-17 01:31:39 +00:00
2026-01-17 01:55:42 +00:00
await fs.appendFile(logFile, logLine, "utf-8");
2026-01-17 01:31:39 +00:00
} catch (err) {
console.error(
2026-01-17 01:55:42 +00:00
"[command-logger] Failed to log command:",
err instanceof Error ? err.message : String(err),
2026-01-17 01:31:39 +00:00
);
}
};
export default logCommand;