@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
152 lines • 7.31 kB
JavaScript
import { Text } from "@earendil-works/pi-tui";
import { Type } from "typebox";
export const TOOL_SEARCH_TOOL_NAME = "tool_search";
const MAX_RESULTS = 5;
const ParamsSchema = Type.Object({
query: Type.String({ description: "Natural-language description of the capability you need." }),
source: Type.Optional(Type.Union([Type.Literal("mcp"), Type.Literal("extension")], {
description: "Optional: restrict the search to MCP or extension tools.",
})),
group: Type.Optional(Type.String({ description: "Optional: restrict the search to one catalog group." })),
});
/** Author the single shared tool-search definition registered by this builtin. */
export function createToolSearchTool(service) {
return {
name: TOOL_SEARCH_TOOL_NAME,
sessionBound: true,
workspaceEffect: "read",
label: "Tool search",
description: "Search the catalog of deferred tools by capability. Returns at most 5 matching catalog tools with their parameter schemas and never changes your active tool set; call a returned catalog tool by name and it activates on that first call. Up to 5 matching eval-only tools are listed separately; call those inside an eval cell as tool.<name>(...).",
promptSnippet: "Search deferred tool catalogs by capability; call a returned tool by name to use it.",
parameters: ParamsSchema,
prepareArguments: prepareToolSearchArguments,
executionMode: "parallel",
async execute(_toolCallId, params) {
const options = {
...(params.source === undefined ? {} : { source: params.source }),
...(params.group === undefined ? {} : { group: params.group }),
};
const matches = service.search(params.query, MAX_RESULTS, options);
const hiddenHints = service.hiddenToolHints(params.query);
// A tool the query names keeps its redirect hint, which already carries its exact eval call.
const hinted = new Set(hiddenHints.map((hint) => hint.name));
const evalOnlyMatches = service
.searchEvalOnly(params.query, MAX_RESULTS, options)
.filter((match) => !hinted.has(match.name));
const evalOnlyNames = new Set(evalOnlyMatches.map((match) => match.name));
const text = buildToolSearchResultText({
group: params.group,
hiddenHints,
matches,
evalOnlyMatches,
parametersOf: (name) => service.getToolParameters(name),
query: params.query,
source: params.source,
});
return {
content: [{ type: "text", text }],
details: {
matched: matches.map((match) => match.name),
query: params.query,
...(evalOnlyNames.size === 0 ? {} : { evalOnly: [...evalOnlyNames] }),
},
};
},
renderCall(args, theme) {
const source = args.source === undefined ? "" : ` source:${args.source}`;
const group = args.group === undefined ? "" : ` @${args.group}`;
return new Text(theme.fg("toolTitle", theme.bold(`${TOOL_SEARCH_TOOL_NAME} "${args.query}"${source}${group}`)), 0, 0);
},
renderResult(result, options, theme) {
const count = (result.details?.matched.length ?? 0) + (result.details?.evalOnly?.length ?? 0);
const title = options.isPartial
? `${TOOL_SEARCH_TOOL_NAME}: searching`
: `${TOOL_SEARCH_TOOL_NAME}: ${count} tool(s) found`;
return new Text(theme.fg("toolOutput", title), 0, 0);
},
};
}
function prepareToolSearchArguments(args) {
if (!isRecord(args))
return args;
const { server, ...rest } = args;
return {
...rest,
...(rest.source === undefined && server === undefined ? {} : { source: rest.source ?? "mcp" }),
...(rest.group === undefined && server === undefined ? {} : { group: rest.group ?? server }),
};
}
export function buildToolSearchResultText(input) {
const { query, matches, hiddenHints, source, group } = input;
const scope = [
source === undefined ? undefined : `source "${source}"`,
group === undefined ? undefined : `group "${group}"`,
]
.filter((part) => part !== undefined)
.join(" in ");
const scopeText = scope.length === 0 ? "" : ` in ${scope}`;
const hintLines = hiddenHints.map((entry) => `- ${entry.name}: ${entry.hint}`);
const evalOnlyLines = evalOnlySection(input);
if (matches.length === 0) {
const head = `No catalog tools matched "${query}"${scopeText}. Your active tool set is unchanged.`;
if (hintLines.length === 0 && evalOnlyLines.length === 0) {
return `${head} Try different keywords or a broader query.`;
}
const lines = [head, ...evalOnlyLines];
if (hintLines.length > 0)
lines.push("", "The query names a tool that is hidden in this session:", ...hintLines);
return lines.join("\n");
}
const lines = [
`Found ${matches.length} tool(s) matching "${query}"${scopeText}. Nothing was activated; call one by name and it activates on that first call:`,
"",
...matches.map((match) => toolBullet(match, input.parametersOf)),
...evalOnlyLines,
];
if (hintLines.length > 0)
lines.push("", "The query also names a tool that is hidden in this session:", ...hintLines);
return lines.join("\n");
}
/** Eval-only matches (senpi#6886): reachable only from an eval cell, so they carry their call form and stay inactive. */
function evalOnlySection(input) {
const matches = input.evalOnlyMatches ?? [];
if (matches.length === 0)
return [];
return [
"",
`Eval-only tools matching "${input.query}" (registered, but not in your direct tool list; nothing was activated). Call them inside an eval cell:`,
...matches.map((match) => `${toolBullet(match, input.parametersOf)}\n call: tool.${match.name}({ ... }) inside eval`),
];
}
function toolBullet(match, parametersOf) {
const description = oneLine(match.doc.description) ?? "(no description)";
const parameters = compactParameters(parametersOf(match.name));
return parameters === undefined
? `- ${match.name} - ${description}`
: `- ${match.name} - ${description}\n parameters: ${parameters}`;
}
function isRecord(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function oneLine(text) {
if (text === undefined)
return undefined;
const collapsed = text.replace(/\s+/g, " ").trim();
if (collapsed.length === 0)
return undefined;
return collapsed.length <= 160 ? collapsed : `${collapsed.slice(0, 157)}...`;
}
/** One-line JSON schema so the model can call the tool without a second round trip. */
function compactParameters(parameters) {
if (!isRecord(parameters))
return undefined;
try {
return JSON.stringify(parameters);
}
catch (error) {
if (error instanceof TypeError)
return undefined;
throw error;
}
}
//# sourceMappingURL=tool.js.map