Custom tools with session lifecycle, examples for hooks and tools

- Custom tools: TypeScript modules that extend pi with new tools
  - Custom TUI rendering via renderCall/renderResult
  - User interaction via pi.ui (select, confirm, input, notify)
  - Session lifecycle via onSession callback for state reconstruction
  - Examples: todo.ts, question.ts, hello.ts

- Hook examples: permission-gate, git-checkpoint, protected-paths

- Session lifecycle centralized in AgentSession
  - Works across all modes (interactive, print, RPC)
  - Unified session event for hooks (replaces session_start/session_switch)

- Box component added to pi-tui

- Examples bundled in npm and binary releases

Fixes #190
This commit is contained in:
Mario Zechner 2025-12-17 16:03:23 +01:00
parent 295f51b53f
commit e7097d911a
33 changed files with 1926 additions and 117 deletions

View file

@ -0,0 +1,101 @@
# Custom Tools Examples
Example custom tools for pi-coding-agent.
## Examples
### hello.ts
Minimal example showing the basic structure of a custom tool.
### question.ts
Demonstrates `pi.ui.select()` for asking the user questions with options.
### todo.ts
Full-featured example demonstrating:
- `onSession` for state reconstruction from session history
- Custom `renderCall` and `renderResult`
- Proper branching support via details storage
- State management without external files
## Usage
```bash
# Test directly
pi --tool examples/custom-tools/todo.ts
# Or copy to tools directory for persistent use
cp todo.ts ~/.pi/agent/tools/
```
Then in pi:
```
> add a todo "test custom tools"
> list todos
> toggle todo #1
> clear todos
```
## Writing Custom Tools
See [docs/custom-tools.md](../../docs/custom-tools.md) for full documentation.
### Key Points
**Factory pattern:**
```typescript
import { Type } from "@sinclair/typebox";
import { StringEnum } from "@mariozechner/pi-ai";
import { Text } from "@mariozechner/pi-tui";
import type { CustomToolFactory } from "@mariozechner/pi-coding-agent";
const factory: CustomToolFactory = (pi) => ({
name: "my_tool",
label: "My Tool",
description: "Tool description for LLM",
parameters: Type.Object({
action: StringEnum(["list", "add"] as const),
}),
// Called on session start/switch/branch/clear
onSession(event) {
// Reconstruct state from event.entries
},
async execute(toolCallId, params) {
return {
content: [{ type: "text", text: "Result" }],
details: { /* for rendering and state reconstruction */ },
};
},
});
export default factory;
```
**Custom rendering:**
```typescript
renderCall(args, theme) {
return new Text(
theme.fg("toolTitle", theme.bold("my_tool ")) + args.action,
0, 0 // No padding - Box handles it
);
},
renderResult(result, { expanded, isPartial }, theme) {
if (isPartial) {
return new Text(theme.fg("warning", "Working..."), 0, 0);
}
return new Text(theme.fg("success", "✓ Done"), 0, 0);
},
```
**Use StringEnum for string parameters** (required for Google API compatibility):
```typescript
import { StringEnum } from "@mariozechner/pi-ai";
// Good
action: StringEnum(["list", "add"] as const)
// Bad - doesn't work with Google
action: Type.Union([Type.Literal("list"), Type.Literal("add")])
```

View file

@ -0,0 +1,20 @@
import { Type } from "@sinclair/typebox";
import type { CustomToolFactory } from "@mariozechner/pi-coding-agent";
const factory: CustomToolFactory = (pi) => ({
name: "hello",
label: "Hello",
description: "A simple greeting tool",
parameters: Type.Object({
name: Type.String({ description: "Name to greet" }),
}),
async execute(toolCallId, params) {
return {
content: [{ type: "text", text: `Hello, ${params.name}!` }],
details: { greeted: params.name },
};
},
});
export default factory;

View file

@ -0,0 +1,83 @@
/**
* Question Tool - Let the LLM ask the user a question with options
*/
import { Type } from "@sinclair/typebox";
import { Text } from "@mariozechner/pi-tui";
import type { CustomAgentTool, CustomToolFactory } from "@mariozechner/pi-coding-agent";
interface QuestionDetails {
question: string;
options: string[];
answer: string | null;
}
const QuestionParams = Type.Object({
question: Type.String({ description: "The question to ask the user" }),
options: Type.Array(Type.String(), { description: "Options for the user to choose from" }),
});
const factory: CustomToolFactory = (pi) => {
const tool: CustomAgentTool<typeof QuestionParams, QuestionDetails> = {
name: "question",
label: "Question",
description: "Ask the user a question and let them pick from options. Use when you need user input to proceed.",
parameters: QuestionParams,
async execute(_toolCallId, params) {
if (!pi.hasUI) {
return {
content: [{ type: "text", text: "Error: UI not available (running in non-interactive mode)" }],
details: { question: params.question, options: params.options, answer: null },
};
}
if (params.options.length === 0) {
return {
content: [{ type: "text", text: "Error: No options provided" }],
details: { question: params.question, options: [], answer: null },
};
}
const answer = await pi.ui.select(params.question, params.options);
if (answer === null) {
return {
content: [{ type: "text", text: "User cancelled the selection" }],
details: { question: params.question, options: params.options, answer: null },
};
}
return {
content: [{ type: "text", text: `User selected: ${answer}` }],
details: { question: params.question, options: params.options, answer },
};
},
renderCall(args, theme) {
let text = theme.fg("toolTitle", theme.bold("question ")) + theme.fg("muted", args.question);
if (args.options?.length) {
text += "\n" + theme.fg("dim", ` Options: ${args.options.join(", ")}`);
}
return new Text(text, 0, 0);
},
renderResult(result, _options, theme) {
const { details } = result;
if (!details) {
const text = result.content[0];
return new Text(text?.type === "text" ? text.text : "", 0, 0);
}
if (details.answer === null) {
return new Text(theme.fg("warning", "Cancelled"), 0, 0);
}
return new Text(theme.fg("success", "✓ ") + theme.fg("accent", details.answer), 0, 0);
},
};
return tool;
};
export default factory;

View file

@ -0,0 +1,192 @@
/**
* Todo Tool - Demonstrates state management via session entries
*
* This tool stores state in tool result details (not external files),
* which allows proper branching - when you branch, the todo state
* is automatically correct for that point in history.
*
* The onSession callback reconstructs state by scanning past tool results.
*/
import { Type } from "@sinclair/typebox";
import { StringEnum } from "@mariozechner/pi-ai";
import { Text } from "@mariozechner/pi-tui";
import type { CustomAgentTool, CustomToolFactory, ToolSessionEvent } from "@mariozechner/pi-coding-agent";
interface Todo {
id: number;
text: string;
done: boolean;
}
// State stored in tool result details
interface TodoDetails {
action: "list" | "add" | "toggle" | "clear";
todos: Todo[];
nextId: number;
error?: string;
}
// Define schema separately for proper type inference
const TodoParams = Type.Object({
action: StringEnum(["list", "add", "toggle", "clear"] as const),
text: Type.Optional(Type.String({ description: "Todo text (for add)" })),
id: Type.Optional(Type.Number({ description: "Todo ID (for toggle)" })),
});
const factory: CustomToolFactory = (_pi) => {
// In-memory state (reconstructed from session on load)
let todos: Todo[] = [];
let nextId = 1;
/**
* Reconstruct state from session entries.
* Scans tool results for this tool and applies them in order.
*/
const reconstructState = (event: ToolSessionEvent) => {
todos = [];
nextId = 1;
for (const entry of event.entries) {
if (entry.type !== "message") continue;
const msg = entry.message;
// Tool results have role "toolResult"
if (msg.role !== "toolResult") continue;
if (msg.toolName !== "todo") continue;
const details = msg.details as TodoDetails | undefined;
if (details) {
todos = details.todos;
nextId = details.nextId;
}
}
};
const tool: CustomAgentTool<typeof TodoParams, TodoDetails> = {
name: "todo",
label: "Todo",
description: "Manage a todo list. Actions: list, add (text), toggle (id), clear",
parameters: TodoParams,
// Called on session start/switch/branch/clear
onSession: reconstructState,
async execute(_toolCallId, params) {
switch (params.action) {
case "list":
return {
content: [{ type: "text", text: todos.length ? todos.map((t) => `[${t.done ? "x" : " "}] #${t.id}: ${t.text}`).join("\n") : "No todos" }],
details: { action: "list", todos: [...todos], nextId },
};
case "add":
if (!params.text) {
return {
content: [{ type: "text", text: "Error: text required for add" }],
details: { action: "add", todos: [...todos], nextId, error: "text required" },
};
}
const newTodo: Todo = { id: nextId++, text: params.text, done: false };
todos.push(newTodo);
return {
content: [{ type: "text", text: `Added todo #${newTodo.id}: ${newTodo.text}` }],
details: { action: "add", todos: [...todos], nextId },
};
case "toggle":
if (params.id === undefined) {
return {
content: [{ type: "text", text: "Error: id required for toggle" }],
details: { action: "toggle", todos: [...todos], nextId, error: "id required" },
};
}
const todo = todos.find((t) => t.id === params.id);
if (!todo) {
return {
content: [{ type: "text", text: `Todo #${params.id} not found` }],
details: { action: "toggle", todos: [...todos], nextId, error: `#${params.id} not found` },
};
}
todo.done = !todo.done;
return {
content: [{ type: "text", text: `Todo #${todo.id} ${todo.done ? "completed" : "uncompleted"}` }],
details: { action: "toggle", todos: [...todos], nextId },
};
case "clear":
const count = todos.length;
todos = [];
nextId = 1;
return {
content: [{ type: "text", text: `Cleared ${count} todos` }],
details: { action: "clear", todos: [], nextId: 1 },
};
default:
return {
content: [{ type: "text", text: `Unknown action: ${params.action}` }],
details: { action: "list", todos: [...todos], nextId, error: `unknown action: ${params.action}` },
};
}
},
renderCall(args, theme) {
let text = theme.fg("toolTitle", theme.bold("todo ")) + theme.fg("muted", args.action);
if (args.text) text += " " + theme.fg("dim", `"${args.text}"`);
if (args.id !== undefined) text += " " + theme.fg("accent", `#${args.id}`);
return new Text(text, 0, 0);
},
renderResult(result, { expanded }, theme) {
const { details } = result;
if (!details) {
const text = result.content[0];
return new Text(text?.type === "text" ? text.text : "", 0, 0);
}
// Error
if (details.error) {
return new Text(theme.fg("error", `Error: ${details.error}`), 0, 0);
}
const todoList = details.todos;
switch (details.action) {
case "list":
if (todoList.length === 0) {
return new Text(theme.fg("dim", "No todos"), 0, 0);
}
let listText = theme.fg("muted", `${todoList.length} todo(s):`);
const display = expanded ? todoList : todoList.slice(0, 5);
for (const t of display) {
const check = t.done ? theme.fg("success", "✓") : theme.fg("dim", "○");
const itemText = t.done ? theme.fg("dim", t.text) : theme.fg("muted", t.text);
listText += "\n" + check + " " + theme.fg("accent", `#${t.id}`) + " " + itemText;
}
if (!expanded && todoList.length > 5) {
listText += "\n" + theme.fg("dim", `... ${todoList.length - 5} more`);
}
return new Text(listText, 0, 0);
case "add": {
const added = todoList[todoList.length - 1];
return new Text(theme.fg("success", "✓ Added ") + theme.fg("accent", `#${added.id}`) + " " + theme.fg("muted", added.text), 0, 0);
}
case "toggle": {
const text = result.content[0];
const msg = text?.type === "text" ? text.text : "";
return new Text(theme.fg("success", "✓ ") + theme.fg("muted", msg), 0, 0);
}
case "clear":
return new Text(theme.fg("success", "✓ ") + theme.fg("muted", "Cleared all todos"), 0, 0);
}
},
};
return tool;
};
export default factory;

View file

@ -0,0 +1,76 @@
# Hooks Examples
Example hooks for pi-coding-agent.
## Examples
### permission-gate.ts
Prompts for confirmation before running dangerous bash commands (rm -rf, sudo, chmod 777, etc.).
### git-checkpoint.ts
Creates git stash checkpoints at each turn, allowing code restoration when branching.
### protected-paths.ts
Blocks writes to protected paths (.env, .git/, node_modules/).
## Usage
```bash
# Test directly
pi --hook examples/hooks/permission-gate.ts
# Or copy to hooks directory for persistent use
cp permission-gate.ts ~/.pi/agent/hooks/
```
## Writing Hooks
See [docs/hooks.md](../../docs/hooks.md) for full documentation.
### Key Points
**Hook structure:**
```typescript
import type { HookAPI } from "@mariozechner/pi-coding-agent/hooks";
export default function (pi: HookAPI) {
pi.on("session", async (event, ctx) => {
// event.reason: "start" | "switch" | "clear"
// ctx.ui, ctx.exec, ctx.cwd, ctx.sessionFile, ctx.hasUI
});
pi.on("tool_call", async (event, ctx) => {
// Can block tool execution
if (dangerous) {
return { block: true, reason: "Blocked" };
}
return undefined;
});
pi.on("tool_result", async (event, ctx) => {
// Can modify result
return { result: "modified result" };
});
}
```
**Available events:**
- `session` - startup, session switch, clear
- `branch` - before branching (can skip conversation restore)
- `agent_start` / `agent_end` - per user prompt
- `turn_start` / `turn_end` - per LLM turn
- `tool_call` - before tool execution (can block)
- `tool_result` - after tool execution (can modify)
**UI methods:**
```typescript
const choice = await ctx.ui.select("Title", ["Option A", "Option B"]);
const confirmed = await ctx.ui.confirm("Title", "Are you sure?");
const input = await ctx.ui.input("Title", "placeholder");
ctx.ui.notify("Message", "info"); // or "warning", "error"
```
**Sending messages:**
```typescript
pi.send("Message to inject into conversation");
```

View file

@ -0,0 +1,48 @@
/**
* Git Checkpoint Hook
*
* Creates git stash checkpoints at each turn so /branch can restore code state.
* When branching, offers to restore code to that point in history.
*/
import type { HookAPI } from "@mariozechner/pi-coding-agent/hooks";
export default function (pi: HookAPI) {
const checkpoints = new Map<number, string>();
pi.on("turn_start", async (event, ctx) => {
// Create a git stash entry before LLM makes changes
const { stdout } = await ctx.exec("git", ["stash", "create"]);
const ref = stdout.trim();
if (ref) {
checkpoints.set(event.turnIndex, ref);
}
});
pi.on("branch", async (event, ctx) => {
const ref = checkpoints.get(event.targetTurnIndex);
if (!ref) return undefined;
if (!ctx.hasUI) {
// In non-interactive mode, don't restore automatically
return undefined;
}
const choice = await ctx.ui.select("Restore code state?", [
"Yes, restore code to that point",
"No, keep current code",
]);
if (choice?.startsWith("Yes")) {
await ctx.exec("git", ["stash", "apply", ref]);
ctx.ui.notify("Code restored to checkpoint", "info");
}
return undefined;
});
pi.on("agent_end", async () => {
// Clear checkpoints after agent completes
checkpoints.clear();
});
}

View file

@ -0,0 +1,38 @@
/**
* Permission Gate Hook
*
* Prompts for confirmation before running potentially dangerous bash commands.
* Patterns checked: rm -rf, sudo, chmod/chown 777
*/
import type { HookAPI } from "@mariozechner/pi-coding-agent/hooks";
export default function (pi: HookAPI) {
const dangerousPatterns = [
/\brm\s+(-rf?|--recursive)/i,
/\bsudo\b/i,
/\b(chmod|chown)\b.*777/i,
];
pi.on("tool_call", async (event, ctx) => {
if (event.toolName !== "bash") return undefined;
const command = event.input.command as string;
const isDangerous = dangerousPatterns.some((p) => p.test(command));
if (isDangerous) {
if (!ctx.hasUI) {
// In non-interactive mode, block by default
return { block: true, reason: "Dangerous command blocked (no UI for confirmation)" };
}
const choice = await ctx.ui.select(`⚠️ Dangerous command:\n\n ${command}\n\nAllow?`, ["Yes", "No"]);
if (choice !== "Yes") {
return { block: true, reason: "Blocked by user" };
}
}
return undefined;
});
}

View file

@ -0,0 +1,30 @@
/**
* Protected Paths Hook
*
* Blocks write and edit operations to protected paths.
* Useful for preventing accidental modifications to sensitive files.
*/
import type { HookAPI } from "@mariozechner/pi-coding-agent/hooks";
export default function (pi: HookAPI) {
const protectedPaths = [".env", ".git/", "node_modules/"];
pi.on("tool_call", async (event, ctx) => {
if (event.toolName !== "write" && event.toolName !== "edit") {
return undefined;
}
const path = event.input.path as string;
const isProtected = protectedPaths.some((p) => path.includes(p));
if (isProtected) {
if (ctx.hasUI) {
ctx.ui.notify(`Blocked write to protected path: ${path}`, "warning");
}
return { block: true, reason: `Path "${path}" is protected` };
}
return undefined;
});
}