style: apply oxfmt
This commit is contained in:
@@ -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;
|
||||
|
||||
@@ -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 .
|
||||
```
|
||||
|
||||
@@ -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),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -84,12 +84,7 @@ function parseFrontmatterBool(value: string | undefined, fallback: boolean): boo
|
||||
if (normalized === "true" || normalized === "1" || normalized === "yes" || normalized === "on") {
|
||||
return true;
|
||||
}
|
||||
if (
|
||||
normalized === "false" ||
|
||||
normalized === "0" ||
|
||||
normalized === "no" ||
|
||||
normalized === "off"
|
||||
) {
|
||||
if (normalized === "false" || normalized === "0" || normalized === "no" || normalized === "off") {
|
||||
return false;
|
||||
}
|
||||
return fallback;
|
||||
|
||||
@@ -2,17 +2,8 @@ import path from "node:path";
|
||||
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import { CONFIG_DIR } from "../utils.js";
|
||||
import {
|
||||
hasBinary,
|
||||
isConfigPathTruthy,
|
||||
resolveConfigPath,
|
||||
resolveHookConfig,
|
||||
} from "./config.js";
|
||||
import type {
|
||||
HookEligibilityContext,
|
||||
HookEntry,
|
||||
HookInstallSpec,
|
||||
} from "./types.js";
|
||||
import { hasBinary, isConfigPathTruthy, resolveConfigPath, resolveHookConfig } from "./config.js";
|
||||
import type { HookEligibilityContext, HookEntry, HookInstallSpec } from "./types.js";
|
||||
import { loadWorkspaceHookEntries } from "./workspace.js";
|
||||
|
||||
export type HookStatusConfigCheck = {
|
||||
@@ -155,9 +146,7 @@ function buildHookStatus(
|
||||
return { path: pathStr, value, satisfied };
|
||||
});
|
||||
|
||||
const missingConfig = configChecks
|
||||
.filter((check) => !check.satisfied)
|
||||
.map((check) => check.path);
|
||||
const missingConfig = configChecks.filter((check) => !check.satisfied).map((check) => check.path);
|
||||
|
||||
const missing = always
|
||||
? { bins: [], anyBins: [], env: [], config: [], os: [] }
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
clearInternalHooks,
|
||||
createInternalHookEvent,
|
||||
@@ -7,9 +7,9 @@ import {
|
||||
triggerInternalHook,
|
||||
unregisterInternalHook,
|
||||
type InternalHookEvent,
|
||||
} from './internal-hooks.js';
|
||||
} from "./internal-hooks.js";
|
||||
|
||||
describe('internal-hooks', () => {
|
||||
describe("internal-hooks", () => {
|
||||
beforeEach(() => {
|
||||
clearInternalHooks();
|
||||
});
|
||||
@@ -18,174 +18,174 @@ describe('internal-hooks', () => {
|
||||
clearInternalHooks();
|
||||
});
|
||||
|
||||
describe('registerInternalHook', () => {
|
||||
it('should register a hook handler', () => {
|
||||
describe("registerInternalHook", () => {
|
||||
it("should register a hook handler", () => {
|
||||
const handler = vi.fn();
|
||||
registerInternalHook('command:new', handler);
|
||||
registerInternalHook("command:new", handler);
|
||||
|
||||
const keys = getRegisteredEventKeys();
|
||||
expect(keys).toContain('command:new');
|
||||
expect(keys).toContain("command:new");
|
||||
});
|
||||
|
||||
it('should allow multiple handlers for the same event', () => {
|
||||
it("should allow multiple handlers for the same event", () => {
|
||||
const handler1 = vi.fn();
|
||||
const handler2 = vi.fn();
|
||||
|
||||
registerInternalHook('command:new', handler1);
|
||||
registerInternalHook('command:new', handler2);
|
||||
registerInternalHook("command:new", handler1);
|
||||
registerInternalHook("command:new", handler2);
|
||||
|
||||
const keys = getRegisteredEventKeys();
|
||||
expect(keys).toContain('command:new');
|
||||
expect(keys).toContain("command:new");
|
||||
});
|
||||
});
|
||||
|
||||
describe('unregisterInternalHook', () => {
|
||||
it('should unregister a specific handler', () => {
|
||||
describe("unregisterInternalHook", () => {
|
||||
it("should unregister a specific handler", () => {
|
||||
const handler1 = vi.fn();
|
||||
const handler2 = vi.fn();
|
||||
|
||||
registerInternalHook('command:new', handler1);
|
||||
registerInternalHook('command:new', handler2);
|
||||
registerInternalHook("command:new", handler1);
|
||||
registerInternalHook("command:new", handler2);
|
||||
|
||||
unregisterInternalHook('command:new', handler1);
|
||||
unregisterInternalHook("command:new", handler1);
|
||||
|
||||
const event = createInternalHookEvent('command', 'new', 'test-session');
|
||||
const event = createInternalHookEvent("command", "new", "test-session");
|
||||
void triggerInternalHook(event);
|
||||
|
||||
expect(handler1).not.toHaveBeenCalled();
|
||||
expect(handler2).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should clean up empty handler arrays', () => {
|
||||
it("should clean up empty handler arrays", () => {
|
||||
const handler = vi.fn();
|
||||
|
||||
registerInternalHook('command:new', handler);
|
||||
unregisterInternalHook('command:new', handler);
|
||||
registerInternalHook("command:new", handler);
|
||||
unregisterInternalHook("command:new", handler);
|
||||
|
||||
const keys = getRegisteredEventKeys();
|
||||
expect(keys).not.toContain('command:new');
|
||||
expect(keys).not.toContain("command:new");
|
||||
});
|
||||
});
|
||||
|
||||
describe('triggerInternalHook', () => {
|
||||
it('should trigger handlers for general event type', async () => {
|
||||
describe("triggerInternalHook", () => {
|
||||
it("should trigger handlers for general event type", async () => {
|
||||
const handler = vi.fn();
|
||||
registerInternalHook('command', handler);
|
||||
registerInternalHook("command", handler);
|
||||
|
||||
const event = createInternalHookEvent('command', 'new', 'test-session');
|
||||
const event = createInternalHookEvent("command", "new", "test-session");
|
||||
await triggerInternalHook(event);
|
||||
|
||||
expect(handler).toHaveBeenCalledWith(event);
|
||||
});
|
||||
|
||||
it('should trigger handlers for specific event action', async () => {
|
||||
it("should trigger handlers for specific event action", async () => {
|
||||
const handler = vi.fn();
|
||||
registerInternalHook('command:new', handler);
|
||||
registerInternalHook("command:new", handler);
|
||||
|
||||
const event = createInternalHookEvent('command', 'new', 'test-session');
|
||||
const event = createInternalHookEvent("command", "new", "test-session");
|
||||
await triggerInternalHook(event);
|
||||
|
||||
expect(handler).toHaveBeenCalledWith(event);
|
||||
});
|
||||
|
||||
it('should trigger both general and specific handlers', async () => {
|
||||
it("should trigger both general and specific handlers", async () => {
|
||||
const generalHandler = vi.fn();
|
||||
const specificHandler = vi.fn();
|
||||
|
||||
registerInternalHook('command', generalHandler);
|
||||
registerInternalHook('command:new', specificHandler);
|
||||
registerInternalHook("command", generalHandler);
|
||||
registerInternalHook("command:new", specificHandler);
|
||||
|
||||
const event = createInternalHookEvent('command', 'new', 'test-session');
|
||||
const event = createInternalHookEvent("command", "new", "test-session");
|
||||
await triggerInternalHook(event);
|
||||
|
||||
expect(generalHandler).toHaveBeenCalledWith(event);
|
||||
expect(specificHandler).toHaveBeenCalledWith(event);
|
||||
});
|
||||
|
||||
it('should handle async handlers', async () => {
|
||||
it("should handle async handlers", async () => {
|
||||
const handler = vi.fn(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
});
|
||||
|
||||
registerInternalHook('command:new', handler);
|
||||
registerInternalHook("command:new", handler);
|
||||
|
||||
const event = createInternalHookEvent('command', 'new', 'test-session');
|
||||
const event = createInternalHookEvent("command", "new", "test-session");
|
||||
await triggerInternalHook(event);
|
||||
|
||||
expect(handler).toHaveBeenCalledWith(event);
|
||||
});
|
||||
|
||||
it('should catch and log errors from handlers', async () => {
|
||||
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
it("should catch and log errors from handlers", async () => {
|
||||
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const errorHandler = vi.fn(() => {
|
||||
throw new Error('Handler failed');
|
||||
throw new Error("Handler failed");
|
||||
});
|
||||
const successHandler = vi.fn();
|
||||
|
||||
registerInternalHook('command:new', errorHandler);
|
||||
registerInternalHook('command:new', successHandler);
|
||||
registerInternalHook("command:new", errorHandler);
|
||||
registerInternalHook("command:new", successHandler);
|
||||
|
||||
const event = createInternalHookEvent('command', 'new', 'test-session');
|
||||
const event = createInternalHookEvent("command", "new", "test-session");
|
||||
await triggerInternalHook(event);
|
||||
|
||||
expect(errorHandler).toHaveBeenCalled();
|
||||
expect(successHandler).toHaveBeenCalled();
|
||||
expect(consoleError).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Internal hook error'),
|
||||
expect.stringContaining('Handler failed')
|
||||
expect.stringContaining("Internal hook error"),
|
||||
expect.stringContaining("Handler failed"),
|
||||
);
|
||||
|
||||
consoleError.mockRestore();
|
||||
});
|
||||
|
||||
it('should not throw if no handlers are registered', async () => {
|
||||
const event = createInternalHookEvent('command', 'new', 'test-session');
|
||||
it("should not throw if no handlers are registered", async () => {
|
||||
const event = createInternalHookEvent("command", "new", "test-session");
|
||||
await expect(triggerInternalHook(event)).resolves.not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('createInternalHookEvent', () => {
|
||||
it('should create a properly formatted event', () => {
|
||||
const event = createInternalHookEvent('command', 'new', 'test-session', {
|
||||
foo: 'bar',
|
||||
describe("createInternalHookEvent", () => {
|
||||
it("should create a properly formatted event", () => {
|
||||
const event = createInternalHookEvent("command", "new", "test-session", {
|
||||
foo: "bar",
|
||||
});
|
||||
|
||||
expect(event.type).toBe('command');
|
||||
expect(event.action).toBe('new');
|
||||
expect(event.sessionKey).toBe('test-session');
|
||||
expect(event.context).toEqual({ foo: 'bar' });
|
||||
expect(event.type).toBe("command");
|
||||
expect(event.action).toBe("new");
|
||||
expect(event.sessionKey).toBe("test-session");
|
||||
expect(event.context).toEqual({ foo: "bar" });
|
||||
expect(event.timestamp).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
it('should use empty context if not provided', () => {
|
||||
const event = createInternalHookEvent('command', 'new', 'test-session');
|
||||
it("should use empty context if not provided", () => {
|
||||
const event = createInternalHookEvent("command", "new", "test-session");
|
||||
|
||||
expect(event.context).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe('getRegisteredEventKeys', () => {
|
||||
it('should return all registered event keys', () => {
|
||||
registerInternalHook('command:new', vi.fn());
|
||||
registerInternalHook('command:stop', vi.fn());
|
||||
registerInternalHook('session:start', vi.fn());
|
||||
describe("getRegisteredEventKeys", () => {
|
||||
it("should return all registered event keys", () => {
|
||||
registerInternalHook("command:new", vi.fn());
|
||||
registerInternalHook("command:stop", vi.fn());
|
||||
registerInternalHook("session:start", vi.fn());
|
||||
|
||||
const keys = getRegisteredEventKeys();
|
||||
expect(keys).toContain('command:new');
|
||||
expect(keys).toContain('command:stop');
|
||||
expect(keys).toContain('session:start');
|
||||
expect(keys).toContain("command:new");
|
||||
expect(keys).toContain("command:stop");
|
||||
expect(keys).toContain("session:start");
|
||||
});
|
||||
|
||||
it('should return empty array when no handlers are registered', () => {
|
||||
it("should return empty array when no handlers are registered", () => {
|
||||
const keys = getRegisteredEventKeys();
|
||||
expect(keys).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('clearInternalHooks', () => {
|
||||
it('should remove all registered handlers', () => {
|
||||
registerInternalHook('command:new', vi.fn());
|
||||
registerInternalHook('command:stop', vi.fn());
|
||||
describe("clearInternalHooks", () => {
|
||||
it("should remove all registered handlers", () => {
|
||||
registerInternalHook("command:new", vi.fn());
|
||||
registerInternalHook("command:stop", vi.fn());
|
||||
|
||||
clearInternalHooks();
|
||||
|
||||
@@ -194,33 +194,33 @@ describe('internal-hooks', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('integration', () => {
|
||||
it('should handle a complete hook lifecycle', async () => {
|
||||
describe("integration", () => {
|
||||
it("should handle a complete hook lifecycle", async () => {
|
||||
const results: InternalHookEvent[] = [];
|
||||
const handler = vi.fn((event: InternalHookEvent) => {
|
||||
results.push(event);
|
||||
});
|
||||
|
||||
// Register
|
||||
registerInternalHook('command:new', handler);
|
||||
registerInternalHook("command:new", handler);
|
||||
|
||||
// Trigger
|
||||
const event1 = createInternalHookEvent('command', 'new', 'session-1');
|
||||
const event1 = createInternalHookEvent("command", "new", "session-1");
|
||||
await triggerInternalHook(event1);
|
||||
|
||||
const event2 = createInternalHookEvent('command', 'new', 'session-2');
|
||||
const event2 = createInternalHookEvent("command", "new", "session-2");
|
||||
await triggerInternalHook(event2);
|
||||
|
||||
// Verify
|
||||
expect(results).toHaveLength(2);
|
||||
expect(results[0].sessionKey).toBe('session-1');
|
||||
expect(results[1].sessionKey).toBe('session-2');
|
||||
expect(results[0].sessionKey).toBe("session-1");
|
||||
expect(results[1].sessionKey).toBe("session-2");
|
||||
|
||||
// Unregister
|
||||
unregisterInternalHook('command:new', handler);
|
||||
unregisterInternalHook("command:new", handler);
|
||||
|
||||
// Trigger again - should not call handler
|
||||
const event3 = createInternalHookEvent('command', 'new', 'session-3');
|
||||
const event3 = createInternalHookEvent("command", "new", "session-3");
|
||||
await triggerInternalHook(event3);
|
||||
|
||||
expect(results).toHaveLength(2);
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
* like command processing, session lifecycle, etc.
|
||||
*/
|
||||
|
||||
export type InternalHookEventType = 'command' | 'session' | 'agent';
|
||||
export type InternalHookEventType = "command" | "session" | "agent";
|
||||
|
||||
export interface InternalHookEvent {
|
||||
/** The type of event (command, session, agent, etc.) */
|
||||
@@ -46,10 +46,7 @@ const handlers = new Map<string, InternalHookHandler[]>();
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function registerInternalHook(
|
||||
eventKey: string,
|
||||
handler: InternalHookHandler
|
||||
): void {
|
||||
export function registerInternalHook(eventKey: string, handler: InternalHookHandler): void {
|
||||
if (!handlers.has(eventKey)) {
|
||||
handlers.set(eventKey, []);
|
||||
}
|
||||
@@ -62,10 +59,7 @@ export function registerInternalHook(
|
||||
* @param eventKey - Event key the handler was registered for
|
||||
* @param handler - The handler function to remove
|
||||
*/
|
||||
export function unregisterInternalHook(
|
||||
eventKey: string,
|
||||
handler: InternalHookHandler
|
||||
): void {
|
||||
export function unregisterInternalHook(eventKey: string, handler: InternalHookHandler): void {
|
||||
const eventHandlers = handlers.get(eventKey);
|
||||
if (!eventHandlers) {
|
||||
return;
|
||||
@@ -124,7 +118,7 @@ export async function triggerInternalHook(event: InternalHookEvent): Promise<voi
|
||||
} catch (err) {
|
||||
console.error(
|
||||
`Internal hook error [${event.type}:${event.action}]:`,
|
||||
err instanceof Error ? err.message : String(err)
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -142,7 +136,7 @@ export function createInternalHookEvent(
|
||||
type: InternalHookEventType,
|
||||
action: string,
|
||||
sessionKey: string,
|
||||
context: Record<string, unknown> = {}
|
||||
context: Record<string, unknown> = {},
|
||||
): InternalHookEvent {
|
||||
return {
|
||||
type,
|
||||
|
||||
@@ -2,12 +2,16 @@
|
||||
* LLM-based slug generator for session memory filenames
|
||||
*/
|
||||
|
||||
import fs from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { runEmbeddedPiAgent } from '../agents/pi-embedded.js';
|
||||
import type { ClawdbotConfig } from '../config/config.js';
|
||||
import { resolveDefaultAgentId, resolveAgentWorkspaceDir, resolveAgentDir } from '../agents/agent-scope.js';
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { runEmbeddedPiAgent } from "../agents/pi-embedded.js";
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import {
|
||||
resolveDefaultAgentId,
|
||||
resolveAgentWorkspaceDir,
|
||||
resolveAgentDir,
|
||||
} from "../agents/agent-scope.js";
|
||||
|
||||
/**
|
||||
* Generate a short 1-2 word filename slug from session content using LLM
|
||||
@@ -24,8 +28,8 @@ export async function generateSlugViaLLM(params: {
|
||||
const agentDir = resolveAgentDir(params.cfg, agentId);
|
||||
|
||||
// Create a temporary session file for this one-off LLM call
|
||||
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'clawdbot-slug-'));
|
||||
tempSessionFile = path.join(tempDir, 'session.jsonl');
|
||||
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-slug-"));
|
||||
tempSessionFile = path.join(tempDir, "session.jsonl");
|
||||
|
||||
const prompt = `Based on this conversation, generate a short 1-2 word filename slug (lowercase, hyphen-separated, no file extension).
|
||||
|
||||
@@ -36,7 +40,7 @@ Reply with ONLY the slug, nothing else. Examples: "vendor-pitch", "api-design",
|
||||
|
||||
const result = await runEmbeddedPiAgent({
|
||||
sessionId: `slug-generator-${Date.now()}`,
|
||||
sessionKey: 'temp:slug-generator',
|
||||
sessionKey: "temp:slug-generator",
|
||||
sessionFile: tempSessionFile,
|
||||
workspaceDir,
|
||||
agentDir,
|
||||
@@ -54,9 +58,9 @@ Reply with ONLY the slug, nothing else. Examples: "vendor-pitch", "api-design",
|
||||
const slug = text
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9-]/g, '-')
|
||||
.replace(/-+/g, '-')
|
||||
.replace(/^-|-$/g, '')
|
||||
.replace(/[^a-z0-9-]/g, "-")
|
||||
.replace(/-+/g, "-")
|
||||
.replace(/^-|-$/g, "")
|
||||
.slice(0, 30); // Max 30 chars
|
||||
|
||||
return slug || null;
|
||||
@@ -65,7 +69,7 @@ Reply with ONLY the slug, nothing else. Examples: "vendor-pitch", "api-design",
|
||||
|
||||
return null;
|
||||
} catch (err) {
|
||||
console.error('[llm-slug-generator] Failed to generate slug:', err);
|
||||
console.error("[llm-slug-generator] Failed to generate slug:", err);
|
||||
return null;
|
||||
} finally {
|
||||
// Clean up temporary session file
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { loadInternalHooks } from './loader.js';
|
||||
import { clearInternalHooks, getRegisteredEventKeys, triggerInternalHook, createInternalHookEvent } from './internal-hooks.js';
|
||||
import type { ClawdbotConfig } from '../config/config.js';
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { loadInternalHooks } from "./loader.js";
|
||||
import {
|
||||
clearInternalHooks,
|
||||
getRegisteredEventKeys,
|
||||
triggerInternalHook,
|
||||
createInternalHookEvent,
|
||||
} from "./internal-hooks.js";
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
|
||||
describe('loader', () => {
|
||||
describe("loader", () => {
|
||||
let tmpDir: string;
|
||||
let originalBundledDir: string | undefined;
|
||||
|
||||
@@ -18,7 +23,7 @@ describe('loader', () => {
|
||||
|
||||
// Disable bundled hooks during tests by setting env var to non-existent directory
|
||||
originalBundledDir = process.env.CLAWDBOT_BUNDLED_HOOKS_DIR;
|
||||
process.env.CLAWDBOT_BUNDLED_HOOKS_DIR = '/nonexistent/bundled/hooks';
|
||||
process.env.CLAWDBOT_BUNDLED_HOOKS_DIR = "/nonexistent/bundled/hooks";
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
@@ -37,8 +42,8 @@ describe('loader', () => {
|
||||
}
|
||||
});
|
||||
|
||||
describe('loadInternalHooks', () => {
|
||||
it('should return 0 when internal hooks are not enabled', async () => {
|
||||
describe("loadInternalHooks", () => {
|
||||
it("should return 0 when internal hooks are not enabled", async () => {
|
||||
const cfg: ClawdbotConfig = {
|
||||
hooks: {
|
||||
internal: {
|
||||
@@ -51,21 +56,21 @@ describe('loader', () => {
|
||||
expect(count).toBe(0);
|
||||
});
|
||||
|
||||
it('should return 0 when hooks config is missing', async () => {
|
||||
it("should return 0 when hooks config is missing", async () => {
|
||||
const cfg: ClawdbotConfig = {};
|
||||
const count = await loadInternalHooks(cfg, tmpDir);
|
||||
expect(count).toBe(0);
|
||||
});
|
||||
|
||||
it('should load a handler from a module', async () => {
|
||||
it("should load a handler from a module", async () => {
|
||||
// Create a test handler module
|
||||
const handlerPath = path.join(tmpDir, 'test-handler.js');
|
||||
const handlerPath = path.join(tmpDir, "test-handler.js");
|
||||
const handlerCode = `
|
||||
export default async function(event) {
|
||||
// Test handler
|
||||
}
|
||||
`;
|
||||
await fs.writeFile(handlerPath, handlerCode, 'utf-8');
|
||||
await fs.writeFile(handlerPath, handlerCode, "utf-8");
|
||||
|
||||
const cfg: ClawdbotConfig = {
|
||||
hooks: {
|
||||
@@ -73,7 +78,7 @@ describe('loader', () => {
|
||||
enabled: true,
|
||||
handlers: [
|
||||
{
|
||||
event: 'command:new',
|
||||
event: "command:new",
|
||||
module: handlerPath,
|
||||
},
|
||||
],
|
||||
@@ -85,24 +90,24 @@ describe('loader', () => {
|
||||
expect(count).toBe(1);
|
||||
|
||||
const keys = getRegisteredEventKeys();
|
||||
expect(keys).toContain('command:new');
|
||||
expect(keys).toContain("command:new");
|
||||
});
|
||||
|
||||
it('should load multiple handlers', async () => {
|
||||
it("should load multiple handlers", async () => {
|
||||
// Create test handler modules
|
||||
const handler1Path = path.join(tmpDir, 'handler1.js');
|
||||
const handler2Path = path.join(tmpDir, 'handler2.js');
|
||||
const handler1Path = path.join(tmpDir, "handler1.js");
|
||||
const handler2Path = path.join(tmpDir, "handler2.js");
|
||||
|
||||
await fs.writeFile(handler1Path, 'export default async function() {}', 'utf-8');
|
||||
await fs.writeFile(handler2Path, 'export default async function() {}', 'utf-8');
|
||||
await fs.writeFile(handler1Path, "export default async function() {}", "utf-8");
|
||||
await fs.writeFile(handler2Path, "export default async function() {}", "utf-8");
|
||||
|
||||
const cfg: ClawdbotConfig = {
|
||||
hooks: {
|
||||
internal: {
|
||||
enabled: true,
|
||||
handlers: [
|
||||
{ event: 'command:new', module: handler1Path },
|
||||
{ event: 'command:stop', module: handler2Path },
|
||||
{ event: "command:new", module: handler1Path },
|
||||
{ event: "command:stop", module: handler2Path },
|
||||
],
|
||||
},
|
||||
},
|
||||
@@ -112,19 +117,19 @@ describe('loader', () => {
|
||||
expect(count).toBe(2);
|
||||
|
||||
const keys = getRegisteredEventKeys();
|
||||
expect(keys).toContain('command:new');
|
||||
expect(keys).toContain('command:stop');
|
||||
expect(keys).toContain("command:new");
|
||||
expect(keys).toContain("command:stop");
|
||||
});
|
||||
|
||||
it('should support named exports', async () => {
|
||||
it("should support named exports", async () => {
|
||||
// Create a handler module with named export
|
||||
const handlerPath = path.join(tmpDir, 'named-export.js');
|
||||
const handlerPath = path.join(tmpDir, "named-export.js");
|
||||
const handlerCode = `
|
||||
export const myHandler = async function(event) {
|
||||
// Named export handler
|
||||
}
|
||||
`;
|
||||
await fs.writeFile(handlerPath, handlerCode, 'utf-8');
|
||||
await fs.writeFile(handlerPath, handlerCode, "utf-8");
|
||||
|
||||
const cfg: ClawdbotConfig = {
|
||||
hooks: {
|
||||
@@ -132,9 +137,9 @@ describe('loader', () => {
|
||||
enabled: true,
|
||||
handlers: [
|
||||
{
|
||||
event: 'command:new',
|
||||
event: "command:new",
|
||||
module: handlerPath,
|
||||
export: 'myHandler',
|
||||
export: "myHandler",
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -145,8 +150,8 @@ describe('loader', () => {
|
||||
expect(count).toBe(1);
|
||||
});
|
||||
|
||||
it('should handle module loading errors gracefully', async () => {
|
||||
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
it("should handle module loading errors gracefully", async () => {
|
||||
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
|
||||
const cfg: ClawdbotConfig = {
|
||||
hooks: {
|
||||
@@ -154,8 +159,8 @@ describe('loader', () => {
|
||||
enabled: true,
|
||||
handlers: [
|
||||
{
|
||||
event: 'command:new',
|
||||
module: '/nonexistent/path/handler.js',
|
||||
event: "command:new",
|
||||
module: "/nonexistent/path/handler.js",
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -165,19 +170,19 @@ describe('loader', () => {
|
||||
const count = await loadInternalHooks(cfg, tmpDir);
|
||||
expect(count).toBe(0);
|
||||
expect(consoleError).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Failed to load internal hook handler'),
|
||||
expect.any(String)
|
||||
expect.stringContaining("Failed to load internal hook handler"),
|
||||
expect.any(String),
|
||||
);
|
||||
|
||||
consoleError.mockRestore();
|
||||
});
|
||||
|
||||
it('should handle non-function exports', async () => {
|
||||
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
it("should handle non-function exports", async () => {
|
||||
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
|
||||
// Create a module with a non-function export
|
||||
const handlerPath = path.join(tmpDir, 'bad-export.js');
|
||||
await fs.writeFile(handlerPath, 'export default "not a function";', 'utf-8');
|
||||
const handlerPath = path.join(tmpDir, "bad-export.js");
|
||||
await fs.writeFile(handlerPath, 'export default "not a function";', "utf-8");
|
||||
|
||||
const cfg: ClawdbotConfig = {
|
||||
hooks: {
|
||||
@@ -185,7 +190,7 @@ describe('loader', () => {
|
||||
enabled: true,
|
||||
handlers: [
|
||||
{
|
||||
event: 'command:new',
|
||||
event: "command:new",
|
||||
module: handlerPath,
|
||||
},
|
||||
],
|
||||
@@ -195,17 +200,15 @@ describe('loader', () => {
|
||||
|
||||
const count = await loadInternalHooks(cfg, tmpDir);
|
||||
expect(count).toBe(0);
|
||||
expect(consoleError).toHaveBeenCalledWith(
|
||||
expect.stringContaining('is not a function')
|
||||
);
|
||||
expect(consoleError).toHaveBeenCalledWith(expect.stringContaining("is not a function"));
|
||||
|
||||
consoleError.mockRestore();
|
||||
});
|
||||
|
||||
it('should handle relative paths', async () => {
|
||||
it("should handle relative paths", async () => {
|
||||
// Create a handler module
|
||||
const handlerPath = path.join(tmpDir, 'relative-handler.js');
|
||||
await fs.writeFile(handlerPath, 'export default async function() {}', 'utf-8');
|
||||
const handlerPath = path.join(tmpDir, "relative-handler.js");
|
||||
await fs.writeFile(handlerPath, "export default async function() {}", "utf-8");
|
||||
|
||||
// Get relative path from cwd
|
||||
const relativePath = path.relative(process.cwd(), handlerPath);
|
||||
@@ -216,7 +219,7 @@ describe('loader', () => {
|
||||
enabled: true,
|
||||
handlers: [
|
||||
{
|
||||
event: 'command:new',
|
||||
event: "command:new",
|
||||
module: relativePath,
|
||||
},
|
||||
],
|
||||
@@ -228,9 +231,9 @@ describe('loader', () => {
|
||||
expect(count).toBe(1);
|
||||
});
|
||||
|
||||
it('should actually call the loaded handler', async () => {
|
||||
it("should actually call the loaded handler", async () => {
|
||||
// Create a handler that we can verify was called
|
||||
const handlerPath = path.join(tmpDir, 'callable-handler.js');
|
||||
const handlerPath = path.join(tmpDir, "callable-handler.js");
|
||||
const handlerCode = `
|
||||
let callCount = 0;
|
||||
export default async function(event) {
|
||||
@@ -240,7 +243,7 @@ describe('loader', () => {
|
||||
return callCount;
|
||||
}
|
||||
`;
|
||||
await fs.writeFile(handlerPath, handlerCode, 'utf-8');
|
||||
await fs.writeFile(handlerPath, handlerCode, "utf-8");
|
||||
|
||||
const cfg: ClawdbotConfig = {
|
||||
hooks: {
|
||||
@@ -248,7 +251,7 @@ describe('loader', () => {
|
||||
enabled: true,
|
||||
handlers: [
|
||||
{
|
||||
event: 'command:new',
|
||||
event: "command:new",
|
||||
module: handlerPath,
|
||||
},
|
||||
],
|
||||
@@ -259,13 +262,13 @@ describe('loader', () => {
|
||||
await loadInternalHooks(cfg, tmpDir);
|
||||
|
||||
// Trigger the hook
|
||||
const event = createInternalHookEvent('command', 'new', 'test-session');
|
||||
const event = createInternalHookEvent("command", "new", "test-session");
|
||||
await triggerInternalHook(event);
|
||||
|
||||
// The handler should have been called, but we can't directly verify
|
||||
// the call count from this context without more complex test infrastructure
|
||||
// This test mainly verifies that loading and triggering doesn't crash
|
||||
expect(getRegisteredEventKeys()).toContain('command:new');
|
||||
expect(getRegisteredEventKeys()).toContain("command:new");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,14 +5,14 @@
|
||||
* and from directory-based discovery (bundled, managed, workspace)
|
||||
*/
|
||||
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import path from 'node:path';
|
||||
import { registerInternalHook } from './internal-hooks.js';
|
||||
import type { ClawdbotConfig } from '../config/config.js';
|
||||
import type { InternalHookHandler } from './internal-hooks.js';
|
||||
import { loadWorkspaceHookEntries } from './workspace.js';
|
||||
import { resolveHookConfig } from './config.js';
|
||||
import { shouldIncludeHook } from './config.js';
|
||||
import { pathToFileURL } from "node:url";
|
||||
import path from "node:path";
|
||||
import { registerInternalHook } from "./internal-hooks.js";
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { InternalHookHandler } from "./internal-hooks.js";
|
||||
import { loadWorkspaceHookEntries } from "./workspace.js";
|
||||
import { resolveHookConfig } from "./config.js";
|
||||
import { shouldIncludeHook } from "./config.js";
|
||||
|
||||
/**
|
||||
* Load and register all internal hook handlers
|
||||
@@ -49,9 +49,7 @@ export async function loadInternalHooks(
|
||||
const hookEntries = loadWorkspaceHookEntries(workspaceDir, { config: cfg });
|
||||
|
||||
// Filter by eligibility
|
||||
const eligible = hookEntries.filter((entry) =>
|
||||
shouldIncludeHook({ entry, config: cfg }),
|
||||
);
|
||||
const eligible = hookEntries.filter((entry) => shouldIncludeHook({ entry, config: cfg }));
|
||||
|
||||
for (const entry of eligible) {
|
||||
const hookConfig = resolveHookConfig(cfg, entry.hook.name);
|
||||
@@ -68,10 +66,10 @@ export async function loadInternalHooks(
|
||||
const mod = (await import(cacheBustedUrl)) as Record<string, unknown>;
|
||||
|
||||
// Get handler function (default or named export)
|
||||
const exportName = entry.clawdbot?.export ?? 'default';
|
||||
const exportName = entry.clawdbot?.export ?? "default";
|
||||
const handler = mod[exportName];
|
||||
|
||||
if (typeof handler !== 'function') {
|
||||
if (typeof handler !== "function") {
|
||||
console.error(
|
||||
`Internal hook error: Handler '${exportName}' from ${entry.hook.name} is not a function`,
|
||||
);
|
||||
@@ -92,7 +90,7 @@ export async function loadInternalHooks(
|
||||
}
|
||||
|
||||
console.log(
|
||||
`Registered internal hook: ${entry.hook.name} -> ${events.join(', ')}${exportName !== 'default' ? ` (export: ${exportName})` : ''}`,
|
||||
`Registered internal hook: ${entry.hook.name} -> ${events.join(", ")}${exportName !== "default" ? ` (export: ${exportName})` : ""}`,
|
||||
);
|
||||
loadedCount++;
|
||||
} catch (err) {
|
||||
@@ -104,7 +102,7 @@ export async function loadInternalHooks(
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(
|
||||
'Failed to load directory-based hooks:',
|
||||
"Failed to load directory-based hooks:",
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
@@ -124,10 +122,10 @@ export async function loadInternalHooks(
|
||||
const mod = (await import(cacheBustedUrl)) as Record<string, unknown>;
|
||||
|
||||
// Get the handler function
|
||||
const exportName = handlerConfig.export ?? 'default';
|
||||
const exportName = handlerConfig.export ?? "default";
|
||||
const handler = mod[exportName];
|
||||
|
||||
if (typeof handler !== 'function') {
|
||||
if (typeof handler !== "function") {
|
||||
console.error(
|
||||
`Internal hook error: Handler '${exportName}' from ${modulePath} is not a function`,
|
||||
);
|
||||
@@ -137,7 +135,7 @@ export async function loadInternalHooks(
|
||||
// Register the handler
|
||||
registerInternalHook(handlerConfig.event, handler as InternalHookHandler);
|
||||
console.log(
|
||||
`Registered internal hook (legacy): ${handlerConfig.event} -> ${modulePath}${exportName !== 'default' ? `#${exportName}` : ''}`,
|
||||
`Registered internal hook (legacy): ${handlerConfig.event} -> ${modulePath}${exportName !== "default" ? `#${exportName}` : ""}`,
|
||||
);
|
||||
loadedCount++;
|
||||
} catch (err) {
|
||||
|
||||
@@ -59,12 +59,7 @@ function loadHooksFromDir(params: { dir: string; source: string }): Hook[] {
|
||||
const description = frontmatter.description || "";
|
||||
|
||||
// Locate handler file (handler.ts, handler.js, index.ts, index.js)
|
||||
const handlerCandidates = [
|
||||
"handler.ts",
|
||||
"handler.js",
|
||||
"index.ts",
|
||||
"index.js",
|
||||
];
|
||||
const handlerCandidates = ["handler.ts", "handler.js", "index.ts", "index.js"];
|
||||
|
||||
let handlerPath: string | undefined;
|
||||
for (const candidate of handlerCandidates) {
|
||||
|
||||
Reference in New Issue
Block a user