@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
80 lines • 3.26 kB
JavaScript
import { validateToolArguments } from "@earendil-works/pi-ai";
function errorResult(message) {
return { content: [{ type: "text", text: message }], details: undefined, isError: true };
}
function withOverride(result, override) {
const structuredContent = override.structuredContent ?? (override.content ? undefined : result.structuredContent);
const next = {
...result,
content: override.content ?? result.content,
details: override.details ?? result.details,
usage: override.usage ?? result.usage,
isError: override.isError ?? result.isError === true,
};
if (structuredContent === undefined)
delete next.structuredContent;
else
next.structuredContent = structuredContent;
return next;
}
/**
* Runs one tool call the way the agent loop runs a model-issued one (`runToolCall`, agent-loop.ts): argument preparation
* and schema validation; then, when `handlers` are given, the `tool_call` handlers, where a block, an abort or a handler
* that throws stops the call before the tool runs (fail-closed, as a session does); the tool; and the `tool_result`
* handlers. Invalid arguments, a blocked call and a failing tool come back as an `isError` result, never a rejection
* (senpi#5413).
*/
export async function runLooplessToolCall(tool, call, handlers) {
const { toolCallId, signal } = call;
const nested = call.nested === undefined ? {} : { nested: call.nested };
let args;
try {
const prepared = tool.prepareArguments ? tool.prepareArguments(call.params) : call.params;
const toolCall = { type: "toolCall", id: toolCallId, name: tool.name, arguments: prepared };
args = validateToolArguments(tool, toolCall);
}
catch (error) {
return errorResult(error instanceof Error ? error.message : String(error));
}
if (handlers) {
let before;
try {
before = await handlers.beforeToolCall({ toolName: tool.name, toolCallId, input: args, ...nested });
}
catch (error) {
return errorResult(error instanceof Error ? error.message : `Extension failed, blocking execution: ${String(error)}`);
}
if (signal?.aborted)
return errorResult("Operation aborted");
if (before?.block) {
const blocked = errorResult(before.reason || "Tool execution was blocked");
if (before.terminate === true)
blocked.terminate = true;
return blocked;
}
}
let result;
try {
result = await tool.execute(toolCallId, args, signal, undefined);
}
catch (error) {
result = errorResult(error instanceof Error ? error.message : String(error));
}
if (!handlers)
return result;
try {
const override = await handlers.afterToolCall({
toolName: tool.name,
toolCallId,
input: args,
result,
isError: result.isError === true,
...nested,
});
return override ? withOverride(result, override) : result;
}
catch (error) {
return errorResult(error instanceof Error ? error.message : String(error));
}
}
//# sourceMappingURL=loopless-tool-call.js.map