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

@ -16,10 +16,7 @@ import {
} from "../auto-reply/reply/queue.js"; } from "../auto-reply/reply/queue.js";
import { callGateway } from "../gateway/call.js"; import { callGateway } from "../gateway/call.js";
import { defaultRuntime } from "../runtime.js"; import { defaultRuntime } from "../runtime.js";
import { import { isEmbeddedPiRunActive, queueEmbeddedPiMessage } from "./pi-embedded.js";
isEmbeddedPiRunActive,
queueEmbeddedPiMessage,
} from "./pi-embedded.js";
import { readLatestAssistantReply } from "./tools/agent-step.js"; import { readLatestAssistantReply } from "./tools/agent-step.js";
function formatDurationShort(valueMs?: number) { function formatDurationShort(valueMs?: number) {
@ -111,7 +108,10 @@ type AnnounceQueueState = {
const ANNOUNCE_QUEUES = new Map<string, AnnounceQueueState>(); const ANNOUNCE_QUEUES = new Map<string, AnnounceQueueState>();
function getAnnounceQueue(key: string, settings: { mode: QueueMode; debounceMs?: number; cap?: number; dropPolicy?: QueueDropPolicy }) { function getAnnounceQueue(
key: string,
settings: { mode: QueueMode; debounceMs?: number; cap?: number; dropPolicy?: QueueDropPolicy },
) {
const existing = ANNOUNCE_QUEUES.get(key); const existing = ANNOUNCE_QUEUES.get(key);
if (existing) { if (existing) {
existing.mode = settings.mode; existing.mode = settings.mode;
@ -131,8 +131,7 @@ function getAnnounceQueue(key: string, settings: { mode: QueueMode; debounceMs?:
draining: false, draining: false,
lastEnqueuedAt: 0, lastEnqueuedAt: 0,
mode: settings.mode, mode: settings.mode,
debounceMs: debounceMs: typeof settings.debounceMs === "number" ? Math.max(0, settings.debounceMs) : 1000,
typeof settings.debounceMs === "number" ? Math.max(0, settings.debounceMs) : 1000,
cap: typeof settings.cap === "number" && settings.cap > 0 ? Math.floor(settings.cap) : 20, cap: typeof settings.cap === "number" && settings.cap > 0 ? Math.floor(settings.cap) : 20,
dropPolicy: settings.dropPolicy ?? "summarize", dropPolicy: settings.dropPolicy ?? "summarize",
droppedCount: 0, droppedCount: 0,
@ -341,9 +340,7 @@ function loadRequesterSessionEntry(requesterSessionKey: string) {
? canonicalKey.split(":").slice(2).join(":") ? canonicalKey.split(":").slice(2).join(":")
: undefined; : undefined;
const entry = const entry =
store[canonicalKey] ?? store[canonicalKey] ?? store[requesterSessionKey] ?? (legacyKey ? store[legacyKey] : undefined);
store[requesterSessionKey] ??
(legacyKey ? store[legacyKey] : undefined);
return { cfg, entry, canonicalKey }; return { cfg, entry, canonicalKey };
} }

View File

@ -56,18 +56,13 @@ export async function handleCommands(params: HandleCommandsParams): Promise<Comm
// Trigger internal hook for reset/new commands // Trigger internal hook for reset/new commands
if (resetRequested && params.command.isAuthorizedSender) { if (resetRequested && params.command.isAuthorizedSender) {
const commandAction = resetMatch?.[1] ?? "new"; const commandAction = resetMatch?.[1] ?? "new";
const hookEvent = createInternalHookEvent( const hookEvent = createInternalHookEvent("command", commandAction, params.sessionKey ?? "", {
'command', sessionEntry: params.sessionEntry,
commandAction, previousSessionEntry: params.previousSessionEntry,
params.sessionKey ?? '', commandSource: params.command.surface,
{ senderId: params.command.senderId,
sessionEntry: params.sessionEntry, cfg: params.cfg, // Pass config for LLM slug generation
previousSessionEntry: params.previousSessionEntry, });
commandSource: params.command.surface,
senderId: params.command.senderId,
cfg: params.cfg, // Pass config for LLM slug generation
}
);
await triggerInternalHook(hookEvent); await triggerInternalHook(hookEvent);
// Send hook messages immediately if present // Send hook messages immediately if present
@ -78,7 +73,7 @@ export async function handleCommands(params: HandleCommandsParams): Promise<Comm
const to = params.ctx.OriginatingTo || params.command.from || params.command.to; const to = params.ctx.OriginatingTo || params.command.from || params.command.to;
if (channel && to) { if (channel && to) {
const hookReply = { text: hookEvent.messages.join('\n\n') }; const hookReply = { text: hookEvent.messages.join("\n\n") };
await routeReply({ await routeReply({
payload: hookReply, payload: hookReply,
channel: channel, channel: channel,

View File

@ -217,15 +217,15 @@ export const handleStopCommand: CommandHandler = async (params, allowTextCommand
// Trigger internal hook for stop command // Trigger internal hook for stop command
const hookEvent = createInternalHookEvent( const hookEvent = createInternalHookEvent(
'command', "command",
'stop', "stop",
abortTarget.key ?? params.sessionKey ?? '', abortTarget.key ?? params.sessionKey ?? "",
{ {
sessionEntry: abortTarget.entry ?? params.sessionEntry, sessionEntry: abortTarget.entry ?? params.sessionEntry,
sessionId: abortTarget.sessionId, sessionId: abortTarget.sessionId,
commandSource: params.command.surface, commandSource: params.command.surface,
senderId: params.command.senderId, senderId: params.command.senderId,
} },
); );
await triggerInternalHook(hookEvent); await triggerInternalHook(hookEvent);

View File

@ -155,9 +155,7 @@ describe("handleCommands internal hooks", () => {
await handleCommands(params); await handleCommands(params);
expect(spy).toHaveBeenCalledWith( expect(spy).toHaveBeenCalledWith(expect.objectContaining({ type: "command", action: "new" }));
expect.objectContaining({ type: "command", action: "new" }),
);
spy.mockRestore(); spy.mockRestore();
}); });
}); });

View File

@ -67,9 +67,9 @@ export async function handleInlineActions(params: {
sessionCtx, sessionCtx,
cfg, cfg,
agentId, agentId,
sessionEntry, sessionEntry,
previousSessionEntry, previousSessionEntry,
sessionStore, sessionStore,
sessionKey, sessionKey,
storePath, storePath,
sessionScope, sessionScope,

View File

@ -202,9 +202,7 @@ export function formatHookInfo(
} }
if (hook.requirements.config.length > 0) { if (hook.requirements.config.length > 0) {
const configStatus = hook.configChecks.map((check) => { const configStatus = hook.configChecks.map((check) => {
return check.satisfied return check.satisfied ? chalk.green(`${check.path}`) : chalk.red(`${check.path}`);
? chalk.green(`${check.path}`)
: chalk.red(`${check.path}`);
}); });
lines.push(` Config: ${configStatus.join(", ")}`); lines.push(` Config: ${configStatus.join(", ")}`);
} }
@ -265,8 +263,7 @@ export function formatHooksCheck(report: HookStatusReport, opts: HooksCheckOptio
if (hook.missing.anyBins.length > 0) if (hook.missing.anyBins.length > 0)
reasons.push(`anyBins: ${hook.missing.anyBins.join(", ")}`); reasons.push(`anyBins: ${hook.missing.anyBins.join(", ")}`);
if (hook.missing.env.length > 0) reasons.push(`env: ${hook.missing.env.join(", ")}`); if (hook.missing.env.length > 0) reasons.push(`env: ${hook.missing.env.join(", ")}`);
if (hook.missing.config.length > 0) if (hook.missing.config.length > 0) reasons.push(`config: ${hook.missing.config.join(", ")}`);
reasons.push(`config: ${hook.missing.config.join(", ")}`);
if (hook.missing.os.length > 0) reasons.push(`os: ${hook.missing.os.join(", ")}`); if (hook.missing.os.length > 0) reasons.push(`os: ${hook.missing.os.join(", ")}`);
lines.push(` ${hook.emoji ?? "🔗"} ${hook.name} - ${reasons.join("; ")}`); lines.push(` ${hook.emoji ?? "🔗"} ${hook.name} - ${reasons.join("; ")}`);
} }

View File

@ -1,21 +1,21 @@
import { describe, expect, it, vi, beforeEach } from 'vitest'; import { describe, expect, it, vi, beforeEach } from "vitest";
import { setupInternalHooks } from './onboard-hooks.js'; import { setupInternalHooks } from "./onboard-hooks.js";
import type { ClawdbotConfig } from '../config/config.js'; import type { ClawdbotConfig } from "../config/config.js";
import type { RuntimeEnv } from '../runtime.js'; import type { RuntimeEnv } from "../runtime.js";
import type { WizardPrompter } from '../wizard/prompts.js'; import type { WizardPrompter } from "../wizard/prompts.js";
import type { HookStatusReport } from '../hooks/hooks-status.js'; import type { HookStatusReport } from "../hooks/hooks-status.js";
// Mock hook discovery modules // Mock hook discovery modules
vi.mock('../hooks/hooks-status.js', () => ({ vi.mock("../hooks/hooks-status.js", () => ({
buildWorkspaceHookStatus: vi.fn(), buildWorkspaceHookStatus: vi.fn(),
})); }));
vi.mock('../agents/agent-scope.js', () => ({ vi.mock("../agents/agent-scope.js", () => ({
resolveAgentWorkspaceDir: vi.fn().mockReturnValue('/mock/workspace'), resolveAgentWorkspaceDir: vi.fn().mockReturnValue("/mock/workspace"),
resolveDefaultAgentId: vi.fn().mockReturnValue('main'), resolveDefaultAgentId: vi.fn().mockReturnValue("main"),
})); }));
describe('onboard-hooks', () => { describe("onboard-hooks", () => {
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
}); });
@ -25,8 +25,8 @@ describe('onboard-hooks', () => {
note: vi.fn().mockResolvedValue(undefined), note: vi.fn().mockResolvedValue(undefined),
intro: vi.fn().mockResolvedValue(undefined), intro: vi.fn().mockResolvedValue(undefined),
outro: vi.fn().mockResolvedValue(undefined), outro: vi.fn().mockResolvedValue(undefined),
text: vi.fn().mockResolvedValue(''), text: vi.fn().mockResolvedValue(""),
select: vi.fn().mockResolvedValue(''), select: vi.fn().mockResolvedValue(""),
multiselect: vi.fn().mockResolvedValue(multiselectValue), multiselect: vi.fn().mockResolvedValue(multiselectValue),
progress: vi.fn().mockReturnValue({ progress: vi.fn().mockReturnValue({
stop: vi.fn(), stop: vi.fn(),
@ -41,58 +41,58 @@ describe('onboard-hooks', () => {
}); });
const createMockHookReport = (eligible = true): HookStatusReport => ({ const createMockHookReport = (eligible = true): HookStatusReport => ({
workspaceDir: '/mock/workspace', workspaceDir: "/mock/workspace",
managedHooksDir: '/mock/.clawdbot/hooks', managedHooksDir: "/mock/.clawdbot/hooks",
hooks: [ hooks: [
{ {
name: 'session-memory', name: "session-memory",
description: 'Save session context to memory when /new command is issued', description: "Save session context to memory when /new command is issued",
source: 'clawdbot-bundled', source: "clawdbot-bundled",
emoji: '💾', emoji: "💾",
events: ['command:new'], events: ["command:new"],
disabled: false, disabled: false,
eligible, eligible,
requirements: { config: ['workspace.dir'] }, requirements: { config: ["workspace.dir"] },
missing: {}, missing: {},
}, },
], ],
}); });
describe('setupInternalHooks', () => { describe("setupInternalHooks", () => {
it('should enable internal hooks when user selects them', async () => { it("should enable internal hooks when user selects them", async () => {
const { buildWorkspaceHookStatus } = await import('../hooks/hooks-status.js'); const { buildWorkspaceHookStatus } = await import("../hooks/hooks-status.js");
vi.mocked(buildWorkspaceHookStatus).mockReturnValue(createMockHookReport()); vi.mocked(buildWorkspaceHookStatus).mockReturnValue(createMockHookReport());
const cfg: ClawdbotConfig = {}; const cfg: ClawdbotConfig = {};
const prompter = createMockPrompter(['session-memory']); const prompter = createMockPrompter(["session-memory"]);
const runtime = createMockRuntime(); const runtime = createMockRuntime();
const result = await setupInternalHooks(cfg, runtime, prompter); const result = await setupInternalHooks(cfg, runtime, prompter);
expect(result.hooks?.internal?.enabled).toBe(true); expect(result.hooks?.internal?.enabled).toBe(true);
expect(result.hooks?.internal?.entries).toEqual({ expect(result.hooks?.internal?.entries).toEqual({
'session-memory': { enabled: true }, "session-memory": { enabled: true },
}); });
expect(prompter.note).toHaveBeenCalledTimes(2); expect(prompter.note).toHaveBeenCalledTimes(2);
expect(prompter.multiselect).toHaveBeenCalledWith({ expect(prompter.multiselect).toHaveBeenCalledWith({
message: 'Enable internal hooks?', message: "Enable internal hooks?",
options: [ options: [
{ value: '__skip__', label: 'Skip for now' }, { value: "__skip__", label: "Skip for now" },
{ {
value: 'session-memory', value: "session-memory",
label: '💾 session-memory', label: "💾 session-memory",
hint: 'Save session context to memory when /new command is issued', hint: "Save session context to memory when /new command is issued",
}, },
], ],
}); });
}); });
it('should not enable hooks when user skips', async () => { it("should not enable hooks when user skips", async () => {
const { buildWorkspaceHookStatus } = await import('../hooks/hooks-status.js'); const { buildWorkspaceHookStatus } = await import("../hooks/hooks-status.js");
vi.mocked(buildWorkspaceHookStatus).mockReturnValue(createMockHookReport()); vi.mocked(buildWorkspaceHookStatus).mockReturnValue(createMockHookReport());
const cfg: ClawdbotConfig = {}; const cfg: ClawdbotConfig = {};
const prompter = createMockPrompter(['__skip__']); const prompter = createMockPrompter(["__skip__"]);
const runtime = createMockRuntime(); const runtime = createMockRuntime();
const result = await setupInternalHooks(cfg, runtime, prompter); const result = await setupInternalHooks(cfg, runtime, prompter);
@ -101,8 +101,8 @@ describe('onboard-hooks', () => {
expect(prompter.note).toHaveBeenCalledTimes(1); expect(prompter.note).toHaveBeenCalledTimes(1);
}); });
it('should handle no eligible hooks', async () => { it("should handle no eligible hooks", async () => {
const { buildWorkspaceHookStatus } = await import('../hooks/hooks-status.js'); const { buildWorkspaceHookStatus } = await import("../hooks/hooks-status.js");
vi.mocked(buildWorkspaceHookStatus).mockReturnValue(createMockHookReport(false)); vi.mocked(buildWorkspaceHookStatus).mockReturnValue(createMockHookReport(false));
const cfg: ClawdbotConfig = {}; const cfg: ClawdbotConfig = {};
@ -114,58 +114,58 @@ describe('onboard-hooks', () => {
expect(result).toEqual(cfg); expect(result).toEqual(cfg);
expect(prompter.multiselect).not.toHaveBeenCalled(); expect(prompter.multiselect).not.toHaveBeenCalled();
expect(prompter.note).toHaveBeenCalledWith( expect(prompter.note).toHaveBeenCalledWith(
'No eligible hooks found. You can configure hooks later in your config.', "No eligible hooks found. You can configure hooks later in your config.",
'No Hooks Available', "No Hooks Available",
); );
}); });
it('should preserve existing hooks config when enabled', async () => { it("should preserve existing hooks config when enabled", async () => {
const { buildWorkspaceHookStatus } = await import('../hooks/hooks-status.js'); const { buildWorkspaceHookStatus } = await import("../hooks/hooks-status.js");
vi.mocked(buildWorkspaceHookStatus).mockReturnValue(createMockHookReport()); vi.mocked(buildWorkspaceHookStatus).mockReturnValue(createMockHookReport());
const cfg: ClawdbotConfig = { const cfg: ClawdbotConfig = {
hooks: { hooks: {
enabled: true, enabled: true,
path: '/webhook', path: "/webhook",
token: 'existing-token', token: "existing-token",
}, },
}; };
const prompter = createMockPrompter(['session-memory']); const prompter = createMockPrompter(["session-memory"]);
const runtime = createMockRuntime(); const runtime = createMockRuntime();
const result = await setupInternalHooks(cfg, runtime, prompter); const result = await setupInternalHooks(cfg, runtime, prompter);
expect(result.hooks?.enabled).toBe(true); expect(result.hooks?.enabled).toBe(true);
expect(result.hooks?.path).toBe('/webhook'); expect(result.hooks?.path).toBe("/webhook");
expect(result.hooks?.token).toBe('existing-token'); expect(result.hooks?.token).toBe("existing-token");
expect(result.hooks?.internal?.enabled).toBe(true); expect(result.hooks?.internal?.enabled).toBe(true);
expect(result.hooks?.internal?.entries).toEqual({ expect(result.hooks?.internal?.entries).toEqual({
'session-memory': { enabled: true }, "session-memory": { enabled: true },
}); });
}); });
it('should preserve existing config when user skips', async () => { it("should preserve existing config when user skips", async () => {
const { buildWorkspaceHookStatus } = await import('../hooks/hooks-status.js'); const { buildWorkspaceHookStatus } = await import("../hooks/hooks-status.js");
vi.mocked(buildWorkspaceHookStatus).mockReturnValue(createMockHookReport()); vi.mocked(buildWorkspaceHookStatus).mockReturnValue(createMockHookReport());
const cfg: ClawdbotConfig = { const cfg: ClawdbotConfig = {
agents: { defaults: { workspace: '/workspace' } }, agents: { defaults: { workspace: "/workspace" } },
}; };
const prompter = createMockPrompter(['__skip__']); const prompter = createMockPrompter(["__skip__"]);
const runtime = createMockRuntime(); const runtime = createMockRuntime();
const result = await setupInternalHooks(cfg, runtime, prompter); const result = await setupInternalHooks(cfg, runtime, prompter);
expect(result).toEqual(cfg); expect(result).toEqual(cfg);
expect(result.agents?.defaults?.workspace).toBe('/workspace'); expect(result.agents?.defaults?.workspace).toBe("/workspace");
}); });
it('should show informative notes to user', async () => { it("should show informative notes to user", async () => {
const { buildWorkspaceHookStatus } = await import('../hooks/hooks-status.js'); const { buildWorkspaceHookStatus } = await import("../hooks/hooks-status.js");
vi.mocked(buildWorkspaceHookStatus).mockReturnValue(createMockHookReport()); vi.mocked(buildWorkspaceHookStatus).mockReturnValue(createMockHookReport());
const cfg: ClawdbotConfig = {}; const cfg: ClawdbotConfig = {};
const prompter = createMockPrompter(['session-memory']); const prompter = createMockPrompter(["session-memory"]);
const runtime = createMockRuntime(); const runtime = createMockRuntime();
await setupInternalHooks(cfg, runtime, prompter); await setupInternalHooks(cfg, runtime, prompter);
@ -174,12 +174,12 @@ describe('onboard-hooks', () => {
expect(noteCalls).toHaveLength(2); expect(noteCalls).toHaveLength(2);
// First note should explain what internal hooks are // First note should explain what internal hooks are
expect(noteCalls[0][0]).toContain('Internal hooks'); expect(noteCalls[0][0]).toContain("Internal hooks");
expect(noteCalls[0][0]).toContain('automate actions'); expect(noteCalls[0][0]).toContain("automate actions");
// Second note should confirm configuration // Second note should confirm configuration
expect(noteCalls[1][0]).toContain('Enabled 1 hook: session-memory'); expect(noteCalls[1][0]).toContain("Enabled 1 hook: session-memory");
expect(noteCalls[1][0]).toContain('clawdbot hooks internal list'); expect(noteCalls[1][0]).toContain("clawdbot hooks internal list");
}); });
}); });
}); });

View File

@ -24,9 +24,7 @@ export async function setupInternalHooks(
const report = buildWorkspaceHookStatus(workspaceDir, { config: cfg }); const report = buildWorkspaceHookStatus(workspaceDir, { config: cfg });
// Filter for eligible and recommended hooks (session-memory is recommended) // Filter for eligible and recommended hooks (session-memory is recommended)
const recommendedHooks = report.hooks.filter( const recommendedHooks = report.hooks.filter((h) => h.eligible && h.name === "session-memory");
(h) => h.eligible && h.name === "session-memory",
);
if (recommendedHooks.length === 0) { if (recommendedHooks.length === 0) {
await prompter.note( await prompter.note(

View File

@ -98,7 +98,9 @@ export async function startGatewaySidecars(params: {
clearInternalHooks(); clearInternalHooks();
const loadedCount = await loadInternalHooks(params.cfg, params.defaultWorkspaceDir); const loadedCount = await loadInternalHooks(params.cfg, params.defaultWorkspaceDir);
if (loadedCount > 0) { if (loadedCount > 0) {
params.logHooks.info(`loaded ${loadedCount} internal hook handler${loadedCount > 1 ? 's' : ''}`); params.logHooks.info(
`loaded ${loadedCount} internal hook handler${loadedCount > 1 ? "s" : ""}`,
);
} }
} catch (err) { } catch (err) {
params.logHooks.error(`failed to load internal hooks: ${String(err)}`); params.logHooks.error(`failed to load internal hooks: ${String(err)}`);

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

View File

@ -2,7 +2,15 @@
name: command-logger name: command-logger
description: "Log all command events to a centralized audit file" description: "Log all command events to a centralized audit file"
homepage: https://docs.clawd.bot/internal-hooks#command-logger 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 # Command Logger Hook
@ -44,6 +52,7 @@ No requirements - this hook works out of the box on all platforms.
## Configuration ## Configuration
No configuration needed. The hook automatically: No configuration needed. The hook automatically:
- Creates the log directory if it doesn't exist - Creates the log directory if it doesn't exist
- Appends to the log file (doesn't overwrite) - Appends to the log file (doesn't overwrite)
- Handles errors silently without disrupting command execution - 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: The hook does not automatically rotate logs. To manage log size, you can:
1. **Manual rotation**: 1. **Manual rotation**:
```bash ```bash
mv ~/.clawdbot/logs/commands.log ~/.clawdbot/logs/commands.log.old 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 ## Viewing Logs
View recent commands: View recent commands:
```bash ```bash
tail -n 20 ~/.clawdbot/logs/commands.log tail -n 20 ~/.clawdbot/logs/commands.log
``` ```
Pretty-print with jq: Pretty-print with jq:
```bash ```bash
cat ~/.clawdbot/logs/commands.log | jq . cat ~/.clawdbot/logs/commands.log | jq .
``` ```
Filter by action: Filter by action:
```bash ```bash
grep '"action":"new"' ~/.clawdbot/logs/commands.log | jq . grep '"action":"new"' ~/.clawdbot/logs/commands.log | jq .
``` ```

View File

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

View File

@ -2,7 +2,16 @@
name: session-memory name: session-memory
description: "Save session context to memory when /new command is issued" description: "Save session context to memory when /new command is issued"
homepage: https://docs.clawd.bot/internal-hooks#session-memory 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 # Session Memory Hook
@ -49,6 +58,7 @@ The hook uses your configured LLM provider to generate slugs, so it works with a
## Configuration ## Configuration
No additional configuration required. The hook automatically: No additional configuration required. The hook automatically:
- Uses your workspace directory (`~/clawd` by default) - Uses your workspace directory (`~/clawd` by default)
- Uses your configured LLM for slug generation - Uses your configured LLM for slug generation
- Falls back to timestamp slugs if LLM is unavailable - 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 * Creates a new dated memory file with LLM-generated slug
*/ */
import fs from 'node:fs/promises'; import fs from "node:fs/promises";
import path from 'node:path'; import path from "node:path";
import os from 'node:os'; import os from "node:os";
import type { ClawdbotConfig } from '../../../config/config.js'; import type { ClawdbotConfig } from "../../../config/config.js";
import { resolveAgentWorkspaceDir } from '../../../agents/agent-scope.js'; import { resolveAgentWorkspaceDir } from "../../../agents/agent-scope.js";
import { resolveAgentIdFromSessionKey } from '../../../routing/session-key.js'; import { resolveAgentIdFromSessionKey } from "../../../routing/session-key.js";
import type { InternalHookHandler } from '../../internal-hooks.js'; import type { InternalHookHandler } from "../../internal-hooks.js";
/** /**
* Read recent messages from session file for slug generation * Read recent messages from session file for slug generation
*/ */
async function getRecentSessionContent(sessionFilePath: string): Promise<string | null> { async function getRecentSessionContent(sessionFilePath: string): Promise<string | null> {
try { try {
const content = await fs.readFile(sessionFilePath, 'utf-8'); const content = await fs.readFile(sessionFilePath, "utf-8");
const lines = content.trim().split('\n'); const lines = content.trim().split("\n");
// Get last 15 lines (recent conversation) // Get last 15 lines (recent conversation)
const recentLines = lines.slice(-15); const recentLines = lines.slice(-15);
@ -30,15 +30,15 @@ async function getRecentSessionContent(sessionFilePath: string): Promise<string
try { try {
const entry = JSON.parse(line); const entry = JSON.parse(line);
// Session files have entries with type="message" containing a nested message object // 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 msg = entry.message;
const role = msg.role; const role = msg.role;
if ((role === 'user' || role === 'assistant') && msg.content) { if ((role === "user" || role === "assistant") && msg.content) {
// Extract text content // Extract text content
const text = Array.isArray(msg.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; : msg.content;
if (text && !text.startsWith('/')) { if (text && !text.startsWith("/")) {
messages.push(`${role}: ${text}`); messages.push(`${role}: ${text}`);
} }
} }
@ -48,7 +48,7 @@ async function getRecentSessionContent(sessionFilePath: string): Promise<string
} }
} }
return messages.join('\n'); return messages.join("\n");
} catch { } catch {
return null; return null;
} }
@ -59,38 +59,37 @@ async function getRecentSessionContent(sessionFilePath: string): Promise<string
*/ */
const saveSessionToMemory: InternalHookHandler = async (event) => { const saveSessionToMemory: InternalHookHandler = async (event) => {
// Only trigger on 'new' command // Only trigger on 'new' command
if (event.type !== 'command' || event.action !== 'new') { if (event.type !== "command" || event.action !== "new") {
return; return;
} }
try { try {
console.log('[session-memory] Hook triggered for /new command'); console.log("[session-memory] Hook triggered for /new command");
const context = event.context || {}; const context = event.context || {};
const cfg = context.cfg as ClawdbotConfig | undefined; const cfg = context.cfg as ClawdbotConfig | undefined;
const agentId = resolveAgentIdFromSessionKey(event.sessionKey); const agentId = resolveAgentIdFromSessionKey(event.sessionKey);
const workspaceDir = cfg const workspaceDir = cfg
? resolveAgentWorkspaceDir(cfg, agentId) ? resolveAgentWorkspaceDir(cfg, agentId)
: path.join(os.homedir(), 'clawd'); : path.join(os.homedir(), "clawd");
const memoryDir = path.join(workspaceDir, 'memory'); const memoryDir = path.join(workspaceDir, "memory");
await fs.mkdir(memoryDir, { recursive: true }); await fs.mkdir(memoryDir, { recursive: true });
// Get today's date for filename // Get today's date for filename
const now = new Date(event.timestamp); 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 // Generate descriptive slug from session using LLM
const sessionEntry = ( const sessionEntry = (context.previousSessionEntry || context.sessionEntry || {}) as Record<
context.previousSessionEntry || string,
context.sessionEntry || unknown
{} >;
) as Record<string, unknown>;
const currentSessionId = sessionEntry.sessionId as string; const currentSessionId = sessionEntry.sessionId as string;
const currentSessionFile = sessionEntry.sessionFile as string; const currentSessionFile = sessionEntry.sessionFile as string;
console.log('[session-memory] Current sessionId:', currentSessionId); console.log("[session-memory] Current sessionId:", currentSessionId);
console.log('[session-memory] Current sessionFile:', currentSessionFile); console.log("[session-memory] Current sessionFile:", currentSessionFile);
console.log('[session-memory] cfg present:', !!cfg); console.log("[session-memory] cfg present:", !!cfg);
const sessionFile = currentSessionFile || undefined; const sessionFile = currentSessionFile || undefined;
@ -100,73 +99,76 @@ const saveSessionToMemory: InternalHookHandler = async (event) => {
if (sessionFile) { if (sessionFile) {
// Get recent conversation content // Get recent conversation content
sessionContent = await getRecentSessionContent(sessionFile); 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) { 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) // Dynamically import the LLM slug generator (avoids module caching issues)
// When compiled, handler is at dist/hooks/bundled/session-memory/handler.js // 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 // 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 clawdbotRoot = path.resolve(
const slugGenPath = path.join(clawdbotRoot, 'llm-slug-generator.js'); path.dirname(import.meta.url.replace("file://", "")),
"../..",
);
const slugGenPath = path.join(clawdbotRoot, "llm-slug-generator.js");
const { generateSlugViaLLM } = await import(slugGenPath); const { generateSlugViaLLM } = await import(slugGenPath);
// Use LLM to generate a descriptive slug // Use LLM to generate a descriptive slug
slug = await generateSlugViaLLM({ sessionContent, cfg }); 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 no slug, use timestamp
if (!slug) { 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 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 // Create filename with date and slug
const filename = `${dateStr}-${slug}.md`; const filename = `${dateStr}-${slug}.md`;
const memoryFilePath = path.join(memoryDir, filename); const memoryFilePath = path.join(memoryDir, filename);
console.log('[session-memory] Generated filename:', filename); console.log("[session-memory] Generated filename:", filename);
console.log('[session-memory] Full path:', memoryFilePath); console.log("[session-memory] Full path:", memoryFilePath);
// Format time as HH:MM:SS UTC // 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 // Extract context details
const sessionId = (sessionEntry.sessionId as string) || 'unknown'; const sessionId = (sessionEntry.sessionId as string) || "unknown";
const source = (context.commandSource as string) || 'unknown'; const source = (context.commandSource as string) || "unknown";
// Build Markdown entry // Build Markdown entry
const entryParts = [ const entryParts = [
`# Session: ${dateStr} ${timeStr} UTC`, `# Session: ${dateStr} ${timeStr} UTC`,
'', "",
`- **Session Key**: ${event.sessionKey}`, `- **Session Key**: ${event.sessionKey}`,
`- **Session ID**: ${sessionId}`, `- **Session ID**: ${sessionId}`,
`- **Source**: ${source}`, `- **Source**: ${source}`,
'', "",
]; ];
// Include conversation content if available // Include conversation content if available
if (sessionContent) { 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 // Write to new memory file
await fs.writeFile(memoryFilePath, entry, 'utf-8'); await fs.writeFile(memoryFilePath, entry, "utf-8");
console.log('[session-memory] Memory file written successfully'); console.log("[session-memory] Memory file written successfully");
// Send confirmation message to user with filename // 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}`; const confirmMsg = `💾 Session context saved to memory before reset.\n📄 ${relPath}`;
event.messages.push(confirmMsg); event.messages.push(confirmMsg);
console.log('[session-memory] Confirmation message queued:', confirmMsg); console.log("[session-memory] Confirmation message queued:", confirmMsg);
} catch (err) { } catch (err) {
console.error( console.error(
'[session-memory] Failed to save session memory:', "[session-memory] Failed to save session memory:",
err instanceof Error ? err.message : String(err) err instanceof Error ? err.message : String(err),
); );
} }
}; };

View File

@ -84,12 +84,7 @@ function parseFrontmatterBool(value: string | undefined, fallback: boolean): boo
if (normalized === "true" || normalized === "1" || normalized === "yes" || normalized === "on") { if (normalized === "true" || normalized === "1" || normalized === "yes" || normalized === "on") {
return true; return true;
} }
if ( if (normalized === "false" || normalized === "0" || normalized === "no" || normalized === "off") {
normalized === "false" ||
normalized === "0" ||
normalized === "no" ||
normalized === "off"
) {
return false; return false;
} }
return fallback; return fallback;

View File

@ -2,17 +2,8 @@ import path from "node:path";
import type { ClawdbotConfig } from "../config/config.js"; import type { ClawdbotConfig } from "../config/config.js";
import { CONFIG_DIR } from "../utils.js"; import { CONFIG_DIR } from "../utils.js";
import { import { hasBinary, isConfigPathTruthy, resolveConfigPath, resolveHookConfig } from "./config.js";
hasBinary, import type { HookEligibilityContext, HookEntry, HookInstallSpec } from "./types.js";
isConfigPathTruthy,
resolveConfigPath,
resolveHookConfig,
} from "./config.js";
import type {
HookEligibilityContext,
HookEntry,
HookInstallSpec,
} from "./types.js";
import { loadWorkspaceHookEntries } from "./workspace.js"; import { loadWorkspaceHookEntries } from "./workspace.js";
export type HookStatusConfigCheck = { export type HookStatusConfigCheck = {
@ -155,9 +146,7 @@ function buildHookStatus(
return { path: pathStr, value, satisfied }; return { path: pathStr, value, satisfied };
}); });
const missingConfig = configChecks const missingConfig = configChecks.filter((check) => !check.satisfied).map((check) => check.path);
.filter((check) => !check.satisfied)
.map((check) => check.path);
const missing = always const missing = always
? { bins: [], anyBins: [], env: [], config: [], os: [] } ? { bins: [], anyBins: [], env: [], config: [], os: [] }

View File

@ -1,4 +1,4 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { import {
clearInternalHooks, clearInternalHooks,
createInternalHookEvent, createInternalHookEvent,
@ -7,9 +7,9 @@ import {
triggerInternalHook, triggerInternalHook,
unregisterInternalHook, unregisterInternalHook,
type InternalHookEvent, type InternalHookEvent,
} from './internal-hooks.js'; } from "./internal-hooks.js";
describe('internal-hooks', () => { describe("internal-hooks", () => {
beforeEach(() => { beforeEach(() => {
clearInternalHooks(); clearInternalHooks();
}); });
@ -18,174 +18,174 @@ describe('internal-hooks', () => {
clearInternalHooks(); clearInternalHooks();
}); });
describe('registerInternalHook', () => { describe("registerInternalHook", () => {
it('should register a hook handler', () => { it("should register a hook handler", () => {
const handler = vi.fn(); const handler = vi.fn();
registerInternalHook('command:new', handler); registerInternalHook("command:new", handler);
const keys = getRegisteredEventKeys(); 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 handler1 = vi.fn();
const handler2 = vi.fn(); const handler2 = vi.fn();
registerInternalHook('command:new', handler1); registerInternalHook("command:new", handler1);
registerInternalHook('command:new', handler2); registerInternalHook("command:new", handler2);
const keys = getRegisteredEventKeys(); const keys = getRegisteredEventKeys();
expect(keys).toContain('command:new'); expect(keys).toContain("command:new");
}); });
}); });
describe('unregisterInternalHook', () => { describe("unregisterInternalHook", () => {
it('should unregister a specific handler', () => { it("should unregister a specific handler", () => {
const handler1 = vi.fn(); const handler1 = vi.fn();
const handler2 = vi.fn(); const handler2 = vi.fn();
registerInternalHook('command:new', handler1); registerInternalHook("command:new", handler1);
registerInternalHook('command:new', handler2); 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); void triggerInternalHook(event);
expect(handler1).not.toHaveBeenCalled(); expect(handler1).not.toHaveBeenCalled();
expect(handler2).toHaveBeenCalled(); expect(handler2).toHaveBeenCalled();
}); });
it('should clean up empty handler arrays', () => { it("should clean up empty handler arrays", () => {
const handler = vi.fn(); const handler = vi.fn();
registerInternalHook('command:new', handler); registerInternalHook("command:new", handler);
unregisterInternalHook('command:new', handler); unregisterInternalHook("command:new", handler);
const keys = getRegisteredEventKeys(); const keys = getRegisteredEventKeys();
expect(keys).not.toContain('command:new'); expect(keys).not.toContain("command:new");
}); });
}); });
describe('triggerInternalHook', () => { describe("triggerInternalHook", () => {
it('should trigger handlers for general event type', async () => { it("should trigger handlers for general event type", async () => {
const handler = vi.fn(); 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); await triggerInternalHook(event);
expect(handler).toHaveBeenCalledWith(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(); 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); await triggerInternalHook(event);
expect(handler).toHaveBeenCalledWith(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 generalHandler = vi.fn();
const specificHandler = vi.fn(); const specificHandler = vi.fn();
registerInternalHook('command', generalHandler); registerInternalHook("command", generalHandler);
registerInternalHook('command:new', specificHandler); registerInternalHook("command:new", specificHandler);
const event = createInternalHookEvent('command', 'new', 'test-session'); const event = createInternalHookEvent("command", "new", "test-session");
await triggerInternalHook(event); await triggerInternalHook(event);
expect(generalHandler).toHaveBeenCalledWith(event); expect(generalHandler).toHaveBeenCalledWith(event);
expect(specificHandler).toHaveBeenCalledWith(event); expect(specificHandler).toHaveBeenCalledWith(event);
}); });
it('should handle async handlers', async () => { it("should handle async handlers", async () => {
const handler = vi.fn(async () => { const handler = vi.fn(async () => {
await new Promise((resolve) => setTimeout(resolve, 10)); 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); await triggerInternalHook(event);
expect(handler).toHaveBeenCalledWith(event); expect(handler).toHaveBeenCalledWith(event);
}); });
it('should catch and log errors from handlers', async () => { it("should catch and log errors from handlers", async () => {
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}); const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
const errorHandler = vi.fn(() => { const errorHandler = vi.fn(() => {
throw new Error('Handler failed'); throw new Error("Handler failed");
}); });
const successHandler = vi.fn(); const successHandler = vi.fn();
registerInternalHook('command:new', errorHandler); registerInternalHook("command:new", errorHandler);
registerInternalHook('command:new', successHandler); registerInternalHook("command:new", successHandler);
const event = createInternalHookEvent('command', 'new', 'test-session'); const event = createInternalHookEvent("command", "new", "test-session");
await triggerInternalHook(event); await triggerInternalHook(event);
expect(errorHandler).toHaveBeenCalled(); expect(errorHandler).toHaveBeenCalled();
expect(successHandler).toHaveBeenCalled(); expect(successHandler).toHaveBeenCalled();
expect(consoleError).toHaveBeenCalledWith( expect(consoleError).toHaveBeenCalledWith(
expect.stringContaining('Internal hook error'), expect.stringContaining("Internal hook error"),
expect.stringContaining('Handler failed') expect.stringContaining("Handler failed"),
); );
consoleError.mockRestore(); consoleError.mockRestore();
}); });
it('should not throw if no handlers are registered', async () => { it("should not throw if no handlers are registered", async () => {
const event = createInternalHookEvent('command', 'new', 'test-session'); const event = createInternalHookEvent("command", "new", "test-session");
await expect(triggerInternalHook(event)).resolves.not.toThrow(); await expect(triggerInternalHook(event)).resolves.not.toThrow();
}); });
}); });
describe('createInternalHookEvent', () => { describe("createInternalHookEvent", () => {
it('should create a properly formatted event', () => { it("should create a properly formatted event", () => {
const event = createInternalHookEvent('command', 'new', 'test-session', { const event = createInternalHookEvent("command", "new", "test-session", {
foo: 'bar', foo: "bar",
}); });
expect(event.type).toBe('command'); expect(event.type).toBe("command");
expect(event.action).toBe('new'); expect(event.action).toBe("new");
expect(event.sessionKey).toBe('test-session'); expect(event.sessionKey).toBe("test-session");
expect(event.context).toEqual({ foo: 'bar' }); expect(event.context).toEqual({ foo: "bar" });
expect(event.timestamp).toBeInstanceOf(Date); expect(event.timestamp).toBeInstanceOf(Date);
}); });
it('should use empty context if not provided', () => { it("should use empty context if not provided", () => {
const event = createInternalHookEvent('command', 'new', 'test-session'); const event = createInternalHookEvent("command", "new", "test-session");
expect(event.context).toEqual({}); expect(event.context).toEqual({});
}); });
}); });
describe('getRegisteredEventKeys', () => { describe("getRegisteredEventKeys", () => {
it('should return all registered event keys', () => { it("should return all registered event keys", () => {
registerInternalHook('command:new', vi.fn()); registerInternalHook("command:new", vi.fn());
registerInternalHook('command:stop', vi.fn()); registerInternalHook("command:stop", vi.fn());
registerInternalHook('session:start', vi.fn()); registerInternalHook("session:start", vi.fn());
const keys = getRegisteredEventKeys(); const keys = getRegisteredEventKeys();
expect(keys).toContain('command:new'); expect(keys).toContain("command:new");
expect(keys).toContain('command:stop'); expect(keys).toContain("command:stop");
expect(keys).toContain('session:start'); 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(); const keys = getRegisteredEventKeys();
expect(keys).toEqual([]); expect(keys).toEqual([]);
}); });
}); });
describe('clearInternalHooks', () => { describe("clearInternalHooks", () => {
it('should remove all registered handlers', () => { it("should remove all registered handlers", () => {
registerInternalHook('command:new', vi.fn()); registerInternalHook("command:new", vi.fn());
registerInternalHook('command:stop', vi.fn()); registerInternalHook("command:stop", vi.fn());
clearInternalHooks(); clearInternalHooks();
@ -194,33 +194,33 @@ describe('internal-hooks', () => {
}); });
}); });
describe('integration', () => { describe("integration", () => {
it('should handle a complete hook lifecycle', async () => { it("should handle a complete hook lifecycle", async () => {
const results: InternalHookEvent[] = []; const results: InternalHookEvent[] = [];
const handler = vi.fn((event: InternalHookEvent) => { const handler = vi.fn((event: InternalHookEvent) => {
results.push(event); results.push(event);
}); });
// Register // Register
registerInternalHook('command:new', handler); registerInternalHook("command:new", handler);
// Trigger // Trigger
const event1 = createInternalHookEvent('command', 'new', 'session-1'); const event1 = createInternalHookEvent("command", "new", "session-1");
await triggerInternalHook(event1); await triggerInternalHook(event1);
const event2 = createInternalHookEvent('command', 'new', 'session-2'); const event2 = createInternalHookEvent("command", "new", "session-2");
await triggerInternalHook(event2); await triggerInternalHook(event2);
// Verify // Verify
expect(results).toHaveLength(2); expect(results).toHaveLength(2);
expect(results[0].sessionKey).toBe('session-1'); expect(results[0].sessionKey).toBe("session-1");
expect(results[1].sessionKey).toBe('session-2'); expect(results[1].sessionKey).toBe("session-2");
// Unregister // Unregister
unregisterInternalHook('command:new', handler); unregisterInternalHook("command:new", handler);
// Trigger again - should not call handler // Trigger again - should not call handler
const event3 = createInternalHookEvent('command', 'new', 'session-3'); const event3 = createInternalHookEvent("command", "new", "session-3");
await triggerInternalHook(event3); await triggerInternalHook(event3);
expect(results).toHaveLength(2); expect(results).toHaveLength(2);

View File

@ -5,7 +5,7 @@
* like command processing, session lifecycle, etc. * like command processing, session lifecycle, etc.
*/ */
export type InternalHookEventType = 'command' | 'session' | 'agent'; export type InternalHookEventType = "command" | "session" | "agent";
export interface InternalHookEvent { export interface InternalHookEvent {
/** The type of event (command, session, agent, etc.) */ /** The type of event (command, session, agent, etc.) */
@ -46,10 +46,7 @@ const handlers = new Map<string, InternalHookHandler[]>();
* }); * });
* ``` * ```
*/ */
export function registerInternalHook( export function registerInternalHook(eventKey: string, handler: InternalHookHandler): void {
eventKey: string,
handler: InternalHookHandler
): void {
if (!handlers.has(eventKey)) { if (!handlers.has(eventKey)) {
handlers.set(eventKey, []); handlers.set(eventKey, []);
} }
@ -62,10 +59,7 @@ export function registerInternalHook(
* @param eventKey - Event key the handler was registered for * @param eventKey - Event key the handler was registered for
* @param handler - The handler function to remove * @param handler - The handler function to remove
*/ */
export function unregisterInternalHook( export function unregisterInternalHook(eventKey: string, handler: InternalHookHandler): void {
eventKey: string,
handler: InternalHookHandler
): void {
const eventHandlers = handlers.get(eventKey); const eventHandlers = handlers.get(eventKey);
if (!eventHandlers) { if (!eventHandlers) {
return; return;
@ -124,7 +118,7 @@ export async function triggerInternalHook(event: InternalHookEvent): Promise<voi
} catch (err) { } catch (err) {
console.error( console.error(
`Internal hook error [${event.type}:${event.action}]:`, `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, type: InternalHookEventType,
action: string, action: string,
sessionKey: string, sessionKey: string,
context: Record<string, unknown> = {} context: Record<string, unknown> = {},
): InternalHookEvent { ): InternalHookEvent {
return { return {
type, type,

View File

@ -2,12 +2,16 @@
* LLM-based slug generator for session memory filenames * LLM-based slug generator for session memory filenames
*/ */
import fs from 'node:fs/promises'; import fs from "node:fs/promises";
import os from 'node:os'; import os from "node:os";
import path from 'node:path'; import path from "node:path";
import { runEmbeddedPiAgent } from '../agents/pi-embedded.js'; import { runEmbeddedPiAgent } from "../agents/pi-embedded.js";
import type { ClawdbotConfig } from '../config/config.js'; import type { ClawdbotConfig } from "../config/config.js";
import { resolveDefaultAgentId, resolveAgentWorkspaceDir, resolveAgentDir } from '../agents/agent-scope.js'; import {
resolveDefaultAgentId,
resolveAgentWorkspaceDir,
resolveAgentDir,
} from "../agents/agent-scope.js";
/** /**
* Generate a short 1-2 word filename slug from session content using LLM * 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); const agentDir = resolveAgentDir(params.cfg, agentId);
// Create a temporary session file for this one-off LLM call // Create a temporary session file for this one-off LLM call
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'clawdbot-slug-')); const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-slug-"));
tempSessionFile = path.join(tempDir, 'session.jsonl'); 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). 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({ const result = await runEmbeddedPiAgent({
sessionId: `slug-generator-${Date.now()}`, sessionId: `slug-generator-${Date.now()}`,
sessionKey: 'temp:slug-generator', sessionKey: "temp:slug-generator",
sessionFile: tempSessionFile, sessionFile: tempSessionFile,
workspaceDir, workspaceDir,
agentDir, agentDir,
@ -54,9 +58,9 @@ Reply with ONLY the slug, nothing else. Examples: "vendor-pitch", "api-design",
const slug = text const slug = text
.trim() .trim()
.toLowerCase() .toLowerCase()
.replace(/[^a-z0-9-]/g, '-') .replace(/[^a-z0-9-]/g, "-")
.replace(/-+/g, '-') .replace(/-+/g, "-")
.replace(/^-|-$/g, '') .replace(/^-|-$/g, "")
.slice(0, 30); // Max 30 chars .slice(0, 30); // Max 30 chars
return slug || null; return slug || null;
@ -65,7 +69,7 @@ Reply with ONLY the slug, nothing else. Examples: "vendor-pitch", "api-design",
return null; return null;
} catch (err) { } catch (err) {
console.error('[llm-slug-generator] Failed to generate slug:', err); console.error("[llm-slug-generator] Failed to generate slug:", err);
return null; return null;
} finally { } finally {
// Clean up temporary session file // Clean up temporary session file

View File

@ -1,12 +1,17 @@
import fs from 'node:fs/promises'; import fs from "node:fs/promises";
import os from 'node:os'; import os from "node:os";
import path from 'node:path'; import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { loadInternalHooks } from './loader.js'; import { loadInternalHooks } from "./loader.js";
import { clearInternalHooks, getRegisteredEventKeys, triggerInternalHook, createInternalHookEvent } from './internal-hooks.js'; import {
import type { ClawdbotConfig } from '../config/config.js'; clearInternalHooks,
getRegisteredEventKeys,
triggerInternalHook,
createInternalHookEvent,
} from "./internal-hooks.js";
import type { ClawdbotConfig } from "../config/config.js";
describe('loader', () => { describe("loader", () => {
let tmpDir: string; let tmpDir: string;
let originalBundledDir: string | undefined; let originalBundledDir: string | undefined;
@ -18,7 +23,7 @@ describe('loader', () => {
// Disable bundled hooks during tests by setting env var to non-existent directory // Disable bundled hooks during tests by setting env var to non-existent directory
originalBundledDir = process.env.CLAWDBOT_BUNDLED_HOOKS_DIR; 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 () => { afterEach(async () => {
@ -37,8 +42,8 @@ describe('loader', () => {
} }
}); });
describe('loadInternalHooks', () => { describe("loadInternalHooks", () => {
it('should return 0 when internal hooks are not enabled', async () => { it("should return 0 when internal hooks are not enabled", async () => {
const cfg: ClawdbotConfig = { const cfg: ClawdbotConfig = {
hooks: { hooks: {
internal: { internal: {
@ -51,21 +56,21 @@ describe('loader', () => {
expect(count).toBe(0); 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 cfg: ClawdbotConfig = {};
const count = await loadInternalHooks(cfg, tmpDir); const count = await loadInternalHooks(cfg, tmpDir);
expect(count).toBe(0); 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 // Create a test handler module
const handlerPath = path.join(tmpDir, 'test-handler.js'); const handlerPath = path.join(tmpDir, "test-handler.js");
const handlerCode = ` const handlerCode = `
export default async function(event) { export default async function(event) {
// Test handler // Test handler
} }
`; `;
await fs.writeFile(handlerPath, handlerCode, 'utf-8'); await fs.writeFile(handlerPath, handlerCode, "utf-8");
const cfg: ClawdbotConfig = { const cfg: ClawdbotConfig = {
hooks: { hooks: {
@ -73,7 +78,7 @@ describe('loader', () => {
enabled: true, enabled: true,
handlers: [ handlers: [
{ {
event: 'command:new', event: "command:new",
module: handlerPath, module: handlerPath,
}, },
], ],
@ -85,24 +90,24 @@ describe('loader', () => {
expect(count).toBe(1); expect(count).toBe(1);
const keys = getRegisteredEventKeys(); 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 // Create test handler modules
const handler1Path = path.join(tmpDir, 'handler1.js'); const handler1Path = path.join(tmpDir, "handler1.js");
const handler2Path = path.join(tmpDir, 'handler2.js'); const handler2Path = path.join(tmpDir, "handler2.js");
await fs.writeFile(handler1Path, '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'); await fs.writeFile(handler2Path, "export default async function() {}", "utf-8");
const cfg: ClawdbotConfig = { const cfg: ClawdbotConfig = {
hooks: { hooks: {
internal: { internal: {
enabled: true, enabled: true,
handlers: [ handlers: [
{ event: 'command:new', module: handler1Path }, { event: "command:new", module: handler1Path },
{ event: 'command:stop', module: handler2Path }, { event: "command:stop", module: handler2Path },
], ],
}, },
}, },
@ -112,19 +117,19 @@ describe('loader', () => {
expect(count).toBe(2); expect(count).toBe(2);
const keys = getRegisteredEventKeys(); const keys = getRegisteredEventKeys();
expect(keys).toContain('command:new'); expect(keys).toContain("command:new");
expect(keys).toContain('command:stop'); expect(keys).toContain("command:stop");
}); });
it('should support named exports', async () => { it("should support named exports", async () => {
// Create a handler module with named export // 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 = ` const handlerCode = `
export const myHandler = async function(event) { export const myHandler = async function(event) {
// Named export handler // Named export handler
} }
`; `;
await fs.writeFile(handlerPath, handlerCode, 'utf-8'); await fs.writeFile(handlerPath, handlerCode, "utf-8");
const cfg: ClawdbotConfig = { const cfg: ClawdbotConfig = {
hooks: { hooks: {
@ -132,9 +137,9 @@ describe('loader', () => {
enabled: true, enabled: true,
handlers: [ handlers: [
{ {
event: 'command:new', event: "command:new",
module: handlerPath, module: handlerPath,
export: 'myHandler', export: "myHandler",
}, },
], ],
}, },
@ -145,8 +150,8 @@ describe('loader', () => {
expect(count).toBe(1); expect(count).toBe(1);
}); });
it('should handle module loading errors gracefully', async () => { it("should handle module loading errors gracefully", async () => {
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}); const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
const cfg: ClawdbotConfig = { const cfg: ClawdbotConfig = {
hooks: { hooks: {
@ -154,8 +159,8 @@ describe('loader', () => {
enabled: true, enabled: true,
handlers: [ handlers: [
{ {
event: 'command:new', event: "command:new",
module: '/nonexistent/path/handler.js', module: "/nonexistent/path/handler.js",
}, },
], ],
}, },
@ -165,19 +170,19 @@ describe('loader', () => {
const count = await loadInternalHooks(cfg, tmpDir); const count = await loadInternalHooks(cfg, tmpDir);
expect(count).toBe(0); expect(count).toBe(0);
expect(consoleError).toHaveBeenCalledWith( expect(consoleError).toHaveBeenCalledWith(
expect.stringContaining('Failed to load internal hook handler'), expect.stringContaining("Failed to load internal hook handler"),
expect.any(String) expect.any(String),
); );
consoleError.mockRestore(); consoleError.mockRestore();
}); });
it('should handle non-function exports', async () => { it("should handle non-function exports", async () => {
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}); const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
// Create a module with a non-function export // Create a module with a non-function export
const handlerPath = path.join(tmpDir, 'bad-export.js'); const handlerPath = path.join(tmpDir, "bad-export.js");
await fs.writeFile(handlerPath, 'export default "not a function";', 'utf-8'); await fs.writeFile(handlerPath, 'export default "not a function";', "utf-8");
const cfg: ClawdbotConfig = { const cfg: ClawdbotConfig = {
hooks: { hooks: {
@ -185,7 +190,7 @@ describe('loader', () => {
enabled: true, enabled: true,
handlers: [ handlers: [
{ {
event: 'command:new', event: "command:new",
module: handlerPath, module: handlerPath,
}, },
], ],
@ -195,17 +200,15 @@ describe('loader', () => {
const count = await loadInternalHooks(cfg, tmpDir); const count = await loadInternalHooks(cfg, tmpDir);
expect(count).toBe(0); expect(count).toBe(0);
expect(consoleError).toHaveBeenCalledWith( expect(consoleError).toHaveBeenCalledWith(expect.stringContaining("is not a function"));
expect.stringContaining('is not a function')
);
consoleError.mockRestore(); consoleError.mockRestore();
}); });
it('should handle relative paths', async () => { it("should handle relative paths", async () => {
// Create a handler module // Create a handler module
const handlerPath = path.join(tmpDir, 'relative-handler.js'); const handlerPath = path.join(tmpDir, "relative-handler.js");
await fs.writeFile(handlerPath, 'export default async function() {}', 'utf-8'); await fs.writeFile(handlerPath, "export default async function() {}", "utf-8");
// Get relative path from cwd // Get relative path from cwd
const relativePath = path.relative(process.cwd(), handlerPath); const relativePath = path.relative(process.cwd(), handlerPath);
@ -216,7 +219,7 @@ describe('loader', () => {
enabled: true, enabled: true,
handlers: [ handlers: [
{ {
event: 'command:new', event: "command:new",
module: relativePath, module: relativePath,
}, },
], ],
@ -228,9 +231,9 @@ describe('loader', () => {
expect(count).toBe(1); 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 // 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 = ` const handlerCode = `
let callCount = 0; let callCount = 0;
export default async function(event) { export default async function(event) {
@ -240,7 +243,7 @@ describe('loader', () => {
return callCount; return callCount;
} }
`; `;
await fs.writeFile(handlerPath, handlerCode, 'utf-8'); await fs.writeFile(handlerPath, handlerCode, "utf-8");
const cfg: ClawdbotConfig = { const cfg: ClawdbotConfig = {
hooks: { hooks: {
@ -248,7 +251,7 @@ describe('loader', () => {
enabled: true, enabled: true,
handlers: [ handlers: [
{ {
event: 'command:new', event: "command:new",
module: handlerPath, module: handlerPath,
}, },
], ],
@ -259,13 +262,13 @@ describe('loader', () => {
await loadInternalHooks(cfg, tmpDir); await loadInternalHooks(cfg, tmpDir);
// Trigger the hook // Trigger the hook
const event = createInternalHookEvent('command', 'new', 'test-session'); const event = createInternalHookEvent("command", "new", "test-session");
await triggerInternalHook(event); await triggerInternalHook(event);
// The handler should have been called, but we can't directly verify // The handler should have been called, but we can't directly verify
// the call count from this context without more complex test infrastructure // the call count from this context without more complex test infrastructure
// This test mainly verifies that loading and triggering doesn't crash // This test mainly verifies that loading and triggering doesn't crash
expect(getRegisteredEventKeys()).toContain('command:new'); expect(getRegisteredEventKeys()).toContain("command:new");
}); });
}); });
}); });

View File

@ -5,14 +5,14 @@
* and from directory-based discovery (bundled, managed, workspace) * and from directory-based discovery (bundled, managed, workspace)
*/ */
import { pathToFileURL } from 'node:url'; import { pathToFileURL } from "node:url";
import path from 'node:path'; import path from "node:path";
import { registerInternalHook } from './internal-hooks.js'; import { registerInternalHook } from "./internal-hooks.js";
import type { ClawdbotConfig } from '../config/config.js'; import type { ClawdbotConfig } from "../config/config.js";
import type { InternalHookHandler } from './internal-hooks.js'; import type { InternalHookHandler } from "./internal-hooks.js";
import { loadWorkspaceHookEntries } from './workspace.js'; import { loadWorkspaceHookEntries } from "./workspace.js";
import { resolveHookConfig } from './config.js'; import { resolveHookConfig } from "./config.js";
import { shouldIncludeHook } from './config.js'; import { shouldIncludeHook } from "./config.js";
/** /**
* Load and register all internal hook handlers * Load and register all internal hook handlers
@ -49,9 +49,7 @@ export async function loadInternalHooks(
const hookEntries = loadWorkspaceHookEntries(workspaceDir, { config: cfg }); const hookEntries = loadWorkspaceHookEntries(workspaceDir, { config: cfg });
// Filter by eligibility // Filter by eligibility
const eligible = hookEntries.filter((entry) => const eligible = hookEntries.filter((entry) => shouldIncludeHook({ entry, config: cfg }));
shouldIncludeHook({ entry, config: cfg }),
);
for (const entry of eligible) { for (const entry of eligible) {
const hookConfig = resolveHookConfig(cfg, entry.hook.name); const hookConfig = resolveHookConfig(cfg, entry.hook.name);
@ -68,10 +66,10 @@ export async function loadInternalHooks(
const mod = (await import(cacheBustedUrl)) as Record<string, unknown>; const mod = (await import(cacheBustedUrl)) as Record<string, unknown>;
// Get handler function (default or named export) // Get handler function (default or named export)
const exportName = entry.clawdbot?.export ?? 'default'; const exportName = entry.clawdbot?.export ?? "default";
const handler = mod[exportName]; const handler = mod[exportName];
if (typeof handler !== 'function') { if (typeof handler !== "function") {
console.error( console.error(
`Internal hook error: Handler '${exportName}' from ${entry.hook.name} is not a function`, `Internal hook error: Handler '${exportName}' from ${entry.hook.name} is not a function`,
); );
@ -92,7 +90,7 @@ export async function loadInternalHooks(
} }
console.log( 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++; loadedCount++;
} catch (err) { } catch (err) {
@ -104,7 +102,7 @@ export async function loadInternalHooks(
} }
} catch (err) { } catch (err) {
console.error( console.error(
'Failed to load directory-based hooks:', "Failed to load directory-based hooks:",
err instanceof Error ? err.message : String(err), err instanceof Error ? err.message : String(err),
); );
} }
@ -124,10 +122,10 @@ export async function loadInternalHooks(
const mod = (await import(cacheBustedUrl)) as Record<string, unknown>; const mod = (await import(cacheBustedUrl)) as Record<string, unknown>;
// Get the handler function // Get the handler function
const exportName = handlerConfig.export ?? 'default'; const exportName = handlerConfig.export ?? "default";
const handler = mod[exportName]; const handler = mod[exportName];
if (typeof handler !== 'function') { if (typeof handler !== "function") {
console.error( console.error(
`Internal hook error: Handler '${exportName}' from ${modulePath} is not a function`, `Internal hook error: Handler '${exportName}' from ${modulePath} is not a function`,
); );
@ -137,7 +135,7 @@ export async function loadInternalHooks(
// Register the handler // Register the handler
registerInternalHook(handlerConfig.event, handler as InternalHookHandler); registerInternalHook(handlerConfig.event, handler as InternalHookHandler);
console.log( console.log(
`Registered internal hook (legacy): ${handlerConfig.event} -> ${modulePath}${exportName !== 'default' ? `#${exportName}` : ''}`, `Registered internal hook (legacy): ${handlerConfig.event} -> ${modulePath}${exportName !== "default" ? `#${exportName}` : ""}`,
); );
loadedCount++; loadedCount++;
} catch (err) { } catch (err) {

View File

@ -59,12 +59,7 @@ function loadHooksFromDir(params: { dir: string; source: string }): Hook[] {
const description = frontmatter.description || ""; const description = frontmatter.description || "";
// Locate handler file (handler.ts, handler.js, index.ts, index.js) // Locate handler file (handler.ts, handler.js, index.ts, index.js)
const handlerCandidates = [ const handlerCandidates = ["handler.ts", "handler.js", "index.ts", "index.js"];
"handler.ts",
"handler.js",
"index.ts",
"index.js",
];
let handlerPath: string | undefined; let handlerPath: string | undefined;
for (const candidate of handlerCandidates) { for (const candidate of handlerCandidates) {