@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
96 lines • 3.53 kB
JavaScript
import { BatchStoreMissingError, createPreparedToolHost, } from "@earendil-works/pi-agent-core";
import { Type } from "typebox";
import { carryPreflightFacts } from "./execution/preflight-carry.js";
const PREFLIGHTED_ARGUMENTS = Type.Unknown();
function issuingMessage(prepared) {
return {
role: "assistant",
content: [prepared.toolCall],
api: "execute-tool",
provider: "senpi",
model: "execute-tool",
usage: {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0,
totalTokens: 0,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
},
stopReason: "toolUse",
timestamp: Date.now(),
};
}
function thrownResult(error) {
return {
content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }],
details: { isError: true },
};
}
/**
* Runs a call `executeTool()` already prepared and preflighted on the in-process prepared ToolHost (S19a). The host
* freezes the preflighted arguments; the caller's own signal and `onUpdate` reach the body, since `executeTool()` never
* raced an abort.
*/
export async function runExecuteToolOnHost(session, prepared, options) {
const openStore = session.agent.batchStoreFactory;
if (openStore === undefined)
throw new BatchStoreMissingError();
const tool = prepared.tool;
let failure;
let settled;
let threw = false;
const body = Object.create(tool, {
prepareArguments: { value: undefined },
// The `tool_call` chain may rewrite the arguments, and its contract is that they are not validated again.
parameters: { value: PREFLIGHTED_ARGUMENTS },
execute: {
value: async (toolCallId, args) => {
try {
return await tool.execute(toolCallId, args, options.signal, options.onUpdate);
}
catch (error) {
threw = true;
return thrownResult(error);
}
},
},
});
const host = createPreparedToolHost({
afterToolFreeze: carryPreflightFacts,
beforeToolCall: async ({ args }) => {
carryPreflightFacts(prepared.args, args);
return undefined;
},
afterToolCall: async ({ result, isError }) => {
try {
settled = { result, hook: await session.afterHooks(prepared, result, isError || threw) };
}
catch (error) {
failure = { error };
}
return undefined;
},
removedToolHints: {},
}, openStore);
const agent = session.agent;
await host.execute({
scope: agent.getExecutionScope?.() ?? agent.executionScope,
calls: [{ ...prepared.toolCall, arguments: prepared.args }],
mode: "sequential",
}, {
emit: () => undefined,
...(agent.onExecutionPipeline === undefined ? {} : { recordWitness: agent.onExecutionPipeline }),
local: {
context: { systemPrompt: "", messages: [], tools: [body] },
assistantMessage: issuingMessage(prepared),
},
});
if (failure !== undefined)
throw failure.error;
if (settled === undefined) {
throw new Error(`executeTool: the prepared host settled no result for ${prepared.toolCall.name}`);
}
return settled;
}
//# sourceMappingURL=execute-tool-on-host.js.map