mirror of
https://github.com/getcompanion-ai/co-mono.git
synced 2026-04-16 00:03:00 +00:00
Add hooks system with pi.send() for external message injection
- Hook discovery from ~/.pi/agent/hooks/, .pi/hooks/, --hook flag - Events: session_start, session_switch, agent_start/end, turn_start/end, tool_call, tool_result, branch - tool_call can block execution, tool_result can modify results - pi.send(text, attachments?) to inject messages from external sources - UI primitives: ctx.ui.select/confirm/input/notify - Context: ctx.exec(), ctx.cwd, ctx.sessionFile, ctx.hasUI - Docs shipped with npm package and binary builds - System prompt references docs folder
This commit is contained in:
parent
942d8d3c95
commit
7c553acd1e
21 changed files with 1307 additions and 83 deletions
|
|
@ -24,6 +24,7 @@ export interface Args {
|
|||
session?: string;
|
||||
models?: string[];
|
||||
tools?: ToolName[];
|
||||
hooks?: string[];
|
||||
print?: boolean;
|
||||
export?: string;
|
||||
messages: string[];
|
||||
|
|
@ -100,6 +101,9 @@ export function parseArgs(args: string[]): Args {
|
|||
result.print = true;
|
||||
} else if (arg === "--export" && i + 1 < args.length) {
|
||||
result.export = args[++i];
|
||||
} else if (arg === "--hook" && i + 1 < args.length) {
|
||||
result.hooks = result.hooks ?? [];
|
||||
result.hooks.push(args[++i]);
|
||||
} else if (arg.startsWith("@")) {
|
||||
result.fileArgs.push(arg.slice(1)); // Remove @ prefix
|
||||
} else if (!arg.startsWith("-")) {
|
||||
|
|
@ -132,6 +136,7 @@ ${chalk.bold("Options:")}
|
|||
--tools <tools> Comma-separated list of tools to enable (default: read,bash,edit,write)
|
||||
Available: read, bash, edit, write, grep, find, ls
|
||||
--thinking <level> Set thinking level: off, minimal, low, medium, high, xhigh
|
||||
--hook <path> Load a hook file (can be used multiple times)
|
||||
--export <file> Export session file to HTML and exit
|
||||
--help, -h Show this help
|
||||
|
||||
|
|
|
|||
|
|
@ -70,6 +70,11 @@ export function getReadmePath(): string {
|
|||
return resolve(join(getPackageDir(), "README.md"));
|
||||
}
|
||||
|
||||
/** Get path to docs directory */
|
||||
export function getDocsPath(): string {
|
||||
return resolve(join(getPackageDir(), "docs"));
|
||||
}
|
||||
|
||||
/** Get path to CHANGELOG.md */
|
||||
export function getChangelogPath(): string {
|
||||
return resolve(join(getPackageDir(), "CHANGELOG.md"));
|
||||
|
|
|
|||
|
|
@ -888,6 +888,8 @@ export class AgentSession {
|
|||
* Listeners are preserved and will continue receiving events.
|
||||
*/
|
||||
async switchSession(sessionPath: string): Promise<void> {
|
||||
const previousSessionFile = this.sessionFile;
|
||||
|
||||
this._disconnectFromAgent();
|
||||
await this.abort();
|
||||
this._queuedMessages = [];
|
||||
|
|
@ -895,6 +897,17 @@ export class AgentSession {
|
|||
// Set new session
|
||||
this.sessionManager.setSessionFile(sessionPath);
|
||||
|
||||
// Emit session_switch event
|
||||
if (this._hookRunner) {
|
||||
this._hookRunner.setSessionFile(sessionPath);
|
||||
await this._hookRunner.emit({
|
||||
type: "session_switch",
|
||||
newSessionFile: sessionPath,
|
||||
previousSessionFile,
|
||||
reason: "switch",
|
||||
});
|
||||
}
|
||||
|
||||
// Reload messages
|
||||
const loaded = loadSessionFromEntries(this.sessionManager.loadEntries());
|
||||
this.agent.replaceMessages(loaded.messages);
|
||||
|
|
@ -928,6 +941,7 @@ export class AgentSession {
|
|||
* - skipped: True if a hook requested to skip conversation restore
|
||||
*/
|
||||
async branch(entryIndex: number): Promise<{ selectedText: string; skipped: boolean }> {
|
||||
const previousSessionFile = this.sessionFile;
|
||||
const entries = this.sessionManager.loadEntries();
|
||||
const selectedEntry = entries[entryIndex];
|
||||
|
||||
|
|
@ -956,6 +970,17 @@ export class AgentSession {
|
|||
const newSessionFile = this.sessionManager.createBranchedSessionFromEntries(entries, entryIndex);
|
||||
this.sessionManager.setSessionFile(newSessionFile);
|
||||
|
||||
// Emit session_switch event
|
||||
if (this._hookRunner) {
|
||||
this._hookRunner.setSessionFile(newSessionFile);
|
||||
await this._hookRunner.emit({
|
||||
type: "session_switch",
|
||||
newSessionFile,
|
||||
previousSessionFile,
|
||||
reason: "branch",
|
||||
});
|
||||
}
|
||||
|
||||
// Reload
|
||||
const loaded = loadSessionFromEntries(this.sessionManager.loadEntries());
|
||||
this.agent.replaceMessages(loaded.messages);
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
export { type LoadedHook, type LoadHooksResult, loadHooks } from "./loader.js";
|
||||
export { discoverAndLoadHooks, type LoadedHook, type LoadHooksResult, loadHooks, type SendHandler } from "./loader.js";
|
||||
export { type HookErrorListener, HookRunner } from "./runner.js";
|
||||
export { wrapToolsWithHooks, wrapToolWithHooks } from "./tool-wrapper.js";
|
||||
export type {
|
||||
AgentEndEvent,
|
||||
AgentStartEvent,
|
||||
|
|
@ -12,6 +13,12 @@ export type {
|
|||
HookEventContext,
|
||||
HookFactory,
|
||||
HookUIContext,
|
||||
SessionStartEvent,
|
||||
SessionSwitchEvent,
|
||||
ToolCallEvent,
|
||||
ToolCallEventResult,
|
||||
ToolResultEvent,
|
||||
ToolResultEventResult,
|
||||
TurnEndEvent,
|
||||
TurnStartEvent,
|
||||
} from "./types.js";
|
||||
|
|
|
|||
|
|
@ -2,9 +2,12 @@
|
|||
* Hook loader - loads TypeScript hook modules using jiti.
|
||||
*/
|
||||
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
import type { Attachment } from "@mariozechner/pi-agent-core";
|
||||
import { createJiti } from "jiti";
|
||||
import { getAgentDir } from "../../config.js";
|
||||
import type { HookAPI, HookFactory } from "./types.js";
|
||||
|
||||
/**
|
||||
|
|
@ -12,6 +15,11 @@ import type { HookAPI, HookFactory } from "./types.js";
|
|||
*/
|
||||
type HandlerFn = (...args: unknown[]) => Promise<unknown>;
|
||||
|
||||
/**
|
||||
* Send handler type for pi.send().
|
||||
*/
|
||||
export type SendHandler = (text: string, attachments?: Attachment[]) => void;
|
||||
|
||||
/**
|
||||
* Registered handlers for a loaded hook.
|
||||
*/
|
||||
|
|
@ -22,6 +30,8 @@ export interface LoadedHook {
|
|||
resolvedPath: string;
|
||||
/** Map of event type to handler functions */
|
||||
handlers: Map<string, HandlerFn[]>;
|
||||
/** Set the send handler for this hook's pi.send() */
|
||||
setSendHandler: (handler: SendHandler) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -66,15 +76,33 @@ function resolveHookPath(hookPath: string, cwd: string): string {
|
|||
|
||||
/**
|
||||
* Create a HookAPI instance that collects handlers.
|
||||
* Returns the API and a function to set the send handler later.
|
||||
*/
|
||||
function createHookAPI(handlers: Map<string, HandlerFn[]>): HookAPI {
|
||||
return {
|
||||
function createHookAPI(handlers: Map<string, HandlerFn[]>): {
|
||||
api: HookAPI;
|
||||
setSendHandler: (handler: SendHandler) => void;
|
||||
} {
|
||||
let sendHandler: SendHandler = () => {
|
||||
// Default no-op until mode sets the handler
|
||||
};
|
||||
|
||||
const api: HookAPI = {
|
||||
on(event: string, handler: HandlerFn): void {
|
||||
const list = handlers.get(event) ?? [];
|
||||
list.push(handler);
|
||||
handlers.set(event, list);
|
||||
},
|
||||
send(text: string, attachments?: Attachment[]): void {
|
||||
sendHandler(text, attachments);
|
||||
},
|
||||
} as HookAPI;
|
||||
|
||||
return {
|
||||
api,
|
||||
setSendHandler: (handler: SendHandler) => {
|
||||
sendHandler = handler;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -97,13 +125,13 @@ async function loadHook(hookPath: string, cwd: string): Promise<{ hook: LoadedHo
|
|||
|
||||
// Create handlers map and API
|
||||
const handlers = new Map<string, HandlerFn[]>();
|
||||
const api = createHookAPI(handlers);
|
||||
const { api, setSendHandler } = createHookAPI(handlers);
|
||||
|
||||
// Call factory to register handlers
|
||||
factory(api);
|
||||
|
||||
return {
|
||||
hook: { path: hookPath, resolvedPath, handlers },
|
||||
hook: { path: hookPath, resolvedPath, handlers, setSendHandler },
|
||||
error: null,
|
||||
};
|
||||
} catch (err) {
|
||||
|
|
@ -136,3 +164,59 @@ export async function loadHooks(paths: string[], cwd: string): Promise<LoadHooks
|
|||
|
||||
return { hooks, errors };
|
||||
}
|
||||
|
||||
/**
|
||||
* Discover hook files from a directory.
|
||||
* Returns all .ts files in the directory (non-recursive).
|
||||
*/
|
||||
function discoverHooksInDir(dir: string): string[] {
|
||||
if (!fs.existsSync(dir)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
return entries.filter((e) => e.isFile() && e.name.endsWith(".ts")).map((e) => path.join(dir, e.name));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Discover and load hooks from standard locations:
|
||||
* 1. ~/.pi/agent/hooks/*.ts (global)
|
||||
* 2. cwd/.pi/hooks/*.ts (project-local)
|
||||
*
|
||||
* Plus any explicitly configured paths from settings.
|
||||
*
|
||||
* @param configuredPaths - Explicit paths from settings.json
|
||||
* @param cwd - Current working directory
|
||||
*/
|
||||
export async function discoverAndLoadHooks(configuredPaths: string[], cwd: string): Promise<LoadHooksResult> {
|
||||
const allPaths: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
// Helper to add paths without duplicates
|
||||
const addPaths = (paths: string[]) => {
|
||||
for (const p of paths) {
|
||||
const resolved = path.resolve(p);
|
||||
if (!seen.has(resolved)) {
|
||||
seen.add(resolved);
|
||||
allPaths.push(p);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 1. Global hooks: ~/.pi/agent/hooks/
|
||||
const globalHooksDir = path.join(getAgentDir(), "hooks");
|
||||
addPaths(discoverHooksInDir(globalHooksDir));
|
||||
|
||||
// 2. Project-local hooks: cwd/.pi/hooks/
|
||||
const localHooksDir = path.join(cwd, ".pi", "hooks");
|
||||
addPaths(discoverHooksInDir(localHooksDir));
|
||||
|
||||
// 3. Explicitly configured paths (can override/add)
|
||||
addPaths(configuredPaths.map((p) => resolveHookPath(p, cwd)));
|
||||
|
||||
return loadHooks(allPaths, cwd);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,8 +3,18 @@
|
|||
*/
|
||||
|
||||
import { spawn } from "node:child_process";
|
||||
import type { LoadedHook } from "./loader.js";
|
||||
import type { BranchEventResult, ExecResult, HookError, HookEvent, HookEventContext, HookUIContext } from "./types.js";
|
||||
import type { LoadedHook, SendHandler } from "./loader.js";
|
||||
import type {
|
||||
BranchEventResult,
|
||||
ExecResult,
|
||||
HookError,
|
||||
HookEvent,
|
||||
HookEventContext,
|
||||
HookUIContext,
|
||||
ToolCallEvent,
|
||||
ToolCallEventResult,
|
||||
ToolResultEventResult,
|
||||
} from "./types.js";
|
||||
|
||||
/**
|
||||
* Default timeout for hook execution (30 seconds).
|
||||
|
|
@ -58,23 +68,68 @@ function createTimeout(ms: number): { promise: Promise<never>; clear: () => void
|
|||
};
|
||||
}
|
||||
|
||||
/** No-op UI context used when no UI is available */
|
||||
const noOpUIContext: HookUIContext = {
|
||||
select: async () => null,
|
||||
confirm: async () => false,
|
||||
input: async () => null,
|
||||
notify: () => {},
|
||||
};
|
||||
|
||||
/**
|
||||
* HookRunner executes hooks and manages event emission.
|
||||
*/
|
||||
export class HookRunner {
|
||||
private hooks: LoadedHook[];
|
||||
private uiContext: HookUIContext;
|
||||
private hasUI: boolean;
|
||||
private cwd: string;
|
||||
private sessionFile: string | null;
|
||||
private timeout: number;
|
||||
private errorListeners: Set<HookErrorListener> = new Set();
|
||||
|
||||
constructor(hooks: LoadedHook[], uiContext: HookUIContext, cwd: string, timeout: number = DEFAULT_TIMEOUT) {
|
||||
constructor(hooks: LoadedHook[], cwd: string, timeout: number = DEFAULT_TIMEOUT) {
|
||||
this.hooks = hooks;
|
||||
this.uiContext = uiContext;
|
||||
this.uiContext = noOpUIContext;
|
||||
this.hasUI = false;
|
||||
this.cwd = cwd;
|
||||
this.sessionFile = null;
|
||||
this.timeout = timeout;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the UI context for hooks.
|
||||
* Call this when the mode initializes and UI is available.
|
||||
*/
|
||||
setUIContext(uiContext: HookUIContext, hasUI: boolean): void {
|
||||
this.uiContext = uiContext;
|
||||
this.hasUI = hasUI;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the paths of all loaded hooks.
|
||||
*/
|
||||
getHookPaths(): string[] {
|
||||
return this.hooks.map((h) => h.path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the session file path.
|
||||
*/
|
||||
setSessionFile(sessionFile: string | null): void {
|
||||
this.sessionFile = sessionFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the send handler for all hooks' pi.send().
|
||||
* Call this when the mode initializes.
|
||||
*/
|
||||
setSendHandler(handler: SendHandler): void {
|
||||
for (const hook of this.hooks) {
|
||||
hook.setSendHandler(handler);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to hook errors.
|
||||
* @returns Unsubscribe function
|
||||
|
|
@ -113,17 +168,19 @@ export class HookRunner {
|
|||
return {
|
||||
exec: (command: string, args: string[]) => exec(command, args, this.cwd),
|
||||
ui: this.uiContext,
|
||||
hasUI: this.hasUI,
|
||||
cwd: this.cwd,
|
||||
sessionFile: this.sessionFile,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit an event to all hooks.
|
||||
* Returns the result from branch events (if any handler returns one).
|
||||
* Returns the result from branch/tool_result events (if any handler returns one).
|
||||
*/
|
||||
async emit(event: HookEvent): Promise<BranchEventResult | undefined> {
|
||||
async emit(event: HookEvent): Promise<BranchEventResult | ToolResultEventResult | undefined> {
|
||||
const ctx = this.createContext();
|
||||
let result: BranchEventResult | undefined;
|
||||
let result: BranchEventResult | ToolResultEventResult | undefined;
|
||||
|
||||
for (const hook of this.hooks) {
|
||||
const handlers = hook.handlers.get(event.type);
|
||||
|
|
@ -132,15 +189,18 @@ export class HookRunner {
|
|||
for (const handler of handlers) {
|
||||
try {
|
||||
const timeout = createTimeout(this.timeout);
|
||||
|
||||
const handlerResult = await Promise.race([handler(event, ctx), timeout.promise]);
|
||||
|
||||
timeout.clear();
|
||||
|
||||
// For branch events, capture the result
|
||||
if (event.type === "branch" && handlerResult) {
|
||||
result = handlerResult as BranchEventResult;
|
||||
}
|
||||
|
||||
// For tool_result events, capture the result
|
||||
if (event.type === "tool_result" && handlerResult) {
|
||||
result = handlerResult as ToolResultEventResult;
|
||||
}
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
this.emitError({
|
||||
|
|
@ -154,4 +214,34 @@ export class HookRunner {
|
|||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit a tool_call event to all hooks.
|
||||
* No timeout - user prompts can take as long as needed.
|
||||
* Errors are thrown (not swallowed) so caller can block on failure.
|
||||
*/
|
||||
async emitToolCall(event: ToolCallEvent): Promise<ToolCallEventResult | undefined> {
|
||||
const ctx = this.createContext();
|
||||
let result: ToolCallEventResult | undefined;
|
||||
|
||||
for (const hook of this.hooks) {
|
||||
const handlers = hook.handlers.get("tool_call");
|
||||
if (!handlers || handlers.length === 0) continue;
|
||||
|
||||
for (const handler of handlers) {
|
||||
// No timeout - let user take their time
|
||||
const handlerResult = await handler(event, ctx);
|
||||
|
||||
if (handlerResult) {
|
||||
result = handlerResult as ToolCallEventResult;
|
||||
// If blocked, stop processing further hooks
|
||||
if (result.block) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
81
packages/coding-agent/src/core/hooks/tool-wrapper.ts
Normal file
81
packages/coding-agent/src/core/hooks/tool-wrapper.ts
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
/**
|
||||
* Tool wrapper - wraps tools with hook callbacks for interception.
|
||||
*/
|
||||
|
||||
import type { AgentTool } from "@mariozechner/pi-ai";
|
||||
import type { HookRunner } from "./runner.js";
|
||||
import type { ToolCallEventResult, ToolResultEventResult } from "./types.js";
|
||||
|
||||
/**
|
||||
* Wrap a tool with hook callbacks.
|
||||
* - Emits tool_call event before execution (can block)
|
||||
* - Emits tool_result event after execution (can modify result)
|
||||
*/
|
||||
export function wrapToolWithHooks<T>(tool: AgentTool<any, T>, hookRunner: HookRunner): AgentTool<any, T> {
|
||||
return {
|
||||
...tool,
|
||||
execute: async (toolCallId: string, params: Record<string, unknown>, signal?: AbortSignal) => {
|
||||
// Emit tool_call event - hooks can block execution
|
||||
// If hook errors/times out, block by default (fail-safe)
|
||||
if (hookRunner.hasHandlers("tool_call")) {
|
||||
try {
|
||||
const callResult = (await hookRunner.emitToolCall({
|
||||
type: "tool_call",
|
||||
toolName: tool.name,
|
||||
toolCallId,
|
||||
input: params,
|
||||
})) as ToolCallEventResult | undefined;
|
||||
|
||||
if (callResult?.block) {
|
||||
const reason = callResult.reason || "Tool execution was blocked by a hook";
|
||||
throw new Error(reason);
|
||||
}
|
||||
} catch (err) {
|
||||
// Hook error or block - throw to mark as error
|
||||
if (err instanceof Error) {
|
||||
throw err;
|
||||
}
|
||||
throw new Error(`Hook failed, blocking execution: ${String(err)}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Execute the actual tool
|
||||
const result = await tool.execute(toolCallId, params, signal);
|
||||
|
||||
// Emit tool_result event - hooks can modify the result
|
||||
if (hookRunner.hasHandlers("tool_result")) {
|
||||
// Extract text from result for hooks
|
||||
const resultText = result.content
|
||||
.filter((c): c is { type: "text"; text: string } => c.type === "text")
|
||||
.map((c) => c.text)
|
||||
.join("\n");
|
||||
|
||||
const resultResult = (await hookRunner.emit({
|
||||
type: "tool_result",
|
||||
toolName: tool.name,
|
||||
toolCallId,
|
||||
input: params,
|
||||
result: resultText,
|
||||
isError: false,
|
||||
})) as ToolResultEventResult | undefined;
|
||||
|
||||
// Apply modifications if any
|
||||
if (resultResult?.result !== undefined) {
|
||||
return {
|
||||
...result,
|
||||
content: [{ type: "text", text: resultResult.result }],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap all tools with hook callbacks.
|
||||
*/
|
||||
export function wrapToolsWithHooks<T>(tools: AgentTool<any, T>[], hookRunner: HookRunner): AgentTool<any, T>[] {
|
||||
return tools.map((tool) => wrapToolWithHooks(tool, hookRunner));
|
||||
}
|
||||
|
|
@ -5,7 +5,7 @@
|
|||
* and interact with the user via UI primitives.
|
||||
*/
|
||||
|
||||
import type { AppMessage } from "@mariozechner/pi-agent-core";
|
||||
import type { AppMessage, Attachment } from "@mariozechner/pi-agent-core";
|
||||
import type { SessionEntry } from "../session-manager.js";
|
||||
|
||||
// ============================================================================
|
||||
|
|
@ -60,16 +60,43 @@ export interface HookEventContext {
|
|||
exec(command: string, args: string[]): Promise<ExecResult>;
|
||||
/** UI methods for user interaction */
|
||||
ui: HookUIContext;
|
||||
/** Whether UI is available (false in print mode) */
|
||||
hasUI: boolean;
|
||||
/** Current working directory */
|
||||
cwd: string;
|
||||
/** Path to session file, or null if --no-session */
|
||||
sessionFile: string | null;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Events
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Event data for session_start event.
|
||||
* Fired once when the coding agent starts up.
|
||||
*/
|
||||
export interface SessionStartEvent {
|
||||
type: "session_start";
|
||||
}
|
||||
|
||||
/**
|
||||
* Event data for session_switch event.
|
||||
* Fired when the session changes (branch or session switch).
|
||||
*/
|
||||
export interface SessionSwitchEvent {
|
||||
type: "session_switch";
|
||||
/** New session file path */
|
||||
newSessionFile: string;
|
||||
/** Previous session file path */
|
||||
previousSessionFile: string;
|
||||
/** Reason for the switch */
|
||||
reason: "branch" | "switch";
|
||||
}
|
||||
|
||||
/**
|
||||
* Event data for agent_start event.
|
||||
* Fired when an agent loop starts (once per user prompt).
|
||||
*/
|
||||
export interface AgentStartEvent {
|
||||
type: "agent_start";
|
||||
|
|
@ -102,6 +129,38 @@ export interface TurnEndEvent {
|
|||
toolResults: AppMessage[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Event data for tool_call event.
|
||||
* Fired before a tool is executed. Hooks can block execution.
|
||||
*/
|
||||
export interface ToolCallEvent {
|
||||
type: "tool_call";
|
||||
/** Tool name (e.g., "bash", "edit", "write") */
|
||||
toolName: string;
|
||||
/** Tool call ID */
|
||||
toolCallId: string;
|
||||
/** Tool input parameters */
|
||||
input: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Event data for tool_result event.
|
||||
* Fired after a tool is executed. Hooks can modify the result.
|
||||
*/
|
||||
export interface ToolResultEvent {
|
||||
type: "tool_result";
|
||||
/** Tool name (e.g., "bash", "edit", "write") */
|
||||
toolName: string;
|
||||
/** Tool call ID */
|
||||
toolCallId: string;
|
||||
/** Tool input parameters */
|
||||
input: Record<string, unknown>;
|
||||
/** Tool result content (text) */
|
||||
result: string;
|
||||
/** Whether the tool execution was an error */
|
||||
isError: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Event data for branch event.
|
||||
*/
|
||||
|
|
@ -116,12 +175,43 @@ export interface BranchEvent {
|
|||
/**
|
||||
* Union of all hook event types.
|
||||
*/
|
||||
export type HookEvent = AgentStartEvent | AgentEndEvent | TurnStartEvent | TurnEndEvent | BranchEvent;
|
||||
export type HookEvent =
|
||||
| SessionStartEvent
|
||||
| SessionSwitchEvent
|
||||
| AgentStartEvent
|
||||
| AgentEndEvent
|
||||
| TurnStartEvent
|
||||
| TurnEndEvent
|
||||
| ToolCallEvent
|
||||
| ToolResultEvent
|
||||
| BranchEvent;
|
||||
|
||||
// ============================================================================
|
||||
// Event Results
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Return type for tool_call event handlers.
|
||||
* Allows hooks to block tool execution.
|
||||
*/
|
||||
export interface ToolCallEventResult {
|
||||
/** If true, block the tool from executing */
|
||||
block?: boolean;
|
||||
/** Reason for blocking (returned to LLM as error) */
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return type for tool_result event handlers.
|
||||
* Allows hooks to modify tool results.
|
||||
*/
|
||||
export interface ToolResultEventResult {
|
||||
/** Modified result text (if not set, original result is used) */
|
||||
result?: string;
|
||||
/** Override isError flag */
|
||||
isError?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return type for branch event handlers.
|
||||
* Allows hooks to control branch behavior.
|
||||
|
|
@ -142,14 +232,25 @@ export type HookHandler<E, R = void> = (event: E, ctx: HookEventContext) => Prom
|
|||
|
||||
/**
|
||||
* HookAPI passed to hook factory functions.
|
||||
* Hooks use pi.on() to subscribe to events.
|
||||
* Hooks use pi.on() to subscribe to events and pi.send() to inject messages.
|
||||
*/
|
||||
export interface HookAPI {
|
||||
on(event: "session_start", handler: HookHandler<SessionStartEvent>): void;
|
||||
on(event: "session_switch", handler: HookHandler<SessionSwitchEvent>): void;
|
||||
on(event: "agent_start", handler: HookHandler<AgentStartEvent>): void;
|
||||
on(event: "agent_end", handler: HookHandler<AgentEndEvent>): void;
|
||||
on(event: "turn_start", handler: HookHandler<TurnStartEvent>): void;
|
||||
on(event: "turn_end", handler: HookHandler<TurnEndEvent>): void;
|
||||
on(event: "tool_call", handler: HookHandler<ToolCallEvent, ToolCallEventResult | undefined>): void;
|
||||
on(event: "tool_result", handler: HookHandler<ToolResultEvent, ToolResultEventResult | undefined>): void;
|
||||
on(event: "branch", handler: HookHandler<BranchEvent, BranchEventResult | undefined>): void;
|
||||
|
||||
/**
|
||||
* Send a message to the agent.
|
||||
* If the agent is streaming, the message is queued.
|
||||
* If the agent is idle, a new agent loop is started.
|
||||
*/
|
||||
send(text: string, attachments?: Attachment[]): void;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@
|
|||
import chalk from "chalk";
|
||||
import { existsSync, readFileSync } from "fs";
|
||||
import { join, resolve } from "path";
|
||||
import { getAgentDir, getReadmePath } from "../config.js";
|
||||
import { getAgentDir, getDocsPath, getReadmePath } from "../config.js";
|
||||
import type { ToolName } from "./tools/index.js";
|
||||
|
||||
/** Tool descriptions for system prompt */
|
||||
|
|
@ -148,8 +148,9 @@ export function buildSystemPrompt(
|
|||
return prompt;
|
||||
}
|
||||
|
||||
// Get absolute path to README.md
|
||||
// Get absolute paths to documentation
|
||||
const readmePath = getReadmePath();
|
||||
const docsPath = getDocsPath();
|
||||
|
||||
// Build tools list based on selected tools
|
||||
const tools = selectedTools || (["read", "bash", "edit", "write"] as ToolName[]);
|
||||
|
|
@ -223,7 +224,8 @@ ${guidelines}
|
|||
|
||||
Documentation:
|
||||
- Your own documentation (including custom model setup and theme creation) is at: ${readmePath}
|
||||
- Read it when users ask about features, configuration, or setup, and especially if the user asks you to add a custom model or provider, or create a custom theme.`;
|
||||
- Additional documentation (hooks, themes, RPC, etc.) is in: ${docsPath}
|
||||
- Read it when users ask about features, configuration, or setup, and especially if the user asks you to add a custom model or provider, create a custom theme, or write a hook.`;
|
||||
|
||||
if (appendSection) {
|
||||
prompt += appendSection;
|
||||
|
|
|
|||
|
|
@ -9,6 +9,12 @@ export type {
|
|||
HookEventContext,
|
||||
HookFactory,
|
||||
HookUIContext,
|
||||
SessionStartEvent,
|
||||
SessionSwitchEvent,
|
||||
ToolCallEvent,
|
||||
ToolCallEventResult,
|
||||
ToolResultEvent,
|
||||
ToolResultEventResult,
|
||||
TurnEndEvent,
|
||||
TurnStartEvent,
|
||||
} from "./core/hooks/index.js";
|
||||
|
|
|
|||
|
|
@ -10,13 +10,14 @@ import { selectSession } from "./cli/session-picker.js";
|
|||
import { getModelsPath, VERSION } from "./config.js";
|
||||
import { AgentSession } from "./core/agent-session.js";
|
||||
import { exportFromFile } from "./core/export-html.js";
|
||||
import { discoverAndLoadHooks, HookRunner, wrapToolsWithHooks } from "./core/hooks/index.js";
|
||||
import { messageTransformer } from "./core/messages.js";
|
||||
import { findModel, getApiKeyForModel, getAvailableModels } from "./core/model-config.js";
|
||||
import { resolveModelScope, restoreModelFromSession, type ScopedModel } from "./core/model-resolver.js";
|
||||
import { SessionManager } from "./core/session-manager.js";
|
||||
import { SettingsManager } from "./core/settings-manager.js";
|
||||
import { loadSlashCommands } from "./core/slash-commands.js";
|
||||
import { buildSystemPrompt, loadProjectContextFiles } from "./core/system-prompt.js";
|
||||
import { buildSystemPrompt } from "./core/system-prompt.js";
|
||||
import { allTools, codingTools } from "./core/tools/index.js";
|
||||
import { InteractiveMode, runPrintMode, runRpcMode } from "./modes/index.js";
|
||||
import { initTheme } from "./modes/interactive/theme/theme.js";
|
||||
|
|
@ -270,7 +271,30 @@ export async function main(args: string[]) {
|
|||
}
|
||||
|
||||
// Determine which tools to use
|
||||
const selectedTools = parsed.tools ? parsed.tools.map((name) => allTools[name]) : codingTools;
|
||||
let selectedTools = parsed.tools ? parsed.tools.map((name) => allTools[name]) : codingTools;
|
||||
|
||||
// Discover and load hooks from:
|
||||
// 1. ~/.pi/agent/hooks/*.ts (global)
|
||||
// 2. cwd/.pi/hooks/*.ts (project-local)
|
||||
// 3. Explicit paths in settings.json
|
||||
// 4. CLI --hook flags
|
||||
let hookRunner: HookRunner | null = null;
|
||||
const cwd = process.cwd();
|
||||
const configuredHookPaths = [...settingsManager.getHookPaths(), ...(parsed.hooks ?? [])];
|
||||
const { hooks, errors } = await discoverAndLoadHooks(configuredHookPaths, cwd);
|
||||
|
||||
// Report hook loading errors
|
||||
for (const { path, error } of errors) {
|
||||
console.error(chalk.red(`Failed to load hook "${path}": ${error}`));
|
||||
}
|
||||
|
||||
if (hooks.length > 0) {
|
||||
const timeout = settingsManager.getHookTimeout();
|
||||
hookRunner = new HookRunner(hooks, cwd, timeout);
|
||||
|
||||
// Wrap tools with hook callbacks
|
||||
selectedTools = wrapToolsWithHooks(selectedTools, hookRunner);
|
||||
}
|
||||
|
||||
// Create agent
|
||||
const agent = new Agent({
|
||||
|
|
@ -317,17 +341,6 @@ export async function main(args: string[]) {
|
|||
}
|
||||
}
|
||||
|
||||
// Log loaded context files
|
||||
if (shouldPrintMessages && !parsed.continue && !parsed.resume) {
|
||||
const contextFiles = loadProjectContextFiles();
|
||||
if (contextFiles.length > 0) {
|
||||
console.log(chalk.dim("Loaded project context from:"));
|
||||
for (const { path: filePath } of contextFiles) {
|
||||
console.log(chalk.dim(` - ${filePath}`));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Load file commands for slash command expansion
|
||||
const fileCommands = loadSlashCommands();
|
||||
|
||||
|
|
@ -338,6 +351,7 @@ export async function main(args: string[]) {
|
|||
settingsManager,
|
||||
scopedModels,
|
||||
fileCommands,
|
||||
hookRunner,
|
||||
});
|
||||
|
||||
// Route to appropriate mode
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@
|
|||
|
||||
import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
import type { AgentState, AppMessage } from "@mariozechner/pi-agent-core";
|
||||
import type { AgentState, AppMessage, Attachment } from "@mariozechner/pi-agent-core";
|
||||
import type { AssistantMessage, Message } from "@mariozechner/pi-ai";
|
||||
import type { SlashCommand } from "@mariozechner/pi-tui";
|
||||
import {
|
||||
|
|
@ -30,6 +30,7 @@ import { isBashExecutionMessage } from "../../core/messages.js";
|
|||
import { invalidateOAuthCache } from "../../core/model-config.js";
|
||||
import { listOAuthProviders, login, logout, type SupportedOAuthProvider } from "../../core/oauth/index.js";
|
||||
import { getLatestCompactionEntry, SUMMARY_PREFIX, SUMMARY_SUFFIX } from "../../core/session-manager.js";
|
||||
import { loadProjectContextFiles } from "../../core/system-prompt.js";
|
||||
import type { TruncationResult } from "../../core/tools/truncate.js";
|
||||
import { getChangelogPath, parseChangelog } from "../../utils/changelog.js";
|
||||
import { copyToClipboard } from "../../utils/clipboard.js";
|
||||
|
|
@ -276,24 +277,43 @@ export class InteractiveMode {
|
|||
* Initialize the hook system with TUI-based UI context.
|
||||
*/
|
||||
private async initHooks(): Promise<void> {
|
||||
const hookPaths = this.settingsManager.getHookPaths();
|
||||
if (hookPaths.length === 0) {
|
||||
return; // No hooks configured
|
||||
// Show loaded project context files
|
||||
const contextFiles = loadProjectContextFiles();
|
||||
if (contextFiles.length > 0) {
|
||||
const contextList = contextFiles.map((f) => theme.fg("dim", ` ${f.path}`)).join("\n");
|
||||
this.chatContainer.addChild(new Text(theme.fg("muted", "Loaded context:\n") + contextList, 0, 0));
|
||||
this.chatContainer.addChild(new Spacer(1));
|
||||
}
|
||||
|
||||
// Create hook UI context
|
||||
const hookUIContext = this.createHookUIContext();
|
||||
const hookRunner = this.session.hookRunner;
|
||||
if (!hookRunner) {
|
||||
return; // No hooks loaded
|
||||
}
|
||||
|
||||
// Set context on session
|
||||
this.session.setHookUIContext(hookUIContext, (error) => {
|
||||
// Set TUI-based UI context on the hook runner
|
||||
hookRunner.setUIContext(this.createHookUIContext(), true);
|
||||
hookRunner.setSessionFile(this.session.sessionFile);
|
||||
|
||||
// Subscribe to hook errors
|
||||
hookRunner.onError((error) => {
|
||||
this.showHookError(error.hookPath, error.error);
|
||||
});
|
||||
|
||||
// Initialize hooks and report any loading errors
|
||||
const loadErrors = await this.session.initHooks();
|
||||
for (const { path, error } of loadErrors) {
|
||||
this.showHookError(path, error);
|
||||
// Set up send handler for pi.send()
|
||||
hookRunner.setSendHandler((text, attachments) => {
|
||||
this.handleHookSend(text, attachments);
|
||||
});
|
||||
|
||||
// Show loaded hooks
|
||||
const hookPaths = hookRunner.getHookPaths();
|
||||
if (hookPaths.length > 0) {
|
||||
const hookList = hookPaths.map((p) => theme.fg("dim", ` ${p}`)).join("\n");
|
||||
this.chatContainer.addChild(new Text(theme.fg("muted", "Loaded hooks:\n") + hookList, 0, 0));
|
||||
this.chatContainer.addChild(new Spacer(1));
|
||||
}
|
||||
|
||||
// Emit session_start event
|
||||
await hookRunner.emit({ type: "session_start" });
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -392,10 +412,13 @@ export class InteractiveMode {
|
|||
* Show a notification for hooks.
|
||||
*/
|
||||
private showHookNotify(message: string, type?: "info" | "warning" | "error"): void {
|
||||
const color = type === "error" ? "error" : type === "warning" ? "warning" : "dim";
|
||||
const text = new Text(theme.fg(color, `[Hook] ${message}`), 1, 0);
|
||||
this.chatContainer.addChild(text);
|
||||
this.ui.requestRender();
|
||||
if (type === "error") {
|
||||
this.showError(message);
|
||||
} else if (type === "warning") {
|
||||
this.showWarning(message);
|
||||
} else {
|
||||
this.showStatus(message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -407,6 +430,23 @@ export class InteractiveMode {
|
|||
this.ui.requestRender();
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle pi.send() from hooks.
|
||||
* If streaming, queue the message. Otherwise, start a new agent loop.
|
||||
*/
|
||||
private handleHookSend(text: string, attachments?: Attachment[]): void {
|
||||
if (this.session.isStreaming) {
|
||||
// Queue the message for later (note: attachments are lost when queuing)
|
||||
this.session.queueMessage(text);
|
||||
this.updatePendingMessagesDisplay();
|
||||
} else {
|
||||
// Start a new agent loop immediately
|
||||
this.session.prompt(text, { attachments }).catch((err) => {
|
||||
this.showError(err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Key Handlers
|
||||
// =========================================================================
|
||||
|
|
|
|||
|
|
@ -9,28 +9,6 @@
|
|||
import type { Attachment } from "@mariozechner/pi-agent-core";
|
||||
import type { AssistantMessage } from "@mariozechner/pi-ai";
|
||||
import type { AgentSession } from "../core/agent-session.js";
|
||||
import type { HookUIContext } from "../core/hooks/index.js";
|
||||
|
||||
/**
|
||||
* Create a no-op hook UI context for print mode.
|
||||
* Hooks can still run but can't prompt the user interactively.
|
||||
*/
|
||||
function createNoOpHookUIContext(): HookUIContext {
|
||||
return {
|
||||
async select() {
|
||||
return null;
|
||||
},
|
||||
async confirm() {
|
||||
return false;
|
||||
},
|
||||
async input() {
|
||||
return null;
|
||||
},
|
||||
notify() {
|
||||
// Silent in print mode
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Run in print (single-shot) mode.
|
||||
|
|
@ -49,11 +27,21 @@ export async function runPrintMode(
|
|||
initialMessage?: string,
|
||||
initialAttachments?: Attachment[],
|
||||
): Promise<void> {
|
||||
// Initialize hooks with no-op UI context (hooks run but can't prompt)
|
||||
session.setHookUIContext(createNoOpHookUIContext(), (err) => {
|
||||
console.error(`Hook error (${err.hookPath}): ${err.error}`);
|
||||
});
|
||||
await session.initHooks();
|
||||
// Hook runner already has no-op UI context by default (set in main.ts)
|
||||
// Set up hooks for print mode (no UI, ephemeral session)
|
||||
const hookRunner = session.hookRunner;
|
||||
if (hookRunner) {
|
||||
hookRunner.setSessionFile(null); // Print mode is ephemeral
|
||||
hookRunner.onError((err) => {
|
||||
console.error(`Hook error (${err.hookPath}): ${err.error}`);
|
||||
});
|
||||
// No-op send handler for print mode (single-shot, no async messages)
|
||||
hookRunner.setSendHandler(() => {
|
||||
console.error("Warning: pi.send() is not supported in print mode");
|
||||
});
|
||||
// Emit session_start event
|
||||
await hookRunner.emit({ type: "session_start" });
|
||||
}
|
||||
|
||||
if (mode === "json") {
|
||||
// Output all events as JSON
|
||||
|
|
|
|||
|
|
@ -121,11 +121,27 @@ export async function runRpcMode(session: AgentSession): Promise<never> {
|
|||
});
|
||||
|
||||
// Set up hooks with RPC-based UI context
|
||||
const hookUIContext = createHookUIContext();
|
||||
session.setHookUIContext(hookUIContext, (err) => {
|
||||
output({ type: "hook_error", hookPath: err.hookPath, event: err.event, error: err.error });
|
||||
});
|
||||
await session.initHooks();
|
||||
const hookRunner = session.hookRunner;
|
||||
if (hookRunner) {
|
||||
hookRunner.setUIContext(createHookUIContext(), false);
|
||||
hookRunner.setSessionFile(session.sessionFile);
|
||||
hookRunner.onError((err) => {
|
||||
output({ type: "hook_error", hookPath: err.hookPath, event: err.event, error: err.error });
|
||||
});
|
||||
// Set up send handler for pi.send()
|
||||
hookRunner.setSendHandler((text, attachments) => {
|
||||
// In RPC mode, just queue or prompt based on streaming state
|
||||
if (session.isStreaming) {
|
||||
session.queueMessage(text);
|
||||
} else {
|
||||
session.prompt(text, { attachments }).catch((e) => {
|
||||
output(error(undefined, "hook_send", e.message));
|
||||
});
|
||||
}
|
||||
});
|
||||
// Emit session_start event
|
||||
await hookRunner.emit({ type: "session_start" });
|
||||
}
|
||||
|
||||
// Output all agent events as JSON
|
||||
session.subscribe((event) => {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue