forked from badlogic/pi-mono
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdynamic-tools.ts
More file actions
74 lines (63 loc) · 2.16 KB
/
dynamic-tools.ts
File metadata and controls
74 lines (63 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* Dynamic Tools Extension
*
* Demonstrates registering tools after session initialization.
*
* - Registers one tool during session_start
* - Registers additional tools at runtime via /add-echo-tool <name>
*/
import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
import { Type } from "@sinclair/typebox";
const ECHO_PARAMS = Type.Object({
message: Type.String({ description: "Message to echo" }),
});
function normalizeToolName(input: string): string | undefined {
const trimmed = input.trim().toLowerCase();
if (!trimmed) return undefined;
if (!/^[a-z0-9_]+$/.test(trimmed)) return undefined;
return trimmed;
}
export default function dynamicToolsExtension(pi: ExtensionAPI) {
const registeredToolNames = new Set<string>();
const registerEchoTool = (name: string, label: string, prefix: string): boolean => {
if (registeredToolNames.has(name)) {
return false;
}
registeredToolNames.add(name);
pi.registerTool({
name,
label,
description: `Echo a message with prefix: ${prefix}`,
promptSnippet: `Echo back user-provided text with ${prefix.trim()} prefix`,
promptGuidelines: ["Use this tool when the user asks for exact echo output."],
parameters: ECHO_PARAMS,
async execute(_toolCallId, params) {
return {
content: [{ type: "text", text: `${prefix}${params.message}` }],
details: { tool: name, prefix },
};
},
});
return true;
};
pi.on("session_start", (_event, ctx) => {
registerEchoTool("echo_session", "Echo Session", "[session] ");
ctx.ui.notify("Registered dynamic tool: echo_session", "info");
});
pi.registerCommand("add-echo-tool", {
description: "Register a new echo tool dynamically: /add-echo-tool <tool_name>",
handler: async (args, ctx) => {
const toolName = normalizeToolName(args);
if (!toolName) {
ctx.ui.notify("Usage: /add-echo-tool <tool_name> (lowercase, numbers, underscores)", "warning");
return;
}
const created = registerEchoTool(toolName, `Echo ${toolName}`, `[${toolName}] `);
if (!created) {
ctx.ui.notify(`Tool already registered: ${toolName}`, "warning");
return;
}
ctx.ui.notify(`Registered dynamic tool: ${toolName}`, "info");
},
});
}