feat: add internal hooks system

This commit is contained in:
Peter Steinberger
2026-01-17 01:31:39 +00:00
parent a76cbc43bb
commit faba508fe0
39 changed files with 4241 additions and 28 deletions

View File

@@ -0,0 +1,76 @@
---
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"}]}}
---
# Session Memory Hook
Automatically saves session context to your workspace memory when you issue the `/new` command.
## What It Does
When you run `/new` to start a fresh session:
1. **Finds the previous session** - Uses the pre-reset session entry to locate the correct transcript
2. **Extracts conversation** - Reads the last 15 lines of conversation from the session
3. **Generates descriptive slug** - Uses LLM to create a meaningful filename slug based on conversation content
4. **Saves to memory** - Creates a new file at `<workspace>/memory/YYYY-MM-DD-slug.md`
5. **Sends confirmation** - Notifies you with the file path
## Output Format
Memory files are created with the following format:
```markdown
# Session: 2026-01-16 14:30:00 UTC
- **Session Key**: agent:main:main
- **Session ID**: abc123def456
- **Source**: telegram
```
## Filename Examples
The LLM generates descriptive slugs based on your conversation:
- `2026-01-16-vendor-pitch.md` - Discussion about vendor evaluation
- `2026-01-16-api-design.md` - API architecture planning
- `2026-01-16-bug-fix.md` - Debugging session
- `2026-01-16-1430.md` - Fallback timestamp if slug generation fails
## Requirements
- **Config**: `workspace.dir` must be set (automatically configured during onboarding)
The hook uses your configured LLM provider to generate slugs, so it works with any provider (Anthropic, OpenAI, etc.).
## 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
## Disabling
To disable this hook:
```bash
clawdbot hooks internal disable session-memory
```
Or remove it from your config:
```json
{
"hooks": {
"internal": {
"entries": {
"session-memory": { "enabled": false }
}
}
}
}
```

View File

@@ -0,0 +1,174 @@
/**
* Session memory hook handler
*
* Saves session context to memory when /new command is triggered
* 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';
/**
* 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');
// Get last 15 lines (recent conversation)
const recentLines = lines.slice(-15);
// Parse JSONL and extract messages
const messages: string[] = [];
for (const line of recentLines) {
try {
const entry = JSON.parse(line);
// Session files have entries with type="message" containing a nested message object
if (entry.type === 'message' && entry.message) {
const msg = entry.message;
const role = msg.role;
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;
if (text && !text.startsWith('/')) {
messages.push(`${role}: ${text}`);
}
}
}
} catch {
// Skip invalid JSON lines
}
}
return messages.join('\n');
} catch {
return null;
}
}
/**
* Save session context to memory when /new command is triggered
*/
const saveSessionToMemory: InternalHookHandler = async (event) => {
// Only trigger on 'new' command
if (event.type !== 'command' || event.action !== 'new') {
return;
}
try {
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');
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
// Generate descriptive slug from session using LLM
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);
const sessionFile = currentSessionFile || undefined;
let slug: string | null = null;
let sessionContent: string | null = null;
if (sessionFile) {
// Get recent conversation content
sessionContent = await getRecentSessionContent(sessionFile);
console.log('[session-memory] sessionContent length:', sessionContent?.length || 0);
if (sessionContent && cfg) {
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 { generateSlugViaLLM } = await import(slugGenPath);
// Use LLM to generate a descriptive slug
slug = await generateSlugViaLLM({ sessionContent, cfg });
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, '');
slug = timeSlug.slice(0, 4); // HHMM
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);
// Format time as HH:MM:SS UTC
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';
// 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, '');
}
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');
// Send confirmation message to user with filename
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);
} catch (err) {
console.error(
'[session-memory] Failed to save session memory:',
err instanceof Error ? err.message : String(err)
);
}
};
export default saveSessionToMemory;