style: apply oxfmt

This commit is contained in:
Peter Steinberger
2026-01-17 01:55:42 +00:00
parent 767f55b127
commit 3fb699a84b
22 changed files with 375 additions and 377 deletions

View File

@@ -13,6 +13,7 @@ Automatically saves session context to memory when you issue `/new`.
**Output**: `<workspace>/memory/YYYY-MM-DD-slug.md` (defaults to `~/clawd`)
**Enable**:
```bash
clawdbot hooks internal enable session-memory
```
@@ -26,6 +27,7 @@ Logs all command events to a centralized audit file.
**Output**: `~/.clawdbot/logs/commands.log`
**Enable**:
```bash
clawdbot hooks internal enable command-logger
```
@@ -38,6 +40,7 @@ Each hook is a directory containing:
- **handler.ts**: The hook handler function (default export)
Example structure:
```
session-memory/
├── HOOK.md # Metadata + docs
@@ -51,9 +54,9 @@ session-memory/
name: my-hook
description: "Short description"
homepage: https://docs.clawd.bot/hooks/my-hook
metadata: {"clawdbot":{"emoji":"🔗","events":["command:new"],"requires":{"bins":["node"]}}}
metadata:
{ "clawdbot": { "emoji": "🔗", "events": ["command:new"], "requires": { "bins": ["node"] } } }
---
# Hook Title
Documentation goes here...
@@ -83,21 +86,25 @@ Custom hooks follow the same structure as bundled hooks.
## Managing Hooks
List all hooks:
```bash
clawdbot hooks internal list
```
Show hook details:
```bash
clawdbot hooks internal info session-memory
```
Check hook status:
```bash
clawdbot hooks internal check
```
Enable/disable:
```bash
clawdbot hooks internal enable session-memory
clawdbot hooks internal disable command-logger
@@ -142,30 +149,30 @@ Hook handlers receive an `InternalHookEvent` object:
```typescript
interface InternalHookEvent {
type: 'command' | 'session' | 'agent';
action: string; // e.g., 'new', 'reset', 'stop'
type: "command" | "session" | "agent";
action: string; // e.g., 'new', 'reset', 'stop'
sessionKey: string;
context: Record<string, unknown>;
timestamp: Date;
messages: string[]; // Push messages here to send to user
messages: string[]; // Push messages here to send to user
}
```
Example handler:
```typescript
import type { InternalHookHandler } from '../../src/hooks/internal-hooks.js';
import type { InternalHookHandler } from "../../src/hooks/internal-hooks.js";
const myHandler: InternalHookHandler = async (event) => {
if (event.type !== 'command' || event.action !== 'new') {
if (event.type !== "command" || event.action !== "new") {
return;
}
// Your logic here
console.log('New command triggered!');
console.log("New command triggered!");
// Optionally send message to user
event.messages.push('✨ Hook executed!');
event.messages.push("✨ Hook executed!");
};
export default myHandler;

View File

@@ -2,7 +2,15 @@
name: command-logger
description: "Log all command events to a centralized audit file"
homepage: https://docs.clawd.bot/internal-hooks#command-logger
metadata: {"clawdbot":{"emoji":"📝","events":["command"],"install":[{"id":"bundled","kind":"bundled","label":"Bundled with Clawdbot"}]}}
metadata:
{
"clawdbot":
{
"emoji": "📝",
"events": ["command"],
"install": [{ "id": "bundled", "kind": "bundled", "label": "Bundled with Clawdbot" }],
},
}
---
# Command Logger Hook
@@ -44,6 +52,7 @@ No requirements - this hook works out of the box on all platforms.
## Configuration
No configuration needed. The hook automatically:
- Creates the log directory if it doesn't exist
- Appends to the log file (doesn't overwrite)
- Handles errors silently without disrupting command execution
@@ -75,6 +84,7 @@ Or via config:
The hook does not automatically rotate logs. To manage log size, you can:
1. **Manual rotation**:
```bash
mv ~/.clawdbot/logs/commands.log ~/.clawdbot/logs/commands.log.old
```
@@ -94,16 +104,19 @@ The hook does not automatically rotate logs. To manage log size, you can:
## Viewing Logs
View recent commands:
```bash
tail -n 20 ~/.clawdbot/logs/commands.log
```
Pretty-print with jq:
```bash
cat ~/.clawdbot/logs/commands.log | jq .
```
Filter by action:
```bash
grep '"action":"new"' ~/.clawdbot/logs/commands.log | jq .
```

View File

@@ -23,40 +23,41 @@
* ```
*/
import fs from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import type { InternalHookHandler } from '../../internal-hooks.js';
import fs from "node:fs/promises";
import path from "node:path";
import os from "node:os";
import type { InternalHookHandler } from "../../internal-hooks.js";
/**
* Log all command events to a file
*/
const logCommand: InternalHookHandler = async (event) => {
// Only trigger on command events
if (event.type !== 'command') {
if (event.type !== "command") {
return;
}
try {
// Create log directory
const logDir = path.join(os.homedir(), '.clawdbot', 'logs');
const logDir = path.join(os.homedir(), ".clawdbot", "logs");
await fs.mkdir(logDir, { recursive: true });
// Append to command log file
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';
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";
await fs.appendFile(logFile, logLine, 'utf-8');
await fs.appendFile(logFile, logLine, "utf-8");
} catch (err) {
console.error(
'[command-logger] Failed to log command:',
err instanceof Error ? err.message : String(err)
"[command-logger] Failed to log command:",
err instanceof Error ? err.message : String(err),
);
}
};

View File

@@ -2,7 +2,16 @@
name: session-memory
description: "Save session context to memory when /new command is issued"
homepage: https://docs.clawd.bot/internal-hooks#session-memory
metadata: {"clawdbot":{"emoji":"💾","events":["command:new"],"requires":{"config":["workspace.dir"]},"install":[{"id":"bundled","kind":"bundled","label":"Bundled with Clawdbot"}]}}
metadata:
{
"clawdbot":
{
"emoji": "💾",
"events": ["command:new"],
"requires": { "config": ["workspace.dir"] },
"install": [{ "id": "bundled", "kind": "bundled", "label": "Bundled with Clawdbot" }],
},
}
---
# Session Memory Hook
@@ -49,6 +58,7 @@ The hook uses your configured LLM provider to generate slugs, so it works with a
## Configuration
No additional configuration required. The hook automatically:
- Uses your workspace directory (`~/clawd` by default)
- Uses your configured LLM for slug generation
- Falls back to timestamp slugs if LLM is unavailable

View File

@@ -5,21 +5,21 @@
* Creates a new dated memory file with LLM-generated slug
*/
import fs from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import type { ClawdbotConfig } from '../../../config/config.js';
import { resolveAgentWorkspaceDir } from '../../../agents/agent-scope.js';
import { resolveAgentIdFromSessionKey } from '../../../routing/session-key.js';
import type { InternalHookHandler } from '../../internal-hooks.js';
import fs from "node:fs/promises";
import path from "node:path";
import os from "node:os";
import type { ClawdbotConfig } from "../../../config/config.js";
import { resolveAgentWorkspaceDir } from "../../../agents/agent-scope.js";
import { resolveAgentIdFromSessionKey } from "../../../routing/session-key.js";
import type { InternalHookHandler } from "../../internal-hooks.js";
/**
* Read recent messages from session file for slug generation
*/
async function getRecentSessionContent(sessionFilePath: string): Promise<string | null> {
try {
const content = await fs.readFile(sessionFilePath, 'utf-8');
const lines = content.trim().split('\n');
const content = await fs.readFile(sessionFilePath, "utf-8");
const lines = content.trim().split("\n");
// Get last 15 lines (recent conversation)
const recentLines = lines.slice(-15);
@@ -30,15 +30,15 @@ async function getRecentSessionContent(sessionFilePath: string): Promise<string
try {
const entry = JSON.parse(line);
// Session files have entries with type="message" containing a nested message object
if (entry.type === 'message' && entry.message) {
if (entry.type === "message" && entry.message) {
const msg = entry.message;
const role = msg.role;
if ((role === 'user' || role === 'assistant') && msg.content) {
if ((role === "user" || role === "assistant") && msg.content) {
// Extract text content
const text = Array.isArray(msg.content)
? msg.content.find((c: any) => c.type === 'text')?.text
? msg.content.find((c: any) => c.type === "text")?.text
: msg.content;
if (text && !text.startsWith('/')) {
if (text && !text.startsWith("/")) {
messages.push(`${role}: ${text}`);
}
}
@@ -48,7 +48,7 @@ async function getRecentSessionContent(sessionFilePath: string): Promise<string
}
}
return messages.join('\n');
return messages.join("\n");
} catch {
return null;
}
@@ -59,38 +59,37 @@ async function getRecentSessionContent(sessionFilePath: string): Promise<string
*/
const saveSessionToMemory: InternalHookHandler = async (event) => {
// Only trigger on 'new' command
if (event.type !== 'command' || event.action !== 'new') {
if (event.type !== "command" || event.action !== "new") {
return;
}
try {
console.log('[session-memory] Hook triggered for /new command');
console.log("[session-memory] Hook triggered for /new command");
const context = event.context || {};
const cfg = context.cfg as ClawdbotConfig | undefined;
const agentId = resolveAgentIdFromSessionKey(event.sessionKey);
const workspaceDir = cfg
? resolveAgentWorkspaceDir(cfg, agentId)
: path.join(os.homedir(), 'clawd');
const memoryDir = path.join(workspaceDir, 'memory');
: path.join(os.homedir(), "clawd");
const memoryDir = path.join(workspaceDir, "memory");
await fs.mkdir(memoryDir, { recursive: true });
// Get today's date for filename
const now = new Date(event.timestamp);
const dateStr = now.toISOString().split('T')[0]; // YYYY-MM-DD
const dateStr = now.toISOString().split("T")[0]; // YYYY-MM-DD
// Generate descriptive slug from session using LLM
const sessionEntry = (
context.previousSessionEntry ||
context.sessionEntry ||
{}
) as Record<string, unknown>;
const sessionEntry = (context.previousSessionEntry || context.sessionEntry || {}) as Record<
string,
unknown
>;
const currentSessionId = sessionEntry.sessionId as string;
const currentSessionFile = sessionEntry.sessionFile as string;
console.log('[session-memory] Current sessionId:', currentSessionId);
console.log('[session-memory] Current sessionFile:', currentSessionFile);
console.log('[session-memory] cfg present:', !!cfg);
console.log("[session-memory] Current sessionId:", currentSessionId);
console.log("[session-memory] Current sessionFile:", currentSessionFile);
console.log("[session-memory] cfg present:", !!cfg);
const sessionFile = currentSessionFile || undefined;
@@ -100,73 +99,76 @@ const saveSessionToMemory: InternalHookHandler = async (event) => {
if (sessionFile) {
// Get recent conversation content
sessionContent = await getRecentSessionContent(sessionFile);
console.log('[session-memory] sessionContent length:', sessionContent?.length || 0);
console.log("[session-memory] sessionContent length:", sessionContent?.length || 0);
if (sessionContent && cfg) {
console.log('[session-memory] Calling generateSlugViaLLM...');
console.log("[session-memory] Calling generateSlugViaLLM...");
// Dynamically import the LLM slug generator (avoids module caching issues)
// When compiled, handler is at dist/hooks/bundled/session-memory/handler.js
// Going up ../.. puts us at dist/hooks/, so just add llm-slug-generator.js
const clawdbotRoot = path.resolve(path.dirname(import.meta.url.replace('file://', '')), '../..');
const slugGenPath = path.join(clawdbotRoot, 'llm-slug-generator.js');
const clawdbotRoot = path.resolve(
path.dirname(import.meta.url.replace("file://", "")),
"../..",
);
const slugGenPath = path.join(clawdbotRoot, "llm-slug-generator.js");
const { generateSlugViaLLM } = await import(slugGenPath);
// Use LLM to generate a descriptive slug
slug = await generateSlugViaLLM({ sessionContent, cfg });
console.log('[session-memory] Generated slug:', slug);
console.log("[session-memory] Generated slug:", slug);
}
}
// If no slug, use timestamp
if (!slug) {
const timeSlug = now.toISOString().split('T')[1]!.split('.')[0]!.replace(/:/g, '');
const timeSlug = now.toISOString().split("T")[1]!.split(".")[0]!.replace(/:/g, "");
slug = timeSlug.slice(0, 4); // HHMM
console.log('[session-memory] Using fallback timestamp slug:', slug);
console.log("[session-memory] Using fallback timestamp slug:", slug);
}
// Create filename with date and slug
const filename = `${dateStr}-${slug}.md`;
const memoryFilePath = path.join(memoryDir, filename);
console.log('[session-memory] Generated filename:', filename);
console.log('[session-memory] Full path:', memoryFilePath);
console.log("[session-memory] Generated filename:", filename);
console.log("[session-memory] Full path:", memoryFilePath);
// Format time as HH:MM:SS UTC
const timeStr = now.toISOString().split('T')[1]!.split('.')[0];
const timeStr = now.toISOString().split("T")[1]!.split(".")[0];
// Extract context details
const sessionId = (sessionEntry.sessionId as string) || 'unknown';
const source = (context.commandSource as string) || 'unknown';
const sessionId = (sessionEntry.sessionId as string) || "unknown";
const source = (context.commandSource as string) || "unknown";
// Build Markdown entry
const entryParts = [
`# Session: ${dateStr} ${timeStr} UTC`,
'',
"",
`- **Session Key**: ${event.sessionKey}`,
`- **Session ID**: ${sessionId}`,
`- **Source**: ${source}`,
'',
"",
];
// Include conversation content if available
if (sessionContent) {
entryParts.push('## Conversation Summary', '', sessionContent, '');
entryParts.push("## Conversation Summary", "", sessionContent, "");
}
const entry = entryParts.join('\n');
const entry = entryParts.join("\n");
// Write to new memory file
await fs.writeFile(memoryFilePath, entry, 'utf-8');
console.log('[session-memory] Memory file written successfully');
await fs.writeFile(memoryFilePath, entry, "utf-8");
console.log("[session-memory] Memory file written successfully");
// Send confirmation message to user with filename
const relPath = memoryFilePath.replace(os.homedir(), '~');
const relPath = memoryFilePath.replace(os.homedir(), "~");
const confirmMsg = `💾 Session context saved to memory before reset.\n📄 ${relPath}`;
event.messages.push(confirmMsg);
console.log('[session-memory] Confirmation message queued:', confirmMsg);
console.log("[session-memory] Confirmation message queued:", confirmMsg);
} catch (err) {
console.error(
'[session-memory] Failed to save session memory:',
err instanceof Error ? err.message : String(err)
"[session-memory] Failed to save session memory:",
err instanceof Error ? err.message : String(err),
);
}
};